/
decoding.rs
1606 lines (1403 loc) · 51.9 KB
/
decoding.rs
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.
//! Contains all supported decoders for Parquet.
use num::traits::WrappingAdd;
use num::FromPrimitive;
use std::{cmp, marker::PhantomData, mem};
use super::rle::RleDecoder;
use crate::basic::*;
use crate::data_type::private::ParquetValueType;
use crate::data_type::*;
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
use crate::util::{
bit_util::{self, BitReader},
memory::ByteBufferPtr,
};
pub(crate) mod private {
use super::*;
/// A trait that allows getting a [`Decoder`] implementation for a [`DataType`] with
/// the corresponding [`ParquetValueType`]. This is necessary to support
/// [`Decoder`] implementations that may not be applicable for all [`DataType`]
/// and by extension all [`ParquetValueType`]
pub trait GetDecoder {
fn get_decoder<T: DataType<T = Self>>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
get_decoder_default(descr, encoding)
}
}
fn get_decoder_default<T: DataType>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
Encoding::PLAIN => Ok(Box::new(PlainDecoder::new(descr.type_length()))),
Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY => Err(general_err!(
"Cannot initialize this encoding through this function"
)),
Encoding::RLE
| Encoding::DELTA_BINARY_PACKED
| Encoding::DELTA_BYTE_ARRAY
| Encoding::DELTA_LENGTH_BYTE_ARRAY => Err(general_err!(
"Encoding {} is not supported for type",
encoding
)),
e => Err(nyi_err!("Encoding {} is not supported", e)),
}
}
impl GetDecoder for bool {
fn get_decoder<T: DataType<T = Self>>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
Encoding::RLE => Ok(Box::new(RleValueDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
}
}
impl GetDecoder for i32 {
fn get_decoder<T: DataType<T = Self>>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
Encoding::DELTA_BINARY_PACKED => Ok(Box::new(DeltaBitPackDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
}
}
impl GetDecoder for i64 {
fn get_decoder<T: DataType<T = Self>>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
Encoding::DELTA_BINARY_PACKED => Ok(Box::new(DeltaBitPackDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
}
}
impl GetDecoder for f32 {}
impl GetDecoder for f64 {}
impl GetDecoder for ByteArray {
fn get_decoder<T: DataType<T = Self>>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
Encoding::DELTA_BYTE_ARRAY => Ok(Box::new(DeltaByteArrayDecoder::new())),
Encoding::DELTA_LENGTH_BYTE_ARRAY => {
Ok(Box::new(DeltaLengthByteArrayDecoder::new()))
}
_ => get_decoder_default(descr, encoding),
}
}
}
impl GetDecoder for FixedLenByteArray {
fn get_decoder<T: DataType<T = Self>>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
Encoding::DELTA_BYTE_ARRAY => Ok(Box::new(DeltaByteArrayDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
}
}
impl GetDecoder for Int96 {}
}
// ----------------------------------------------------------------------
// Decoders
/// A Parquet decoder for the data type `T`.
pub trait Decoder<T: DataType>: Send {
/// Sets the data to decode to be `data`, which should contain `num_values` of values
/// to decode.
fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()>;
/// Consumes values from this decoder and write the results to `buffer`. This will try
/// to fill up `buffer`.
///
/// Returns the actual number of values decoded, which should be equal to
/// `buffer.len()` unless the remaining number of values is less than
/// `buffer.len()`.
fn get(&mut self, buffer: &mut [T::T]) -> Result<usize>;
/// Consume values from this decoder and write the results to `buffer`, leaving
/// "spaces" for null values.
///
/// `null_count` is the number of nulls we expect to see in `buffer`, after reading.
/// `valid_bits` stores the valid bit for each value in the buffer. It should contain
/// at least number of bits that equal to `buffer.len()`.
///
/// Returns the actual number of values decoded.
///
/// # Panics
///
/// Panics if `null_count` is greater than `buffer.len()`.
fn get_spaced(
&mut self,
buffer: &mut [T::T],
null_count: usize,
valid_bits: &[u8],
) -> Result<usize> {
assert!(buffer.len() >= null_count);
// TODO: check validity of the input arguments?
if null_count == 0 {
return self.get(buffer);
}
let num_values = buffer.len();
let values_to_read = num_values - null_count;
let values_read = self.get(buffer)?;
if values_read != values_to_read {
return Err(general_err!(
"Number of values read: {}, doesn't match expected: {}",
values_read,
values_to_read
));
}
let mut values_to_move = values_read;
for i in (0..num_values).rev() {
if bit_util::get_bit(valid_bits, i) {
values_to_move -= 1;
buffer.swap(i, values_to_move);
}
}
Ok(num_values)
}
/// Returns the number of values left in this decoder stream.
fn values_left(&self) -> usize;
/// Returns the encoding for this decoder.
fn encoding(&self) -> Encoding;
}
/// Gets a decoder for the column descriptor `descr` and encoding type `encoding`.
///
/// NOTE: the primitive type in `descr` MUST match the data type `T`, otherwise
/// disastrous consequence could occur.
pub fn get_decoder<T: DataType>(
descr: ColumnDescPtr,
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
use self::private::GetDecoder;
T::T::get_decoder(descr, encoding)
}
// ----------------------------------------------------------------------
// PLAIN Decoding
#[derive(Default)]
pub struct PlainDecoderDetails {
// The remaining number of values in the byte array
pub(crate) num_values: usize,
// The current starting index in the byte array. Not used when `T` is bool.
pub(crate) start: usize,
// The length for the type `T`. Only used when `T` is `FixedLenByteArrayType`
pub(crate) type_length: i32,
// The byte array to decode from. Not set if `T` is bool.
pub(crate) data: Option<ByteBufferPtr>,
// Read `data` bit by bit. Only set if `T` is bool.
pub(crate) bit_reader: Option<BitReader>,
}
/// Plain decoding that supports all types.
/// Values are encoded back to back. For native types, data is encoded as little endian.
/// Floating point types are encoded in IEEE.
/// See [`PlainEncoder`](crate::encoding::PlainEncoder) for more information.
pub struct PlainDecoder<T: DataType> {
// The binary details needed for decoding
inner: PlainDecoderDetails,
// To allow `T` in the generic parameter for this struct. This doesn't take any
// space.
_phantom: PhantomData<T>,
}
impl<T: DataType> PlainDecoder<T> {
/// Creates new plain decoder.
pub fn new(type_length: i32) -> Self {
PlainDecoder {
inner: PlainDecoderDetails {
type_length,
num_values: 0,
start: 0,
data: None,
bit_reader: None,
},
_phantom: PhantomData,
}
}
}
impl<T: DataType> Decoder<T> for PlainDecoder<T> {
#[inline]
fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
T::T::set_data(&mut self.inner, data, num_values);
Ok(())
}
#[inline]
fn values_left(&self) -> usize {
self.inner.num_values
}
#[inline]
fn encoding(&self) -> Encoding {
Encoding::PLAIN
}
#[inline]
fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {
T::T::decode(buffer, &mut self.inner)
}
}
// ----------------------------------------------------------------------
// RLE_DICTIONARY/PLAIN_DICTIONARY Decoding
/// Dictionary decoder.
/// The dictionary encoding builds a dictionary of values encountered in a given column.
/// The dictionary is be stored in a dictionary page per column chunk.
/// See [`DictEncoder`](crate::encoding::DictEncoder) for more information.
pub struct DictDecoder<T: DataType> {
// The dictionary, which maps ids to the values
dictionary: Vec<T::T>,
// Whether `dictionary` has been initialized
has_dictionary: bool,
// The decoder for the value ids
rle_decoder: Option<RleDecoder>,
// Number of values left in the data stream
num_values: usize,
}
impl<T: DataType> DictDecoder<T> {
/// Creates new dictionary decoder.
pub fn new() -> Self {
Self {
dictionary: vec![],
has_dictionary: false,
rle_decoder: None,
num_values: 0,
}
}
/// Decodes and sets values for dictionary using `decoder` decoder.
pub fn set_dict(&mut self, mut decoder: Box<dyn Decoder<T>>) -> Result<()> {
let num_values = decoder.values_left();
self.dictionary.resize(num_values, T::T::default());
let _ = decoder.get(&mut self.dictionary)?;
self.has_dictionary = true;
Ok(())
}
}
impl<T: DataType> Decoder<T> for DictDecoder<T> {
fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
// First byte in `data` is bit width
let bit_width = data.as_ref()[0];
let mut rle_decoder = RleDecoder::new(bit_width);
rle_decoder.set_data(data.start_from(1));
self.num_values = num_values;
self.rle_decoder = Some(rle_decoder);
Ok(())
}
fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {
assert!(self.rle_decoder.is_some());
assert!(self.has_dictionary, "Must call set_dict() first!");
let rle = self.rle_decoder.as_mut().unwrap();
let num_values = cmp::min(buffer.len(), self.num_values);
rle.get_batch_with_dict(&self.dictionary[..], buffer, num_values)
}
/// Number of values left in this decoder stream
fn values_left(&self) -> usize {
self.num_values
}
fn encoding(&self) -> Encoding {
Encoding::RLE_DICTIONARY
}
}
// ----------------------------------------------------------------------
// RLE Decoding
/// RLE/Bit-Packing hybrid decoding for values.
/// Currently is used only for data pages v2 and supports boolean types.
/// See [`RleValueEncoder`](crate::encoding::RleValueEncoder) for more information.
pub struct RleValueDecoder<T: DataType> {
values_left: usize,
decoder: RleDecoder,
_phantom: PhantomData<T>,
}
impl<T: DataType> RleValueDecoder<T> {
pub fn new() -> Self {
Self {
values_left: 0,
decoder: RleDecoder::new(1),
_phantom: PhantomData,
}
}
}
impl<T: DataType> Decoder<T> for RleValueDecoder<T> {
#[inline]
fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
// Only support RLE value reader for boolean values with bit width of 1.
ensure_phys_ty!(Type::BOOLEAN, "RleValueDecoder only supports BoolType");
// We still need to remove prefix of i32 from the stream.
const I32_SIZE: usize = mem::size_of::<i32>();
let data_size = read_num_bytes!(i32, I32_SIZE, data.as_ref()) as usize;
self.decoder = RleDecoder::new(1);
self.decoder.set_data(data.range(I32_SIZE, data_size));
self.values_left = num_values;
Ok(())
}
#[inline]
fn values_left(&self) -> usize {
self.values_left
}
#[inline]
fn encoding(&self) -> Encoding {
Encoding::RLE
}
#[inline]
fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {
let num_values = cmp::min(buffer.len(), self.values_left);
let values_read = self.decoder.get_batch(&mut buffer[..num_values])?;
self.values_left -= values_read;
Ok(values_read)
}
}
// ----------------------------------------------------------------------
// DELTA_BINARY_PACKED Decoding
/// Delta binary packed decoder.
/// Supports INT32 and INT64 types.
/// See [`DeltaBitPackEncoder`](crate::encoding::DeltaBitPackEncoder) for more
/// information.
pub struct DeltaBitPackDecoder<T: DataType> {
bit_reader: BitReader,
initialized: bool,
// Header info
/// The number of values in each block
block_size: usize,
/// The number of values that remain to be read in the current page
values_left: usize,
/// The number of mini-blocks in each block
mini_blocks_per_block: usize,
/// The number of values in each mini block
values_per_mini_block: usize,
// Per block info
/// The minimum delta in the block
min_delta: T::T,
/// The byte offset of the end of the current block
block_end_offset: usize,
/// The index on the current mini block
mini_block_idx: usize,
/// The bit widths of each mini block in the current block
mini_block_bit_widths: Vec<u8>,
/// The number of values remaining in the current mini block
mini_block_remaining: usize,
/// The first value from the block header if not consumed
first_value: Option<T::T>,
/// The last value to compute offsets from
last_value: T::T,
}
impl<T: DataType> DeltaBitPackDecoder<T>
where
T::T: Default + FromPrimitive + WrappingAdd + Copy,
{
/// Creates new delta bit packed decoder.
pub fn new() -> Self {
Self {
bit_reader: BitReader::from(vec![]),
initialized: false,
block_size: 0,
values_left: 0,
mini_blocks_per_block: 0,
values_per_mini_block: 0,
min_delta: Default::default(),
mini_block_idx: 0,
mini_block_bit_widths: vec![],
mini_block_remaining: 0,
block_end_offset: 0,
first_value: None,
last_value: Default::default(),
}
}
/// Returns the current offset
pub fn get_offset(&self) -> usize {
assert!(self.initialized, "Bit reader is not initialized");
match self.values_left {
// If we've exhausted this page report the end of the current block
// as we may not have consumed the trailing padding
//
// The max is necessary to handle pages which don't contain more than
// one value and therefore have no blocks, but still contain a page header
0 => self.bit_reader.get_byte_offset().max(self.block_end_offset),
_ => self.bit_reader.get_byte_offset(),
}
}
/// Initializes the next block and the first mini block within it
#[inline]
fn next_block(&mut self) -> Result<()> {
let min_delta = self
.bit_reader
.get_zigzag_vlq_int()
.ok_or_else(|| eof_err!("Not enough data to decode 'min_delta'"))?;
self.min_delta = T::T::from_i64(min_delta)
.ok_or_else(|| general_err!("'min_delta' too large"))?;
self.mini_block_bit_widths.clear();
self.bit_reader.get_aligned_bytes(
&mut self.mini_block_bit_widths,
self.mini_blocks_per_block as usize,
);
let mut offset = self.bit_reader.get_byte_offset();
let mut remaining = self.values_left;
// Compute the end offset of the current block
for b in &mut self.mini_block_bit_widths {
if remaining == 0 {
// Specification requires handling arbitrary bit widths
// for trailing mini blocks
*b = 0;
}
remaining = remaining.saturating_sub(self.values_per_mini_block);
offset += *b as usize * self.values_per_mini_block / 8;
}
self.block_end_offset = offset;
if self.mini_block_bit_widths.len() != self.mini_blocks_per_block {
return Err(eof_err!("insufficient mini block bit widths"));
}
self.mini_block_remaining = self.values_per_mini_block;
self.mini_block_idx = 0;
Ok(())
}
/// Initializes the next mini block
#[inline]
fn next_mini_block(&mut self) -> Result<()> {
if self.mini_block_idx + 1 < self.mini_block_bit_widths.len() {
self.mini_block_idx += 1;
self.mini_block_remaining = self.values_per_mini_block;
Ok(())
} else {
self.next_block()
}
}
}
impl<T: DataType> Decoder<T> for DeltaBitPackDecoder<T>
where
T::T: Default + FromPrimitive + WrappingAdd + Copy,
{
// # of total values is derived from encoding
#[inline]
fn set_data(&mut self, data: ByteBufferPtr, _index: usize) -> Result<()> {
self.bit_reader = BitReader::new(data);
self.initialized = true;
// Read header information
self.block_size = self
.bit_reader
.get_vlq_int()
.ok_or_else(|| eof_err!("Not enough data to decode 'block_size'"))?
.try_into()
.map_err(|_| general_err!("invalid 'block_size'"))?;
self.mini_blocks_per_block = self
.bit_reader
.get_vlq_int()
.ok_or_else(|| eof_err!("Not enough data to decode 'mini_blocks_per_block'"))?
.try_into()
.map_err(|_| general_err!("invalid 'mini_blocks_per_block'"))?;
self.values_left = self
.bit_reader
.get_vlq_int()
.ok_or_else(|| eof_err!("Not enough data to decode 'values_left'"))?
.try_into()
.map_err(|_| general_err!("invalid 'values_left'"))?;
let first_value = self
.bit_reader
.get_zigzag_vlq_int()
.ok_or_else(|| eof_err!("Not enough data to decode 'first_value'"))?;
self.first_value = Some(
T::T::from_i64(first_value)
.ok_or_else(|| general_err!("first value too large"))?,
);
if self.block_size % 128 != 0 {
return Err(general_err!(
"'block_size' must be a multiple of 128, got {}",
self.block_size
));
}
if self.block_size % self.mini_blocks_per_block != 0 {
return Err(general_err!(
"'block_size' must be a multiple of 'mini_blocks_per_block' got {} and {}",
self.block_size, self.mini_blocks_per_block
));
}
// Reset decoding state
self.mini_block_idx = 0;
self.values_per_mini_block = self.block_size / self.mini_blocks_per_block;
self.mini_block_remaining = 0;
self.mini_block_bit_widths.clear();
if self.values_per_mini_block % 32 != 0 {
return Err(general_err!(
"'values_per_mini_block' must be a multiple of 32 got {}",
self.values_per_mini_block
));
}
Ok(())
}
fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {
assert!(self.initialized, "Bit reader is not initialized");
if buffer.is_empty() {
return Ok(0);
}
let mut read = 0;
let to_read = buffer.len().min(self.values_left);
if let Some(value) = self.first_value.take() {
self.last_value = value;
buffer[0] = value;
read += 1;
self.values_left -= 1;
}
while read != to_read {
if self.mini_block_remaining == 0 {
self.next_mini_block()?;
}
let bit_width = self.mini_block_bit_widths[self.mini_block_idx] as usize;
let batch_to_read = self.mini_block_remaining.min(to_read - read);
let batch_read = self
.bit_reader
.get_batch(&mut buffer[read..read + batch_to_read], bit_width);
if batch_read != batch_to_read {
return Err(general_err!(
"Expected to read {} values from miniblock got {}",
batch_to_read,
batch_read
));
}
// At this point we have read the deltas to `buffer` we now need to offset
// these to get back to the original values that were encoded
for v in &mut buffer[read..read + batch_read] {
// It is OK for deltas to contain "overflowed" values after encoding,
// e.g. i64::MAX - i64::MIN, so we use `wrapping_add` to "overflow" again and
// restore original value.
*v = v
.wrapping_add(&self.min_delta)
.wrapping_add(&self.last_value);
self.last_value = *v;
}
read += batch_read;
self.mini_block_remaining -= batch_read;
self.values_left -= batch_read;
}
Ok(to_read)
}
fn values_left(&self) -> usize {
self.values_left
}
fn encoding(&self) -> Encoding {
Encoding::DELTA_BINARY_PACKED
}
}
// ----------------------------------------------------------------------
// DELTA_LENGTH_BYTE_ARRAY Decoding
/// Delta length byte array decoder.
/// Only applied to byte arrays to separate the length values and the data, the lengths
/// are encoded using DELTA_BINARY_PACKED encoding.
/// See [`DeltaLengthByteArrayEncoder`](crate::encoding::DeltaLengthByteArrayEncoder)
/// for more information.
pub struct DeltaLengthByteArrayDecoder<T: DataType> {
// Lengths for each byte array in `data`
// TODO: add memory tracker to this
lengths: Vec<i32>,
// Current index into `lengths`
current_idx: usize,
// Concatenated byte array data
data: Option<ByteBufferPtr>,
// Offset into `data`, always point to the beginning of next byte array.
offset: usize,
// Number of values left in this decoder stream
num_values: usize,
// Placeholder to allow `T` as generic parameter
_phantom: PhantomData<T>,
}
impl<T: DataType> DeltaLengthByteArrayDecoder<T> {
/// Creates new delta length byte array decoder.
pub fn new() -> Self {
Self {
lengths: vec![],
current_idx: 0,
data: None,
offset: 0,
num_values: 0,
_phantom: PhantomData,
}
}
}
impl<T: DataType> Decoder<T> for DeltaLengthByteArrayDecoder<T> {
fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
match T::get_physical_type() {
Type::BYTE_ARRAY => {
let mut len_decoder = DeltaBitPackDecoder::<Int32Type>::new();
len_decoder.set_data(data.all(), num_values)?;
let num_lengths = len_decoder.values_left();
self.lengths.resize(num_lengths, 0);
len_decoder.get(&mut self.lengths[..])?;
self.data = Some(data.start_from(len_decoder.get_offset()));
self.offset = 0;
self.current_idx = 0;
self.num_values = num_lengths;
Ok(())
}
_ => Err(general_err!(
"DeltaLengthByteArrayDecoder only support ByteArrayType"
)),
}
}
fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {
match T::get_physical_type() {
Type::BYTE_ARRAY => {
assert!(self.data.is_some());
let data = self.data.as_ref().unwrap();
let num_values = cmp::min(buffer.len(), self.num_values);
for item in buffer.iter_mut().take(num_values) {
let len = self.lengths[self.current_idx] as usize;
item.as_mut_any()
.downcast_mut::<ByteArray>()
.unwrap()
.set_data(data.range(self.offset, len));
self.offset += len;
self.current_idx += 1;
}
self.num_values -= num_values;
Ok(num_values)
}
_ => Err(general_err!(
"DeltaLengthByteArrayDecoder only support ByteArrayType"
)),
}
}
fn values_left(&self) -> usize {
self.num_values
}
fn encoding(&self) -> Encoding {
Encoding::DELTA_LENGTH_BYTE_ARRAY
}
}
// ----------------------------------------------------------------------
// DELTA_BYTE_ARRAY Decoding
/// Delta byte array decoder.
/// Prefix lengths are encoded using `DELTA_BINARY_PACKED` encoding, Suffixes are stored
/// using `DELTA_LENGTH_BYTE_ARRAY` encoding.
/// See [`DeltaByteArrayEncoder`](crate::encoding::DeltaByteArrayEncoder) for more
/// information.
pub struct DeltaByteArrayDecoder<T: DataType> {
// Prefix lengths for each byte array
// TODO: add memory tracker to this
prefix_lengths: Vec<i32>,
// The current index into `prefix_lengths`,
current_idx: usize,
// Decoder for all suffixes, the # of which should be the same as
// `prefix_lengths.len()`
suffix_decoder: Option<DeltaLengthByteArrayDecoder<ByteArrayType>>,
// The last byte array, used to derive the current prefix
previous_value: Vec<u8>,
// Number of values left
num_values: usize,
// Placeholder to allow `T` as generic parameter
_phantom: PhantomData<T>,
}
impl<T: DataType> DeltaByteArrayDecoder<T> {
/// Creates new delta byte array decoder.
pub fn new() -> Self {
Self {
prefix_lengths: vec![],
current_idx: 0,
suffix_decoder: None,
previous_value: vec![],
num_values: 0,
_phantom: PhantomData,
}
}
}
impl<T: DataType> Decoder<T> for DeltaByteArrayDecoder<T> {
fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
match T::get_physical_type() {
Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY => {
let mut prefix_len_decoder = DeltaBitPackDecoder::<Int32Type>::new();
prefix_len_decoder.set_data(data.all(), num_values)?;
let num_prefixes = prefix_len_decoder.values_left();
self.prefix_lengths.resize(num_prefixes, 0);
prefix_len_decoder.get(&mut self.prefix_lengths[..])?;
let mut suffix_decoder = DeltaLengthByteArrayDecoder::new();
suffix_decoder
.set_data(data.start_from(prefix_len_decoder.get_offset()), num_values)?;
self.suffix_decoder = Some(suffix_decoder);
self.num_values = num_prefixes;
self.current_idx = 0;
self.previous_value.clear();
Ok(())
}
_ => {
Err(general_err!(
"DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"
))
}
}
}
fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {
match T::get_physical_type() {
ty @ Type::BYTE_ARRAY | ty @ Type::FIXED_LEN_BYTE_ARRAY => {
let num_values = cmp::min(buffer.len(), self.num_values);
let mut v: [ByteArray; 1] = [ByteArray::new(); 1];
for item in buffer.iter_mut().take(num_values) {
// Process suffix
// TODO: this is awkward - maybe we should add a non-vectorized API?
let suffix_decoder = self.suffix_decoder.as_mut().expect("decoder not initialized");
suffix_decoder.get(&mut v[..])?;
let suffix = v[0].data();
// Extract current prefix length, can be 0
let prefix_len = self.prefix_lengths[self.current_idx] as usize;
// Concatenate prefix with suffix
let mut result = Vec::new();
result.extend_from_slice(&self.previous_value[0..prefix_len]);
result.extend_from_slice(suffix);
let data = ByteBufferPtr::new(result.clone());
match ty {
Type::BYTE_ARRAY => item
.as_mut_any()
.downcast_mut::<ByteArray>()
.unwrap()
.set_data(data),
Type::FIXED_LEN_BYTE_ARRAY => item
.as_mut_any()
.downcast_mut::<FixedLenByteArray>()
.unwrap()
.set_data(data),
_ => unreachable!(),
};
self.previous_value = result;
self.current_idx += 1;
}
self.num_values -= num_values;
Ok(num_values)
}
_ => {
Err(general_err!(
"DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"
))
}
}
}
fn values_left(&self) -> usize {
self.num_values
}
fn encoding(&self) -> Encoding {
Encoding::DELTA_BYTE_ARRAY
}
}
#[cfg(test)]
#[allow(clippy::approx_constant)]
mod tests {
use super::{super::encoding::*, *};
use std::sync::Arc;
use crate::schema::types::{
ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType,
};
use crate::util::{bit_util::set_array_bit, test_common::RandGen};
#[test]
fn test_get_decoders() {
// supported encodings
create_and_check_decoder::<Int32Type>(Encoding::PLAIN, None);
create_and_check_decoder::<Int32Type>(Encoding::DELTA_BINARY_PACKED, None);
create_and_check_decoder::<ByteArrayType>(
Encoding::DELTA_LENGTH_BYTE_ARRAY,
None,
);
create_and_check_decoder::<ByteArrayType>(Encoding::DELTA_BYTE_ARRAY, None);
create_and_check_decoder::<BoolType>(Encoding::RLE, None);
// error when initializing
create_and_check_decoder::<Int32Type>(
Encoding::RLE_DICTIONARY,
Some(general_err!(
"Cannot initialize this encoding through this function"
)),
);
create_and_check_decoder::<Int32Type>(
Encoding::PLAIN_DICTIONARY,
Some(general_err!(
"Cannot initialize this encoding through this function"
)),
);
create_and_check_decoder::<Int32Type>(
Encoding::DELTA_LENGTH_BYTE_ARRAY,
Some(general_err!(
"Encoding DELTA_LENGTH_BYTE_ARRAY is not supported for type"
)),
);
create_and_check_decoder::<Int32Type>(
Encoding::DELTA_BYTE_ARRAY,
Some(general_err!(
"Encoding DELTA_BYTE_ARRAY is not supported for type"
)),
);
// unsupported
create_and_check_decoder::<Int32Type>(
Encoding::BIT_PACKED,
Some(nyi_err!("Encoding BIT_PACKED is not supported")),
);
}
#[test]
fn test_plain_decode_int32() {
let data = vec![42, 18, 52];
let data_bytes = Int32Type::to_byte_array(&data[..]);
let mut buffer = vec![0; 3];
test_plain_decode::<Int32Type>(
ByteBufferPtr::new(data_bytes),
3,
-1,
&mut buffer[..],
&data[..],
);
}
#[test]
fn test_plain_decode_int32_spaced() {
let data = [42, 18, 52];