-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathreader.rs
More file actions
3518 lines (3132 loc) · 129 KB
/
reader.rs
File metadata and controls
3518 lines (3132 loc) · 129 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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Arrow IPC File and Stream Readers
//!
//! # Notes
//!
//! The [`FileReader`] and [`StreamReader`] have similar interfaces,
//! however the [`FileReader`] expects a reader that supports [`Seek`]ing
//!
//! [`Seek`]: std::io::Seek
mod stream;
pub use stream::*;
use arrow_select::concat;
use flatbuffers::{VectorIter, VerifierOptions};
use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::sync::Arc;
use arrow_array::*;
use arrow_buffer::{
ArrowNativeType, BooleanBuffer, Buffer, MutableBuffer, NullBuffer, ScalarBuffer,
};
use arrow_data::{ArrayData, ArrayDataBuilder, UnsafeFlag};
use arrow_schema::*;
use crate::compression::{CompressionCodec, DecompressionContext};
use crate::r#gen::Message::{self};
use crate::{Block, CONTINUATION_MARKER, FieldNode, MetadataVersion};
use DataType::*;
/// Read a buffer based on offset and length
/// From <https://github.com/apache/arrow/blob/6a936c4ff5007045e86f65f1a6b6c3c955ad5103/format/Message.fbs#L58>
/// Each constituent buffer is first compressed with the indicated
/// compressor, and then written with the uncompressed length in the first 8
/// bytes as a 64-bit little-endian signed integer followed by the compressed
/// buffer bytes (and then padding as required by the protocol). The
/// uncompressed length may be set to -1 to indicate that the data that
/// follows is not compressed, which can be useful for cases where
/// compression does not yield appreciable savings.
fn read_buffer(
buf: &crate::Buffer,
a_data: &Buffer,
compression_codec: Option<CompressionCodec>,
decompression_context: &mut DecompressionContext,
) -> Result<Buffer, ArrowError> {
let start_offset = buf.offset() as usize;
let buf_data = a_data.slice_with_length(start_offset, buf.length() as usize);
// corner case: empty buffer
match (buf_data.is_empty(), compression_codec) {
(true, _) | (_, None) => Ok(buf_data),
(false, Some(decompressor)) => {
decompressor.decompress_to_buffer(&buf_data, decompression_context)
}
}
}
impl RecordBatchDecoder<'_> {
/// Coordinates reading arrays based on data types.
///
/// `variadic_counts` encodes the number of buffers to read for variadic types (e.g., Utf8View, BinaryView)
/// When encounter such types, we pop from the front of the queue to get the number of buffers to read.
///
/// Notes:
/// * In the IPC format, null buffers are always set, but may be empty. We discard them if an array has 0 nulls
/// * Numeric values inside list arrays are often stored as 64-bit values regardless of their data type size.
/// We thus:
/// - check if the bit width of non-64-bit numbers is 64, and
/// - read the buffer as 64-bit (signed integer or float), and
/// - cast the 64-bit array to the appropriate data type
fn create_array(
&mut self,
field: &Field,
variadic_counts: &mut VecDeque<i64>,
) -> Result<ArrayRef, ArrowError> {
let data_type = field.data_type();
match data_type {
Utf8 | Binary | LargeBinary | LargeUtf8 => {
let field_node = self.next_node(field)?;
let buffers = [
self.next_buffer()?,
self.next_buffer()?,
self.next_buffer()?,
];
self.create_primitive_array(field_node, data_type, &buffers)
}
BinaryView | Utf8View => {
let count = variadic_counts
.pop_front()
.ok_or(ArrowError::IpcError(format!(
"Missing variadic count for {data_type} column"
)))?;
let count = count + 2; // view and null buffer.
let buffers = (0..count)
.map(|_| self.next_buffer())
.collect::<Result<Vec<_>, _>>()?;
let field_node = self.next_node(field)?;
self.create_primitive_array(field_node, data_type, &buffers)
}
FixedSizeBinary(_) => {
let field_node = self.next_node(field)?;
let buffers = [self.next_buffer()?, self.next_buffer()?];
self.create_primitive_array(field_node, data_type, &buffers)
}
List(list_field) | LargeList(list_field) | Map(list_field, _) => {
let list_node = self.next_node(field)?;
let list_buffers = [self.next_buffer()?, self.next_buffer()?];
let values = self.create_array(list_field, variadic_counts)?;
self.create_list_array(list_node, data_type, &list_buffers, values)
}
ListView(list_field) | LargeListView(list_field) => {
let list_node = self.next_node(field)?;
let list_buffers = [
self.next_buffer()?, // null buffer
self.next_buffer()?, // offsets
self.next_buffer()?, // sizes
];
let values = self.create_array(list_field, variadic_counts)?;
self.create_list_view_array(list_node, data_type, &list_buffers, values)
}
FixedSizeList(list_field, _) => {
let list_node = self.next_node(field)?;
let list_buffers = [self.next_buffer()?];
let values = self.create_array(list_field, variadic_counts)?;
self.create_list_array(list_node, data_type, &list_buffers, values)
}
Struct(struct_fields) => {
let struct_node = self.next_node(field)?;
let null_buffer = self.next_buffer()?;
// read the arrays for each field
let mut struct_arrays = vec![];
// TODO investigate whether just knowing the number of buffers could
// still work
for struct_field in struct_fields {
let child = self.create_array(struct_field, variadic_counts)?;
struct_arrays.push(child);
}
self.create_struct_array(struct_node, null_buffer, struct_fields, struct_arrays)
}
RunEndEncoded(run_ends_field, values_field) => {
let run_node = self.next_node(field)?;
let run_ends = self.create_array(run_ends_field, variadic_counts)?;
let values = self.create_array(values_field, variadic_counts)?;
let run_array_length = run_node.length() as usize;
let builder = ArrayData::builder(data_type.clone())
.len(run_array_length)
.offset(0)
.add_child_data(run_ends.into_data())
.add_child_data(values.into_data())
.null_count(run_node.null_count() as usize);
self.create_array_from_builder(builder)
}
// Create dictionary array from RecordBatch
Dictionary(_, _) => {
let index_node = self.next_node(field)?;
let index_buffers = [self.next_buffer()?, self.next_buffer()?];
#[allow(deprecated)]
let dict_id = field.dict_id().ok_or_else(|| {
ArrowError::ParseError(format!("Field {field} does not have dict id"))
})?;
let value_array = match self.dictionaries_by_id.get(&dict_id) {
Some(array) => array.clone(),
None => {
// Per the IPC spec, dictionary batches may be omitted when all
// values in the column are null. In that case we synthesize an
// empty values array so decoding can proceed.
if let Dictionary(_, value_type) = data_type {
arrow_array::new_empty_array(value_type.as_ref())
} else {
unreachable!()
}
}
};
self.create_dictionary_array(index_node, data_type, &index_buffers, value_array)
}
Union(fields, mode) => {
let union_node = self.next_node(field)?;
let len = union_node.length() as usize;
// In V4, union types has validity bitmap
// In V5 and later, union types have no validity bitmap
if self.version < MetadataVersion::V5 {
self.next_buffer()?;
}
let type_ids: ScalarBuffer<i8> =
self.next_buffer()?.slice_with_length(0, len).into();
let value_offsets = match mode {
UnionMode::Dense => {
let offsets: ScalarBuffer<i32> =
self.next_buffer()?.slice_with_length(0, len * 4).into();
Some(offsets)
}
UnionMode::Sparse => None,
};
let mut children = Vec::with_capacity(fields.len());
for (_id, field) in fields.iter() {
let child = self.create_array(field, variadic_counts)?;
children.push(child);
}
let array = if self.skip_validation.get() {
// safety: flag can only be set via unsafe code
unsafe {
UnionArray::new_unchecked(fields.clone(), type_ids, value_offsets, children)
}
} else {
UnionArray::try_new(fields.clone(), type_ids, value_offsets, children)?
};
Ok(Arc::new(array))
}
Null => {
let node = self.next_node(field)?;
let length = node.length();
let null_count = node.null_count();
if length != null_count {
return Err(ArrowError::SchemaError(format!(
"Field {field} of NullArray has unequal null_count {null_count} and len {length}"
)));
}
let builder = ArrayData::builder(data_type.clone())
.len(length as usize)
.offset(0);
self.create_array_from_builder(builder)
}
_ => {
let field_node = self.next_node(field)?;
let buffers = [self.next_buffer()?, self.next_buffer()?];
self.create_primitive_array(field_node, data_type, &buffers)
}
}
}
/// Reads the correct number of buffers based on data type and null_count, and creates a
/// primitive array ref
fn create_primitive_array(
&self,
field_node: &FieldNode,
data_type: &DataType,
buffers: &[Buffer],
) -> Result<ArrayRef, ArrowError> {
let length = field_node.length() as usize;
let null_buffer = (field_node.null_count() > 0).then_some(buffers[0].clone());
let mut builder = match data_type {
Utf8 | Binary | LargeBinary | LargeUtf8 => {
// read 3 buffers: null buffer (optional), offsets buffer and data buffer
ArrayData::builder(data_type.clone())
.len(length)
.buffers(buffers[1..3].to_vec())
.null_bit_buffer(null_buffer)
}
BinaryView | Utf8View => ArrayData::builder(data_type.clone())
.len(length)
.buffers(buffers[1..].to_vec())
.null_bit_buffer(null_buffer),
_ if data_type.is_primitive() || matches!(data_type, Boolean | FixedSizeBinary(_)) => {
// read 2 buffers: null buffer (optional) and data buffer
ArrayData::builder(data_type.clone())
.len(length)
.add_buffer(buffers[1].clone())
.null_bit_buffer(null_buffer)
}
t => unreachable!("Data type {:?} either unsupported or not primitive", t),
};
builder = builder.null_count(field_node.null_count() as usize);
self.create_array_from_builder(builder)
}
/// Update the ArrayDataBuilder based on settings in this decoder
fn create_array_from_builder(&self, builder: ArrayDataBuilder) -> Result<ArrayRef, ArrowError> {
let mut builder = builder.align_buffers(!self.require_alignment);
if self.skip_validation.get() {
// SAFETY: flag can only be set via unsafe code
unsafe { builder = builder.skip_validation(true) }
};
Ok(make_array(builder.build()?))
}
/// Reads the correct number of buffers based on list type and null_count, and creates a
/// list array ref
fn create_list_array(
&self,
field_node: &FieldNode,
data_type: &DataType,
buffers: &[Buffer],
child_array: ArrayRef,
) -> Result<ArrayRef, ArrowError> {
let null_buffer = (field_node.null_count() > 0).then_some(buffers[0].clone());
let length = field_node.length() as usize;
let child_data = child_array.into_data();
let mut builder = match data_type {
List(_) | LargeList(_) | Map(_, _) => ArrayData::builder(data_type.clone())
.len(length)
.add_buffer(buffers[1].clone())
.add_child_data(child_data)
.null_bit_buffer(null_buffer),
FixedSizeList(_, _) => ArrayData::builder(data_type.clone())
.len(length)
.add_child_data(child_data)
.null_bit_buffer(null_buffer),
_ => unreachable!("Cannot create list or map array from {:?}", data_type),
};
builder = builder.null_count(field_node.null_count() as usize);
self.create_array_from_builder(builder)
}
fn create_list_view_array(
&self,
field_node: &FieldNode,
data_type: &DataType,
buffers: &[Buffer],
child_array: ArrayRef,
) -> Result<ArrayRef, ArrowError> {
assert!(matches!(data_type, ListView(_) | LargeListView(_)));
let null_buffer = (field_node.null_count() > 0).then_some(buffers[0].clone());
let length = field_node.length() as usize;
let child_data = child_array.into_data();
self.create_array_from_builder(
ArrayData::builder(data_type.clone())
.len(length)
.add_buffer(buffers[1].clone()) // offsets
.add_buffer(buffers[2].clone()) // sizes
.add_child_data(child_data)
.null_bit_buffer(null_buffer)
.null_count(field_node.null_count() as usize),
)
}
fn create_struct_array(
&self,
struct_node: &FieldNode,
null_buffer: Buffer,
struct_fields: &Fields,
struct_arrays: Vec<ArrayRef>,
) -> Result<ArrayRef, ArrowError> {
let null_count = struct_node.null_count() as usize;
let len = struct_node.length() as usize;
let skip_validation = self.skip_validation.get();
let nulls = if null_count > 0 {
let validity_buffer = BooleanBuffer::new(null_buffer, 0, len);
let null_buffer = if skip_validation {
// safety: flag can only be set via unsafe code
unsafe { NullBuffer::new_unchecked(validity_buffer, null_count) }
} else {
let null_buffer = NullBuffer::new(validity_buffer);
if null_buffer.null_count() != null_count {
return Err(ArrowError::InvalidArgumentError(format!(
"null_count value ({}) doesn't match actual number of nulls in array ({})",
null_count,
null_buffer.null_count()
)));
}
null_buffer
};
Some(null_buffer)
} else {
None
};
if struct_arrays.is_empty() {
// `StructArray::from` can't infer the correct row count
// if we have zero fields
return Ok(Arc::new(StructArray::new_empty_fields(len, nulls)));
}
let struct_array = if skip_validation {
// safety: flag can only be set via unsafe code
unsafe { StructArray::new_unchecked(struct_fields.clone(), struct_arrays, nulls) }
} else {
StructArray::try_new(struct_fields.clone(), struct_arrays, nulls)?
};
Ok(Arc::new(struct_array))
}
/// Reads the correct number of buffers based on list type and null_count, and creates a
/// list array ref
fn create_dictionary_array(
&self,
field_node: &FieldNode,
data_type: &DataType,
buffers: &[Buffer],
value_array: ArrayRef,
) -> Result<ArrayRef, ArrowError> {
if let Dictionary(_, _) = *data_type {
let null_buffer = (field_node.null_count() > 0).then_some(buffers[0].clone());
let builder = ArrayData::builder(data_type.clone())
.len(field_node.length() as usize)
.add_buffer(buffers[1].clone())
.add_child_data(value_array.into_data())
.null_bit_buffer(null_buffer)
.null_count(field_node.null_count() as usize);
self.create_array_from_builder(builder)
} else {
unreachable!("Cannot create dictionary array from {:?}", data_type)
}
}
}
/// State for decoding Arrow arrays from an [IPC RecordBatch] structure to
/// [`RecordBatch`]
///
/// [IPC RecordBatch]: crate::RecordBatch
///
pub struct RecordBatchDecoder<'a> {
/// The flatbuffers encoded record batch
batch: crate::RecordBatch<'a>,
/// The output schema
schema: SchemaRef,
/// Decoded dictionaries indexed by dictionary id
dictionaries_by_id: &'a HashMap<i64, ArrayRef>,
/// Optional compression codec
compression: Option<CompressionCodec>,
/// Decompression context for reusing zstd decompressor state
decompression_context: DecompressionContext,
/// The format version
version: MetadataVersion,
/// The raw data buffer
data: &'a Buffer,
/// The fields comprising this array
nodes: VectorIter<'a, FieldNode>,
/// The buffers comprising this array
buffers: VectorIter<'a, crate::Buffer>,
/// Projection (subset of columns) to read, if any
/// See [`RecordBatchDecoder::with_projection`] for details
projection: Option<&'a [usize]>,
/// Are buffers required to already be aligned? See
/// [`RecordBatchDecoder::with_require_alignment`] for details
require_alignment: bool,
/// Should validation be skipped when reading data? Defaults to false.
///
/// See [`FileDecoder::with_skip_validation`] for details.
skip_validation: UnsafeFlag,
}
impl<'a> RecordBatchDecoder<'a> {
/// Create a reader for decoding arrays from an encoded [`RecordBatch`]
fn try_new(
buf: &'a Buffer,
batch: crate::RecordBatch<'a>,
schema: SchemaRef,
dictionaries_by_id: &'a HashMap<i64, ArrayRef>,
metadata: &'a MetadataVersion,
) -> Result<Self, ArrowError> {
let buffers = batch.buffers().ok_or_else(|| {
ArrowError::IpcError("Unable to get buffers from IPC RecordBatch".to_string())
})?;
let field_nodes = batch.nodes().ok_or_else(|| {
ArrowError::IpcError("Unable to get field nodes from IPC RecordBatch".to_string())
})?;
let batch_compression = batch.compression();
let compression = batch_compression
.map(|batch_compression| batch_compression.codec().try_into())
.transpose()?;
Ok(Self {
batch,
schema,
dictionaries_by_id,
compression,
decompression_context: DecompressionContext::new(),
version: *metadata,
data: buf,
nodes: field_nodes.iter(),
buffers: buffers.iter(),
projection: None,
require_alignment: false,
skip_validation: UnsafeFlag::new(),
})
}
/// Set the projection (default: None)
///
/// If set, the projection is the list of column indices
/// that will be read
pub fn with_projection(mut self, projection: Option<&'a [usize]>) -> Self {
self.projection = projection;
self
}
/// Set require_alignment (default: false)
///
/// If true, buffers must be aligned appropriately or error will
/// result. If false, buffers will be copied to aligned buffers
/// if necessary.
pub fn with_require_alignment(mut self, require_alignment: bool) -> Self {
self.require_alignment = require_alignment;
self
}
/// Specifies if validation should be skipped when reading data (defaults to `false`)
///
/// Note this API is somewhat "funky" as it allows the caller to skip validation
/// without having to use `unsafe` code. If this is ever made public
/// it should be made clearer that this is a potentially unsafe by
/// using an `unsafe` function that takes a boolean flag.
///
/// # Safety
///
/// Relies on the caller only passing a flag with `true` value if they are
/// certain that the data is valid
pub(crate) fn with_skip_validation(mut self, skip_validation: UnsafeFlag) -> Self {
self.skip_validation = skip_validation;
self
}
/// Read the record batch, consuming the reader
fn read_record_batch(mut self) -> Result<RecordBatch, ArrowError> {
let mut variadic_counts: VecDeque<i64> = self
.batch
.variadicBufferCounts()
.into_iter()
.flatten()
.collect();
let options = RecordBatchOptions::new().with_row_count(Some(self.batch.length() as usize));
let schema = Arc::clone(&self.schema);
if let Some(projection) = self.projection {
let mut arrays = vec![];
// project fields
for (idx, field) in schema.fields().iter().enumerate() {
// Create array for projected field
if let Some(proj_idx) = projection.iter().position(|p| p == &idx) {
let child = self.create_array(field, &mut variadic_counts)?;
arrays.push((proj_idx, child));
} else {
self.skip_field(field, &mut variadic_counts)?;
}
}
arrays.sort_by_key(|t| t.0);
let schema = Arc::new(schema.project(projection)?);
let columns = arrays.into_iter().map(|t| t.1).collect::<Vec<_>>();
if self.skip_validation.get() {
// Safety: setting `skip_validation` requires `unsafe`, user assures data is valid
unsafe {
Ok(RecordBatch::new_unchecked(
schema,
columns,
self.batch.length() as usize,
))
}
} else {
assert!(variadic_counts.is_empty());
RecordBatch::try_new_with_options(schema, columns, &options)
}
} else {
let mut children = vec![];
// keep track of index as lists require more than one node
for field in schema.fields() {
let child = self.create_array(field, &mut variadic_counts)?;
children.push(child);
}
if self.skip_validation.get() {
// Safety: setting `skip_validation` requires `unsafe`, user assures data is valid
unsafe {
Ok(RecordBatch::new_unchecked(
schema,
children,
self.batch.length() as usize,
))
}
} else {
assert!(variadic_counts.is_empty());
RecordBatch::try_new_with_options(schema, children, &options)
}
}
}
fn next_buffer(&mut self) -> Result<Buffer, ArrowError> {
let buffer = self.buffers.next().ok_or_else(|| {
ArrowError::IpcError("Buffer count mismatched with metadata".to_string())
})?;
read_buffer(
buffer,
self.data,
self.compression,
&mut self.decompression_context,
)
}
fn skip_buffer(&mut self) {
self.buffers.next().unwrap();
}
fn next_node(&mut self, field: &Field) -> Result<&'a FieldNode, ArrowError> {
self.nodes.next().ok_or_else(|| {
ArrowError::SchemaError(format!(
"Invalid data for schema. {field} refers to node not found in schema",
))
})
}
fn skip_field(
&mut self,
field: &Field,
variadic_count: &mut VecDeque<i64>,
) -> Result<(), ArrowError> {
self.next_node(field)?;
match field.data_type() {
Utf8 | Binary | LargeBinary | LargeUtf8 => {
for _ in 0..3 {
self.skip_buffer()
}
}
Utf8View | BinaryView => {
let count = variadic_count
.pop_front()
.ok_or(ArrowError::IpcError(format!(
"Missing variadic count for {} column",
field.data_type()
)))?;
let count = count + 2; // view and null buffer.
for _i in 0..count {
self.skip_buffer()
}
}
FixedSizeBinary(_) => {
self.skip_buffer();
self.skip_buffer();
}
List(list_field) | LargeList(list_field) | Map(list_field, _) => {
self.skip_buffer();
self.skip_buffer();
self.skip_field(list_field, variadic_count)?;
}
FixedSizeList(list_field, _) => {
self.skip_buffer();
self.skip_field(list_field, variadic_count)?;
}
Struct(struct_fields) => {
self.skip_buffer();
// skip for each field
for struct_field in struct_fields {
self.skip_field(struct_field, variadic_count)?
}
}
RunEndEncoded(run_ends_field, values_field) => {
self.skip_field(run_ends_field, variadic_count)?;
self.skip_field(values_field, variadic_count)?;
}
Dictionary(_, _) => {
self.skip_buffer(); // Nulls
self.skip_buffer(); // Indices
}
Union(fields, mode) => {
self.skip_buffer(); // Nulls
match mode {
UnionMode::Dense => self.skip_buffer(),
UnionMode::Sparse => {}
};
for (_, field) in fields.iter() {
self.skip_field(field, variadic_count)?
}
}
Null => {} // No buffer increases
_ => {
self.skip_buffer();
self.skip_buffer();
}
};
Ok(())
}
}
/// Creates a record batch from binary data using the `crate::RecordBatch` indexes and the `Schema`.
///
/// If `require_alignment` is true, this function will return an error if any array data in the
/// input `buf` is not properly aligned.
/// Under the hood it will use [`arrow_data::ArrayDataBuilder::build`] to construct [`arrow_data::ArrayData`].
///
/// If `require_alignment` is false, this function will automatically allocate a new aligned buffer
/// and copy over the data if any array data in the input `buf` is not properly aligned.
/// (Properly aligned array data will remain zero-copy.)
/// Under the hood it will use [`arrow_data::ArrayDataBuilder::build_aligned`] to construct [`arrow_data::ArrayData`].
pub fn read_record_batch(
buf: &Buffer,
batch: crate::RecordBatch,
schema: SchemaRef,
dictionaries_by_id: &HashMap<i64, ArrayRef>,
projection: Option<&[usize]>,
metadata: &MetadataVersion,
) -> Result<RecordBatch, ArrowError> {
RecordBatchDecoder::try_new(buf, batch, schema, dictionaries_by_id, metadata)?
.with_projection(projection)
.with_require_alignment(false)
.read_record_batch()
}
/// Read the dictionary from the buffer and provided metadata,
/// updating the `dictionaries_by_id` with the resulting dictionary
pub fn read_dictionary(
buf: &Buffer,
batch: crate::DictionaryBatch,
schema: &Schema,
dictionaries_by_id: &mut HashMap<i64, ArrayRef>,
metadata: &MetadataVersion,
) -> Result<(), ArrowError> {
read_dictionary_impl(
buf,
batch,
schema,
dictionaries_by_id,
metadata,
false,
UnsafeFlag::new(),
)
}
fn read_dictionary_impl(
buf: &Buffer,
batch: crate::DictionaryBatch,
schema: &Schema,
dictionaries_by_id: &mut HashMap<i64, ArrayRef>,
metadata: &MetadataVersion,
require_alignment: bool,
skip_validation: UnsafeFlag,
) -> Result<(), ArrowError> {
let id = batch.id();
let dictionary_values = get_dictionary_values(
buf,
batch,
schema,
dictionaries_by_id,
metadata,
require_alignment,
skip_validation,
)?;
update_dictionaries(dictionaries_by_id, batch.isDelta(), id, dictionary_values)?;
Ok(())
}
/// Updates the `dictionaries_by_id` with the provided dictionary values and id.
///
/// # Errors
/// - If `is_delta` is true and there is no existing dictionary for the given
/// `dict_id`
/// - If `is_delta` is true and the concatenation of the existing and new
/// dictionary fails. This usually signals a type mismatch between the old and
/// new values.
fn update_dictionaries(
dictionaries_by_id: &mut HashMap<i64, ArrayRef>,
is_delta: bool,
dict_id: i64,
dict_values: ArrayRef,
) -> Result<(), ArrowError> {
if !is_delta {
// We don't currently record the isOrdered field. This could be general
// attributes of arrays.
// Add (possibly multiple) array refs to the dictionaries array.
dictionaries_by_id.insert(dict_id, dict_values.clone());
return Ok(());
}
let existing = dictionaries_by_id.get(&dict_id).ok_or_else(|| {
ArrowError::InvalidArgumentError(format!(
"No existing dictionary for delta dictionary with id '{dict_id}'"
))
})?;
let combined = concat::concat(&[existing, &dict_values]).map_err(|e| {
ArrowError::InvalidArgumentError(format!("Failed to concat delta dictionary: {e}"))
})?;
dictionaries_by_id.insert(dict_id, combined);
Ok(())
}
/// Given a dictionary batch IPC message/body along with the full state of a
/// stream including schema, dictionary cache, metadata, and other flags, this
/// function will parse the buffer into an array of dictionary values.
fn get_dictionary_values(
buf: &Buffer,
batch: crate::DictionaryBatch,
schema: &Schema,
dictionaries_by_id: &mut HashMap<i64, ArrayRef>,
metadata: &MetadataVersion,
require_alignment: bool,
skip_validation: UnsafeFlag,
) -> Result<ArrayRef, ArrowError> {
let id = batch.id();
#[allow(deprecated)]
let fields_using_this_dictionary = schema.fields_with_dict_id(id);
let first_field = fields_using_this_dictionary.first().ok_or_else(|| {
ArrowError::InvalidArgumentError(format!("dictionary id {id} not found in schema"))
})?;
// As the dictionary batch does not contain the type of the
// values array, we need to retrieve this from the schema.
// Get an array representing this dictionary's values.
let dictionary_values: ArrayRef = match first_field.data_type() {
DataType::Dictionary(_, value_type) => {
// Make a fake schema for the dictionary batch.
let value = value_type.as_ref().clone();
let schema = Schema::new(vec![Field::new("", value, true)]);
// Read a single column
let record_batch = RecordBatchDecoder::try_new(
buf,
batch.data().unwrap(),
Arc::new(schema),
dictionaries_by_id,
metadata,
)?
.with_require_alignment(require_alignment)
.with_skip_validation(skip_validation)
.read_record_batch()?;
Some(record_batch.column(0).clone())
}
_ => None,
}
.ok_or_else(|| {
ArrowError::InvalidArgumentError(format!("dictionary id {id} not found in schema"))
})?;
Ok(dictionary_values)
}
/// Reads the full data block (metadata + body) from the underlying reader.
///
/// Uses a zero-initialized buffer for small blocks. For larger blocks, reads
/// into a temporary `Vec<u8>` and reuses the allocation when it is 64-byte
/// aligned, matching Arrow's `ALIGNMENT` for `MutableBuffer`. Otherwise, it
/// falls back to copying into an Arrow-aligned buffer.
///
/// This reduces redundant zero-initialization on large reads while preserving
/// the alignment expected by Arrow buffers.
fn read_block<R: Read + Seek>(mut reader: R, block: &Block) -> Result<Buffer, ArrowError> {
reader.seek(SeekFrom::Start(block.offset() as u64))?;
let body_len = block.bodyLength().to_usize().unwrap();
let metadata_len = block.metaDataLength().to_usize().unwrap();
let total_len = body_len.checked_add(metadata_len).unwrap();
if total_len < 8 * 1024 {
let mut buf = MutableBuffer::from_len_zeroed(total_len);
reader.read_exact(&mut buf)?;
return Ok(buf.into());
}
let mut vec = Vec::with_capacity(total_len);
reader
.by_ref()
.take(total_len as u64)
.read_to_end(&mut vec)?;
if vec.len() != total_len {
return Err(ArrowError::IpcError(format!(
"Expected IPC block of length {total_len}, got {}",
vec.len()
)));
}
if ((vec.as_ptr() as usize) & 63) == 0 {
Ok(Buffer::from_vec(vec))
} else {
let mut buf = MutableBuffer::from_len_zeroed(total_len);
buf.copy_from_slice(&vec);
Ok(buf.into())
}
}
/// Parse an encapsulated message
///
/// <https://arrow.apache.org/docs/format/Columnar.html#encapsulated-message-format>
fn parse_message(buf: &[u8]) -> Result<Message::Message<'_>, ArrowError> {
let buf = match buf[..4] == CONTINUATION_MARKER {
true => &buf[8..],
false => &buf[4..],
};
crate::root_as_message(buf)
.map_err(|err| ArrowError::ParseError(format!("Unable to get root as message: {err:?}")))
}
/// Read the footer length from the last 10 bytes of an Arrow IPC file
///
/// Expects a 4 byte footer length followed by `b"ARROW1"`
pub fn read_footer_length(buf: [u8; 10]) -> Result<usize, ArrowError> {
if buf[4..] != super::ARROW_MAGIC {
return Err(ArrowError::ParseError(
"Arrow file does not contain correct footer".to_string(),
));
}
// read footer length
let footer_len = i32::from_le_bytes(buf[..4].try_into().unwrap());
footer_len
.try_into()
.map_err(|_| ArrowError::ParseError(format!("Invalid footer length: {footer_len}")))
}
/// A low-level, push-based interface for reading an IPC file
///
/// For a higher-level interface see [`FileReader`]
///
/// For an example of using this API with `mmap` see the [`zero_copy_ipc`] example.
///
/// [`zero_copy_ipc`]: https://github.com/apache/arrow-rs/blob/main/arrow/examples/zero_copy_ipc.rs
///
/// ```
/// # use std::sync::Arc;
/// # use arrow_array::*;
/// # use arrow_array::types::Int32Type;
/// # use arrow_buffer::Buffer;
/// # use arrow_ipc::convert::fb_to_schema;
/// # use arrow_ipc::reader::{FileDecoder, read_footer_length};
/// # use arrow_ipc::root_as_footer;
/// # use arrow_ipc::writer::FileWriter;
/// // Write an IPC file
///
/// let batch = RecordBatch::try_from_iter([
/// ("a", Arc::new(Int32Array::from(vec![1, 2, 3])) as _),
/// ("b", Arc::new(Int32Array::from(vec![1, 2, 3])) as _),
/// ("c", Arc::new(DictionaryArray::<Int32Type>::from_iter(["hello", "hello", "world"])) as _),
/// ]).unwrap();
///
/// let schema = batch.schema();
///
/// let mut out = Vec::with_capacity(1024);
/// let mut writer = FileWriter::try_new(&mut out, schema.as_ref()).unwrap();
/// writer.write(&batch).unwrap();
/// writer.finish().unwrap();
///
/// drop(writer);
///
/// // Read IPC file
///
/// let buffer = Buffer::from_vec(out);
/// let trailer_start = buffer.len() - 10;
/// let footer_len = read_footer_length(buffer[trailer_start..].try_into().unwrap()).unwrap();
/// let footer = root_as_footer(&buffer[trailer_start - footer_len..trailer_start]).unwrap();
///
/// let back = fb_to_schema(footer.schema().unwrap());
/// assert_eq!(&back, schema.as_ref());
///
/// let mut decoder = FileDecoder::new(schema, footer.version());
///
/// // Read dictionaries
/// for block in footer.dictionaries().iter().flatten() {
/// let block_len = block.bodyLength() as usize + block.metaDataLength() as usize;
/// let data = buffer.slice_with_length(block.offset() as _, block_len);
/// decoder.read_dictionary(&block, &data).unwrap();
/// }
///
/// // Read record batch
/// let batches = footer.recordBatches().unwrap();
/// assert_eq!(batches.len(), 1); // Only wrote a single batch
///
/// let block = batches.get(0);