Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
10219 lines (9938 loc) · 423 KB
/
Copy pathmod.rs
File metadata and controls
10219 lines (9938 loc) · 423 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
//! Avro reader
//!
//! Facilities to read Apache Avro–encoded data into Arrow's `RecordBatch` format.
//!
//! ### Limitations
//!
//!- **Avro unions with > 127 branches are not supported.**
//! When decoding Avro unions to Arrow `UnionArray`, Arrow stores the union
//! type identifiers in an **8‑bit signed** buffer (`i8`). This implies a
//! practical limit of **127** distinct branch ids. Inputs that resolve to
//! more than 127 branches will return an error. If you truly need more,
//! model the schema as a **union of unions**, per the Arrow format spec.
//!
//! See: Arrow Columnar Format — Dense Union (“types buffer: 8‑bit signed;
//! a union with more than 127 possible types can be modeled as a union of
//! unions”).
//!
//! This module exposes three layers of the API surface, from highest to lowest-level:
//!
//! * [`ReaderBuilder`]: configures how Avro is read (batch size, strict union handling,
//! string representation, reader schema, etc.) and produces either:
//! * a `Reader` for **Avro Object Container Files (OCF)** read from any `BufRead`, or
//! * a low-level `Decoder` for **unframed Avro datums**, **single‑object encoded** Avro
//! bytes, and Confluent **Schema Registry** framed messages.
//! * [`Reader`]: a convenient, synchronous iterator over `RecordBatch` decoded from an OCF
//! input. Implements [`Iterator<Item = Result<RecordBatch, ArrowError>>`] and
//! `RecordBatchReader`.
//! * [`Decoder`]: a push‑based row decoder that consumes unframed or
//! framed Avro bytes and yields ready `RecordBatch` values when batches fill. This is suitable
//! for integrating with async byte streams, network protocols, or other custom data sources.
//!
//! ## Encodings and when to use which type
//!
//! * **Object Container File (OCF)**: A self‑describing file format with a header containing
//! the writer schema, optional compression codec, and a sync marker, followed by one or
//! more data blocks. Use `Reader` for this format. See the Avro 1.11.1 specification
//! (“Object Container Files”). <https://avro.apache.org/docs/1.11.1/specification/#object-container-files>
//! * **Unframed binary datums**: Bare Avro records without an OCF header, schema fingerprint,
//! or schema-registry prefix. Register the known writer schema in a `SchemaStore`, select it
//! with [`ReaderBuilder::with_active_fingerprint`](crate::reader::ReaderBuilder::with_active_fingerprint),
//! configure [`DecoderMode::UnframedDatum`] with
//! [`ReaderBuilder::with_decoder_mode`](crate::reader::ReaderBuilder::with_decoder_mode), and
//! call [`Decoder::decode`](crate::reader::Decoder::decode) once per record. This supports bare
//! Kafka messages and consecutive records in one buffer.
//! * **Single‑Object Encoding**: A stream‑friendly framing that prefixes each record body with
//! the 2‑byte marker `0xC3 0x01` followed by the **8‑byte little‑endian CRC‑64‑AVRO Rabin
//! fingerprint** of the writer schema, then the Avro binary body. Use `Decoder` with a
//! populated `SchemaStore` to resolve fingerprints to full schemas.
//! See “Single object encoding” in the Avro 1.11.1 spec.
//! <https://avro.apache.org/docs/1.11.1/specification/#single-object-encoding>
//! * **Confluent Schema Registry wire format**: A 1‑byte magic `0x00`, a **4‑byte big‑endian**
//! schema ID, then the Avro‑encoded body. Use `Decoder` with a `SchemaStore` configured
//! for `FingerprintAlgorithm::Id` and entries keyed by `Fingerprint::Id`. See
//! Confluent’s “Wire format” documentation.
//! <https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html#wire-format>
//! * **Apicurio Schema Registry wire format**: A 1‑byte magic `0x00`, a **8‑byte big‑endian**
//! global schema ID, then the Avro‑encoded body. Use `Decoder` with a `SchemaStore` configured
//! for `FingerprintAlgorithm::Id64` and entries keyed by `Fingerprint::Id64`. See
//! Apicurio’s “Avro SerDe” documentation.
//! <https://www.apicur.io/registry/docs/apicurio-registry/1.3.3.Final/getting-started/assembly-using-kafka-client-serdes.html#registry-serdes-types-avro-registry>
//!
//! ## Basic file usage (OCF)
//!
//! Use `ReaderBuilder::build` to construct a `Reader` from any `BufRead`. The doctest below
//! creates a tiny OCF in memory using `AvroWriter` and then reads it back.
//!
//! ```
//! use std::io::Cursor;
//! use std::sync::Arc;
//! use arrow_array::{ArrayRef, Int32Array, RecordBatch};
//! use arrow_schema::{DataType, Field, Schema};
//! use arrow_avro::writer::AvroWriter;
//! use arrow_avro::reader::ReaderBuilder;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Build a minimal Arrow schema and batch
//! let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
//! let batch = RecordBatch::try_new(
//! Arc::new(schema.clone()),
//! vec![Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef],
//! )?;
//!
//! // Write an Avro OCF to memory
//! let buffer: Vec<u8> = Vec::new();
//! let mut writer = AvroWriter::new(buffer, schema.clone())?;
//! writer.write(&batch)?;
//! writer.finish()?;
//! let bytes = writer.into_inner();
//!
//! // Read it back with ReaderBuilder
//! let mut reader = ReaderBuilder::new().build(Cursor::new(bytes))?;
//! let out = reader.next().unwrap()?;
//! assert_eq!(out.num_rows(), 3);
//! # Ok(()) }
//! ```
//!
//! ## Streaming usage (single‑object / Confluent / Apicurio)
//!
//! The `Decoder` lets you integrate Avro decoding with **any** source of bytes by
//! periodically calling `Decoder::decode` with new data and calling `Decoder::flush`
//! to get a `RecordBatch` once at least one row is complete.
//!
//! The example below shows how to decode from an arbitrary stream of `bytes::Bytes` using
//! `futures` utilities. Note: this is illustrative and keeps a single in‑memory `Bytes`
//! buffer for simplicity—real applications typically maintain a rolling buffer.
//!
//! ```
//! use bytes::{Buf, Bytes};
//! use futures::{Stream, StreamExt};
//! use std::task::{Poll, ready};
//! use arrow_array::RecordBatch;
//! use arrow_avro::{reader::Decoder, errors::AvroError};
//!
//! /// Decode a stream of Avro-framed bytes into RecordBatch values.
//! fn decode_stream<S: Stream<Item = Bytes> + Unpin>(
//! mut decoder: Decoder,
//! mut input: S,
//! ) -> impl Stream<Item = Result<RecordBatch, AvroError>> {
//! let mut buffered = Bytes::new();
//! futures::stream::poll_fn(move |cx| {
//! loop {
//! if buffered.is_empty() {
//! buffered = match ready!(input.poll_next_unpin(cx)) {
//! Some(b) => b,
//! None => break, // EOF
//! };
//! }
//! // Feed as much as possible
//! let decoded = match decoder.decode(buffered.as_ref()) {
//! Ok(n) => n,
//! Err(e) => return Poll::Ready(Some(Err(e))),
//! };
//! let read = buffered.len();
//! buffered.advance(decoded);
//! if decoded != read {
//! // decoder made partial progress; request more bytes
//! break
//! }
//! }
//! // Return a batch if one or more rows are complete
//! Poll::Ready(decoder.flush().transpose())
//! })
//! }
//! ```
//!
//! ### Building and using a `Decoder` for **single‑object encoding** (Rabin fingerprints)
//!
//! The doctest below **writes** a single‑object framed record using the Avro writer
//! (no manual varints) for the writer schema
//! (`{"type":"record","name":"User","fields":[{"name":"id","type":"long"}]}`)
//! and then decodes it into a `RecordBatch`.
//!
//! ```
//! use std::sync::Arc;
//! use std::collections::HashMap;
//! use arrow_array::{ArrayRef, Int64Array, RecordBatch};
//! use arrow_schema::{DataType, Field, Schema};
//! use arrow_avro::schema::{AvroSchema, SchemaStore, SCHEMA_METADATA_KEY, FingerprintStrategy};
//! use arrow_avro::writer::{WriterBuilder, format::AvroSoeFormat};
//! use arrow_avro::reader::ReaderBuilder;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Register the writer schema (Rabin fingerprint by default).
//! let mut store = SchemaStore::new();
//! let avro_schema = AvroSchema::new(r#"{"type":"record","name":"User","fields":[
//! {"name":"id","type":"long"}]}"#.to_string());
//! let _fp = store.register(avro_schema.clone())?;
//!
//! // Create a single-object framed record { id: 42 } with the Avro writer.
//! let mut md = HashMap::new();
//! md.insert(SCHEMA_METADATA_KEY.to_string(), avro_schema.json_string.clone());
//! let arrow = Schema::new_with_metadata(vec![Field::new("id", DataType::Int64, false)], md);
//! let batch = RecordBatch::try_new(
//! Arc::new(arrow.clone()),
//! vec![Arc::new(Int64Array::from(vec![42])) as ArrayRef],
//! )?;
//! let mut w = WriterBuilder::new(arrow)
//! .with_fingerprint_strategy(FingerprintStrategy::Rabin) // SOE prefix
//! .build::<_, AvroSoeFormat>(Vec::new())?;
//! w.write(&batch)?;
//! w.finish()?;
//! let frame = w.into_inner(); // C3 01 + fp + Avro body
//!
//! // Decode with a `Decoder`
//! let mut dec = ReaderBuilder::new()
//! .with_writer_schema_store(store)
//! .with_batch_size(1024)
//! .build_decoder()?;
//!
//! dec.decode(&frame)?;
//! let out = dec.flush()?.expect("one batch");
//! assert_eq!(out.num_rows(), 1);
//! # Ok(()) }
//! ```
//!
//! See Avro 1.11.1 “Single object encoding” for details of the 2‑byte marker
//! and little‑endian CRC‑64‑AVRO fingerprint:
//! <https://avro.apache.org/docs/1.11.1/specification/#single-object-encoding>
//!
//! ### Building and using a `Decoder` for **Confluent Schema Registry** framing
//!
//! The Confluent wire format is: 1‑byte magic `0x00`, then a **4‑byte big‑endian** schema ID,
//! then the Avro body. The doctest below crafts two messages for the same schema ID and
//! decodes them into a single `RecordBatch` with two rows.
//!
//! ```
//! use std::sync::Arc;
//! use std::collections::HashMap;
//! use arrow_array::{ArrayRef, Int64Array, StringArray, RecordBatch};
//! use arrow_schema::{DataType, Field, Schema};
//! use arrow_avro::schema::{AvroSchema, SchemaStore, Fingerprint, FingerprintAlgorithm, SCHEMA_METADATA_KEY, FingerprintStrategy};
//! use arrow_avro::writer::{WriterBuilder, format::AvroSoeFormat};
//! use arrow_avro::reader::ReaderBuilder;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Set up a store keyed by numeric IDs (Confluent).
//! let mut store = SchemaStore::new_with_type(FingerprintAlgorithm::Id);
//! let schema_id = 7u32;
//! let avro_schema = AvroSchema::new(r#"{"type":"record","name":"User","fields":[
//! {"name":"id","type":"long"}, {"name":"name","type":"string"}]}"#.to_string());
//! store.set(Fingerprint::Id(schema_id), avro_schema.clone())?;
//!
//! // Write two Confluent-framed messages {id:1,name:"a"} and {id:2,name:"b"}.
//! fn msg(id: i64, name: &str, schema: &AvroSchema, schema_id: u32) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
//! let mut md = HashMap::new();
//! md.insert(SCHEMA_METADATA_KEY.to_string(), schema.json_string.clone());
//! let arrow = Schema::new_with_metadata(
//! vec![Field::new("id", DataType::Int64, false), Field::new("name", DataType::Utf8, false)],
//! md,
//! );
//! let batch = RecordBatch::try_new(
//! Arc::new(arrow.clone()),
//! vec![
//! Arc::new(Int64Array::from(vec![id])) as ArrayRef,
//! Arc::new(StringArray::from(vec![name])) as ArrayRef,
//! ],
//! )?;
//! let mut w = WriterBuilder::new(arrow)
//! .with_fingerprint_strategy(FingerprintStrategy::Id(schema_id)) // 0x00 + ID + body
//! .build::<_, AvroSoeFormat>(Vec::new())?;
//! w.write(&batch)?; w.finish()?;
//! Ok(w.into_inner())
//! }
//! let m1 = msg(1, "a", &avro_schema, schema_id)?;
//! let m2 = msg(2, "b", &avro_schema, schema_id)?;
//!
//! // Decode both into a single batch.
//! let mut dec = ReaderBuilder::new()
//! .with_writer_schema_store(store)
//! .with_batch_size(1024)
//! .build_decoder()?;
//! dec.decode(&m1)?;
//! dec.decode(&m2)?;
//! let batch = dec.flush()?.expect("batch");
//! assert_eq!(batch.num_rows(), 2);
//! # Ok(()) }
//! ```
//!
//! See Confluent’s “Wire format” notes: magic byte `0x00`, 4‑byte **big‑endian** schema ID,
//! then the Avro‑encoded payload.
//! <https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html#wire-format>
//!
//! ## Schema resolution (reader vs. writer schemas)
//!
//! Avro supports resolving data written with one schema (“writer”) into another (“reader”)
//! using rules like **field aliases**, **default values**, and **numeric promotions**.
//! In practice this lets you evolve schemas over time while remaining compatible with old data.
//!
//! *Spec background:* See Avro’s **Schema Resolution** (aliases, defaults) and the Confluent
//! **Wire format** (magic `0x00` + big‑endian schema id + Avro body).
//! <https://avro.apache.org/docs/1.11.1/specification/#schema-resolution>
//! <https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html#wire-format>
//!
//! ### OCF example: rename a field and add a default via a reader schema
//!
//! Below we write an OCF with a *writer schema* having fields `id: long`, `name: string`.
//! We then read it with a *reader schema* that:
//! - **renames** `name` to `full_name` via `aliases`, and
//! - **adds** `is_active: boolean` with a **default** value `true`.
//!
//! ```
//! use std::io::Cursor;
//! use std::sync::Arc;
//! use arrow_array::{ArrayRef, Int64Array, StringArray, RecordBatch};
//! use arrow_schema::{DataType, Field, Schema};
//! use arrow_avro::writer::AvroWriter;
//! use arrow_avro::reader::ReaderBuilder;
//! use arrow_avro::schema::AvroSchema;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Writer (past version): { id: long, name: string }
//! let writer_arrow = Schema::new(vec![
//! Field::new("id", DataType::Int64, false),
//! Field::new("name", DataType::Utf8, false),
//! ]);
//! let batch = RecordBatch::try_new(
//! Arc::new(writer_arrow.clone()),
//! vec![
//! Arc::new(Int64Array::from(vec![1, 2])) as ArrayRef,
//! Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef,
//! ],
//! )?;
//!
//! // Write an OCF entirely in memory
//! let mut w = AvroWriter::new(Vec::<u8>::new(), writer_arrow)?;
//! w.write(&batch)?;
//! w.finish()?;
//! let bytes = w.into_inner();
//!
//! // Reader (current version):
//! // - record name "topLevelRecord" matches the crate's default for OCF
//! // - rename `name` -> `full_name` using aliases (optional)
//! let reader_json = r#"
//! {
//! "type": "record",
//! "name": "topLevelRecord",
//! "fields": [
//! { "name": "id", "type": "long" },
//! { "name": "full_name", "type": ["null","string"], "aliases": ["name"], "default": null },
//! { "name": "is_active", "type": "boolean", "default": true }
//! ]
//! }"#;
//!
//! let mut reader = ReaderBuilder::new()
//! .with_reader_schema(AvroSchema::new(reader_json.to_string()))
//! .build(Cursor::new(bytes))?;
//!
//! let out = reader.next().unwrap()?;
//! assert_eq!(out.num_rows(), 2);
//! # Ok(()) }
//! ```
//!
//! ### Confluent single‑object example: resolve *past* writer versions to the topic’s **current** reader schema
//!
//! In this scenario, the **reader schema** is the topic’s *current* schema, while the two
//! **writer schemas** registered under Confluent IDs **1** and **2** represent *past versions*.
//! The decoder uses the reader schema to resolve both versions.
//!
//! ```
//! use std::sync::Arc;
//! use std::collections::HashMap;
//! use arrow_avro::reader::ReaderBuilder;
//! use arrow_avro::schema::{
//! AvroSchema, Fingerprint, FingerprintAlgorithm, SchemaStore,
//! SCHEMA_METADATA_KEY, FingerprintStrategy,
//! };
//! use arrow_array::{ArrayRef, Int32Array, Int64Array, StringArray, RecordBatch};
//! use arrow_schema::{DataType, Field, Schema};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Reader: current topic schema (no reader-added fields)
//! // {"type":"record","name":"User","fields":[
//! // {"name":"id","type":"long"},
//! // {"name":"name","type":"string"}]}
//! let reader_schema = AvroSchema::new(
//! r#"{"type":"record","name":"User",
//! "fields":[{"name":"id","type":"long"},{"name":"name","type":"string"}]}"#
//! .to_string(),
//! );
//!
//! // Register two *writer* schemas under Confluent IDs 0 and 1
//! let writer_v0 = AvroSchema::new(
//! r#"{"type":"record","name":"User",
//! "fields":[{"name":"id","type":"int"},{"name":"name","type":"string"}]}"#
//! .to_string(),
//! );
//! let writer_v1 = AvroSchema::new(
//! r#"{"type":"record","name":"User",
//! "fields":[{"name":"id","type":"long"},{"name":"name","type":"string"},
//! {"name":"email","type":["null","string"],"default":null}]}"#
//! .to_string(),
//! );
//!
//! let id_v0: u32 = 0;
//! let id_v1: u32 = 1;
//!
//! let mut store = SchemaStore::new_with_type(FingerprintAlgorithm::Id); // integer IDs
//! store.set(Fingerprint::Id(id_v0), writer_v0.clone())?;
//! store.set(Fingerprint::Id(id_v1), writer_v1.clone())?;
//!
//! // Write two Confluent-framed messages using each writer version
//! // frame0: writer v0 body {id:1001_i32, name:"v0-alice"}
//! let mut md0 = HashMap::new();
//! md0.insert(SCHEMA_METADATA_KEY.to_string(), writer_v0.json_string.clone());
//! let arrow0 = Schema::new_with_metadata(
//! vec![Field::new("id", DataType::Int32, false),
//! Field::new("name", DataType::Utf8, false)], md0);
//! let batch0 = RecordBatch::try_new(
//! Arc::new(arrow0.clone()),
//! vec![Arc::new(Int32Array::from(vec![1001])) as ArrayRef,
//! Arc::new(StringArray::from(vec!["v0-alice"])) as ArrayRef])?;
//! let mut w0 = arrow_avro::writer::WriterBuilder::new(arrow0)
//! .with_fingerprint_strategy(FingerprintStrategy::Id(id_v0))
//! .build::<_, arrow_avro::writer::format::AvroSoeFormat>(Vec::new())?;
//! w0.write(&batch0)?; w0.finish()?;
//! let frame0 = w0.into_inner(); // 0x00 + id_v0 + body
//!
//! // frame1: writer v1 body {id:2002_i64, name:"v1-bob", email: Some("[email protected]")}
//! let mut md1 = HashMap::new();
//! md1.insert(SCHEMA_METADATA_KEY.to_string(), writer_v1.json_string.clone());
//! let arrow1 = Schema::new_with_metadata(
//! vec![Field::new("id", DataType::Int64, false),
//! Field::new("name", DataType::Utf8, false),
//! Field::new("email", DataType::Utf8, true)], md1);
//! let batch1 = RecordBatch::try_new(
//! Arc::new(arrow1.clone()),
//! vec![Arc::new(Int64Array::from(vec![2002])) as ArrayRef,
//! Arc::new(StringArray::from(vec!["v1-bob"])) as ArrayRef,
//! Arc::new(StringArray::from(vec![Some("[email protected]")])) as ArrayRef])?;
//! let mut w1 = arrow_avro::writer::WriterBuilder::new(arrow1)
//! .with_fingerprint_strategy(FingerprintStrategy::Id(id_v1))
//! .build::<_, arrow_avro::writer::format::AvroSoeFormat>(Vec::new())?;
//! w1.write(&batch1)?; w1.finish()?;
//! let frame1 = w1.into_inner(); // 0x00 + id_v1 + body
//!
//! // Build a streaming Decoder that understands Confluent framing
//! let mut decoder = ReaderBuilder::new()
//! .with_reader_schema(reader_schema)
//! .with_writer_schema_store(store)
//! .with_batch_size(8) // small demo batches
//! .build_decoder()?;
//!
//! // Decode each whole frame, then drain completed rows with flush()
//! let mut total_rows = 0usize;
//!
//! let consumed0 = decoder.decode(&frame0)?;
//! assert_eq!(consumed0, frame0.len(), "decoder must consume the whole frame");
//! while let Some(batch) = decoder.flush()? { total_rows += batch.num_rows(); }
//!
//! let consumed1 = decoder.decode(&frame1)?;
//! assert_eq!(consumed1, frame1.len(), "decoder must consume the whole frame");
//! while let Some(batch) = decoder.flush()? { total_rows += batch.num_rows(); }
//!
//! // We sent 2 records so we should get 2 rows (possibly one per flush)
//! assert_eq!(total_rows, 2);
//! Ok(())
//! }
//! ```
//!
//! ## Schema evolution and batch boundaries
//!
//! `Decoder` supports mid‑stream schema changes when the input framing carries a schema
//! fingerprint (single‑object or Confluent). When a new fingerprint is observed:
//!
//! * If the current `RecordBatch` is **empty**, the decoder switches to the new schema
//! immediately.
//! * If not, the decoder finishes the current batch first and only then switches.
//!
//! Consequently, the schema of batches produced by `Decoder::flush` may change over time,
//! and `Decoder` intentionally does **not** implement `RecordBatchReader`. In contrast,
//! `Reader` (OCF) has a single writer schema for the entire file and therefore implements
//! `RecordBatchReader`.
//!
//! ## Performance & memory
//!
//! * `batch_size` controls the maximum number of rows per `RecordBatch`. Larger batches
//! amortize per‑batch overhead; smaller batches reduce peak memory usage and latency.
//! * When `utf8_view` is enabled, string columns use Arrow’s `StringViewArray`, which can
//! reduce allocations for short strings.
//! * For OCF, blocks may be compressed; `Reader` will decompress using the codec specified
//! in the file header and feed uncompressed bytes to the row `Decoder`.
//!
//! ## Error handling
//!
//! * Incomplete inputs return parse errors with "Unexpected EOF"; callers typically provide
//! more bytes and try again.
//! * If a fingerprint is unknown to the provided `SchemaStore`, decoding fails with a
//! descriptive error. Populate the store up front to avoid this.
//!
//! ---
use crate::codec::{AvroFieldBuilder, Tz};
use crate::errors::AvroError;
use crate::reader::header::read_header;
use crate::schema::{
AvroSchema, CONFLUENT_MAGIC, Fingerprint, FingerprintAlgorithm, SCHEMA_METADATA_KEY,
SINGLE_OBJECT_MAGIC, Schema, SchemaStore,
};
use arrow_array::{RecordBatch, RecordBatchReader};
use arrow_schema::{ArrowError, SchemaRef};
use block::BlockDecoder;
use header::Header;
use indexmap::IndexMap;
use record::RecordDecoder;
use std::io::BufRead;
mod block;
mod cursor;
mod header;
mod record;
mod vlq;
#[cfg(feature = "async")]
pub mod async_reader;
pub use header::{HeaderInfo, read_header_info};
#[expect(deprecated)]
#[cfg(feature = "object_store")]
pub use async_reader::AvroObjectReader;
#[cfg(feature = "async")]
pub use async_reader::{AsyncAvroFileReader, AsyncFileReader, SpawnedReader};
fn is_incomplete_data(err: &AvroError) -> bool {
matches!(
err,
AvroError::EOF(_) | AvroError::NeedMoreData(_) | AvroError::NeedMoreDataRange(_)
)
}
/// The wire format consumed by a streaming [`Decoder`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DecoderMode {
/// Decode single-object or schema-registry-framed Avro records.
#[default]
Framed,
/// Decode exactly one unframed Avro datum per call using the active writer schema.
UnframedDatum,
}
/// A low‑level, push‑based decoder from Avro bytes to Arrow `RecordBatch`.
///
/// `Decoder` is designed for **streaming** scenarios:
///
/// * You *feed* bytes using [`Self::decode`], potentially multiple times, until at least one row
/// is complete. [`ReaderBuilder::with_decoder_mode`] selects the input wire format.
/// * You then *drain* completed rows with `Self::flush`, which yields a `RecordBatch`
/// if any rows were finished since the last flush.
///
/// Unlike `Reader`, which is specialized for Avro **Object Container Files**, `Decoder`
/// understands **unframed Avro datums**, **framed single‑object** inputs, and **Confluent
/// Schema Registry** messages, switching schemas mid‑stream when framing indicates a new
/// fingerprint. Unframed datums use the writer schema already selected on the decoder.
///
/// ### Supported prefixes
///
/// On each new row boundary, `Decoder` tries to match one of the following "prefixes":
///
/// * **Single‑Object encoding**: magic `0xC3 0x01` + schema fingerprint (length depends on
/// the configured `FingerprintAlgorithm`); see `SINGLE_OBJECT_MAGIC`.
/// * **Confluent wire format**: magic `0x00` + 4‑byte big‑endian schema id; see
/// `CONFLUENT_MAGIC`.
///
/// The active fingerprint determines which cached row decoder is used to decode the following
/// record body bytes.
///
/// ### Schema switching semantics
///
/// When a new fingerprint is observed:
///
/// * If the current batch is empty, the decoder switches immediately;
/// * Otherwise, the current batch is finalized on the next `flush` and only then
/// does the decoder switch to the new schema. This guarantees that a single `RecordBatch`
/// never mixes rows with different schemas.
///
/// ### Examples
///
/// Build and use a `Decoder` for single‑object encoding:
///
/// ```
/// use arrow_avro::schema::{AvroSchema, SchemaStore};
/// use arrow_avro::reader::ReaderBuilder;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Use a record schema at the top level so we can build an Arrow RecordBatch
/// let mut store = SchemaStore::new(); // Rabin fingerprinting by default
/// let avro = AvroSchema::new(
/// r#"{"type":"record","name":"E","fields":[{"name":"x","type":"long"}]}"#.to_string()
/// );
/// let fp = store.register(avro)?;
///
/// // --- Hidden: write a single-object framed row {x:7} ---
/// # use std::sync::Arc;
/// # use std::collections::HashMap;
/// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
/// # use arrow_schema::{DataType, Field, Schema};
/// # use arrow_avro::schema::{SCHEMA_METADATA_KEY, FingerprintStrategy};
/// # use arrow_avro::writer::{WriterBuilder, format::AvroSoeFormat};
/// # let mut md = HashMap::new();
/// # md.insert(SCHEMA_METADATA_KEY.to_string(),
/// # r#"{"type":"record","name":"E","fields":[{"name":"x","type":"long"}]}"#.to_string());
/// # let arrow = Schema::new_with_metadata(vec![Field::new("x", DataType::Int64, false)], md);
/// # let batch = RecordBatch::try_new(Arc::new(arrow.clone()), vec![Arc::new(Int64Array::from(vec![7])) as ArrayRef])?;
/// # let mut w = WriterBuilder::new(arrow)
/// # .with_fingerprint_strategy(fp.into())
/// # .build::<_, AvroSoeFormat>(Vec::new())?;
/// # w.write(&batch)?; w.finish()?; let frame = w.into_inner();
///
/// let mut decoder = ReaderBuilder::new()
/// .with_writer_schema_store(store)
/// .with_batch_size(16)
/// .build_decoder()?;
///
/// # decoder.decode(&frame)?;
/// let batch = decoder.flush()?.expect("one row");
/// assert_eq!(batch.num_rows(), 1);
/// # Ok(()) }
/// ```
///
/// *Background:* Avro's single‑object encoding is defined as `0xC3 0x01` + 8‑byte
/// little‑endian CRC‑64‑AVRO fingerprint of the **writer schema** + Avro binary body.
/// See the Avro 1.11.1 spec for details. <https://avro.apache.org/docs/1.11.1/specification/#single-object-encoding>
///
/// Build and use a `Decoder` for Confluent Registry messages:
///
/// ```
/// use arrow_avro::schema::{AvroSchema, SchemaStore, Fingerprint, FingerprintAlgorithm};
/// use arrow_avro::reader::ReaderBuilder;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut store = SchemaStore::new_with_type(FingerprintAlgorithm::Id);
/// store.set(Fingerprint::Id(1234), AvroSchema::new(r#"{"type":"record","name":"E","fields":[{"name":"x","type":"long"}]}"#.to_string()))?;
///
/// // --- Hidden: encode two Confluent-framed messages {x:1} and {x:2} ---
/// # use std::sync::Arc;
/// # use std::collections::HashMap;
/// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
/// # use arrow_schema::{DataType, Field, Schema};
/// # use arrow_avro::schema::{SCHEMA_METADATA_KEY, FingerprintStrategy};
/// # use arrow_avro::writer::{WriterBuilder, format::AvroSoeFormat};
/// # fn msg(x: i64) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
/// # let mut md = HashMap::new();
/// # md.insert(SCHEMA_METADATA_KEY.to_string(),
/// # r#"{"type":"record","name":"E","fields":[{"name":"x","type":"long"}]}"#.to_string());
/// # let arrow = Schema::new_with_metadata(vec![Field::new("x", DataType::Int64, false)], md);
/// # let batch = RecordBatch::try_new(Arc::new(arrow.clone()), vec![Arc::new(Int64Array::from(vec![x])) as ArrayRef])?;
/// # let mut w = WriterBuilder::new(arrow)
/// # .with_fingerprint_strategy(FingerprintStrategy::Id(1234))
/// # .build::<_, AvroSoeFormat>(Vec::new())?;
/// # w.write(&batch)?; w.finish()?; Ok(w.into_inner())
/// # }
/// # let m1 = msg(1)?;
/// # let m2 = msg(2)?;
///
/// let mut decoder = ReaderBuilder::new()
/// .with_writer_schema_store(store)
/// .build_decoder()?;
/// # decoder.decode(&m1)?;
/// # decoder.decode(&m2)?;
/// let batch = decoder.flush()?.expect("two rows");
/// assert_eq!(batch.num_rows(), 2);
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct Decoder {
active_decoder: RecordDecoder,
active_fingerprint: Option<Fingerprint>,
batch_size: usize,
remaining_capacity: usize,
cache: IndexMap<Fingerprint, RecordDecoder>,
fingerprint_algorithm: FingerprintAlgorithm,
pending_schema: Option<(Fingerprint, RecordDecoder)>,
awaiting_body: bool,
mode: DecoderMode,
}
impl Decoder {
pub(crate) fn from_parts(
batch_size: usize,
active_decoder: RecordDecoder,
active_fingerprint: Option<Fingerprint>,
cache: IndexMap<Fingerprint, RecordDecoder>,
fingerprint_algorithm: FingerprintAlgorithm,
) -> Self {
Self {
batch_size,
remaining_capacity: batch_size,
active_fingerprint,
active_decoder,
cache,
fingerprint_algorithm,
pending_schema: None,
awaiting_body: false,
mode: DecoderMode::Framed,
}
}
/// Returns the Arrow schema for the rows decoded by this decoder.
///
/// **Note:** With single‑object or Confluent framing, the schema may change
/// at a row boundary when the input indicates a new fingerprint.
pub fn schema(&self) -> SchemaRef {
self.active_decoder.schema().clone()
}
/// Returns the configured maximum number of rows per batch.
pub fn batch_size(&self) -> usize {
self.batch_size
}
/// Feed a chunk of bytes into the decoder.
///
/// This will:
///
/// * Decode at most `Self::batch_size` framed rows, or exactly one unframed datum;
/// * Return the number of input bytes **consumed** from `data` (which may be 0 if more
/// bytes are required, or less than `data.len()` if a prefix/body straddles the
/// chunk boundary);
/// * Defer producing a `RecordBatch` until you call `Self::flush`.
///
/// # Returns
/// The number of bytes consumed from `data`.
///
/// # Errors
/// Returns an error if:
///
/// * The input indicates an unknown fingerprint (not present in the provided
/// `SchemaStore`;
/// * The Avro body is malformed;
/// * A strict‑mode union rule is violated (see `ReaderBuilder::with_strict_mode`);
/// * An unframed datum is supplied when the batch is already full
/// ([`AvroError::BatchFull`]).
pub fn decode(&mut self, data: &[u8]) -> Result<usize, AvroError> {
match self.mode {
DecoderMode::Framed => self.decode_framed(data),
DecoderMode::UnframedDatum => self.decode_unframed(data),
}
}
fn decode_framed(&mut self, data: &[u8]) -> Result<usize, AvroError> {
let mut total_consumed = 0usize;
while total_consumed < data.len() && self.remaining_capacity > 0 {
if self.awaiting_body {
match self.active_decoder.decode(&data[total_consumed..], 1) {
Ok(n) => {
self.remaining_capacity -= 1;
total_consumed += n;
self.awaiting_body = false;
continue;
}
Err(ref e) if is_incomplete_data(e) => break,
Err(e) => return Err(e),
};
}
match self.handle_prefix(&data[total_consumed..])? {
Some(0) => break, // Insufficient bytes
Some(n) => {
total_consumed += n;
self.apply_pending_schema_if_batch_empty();
self.awaiting_body = true;
}
None => {
return Err(AvroError::ParseError(
"Missing magic bytes and fingerprint".to_string(),
));
}
}
}
Ok(total_consumed)
}
fn decode_unframed(&mut self, data: &[u8]) -> Result<usize, AvroError> {
if self.remaining_capacity == 0 {
return Err(AvroError::BatchFull);
}
let consumed = self.active_decoder.decode(data, 1)?;
self.remaining_capacity -= 1;
Ok(consumed)
}
// Attempt to handle a prefix at the current position.
// * Ok(None) – buffer does not start with the prefix.
// * Ok(Some(0)) – prefix detected, but the buffer is too short; caller should await more bytes.
// * Ok(Some(n)) – consumed `n > 0` bytes of a complete prefix (magic and fingerprint).
fn handle_prefix(&mut self, buf: &[u8]) -> Result<Option<usize>, AvroError> {
match self.fingerprint_algorithm {
FingerprintAlgorithm::Rabin => {
self.handle_prefix_common(buf, &SINGLE_OBJECT_MAGIC, |bytes| {
Fingerprint::Rabin(u64::from_le_bytes(bytes))
})
}
FingerprintAlgorithm::Id => self.handle_prefix_common(buf, &CONFLUENT_MAGIC, |bytes| {
Fingerprint::Id(u32::from_be_bytes(bytes))
}),
FingerprintAlgorithm::Id64 => {
self.handle_prefix_common(buf, &CONFLUENT_MAGIC, |bytes| {
Fingerprint::Id64(u64::from_be_bytes(bytes))
})
}
#[cfg(feature = "md5")]
FingerprintAlgorithm::MD5 => {
self.handle_prefix_common(buf, &SINGLE_OBJECT_MAGIC, |bytes| {
Fingerprint::MD5(bytes)
})
}
#[cfg(feature = "sha256")]
FingerprintAlgorithm::SHA256 => {
self.handle_prefix_common(buf, &SINGLE_OBJECT_MAGIC, |bytes| {
Fingerprint::SHA256(bytes)
})
}
}
}
/// This method checks for the provided `magic` bytes at the start of `buf` and, if present,
/// attempts to read the following fingerprint of `N` bytes, converting it to a
/// `Fingerprint` using `fingerprint_from`.
fn handle_prefix_common<const MAGIC_LEN: usize, const N: usize>(
&mut self,
buf: &[u8],
magic: &[u8; MAGIC_LEN],
fingerprint_from: impl FnOnce([u8; N]) -> Fingerprint,
) -> Result<Option<usize>, AvroError> {
// Need at least the magic bytes to decide
// 2 bytes for Avro Spec and 1 byte for Confluent Wire Protocol.
if buf.len() < MAGIC_LEN {
return Ok(Some(0));
}
// Bail out early if the magic does not match.
if &buf[..MAGIC_LEN] != magic {
return Ok(None);
}
// Try to parse the fingerprint that follows the magic.
let consumed_fp = self.handle_fingerprint(&buf[MAGIC_LEN..], fingerprint_from)?;
// Convert the inner result into a “bytes consumed” count.
// NOTE: Incomplete fingerprint consumes no bytes.
Ok(Some(consumed_fp.map_or(0, |n| n + MAGIC_LEN)))
}
// Attempts to read and install a new fingerprint of `N` bytes.
//
// * Ok(None) – insufficient bytes (`buf.len() < `N`).
// * Ok(Some(N)) – fingerprint consumed (always `N`).
fn handle_fingerprint<const N: usize>(
&mut self,
buf: &[u8],
fingerprint_from: impl FnOnce([u8; N]) -> Fingerprint,
) -> Result<Option<usize>, AvroError> {
// Need enough bytes to get fingerprint (next N bytes)
let Some(fingerprint_bytes) = buf.get(..N) else {
return Ok(None); // insufficient bytes
};
// SAFETY: length checked above.
let new_fingerprint = fingerprint_from(fingerprint_bytes.try_into().unwrap());
// If the fingerprint indicates a schema change, prepare to switch decoders.
if self.active_fingerprint != Some(new_fingerprint) {
let Some(new_decoder) = self.cache.shift_remove(&new_fingerprint) else {
return Err(AvroError::ParseError(format!(
"Unknown fingerprint: {new_fingerprint:?}"
)));
};
self.pending_schema = Some((new_fingerprint, new_decoder));
// If there are already decoded rows, we must flush them first.
// Reducing `remaining_capacity` to 0 ensures `flush` is called next.
if self.remaining_capacity < self.batch_size {
self.remaining_capacity = 0;
}
}
Ok(Some(N))
}
fn apply_pending_schema(&mut self) {
if let Some((new_fingerprint, new_decoder)) = self.pending_schema.take() {
if let Some(old_fingerprint) = self.active_fingerprint.replace(new_fingerprint) {
let old_decoder = std::mem::replace(&mut self.active_decoder, new_decoder);
self.cache.shift_remove(&old_fingerprint);
self.cache.insert(old_fingerprint, old_decoder);
} else {
self.active_decoder = new_decoder;
}
}
}
fn apply_pending_schema_if_batch_empty(&mut self) {
if self.batch_is_empty() {
self.apply_pending_schema();
}
}
fn flush_and_reset(&mut self) -> Result<Option<RecordBatch>, AvroError> {
if self.batch_is_empty() {
return Ok(None);
}
let batch = self.active_decoder.flush()?;
self.remaining_capacity = self.batch_size;
Ok(Some(batch))
}
/// Produce a `RecordBatch` if at least one row is fully decoded, returning
/// `Ok(None)` if no new rows are available.
///
/// If a schema change was detected while decoding rows for the current batch, the
/// schema switch is applied **after** flushing this batch, so the **next** batch
/// (if any) may have a different schema.
pub fn flush(&mut self) -> Result<Option<RecordBatch>, AvroError> {
// We must flush the active decoder before switching to the pending one.
let batch = self.flush_and_reset();
self.apply_pending_schema();
batch
}
/// Returns the number of rows that can be added to this decoder before it is full.
pub fn capacity(&self) -> usize {
self.remaining_capacity
}
/// Returns true if the decoder has reached its capacity for the current batch.
pub fn batch_is_full(&self) -> bool {
self.remaining_capacity == 0
}
/// Returns true if the decoder has not decoded any batches yet (i.e., the current batch is empty).
pub fn batch_is_empty(&self) -> bool {
self.remaining_capacity == self.batch_size
}
// Decode either the block count or remaining capacity from `data` (an OCF block payload).
//
// Returns the number of bytes consumed from `data` along with the number of records decoded.
fn decode_block(&mut self, data: &[u8], count: usize) -> Result<(usize, usize), AvroError> {
// OCF decoding never interleaves records across blocks, so no chunking.
let to_decode = std::cmp::min(count, self.remaining_capacity);
if to_decode == 0 {
return Ok((0, 0));
}
let consumed = self.active_decoder.decode(data, to_decode)?;
self.remaining_capacity -= to_decode;
Ok((consumed, to_decode))
}
// Produce a `RecordBatch` if at least one row is fully decoded, returning
// `Ok(None)` if no new rows are available.
fn flush_block(&mut self) -> Result<Option<RecordBatch>, AvroError> {
self.flush_and_reset()
}
}
/// A builder that configures and constructs Avro readers and decoders.
///
/// `ReaderBuilder` is the primary entry point for this module. It supports:
///
/// * OCF reading via `Self::build`, returning a `Reader` over any `BufRead`;
/// * streaming decoding via `Self::build_decoder`, returning a `Decoder`.
///
/// ### Options
///
/// * **`batch_size`**: Max rows per `RecordBatch` (default: `1024`). See `Self::with_batch_size`.
/// * **`utf8_view`**: Use Arrow `StringViewArray` for string columns (default: `false`).
/// See `Self::with_utf8_view`.
/// * **`strict_mode`**: Opt‑in to stricter union handling (default: `false`).
/// See `Self::with_strict_mode`.
/// * **`reader_schema`**: Optional reader schema (projection / evolution) used when decoding
/// values (default: `None`). See `Self::with_reader_schema`.
/// * **`projection`**: Optional projection of **top‑level record fields** by index (default: `None`).
///
/// If set, the effective reader schema is **pruned** to include only the projected fields, in the
/// specified order:
///
/// * If a reader schema is provided, that schema is pruned.
/// * Otherwise, a reader schema is derived from the writer schema and then pruned.
/// * For streaming `Decoder` with multiple writer schemas and no reader schema, a projected reader
/// schema is derived **per writer schema** in the `SchemaStore`.
///
/// See `Self::with_projection`.
/// * **`writer_schema_store`**: Required for building a `Decoder` for unframed datums,
/// single‑object encoding, or Confluent framing. Maps fingerprints to Avro schemas. See
/// `Self::with_writer_schema_store`.
/// * **`active_fingerprint`**: Selects the writer schema for unframed datums or provides an
/// optional starting fingerprint for framed streaming decode. See `Self::with_active_fingerprint`.
///
/// ### Examples
///
/// Read an OCF file in batches of 4096 rows:
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use arrow_avro::reader::ReaderBuilder;
///
/// let file = File::open("data.avro")?;
/// let mut reader = ReaderBuilder::new()
/// .with_batch_size(4096)
/// .build(BufReader::new(file))?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Build a `Decoder` for Confluent messages:
///
/// ```
/// use arrow_avro::schema::{AvroSchema, SchemaStore, Fingerprint, FingerprintAlgorithm};
/// use arrow_avro::reader::ReaderBuilder;
///
/// let mut store = SchemaStore::new_with_type(FingerprintAlgorithm::Id);
/// store.set(Fingerprint::Id(1234), AvroSchema::new(r#"{"type":"record","name":"E","fields":[]}"#.to_string()))?;
///
/// let decoder = ReaderBuilder::new()
/// .with_writer_schema_store(store)
/// .build_decoder()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct ReaderBuilder {
batch_size: usize,
strict_mode: bool,
utf8_view: bool,
tz: Tz,
reader_schema: Option<AvroSchema>,