forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDecoding.cpp
More file actions
1440 lines (1280 loc) · 53.5 KB
/
Decoding.cpp
File metadata and controls
1440 lines (1280 loc) · 53.5 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
#include <Processors/Formats/Impl/Parquet/Decoding.h>
#include <base/arithmeticOverflow.h>
#include <Columns/ColumnString.h>
#include <Common/FloatUtils.h>
#include <arrow/util/bit_stream_utils.h>
namespace DB::ErrorCodes
{
extern const int NOT_IMPLEMENTED;
extern const int INCORRECT_DATA;
extern const int CANNOT_PARSE_NUMBER;
extern const int VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE;
}
namespace DB::Parquet
{
/// Used for dictionary indices and repetition/definition levels.
/// Throws if any decoded value is >= `limit`.
template <typename T>
struct BitPackedRLEDecoder : public PageDecoder
{
size_t limit = 0;
size_t bit_width = 0;
size_t run_length = 0;
size_t run_bytes = 0; // if bit-packed run
size_t bit_idx = 0; // if bit-packed run
T val = 0; // if RLE run
bool run_is_rle = false; // otherwise bit-packed
BitPackedRLEDecoder(std::span<const char> data_, size_t limit_, bool has_header_byte, bool has_length_bytes = false)
: PageDecoder(data_), limit(limit_)
{
static_assert(sizeof(T) <= 4);
chassert(limit <= std::numeric_limits<T>::max());
if (has_header_byte)
{
requireRemainingBytes(1);
bit_width = size_t(UInt8(*data));
data += 1;
if (bit_width > 8 * sizeof(T) || (bit_width == 0 && limit > 1))
throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid dict indices bit width: {}", bit_width);
}
else
{
chassert(limit > 0);
bit_width = 32 - __builtin_clz(UInt32(limit - 1));
}
if (has_length_bytes)
{
/// RLE-encoded BOOLEANs have 4-byte length prepended, for some reason. It doesn't add
/// any useful information, but let's validate it just in case.
requireRemainingBytes(4);
UInt32 len = 0;
memcpy(&len, data, 4);
data += 4;
if (ssize_t(len) > end - data)
throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid length of RLE-encoded page: {} > {}", len, end - data);
end = data + size_t(len);
}
chassert(bit_width <= 32);
}
void skip(size_t num_values) override
{
skipOrDecode<true>(num_values, nullptr);
}
void decode(size_t num_values, IColumn & col) override
{
auto & out = assert_cast<ColumnVector<T> &>(col).getData();
decodeArray(num_values, out);
}
void decodeArray(size_t num_values, PaddedPODArray<T> & out)
{
size_t start = out.size();
out.resize(start + num_values);
skipOrDecode<false>(num_values, &out[start]);
}
void startRun()
{
UInt64 len;
data = readVarUInt(len, data, end - data);
if (len & 1)
{
/// Bit-packed run.
size_t groups = len >> 1;
run_bytes = groups * bit_width;
requireRemainingBytes(run_bytes);
run_is_rle = false;
run_length = groups << 3;
bit_idx = 0;
}
else
{
const size_t byte_width = (bit_width + 7) / 8;
chassert(byte_width <= sizeof(T));
const T value_mask = T((1ul << bit_width) - 1);
run_length = len >> 1;
requireRemainingBytes(byte_width);
memcpy(&val, data, sizeof(T));
val &= value_mask;
if (val >= limit)
throw Exception(ErrorCodes::INCORRECT_DATA, "Dict index or rep/def level out of bounds (rle)");
run_is_rle = true;
data += byte_width;
}
}
template <bool skip>
void skipOrDecode(size_t num_values, T * out)
{
if (bit_width == 0)
{
/// bit_width == 0 can be used for dictionary indices if the dictionary has only one value.
if constexpr (!skip)
memset(out, 0, num_values * sizeof(T));
return;
}
const T value_mask = T((1ul << bit_width) - 1);
/// TODO [parquet]: May make sense to have specialized version of this loop for bit_width=1,
/// which is very common as def levels for nullables.
/// (Some stats from hits.parquet, in case it helps with optimization:
/// bit-packed runs: 64879089, total 2548822304 values (~39 values/run),
/// RLE runs: 81177527, total 7373423915 values (~91 values/run).)
while (num_values)
{
if (run_length == 0)
startRun();
size_t n = std::min(run_length, num_values);
run_length -= n;
num_values -= n;
if (run_is_rle)
{
if constexpr (!skip)
{
const T v = val; // without this std::fill reloads it from memory on each iteration
std::fill(out, out + n, v);
out += n;
}
}
else
{
if constexpr (!skip)
{
for (size_t i = 0; i < n; ++i)
{
size_t x;
memcpy(&x, data + (bit_idx >> 3), 8);
x = (x >> (bit_idx & 7)) & value_mask;
if (x >= limit)
throw Exception(ErrorCodes::INCORRECT_DATA, "Dict index or rep/def level out of bounds (bp)");
*out = x;
++out;
bit_idx += bit_width;
}
}
else
{
bit_idx += bit_width * n;
}
if (!run_length)
data += run_bytes;
}
}
}
};
struct PlainFixedSizeDecoder : public PageDecoder
{
std::shared_ptr<FixedSizeConverter> converter;
PlainFixedSizeDecoder(std::span<const char> data_, std::shared_ptr<FixedSizeConverter> converter_) : PageDecoder(data_), converter(std::move(converter_)) {}
void skip(size_t num_values) override
{
size_t bytes = num_values * converter->input_size;
requireRemainingBytes(bytes);
data += bytes;
}
void decode(size_t num_values, IColumn & col) override
{
const char * from = data;
skip(num_values);
converter->convertColumn(std::span(from, num_values * converter->input_size), num_values, col);
}
};
struct PlainBooleanDecoder : public PageDecoder
{
std::shared_ptr<FixedSizeConverter> converter;
size_t bit_idx = 0;
PaddedPODArray<char> temp_buffer;
PlainBooleanDecoder(std::span<const char> data_, std::shared_ptr<FixedSizeConverter> converter_) : PageDecoder(data_), converter(std::move(converter_)) {}
void skip(size_t num_values) override
{
bit_idx += num_values;
}
void decode(size_t num_values, IColumn & col) override
{
size_t end_bit_idx = bit_idx + num_values;
if ((end_bit_idx + 7) / 8 > size_t(end - data))
throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected end of page data");
char * to;
bool direct = converter->isTrivial();
if (direct)
{
auto to_span = col.insertRawUninitialized(num_values);
chassert(to_span.size() == num_values);
to = to_span.data();
}
else
{
temp_buffer.resize(num_values);
to = temp_buffer.data();
}
size_t i = 0;
while (i < num_values)
{
size_t bit_i = bit_idx + i;
if ((bit_i & 7) == 0 && bit_i + 8 <= num_values)
{
/// Unpack 8 bits at once. (I haven't checked whether this is faster.)
UInt64 x = UInt64(UInt8(data[bit_i / 8]));
/// x = 00000000 00000000 00000000 00000000 00000000 00000000 00000000 hgfedcba
x = (x | (x << 28)) & 0x0000000f0000000ful;
/// x = 00000000 00000000 00000000 0000hgfe 00000000 00000000 00000000 0000dcba
x = (x | (x << 14)) & 0x0003000300030003ul;
/// x = 00000000 000000hg 00000000 000000fe 00000000 000000dc 00000000 000000ba
x = (x | (x << 7)) & 0x0101010101010101ul;
/// x = 0000000h 0000000g 0000000f 0000000e 0000000d 0000000c 0000000b 0000000a
memcpy(to + i * 8, &x, 8);
i += 8;
}
else
{
to[i] = (data[bit_i / 8] >> (bit_i & 7)) & 1;
i += 1;
}
}
bit_idx = end_bit_idx;
if (!direct)
converter->convertColumn(std::span(to, num_values), num_values, col);
}
};
struct PlainStringDecoder : public PageDecoder
{
std::shared_ptr<StringConverter> converter;
IColumn::Offsets offsets;
PlainStringDecoder(std::span<const char> data_, std::shared_ptr<StringConverter> converter_) : PageDecoder(data_), converter(std::move(converter_)) {}
void skip(size_t num_values) override
{
for (size_t i = 0; i < num_values; ++i)
{
UInt32 x;
memcpy(&x, data, 4); /// omitting range check because input is padded
size_t len = 4 + size_t(x);
requireRemainingBytes(len);
data += len;
}
}
void decode(size_t num_values, IColumn & col) override
{
if (converter->isTrivial())
{
/// Fast path for directly appending to ColumnString.
auto & col_str = assert_cast<ColumnString &>(col);
col_str.reserve(col_str.size() + num_values);
for (size_t i = 0; i < num_values; ++i)
{
UInt32 x;
memcpy(&x, data, 4); /// omitting range check because input is padded
size_t len = 4 + size_t(x);
requireRemainingBytes(len);
col_str.insertData(data + 4, size_t(x));
data += len;
}
}
else
{
offsets.clear();
offsets.reserve(num_values);
/// We have extra 4 bytes *before* each string, but StringConverter expects
/// separator_bytes *after* each string (for a historical reason).
/// So we offset the `data` start pointer to skip the first 4 bytes.
const char * chars_start = data + 4;
size_t offset = 0;
for (size_t i = 0; i < num_values; ++i)
{
UInt32 x;
memcpy(&x, data, 4); /// omitting range check because input is padded
size_t len = 4 + size_t(x);
requireRemainingBytes(len);
offset += len;
offsets.push_back(offset);
data += len;
}
converter->convertColumn(std::span(chars_start, offset), offsets.data(), /*separator_bytes*/ 4, num_values, col);
}
}
};
template <typename T>
static T identity(T x) { return x; }
struct DeltaBinaryPackedDecoder : public PageDecoder
{
std::shared_ptr<FixedSizeConverter> converter;
UInt64 values_per_block = 0;
UInt64 miniblocks_per_block = 0;
UInt64 total_values_remaining = 0;
/// Do all arithmetic as unsigned to silently wrap on overflow (as DELTA_BINARY_PACKED wants).
/// (Note: signed and unsigned integer addition are exactly the same operation, the only
/// difference is whether overflow is UB or not.)
UInt64 current_value = 0;
UInt64 min_delta = 0;
const UInt8 * miniblock_bit_widths = nullptr;
size_t miniblock_idx = 0; // within block
/// Initially set to 1 as a special case to report the first value.
size_t miniblock_values_remaining = 1;
arrow::bit_util::BitReader bit_reader;
PODArray<UInt64> temp_values;
DeltaBinaryPackedDecoder(std::span<const char> data_, std::shared_ptr<FixedSizeConverter> converter_) : PageDecoder(data_), converter(std::move(converter_))
{
/// From https://parquet.apache.org/docs/file-format/data-pages/encodings/ :
///
/// Delta encoding consists of a header followed by blocks of delta encoded values binary
/// packed. Each block is made of miniblocks, each of them binary packed with its own bit width.
///
/// The header is defined as follows:
/// <block size in values> <number of miniblocks in a block> <total value count> <first value>
/// * the block size is a multiple of 128; it is stored as a ULEB128 int
/// * the miniblock count per block is a divisor of the block size such that their
/// quotient, the number of values in a miniblock, is a multiple of 32; it is stored as a
/// ULEB128 int
/// * the total value count is stored as a ULEB128 int
/// * the first value is stored as a zigzag ULEB128 int
data = readVarUInt(values_per_block, data, end - data);
data = readVarUInt(miniblocks_per_block, data, end - data);
data = readVarUInt(total_values_remaining, data, end - data);
data = readVarUInt(current_value, data, end - data);
current_value = UInt64(decodeZigZag(current_value));
if (values_per_block == 0 || values_per_block % 128 != 0 || miniblocks_per_block == 0 || values_per_block % miniblocks_per_block != 0 || values_per_block / miniblocks_per_block % 32 != 0)
throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid DELTA_BINARY_PACKED header");
/// Sanity-check total_values_remaining: each value takes at least one bit.
/// This is useful to avoid allocating lots of memory if the input is corrupted.
requireRemainingBytes((total_values_remaining + 7)/8);
}
void nextBlock()
{
/// From https://parquet.apache.org/docs/file-format/data-pages/encodings/ :
///
/// Each block contains
/// <min delta> <list of bitwidths of miniblocks> <miniblocks>
/// * the min delta is a zigzag ULEB128 int (we compute a minimum as we need positive
/// integers for bit packing)
/// * the bitwidth of each block is stored as a byte
/// * each miniblock is a list of bit packed ints according to the bit width stored at the
/// beginning of the block
data = readVarUInt(min_delta, data, end - data);
min_delta = UInt64(decodeZigZag(min_delta));
requireRemainingBytes(miniblocks_per_block);
miniblock_bit_widths = reinterpret_cast<const UInt8 *>(data);
data += miniblocks_per_block;
miniblock_idx = 0;
}
void nextMiniblock()
{
++miniblock_idx;
if (miniblock_idx >= miniblocks_per_block || miniblock_bit_widths == nullptr)
nextBlock();
chassert(miniblock_idx < miniblocks_per_block);
miniblock_values_remaining = values_per_block / miniblocks_per_block;
size_t bytes = (miniblock_values_remaining * miniblock_bit_widths[miniblock_idx] + 7) / 8;
requireRemainingBytes(bytes);
bit_reader.Reset(reinterpret_cast<const uint8_t *>(data), int(bytes));
data += bytes;
}
void skip(size_t num_values) override
{
/// Temporary buffer for decoding deltas (needed for updating current_value, can't skip).
size_t num_u64s = converter->input_size == 4 ? (num_values + 1) / 2 : num_values;
temp_values.resize(num_u64s);
char * to = reinterpret_cast<char *>(temp_values.data());
switch (converter->input_size)
{
case 4: decodeImpl<UInt32>(num_values, to, identity<UInt32>); break;
case 8: decodeImpl<UInt64>(num_values, to, identity<UInt64>); break;
default: chassert(false);
}
}
void decode(size_t num_values, IColumn & col) override
{
bool direct = converter->isTrivial();
char * to;
if (direct)
{
auto to_span = col.insertRawUninitialized(num_values);
chassert(to_span.size() == num_values * converter->input_size);
to = to_span.data();
}
else
{
/// (temp_values is array of UInt64 rather than char because it needs to be aligned)
size_t num_u64s = converter->input_size == 4 ? (num_values + 1) / 2 : num_values;
temp_values.resize(num_u64s);
to = reinterpret_cast<char *>(temp_values.data());
}
switch (converter->input_size)
{
case 4: decodeImpl<UInt32>(num_values, to, identity<UInt32>); break;
case 8: decodeImpl<UInt64>(num_values, to, identity<UInt64>); break;
default: chassert(false);
}
if (!direct)
converter->convertColumn(std::span(to, num_values * converter->input_size), num_values, col);
}
template <typename T, typename F>
void decodeImpl(size_t num_values, char * out_bytes, F func)
{
if (total_values_remaining < num_values)
throw Exception(ErrorCodes::INCORRECT_DATA, "Trying to read past total number of values in DELTA_BINARY_PACKED encoding");
total_values_remaining -= num_values;
T * out_values = reinterpret_cast<T *>(out_bytes);
/// The very first value needs special treatment because it has no corresponding delta.
if (!miniblock_bit_widths && miniblock_values_remaining)
{
*out_values = func(T(current_value));
++out_values;
num_values -= 1;
miniblock_values_remaining -= 1;
}
while (num_values)
{
if (!miniblock_values_remaining)
nextMiniblock();
size_t n = std::min(num_values, miniblock_values_remaining);
num_values -= n;
miniblock_values_remaining -= n;
int bits_per_delta = int(miniblock_bit_widths[miniblock_idx]);
int read_count = bit_reader.GetBatch(bits_per_delta, out_values, n);
chassert(read_count == int(n));
for (size_t i = 0; i < n; ++i)
{
current_value += min_delta + UInt64(*out_values);
*out_values = func(T(current_value));
++out_values;
}
}
}
};
struct DeltaLengthByteArrayDecoder : public PageDecoder
{
std::shared_ptr<StringConverter> converter;
PaddedPODArray<UInt64> offsets;
size_t idx = 0;
DeltaLengthByteArrayDecoder(std::span<const char> data_, std::shared_ptr<StringConverter> converter_) : PageDecoder(data_), converter(std::move(converter_))
{
/// Decode all lengths in advance because otherwise there's no way to tell where chars start.
DeltaBinaryPackedDecoder lengths_decoder(data_, nullptr);
offsets.resize(lengths_decoder.total_values_remaining);
UInt64 last_offset = 0;
lengths_decoder.decodeImpl<UInt64>(
lengths_decoder.total_values_remaining, reinterpret_cast<char *>(offsets.data()),
[&](UInt64 len)
{
if (common::addOverflow(last_offset, len, last_offset))
throw Exception(ErrorCodes::INCORRECT_DATA, "Overflow in lengths in DELTA_LENGTH_BYTE_ARRAY data");
return last_offset;
});
chassert(lengths_decoder.end == end);
data = lengths_decoder.data;
requireRemainingBytes(last_offset);
}
void skip(size_t num_values) override
{
if (num_values > offsets.size() - idx)
throw Exception(ErrorCodes::INCORRECT_DATA, "Too few values in page");
idx += num_values;
}
void decode(size_t num_values, IColumn & col) override
{
if (num_values > offsets.size() - idx)
throw Exception(ErrorCodes::INCORRECT_DATA, "Too few values in page");
converter->convertColumn(std::span(data, end - data), offsets.data() + idx, /*separator_bytes*/ 0, num_values, col);
idx += num_values;
}
};
struct DeltaByteArrayDecoder : public PageDecoder
{
/// This encoding is applicable for both BYTE_ARRAY and FIXED_LEN_BYTE_ARRAY.
std::shared_ptr<StringConverter> string_converter;
std::shared_ptr<FixedSizeConverter> fixed_size_converter;
PaddedPODArray<UInt64> prefixes;
PaddedPODArray<UInt64> suffixes;
size_t idx = 0;
String current_value;
MutableColumnPtr temp_column;
PaddedPODArray<char> temp_buffer;
DeltaByteArrayDecoder(std::span<const char> data_, std::shared_ptr<StringConverter> string_converter_, std::shared_ptr<FixedSizeConverter> fixed_size_converter_) : PageDecoder(data_), string_converter(std::move(string_converter_)), fixed_size_converter(fixed_size_converter_)
{
for (auto * lengths : {&prefixes, &suffixes})
{
DeltaBinaryPackedDecoder decoder(std::span(data, end - data), nullptr);
lengths->resize(decoder.total_values_remaining);
decoder.decodeImpl<UInt64>(
decoder.total_values_remaining, reinterpret_cast<char *>(lengths->data()),
identity<UInt64>);
data = decoder.data;
}
if (prefixes.size() != suffixes.size())
throw Exception(ErrorCodes::INCORRECT_DATA, "Value count mismatch in DELTA_BYTE_ARRAY headers");
}
void skip(size_t num_values) override
{
if (fixed_size_converter)
decodeImpl<true, true>(num_values, nullptr, nullptr);
else
decodeImpl<true, false>(num_values, nullptr, nullptr);
}
void decode(size_t num_values, IColumn & col) override
{
if (fixed_size_converter)
{
bool direct = fixed_size_converter->isTrivial();
std::span<char> to;
if (direct)
{
to = col.insertRawUninitialized(num_values);
chassert(to.size() == num_values * fixed_size_converter->input_size);
}
else
{
temp_buffer.resize(num_values * fixed_size_converter->input_size);
to = std::span(temp_buffer.data(), temp_buffer.size());
}
decodeImpl<false, true>(num_values, nullptr, to.data());
if (!direct)
fixed_size_converter->convertColumn(to, num_values, col);
}
else
{
bool direct = string_converter->isTrivial();
ColumnString * col_str;
if (direct)
{
col_str = assert_cast<ColumnString *>(&col);
}
else
{
if (!temp_column)
temp_column = ColumnString::create();
col_str = assert_cast<ColumnString *>(temp_column.get());
col_str->getOffsets().clear();
col_str->getChars().clear();
}
col_str->reserve(col_str->size() + num_values);
decodeImpl<false, false>(num_values, col_str, nullptr);
chassert(col_str->size() == num_values);
if (!direct)
string_converter->convertColumn(std::span(reinterpret_cast<char *>(col_str->getChars().data()), col_str->getChars().size()), col_str->getOffsets().data(), /*separator_bytes*/ 0, num_values, col);
}
}
template <bool skip, bool is_fixed_size>
void decodeImpl(size_t num_values, ColumnString * out_str, char * out_fixed_size)
{
if (num_values > prefixes.size() - idx)
throw Exception(ErrorCodes::INCORRECT_DATA, "Too few values in page");
size_t fixed_size = is_fixed_size ? fixed_size_converter->input_size : 0;
for (size_t i = 0; i < num_values; ++i)
{
if (prefixes[idx] > current_value.size())
throw Exception(ErrorCodes::INCORRECT_DATA, "DELTA_BYTE_ARRAY too long");
current_value.resize(prefixes[idx]);
requireRemainingBytes(suffixes[idx]);
current_value.append(data, suffixes[idx]);
data += suffixes[idx];
++idx;
if constexpr (is_fixed_size)
{
if (current_value.size() != fixed_size)
throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected fixed string size in DELTA_BYTE_ARRAY");
if constexpr (!skip)
{
memcpy(out_fixed_size, current_value.data(), fixed_size);
out_fixed_size += fixed_size;
}
}
else if constexpr (!skip)
{
out_str->insertData(current_value.data(), current_value.size());
}
}
}
};
struct ByteStreamSplitDecoder : public PageDecoder
{
std::shared_ptr<FixedSizeConverter> converter;
size_t stream_size = 0;
PaddedPODArray<char> temp_buffer;
ByteStreamSplitDecoder(std::span<const char> data_, std::shared_ptr<FixedSizeConverter> converter_) : PageDecoder(data_), converter(std::move(converter_))
{
if (data_.size() % converter->input_size != 0)
throw Exception(ErrorCodes::INCORRECT_DATA, "BYTE_STREAM_SPLIT data size not divisible by element size");
stream_size = data_.size() / converter->input_size;
/// Point [data, end) to the first stream.
end = data + stream_size;
}
void skip(size_t num_values) override
{
requireRemainingBytes(num_values);
data += num_values;
}
void decode(size_t num_values, IColumn & col) override
{
size_t num_streams = converter->input_size;
bool direct = converter->isTrivial();
char * to = nullptr;
if (direct)
{
auto span = col.insertRawUninitialized(num_values);
chassert(span.size() == num_values * num_streams);
to = span.data();
}
else
{
temp_buffer.resize(num_values * num_streams);
to = temp_buffer.data();
}
requireRemainingBytes(num_values);
size_t i = 0;
while (i < num_values)
{
if (num_values - i >= 8)
{
/// Slightly faster code path that reads 8 bytes at once.
/// Arrow has ByteStreamSplitDecode with various fancy simd implementations, maybe
/// we should reuse that instead.
for (size_t stream = 0; stream < num_streams; ++stream)
{
UInt64 x = unalignedLoad<UInt64>(&data[i + stream * stream_size]);
to[(i + 0) * num_streams + stream] = char(UInt8(x >> 0));
to[(i + 1) * num_streams + stream] = char(UInt8(x >> 8));
to[(i + 2) * num_streams + stream] = char(UInt8(x >> 16));
to[(i + 3) * num_streams + stream] = char(UInt8(x >> 24));
to[(i + 4) * num_streams + stream] = char(UInt8(x >> 32));
to[(i + 5) * num_streams + stream] = char(UInt8(x >> 40));
to[(i + 6) * num_streams + stream] = char(UInt8(x >> 48));
to[(i + 7) * num_streams + stream] = char(UInt8(x >> 56));
}
i += 8;
}
else
{
for (size_t stream = 0; stream < num_streams; ++stream)
to[i * num_streams + stream] = data[i + stream * stream_size];
i += 1;
}
}
data += num_values;
if (!direct)
converter->convertColumn(std::span(to, num_values * num_streams), num_values, col);
}
};
bool PageDecoderInfo::canReadDirectlyIntoColumn(parq::Encoding::type encoding, size_t num_values, IColumn & col, std::span<char> & out) const
{
if (encoding == parq::Encoding::PLAIN && fixed_size_converter && physical_type != parq::Type::BOOLEAN && fixed_size_converter->isTrivial())
{
chassert(col.sizeOfValueIfFixed() == fixed_size_converter->input_size);
out = col.insertRawUninitialized(num_values);
return true;
}
return false;
}
void PageDecoderInfo::decodeField(std::span<const char> data, bool is_max, Field & out) const
{
if (!allow_stats)
return;
if (fixed_size_converter)
fixed_size_converter->convertField(data, is_max, out);
else if (string_converter)
string_converter->convertField(data, is_max, out);
else
chassert(false);
}
std::unique_ptr<PageDecoder> PageDecoderInfo::makeDecoder(
parq::Encoding::type encoding, std::span<const char> data) const
{
switch (encoding)
{
case parq::Encoding::PLAIN:
switch (physical_type)
{
case parq::Type::INT32:
case parq::Type::INT64:
case parq::Type::INT96:
case parq::Type::FLOAT:
case parq::Type::DOUBLE:
case parq::Type::FIXED_LEN_BYTE_ARRAY:
return std::make_unique<PlainFixedSizeDecoder>(data, fixed_size_converter);
case parq::Type::BYTE_ARRAY:
return std::make_unique<PlainStringDecoder>(data, string_converter);
case parq::Type::BOOLEAN:
return std::make_unique<PlainBooleanDecoder>(data, fixed_size_converter);
//default: break;
}
break;
case parq::Encoding::RLE:
switch (physical_type)
{
case parq::Type::BOOLEAN:
return std::make_unique<BitPackedRLEDecoder<UInt8>>(data, 2, /*has_header_byte=*/ false, /*has_length_bytes=*/ true);
default: break;
}
break;
case parq::Encoding::BIT_PACKED: throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected BIT_PACKED encoding for values");
case parq::Encoding::DELTA_BINARY_PACKED:
switch (physical_type)
{
case parq::Type::INT32:
case parq::Type::INT64:
return std::make_unique<DeltaBinaryPackedDecoder>(data, fixed_size_converter);
default: break;
}
break;
case parq::Encoding::DELTA_LENGTH_BYTE_ARRAY:
switch (physical_type)
{
case parq::Type::BYTE_ARRAY:
return std::make_unique<DeltaLengthByteArrayDecoder>(data, string_converter);
default: break;
}
break;
case parq::Encoding::DELTA_BYTE_ARRAY:
switch (physical_type)
{
case parq::Type::BYTE_ARRAY:
case parq::Type::FIXED_LEN_BYTE_ARRAY:
return std::make_unique<DeltaByteArrayDecoder>(data, string_converter, fixed_size_converter);
default: break;
}
break;
case parq::Encoding::BYTE_STREAM_SPLIT:
/// Documentation says this encoding is only for FLOAT and DOUBLE, but arrow supports
/// any fixed-size types, so we do the same just in case.
if (fixed_size_converter)
return std::make_unique<ByteStreamSplitDecoder>(data, fixed_size_converter);
break;
default: throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected page encoding: {}", thriftToString(encoding));
}
throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected encoding {} for type {}", thriftToString(encoding), thriftToString(physical_type));
}
void decodeRepOrDefLevels(parq::Encoding::type encoding, UInt8 max, size_t num_values, std::span<const char> data, PaddedPODArray<UInt8> & out)
{
if (max == 0)
return;
switch (encoding)
{
case parq::Encoding::RLE:
BitPackedRLEDecoder<UInt8>(data, size_t(max) + 1, /*has_header_byte=*/ false).decodeArray(num_values, out);
break;
case parq::Encoding::BIT_PACKED:
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "BIT_PACKED levels not implemented");
default: throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected repetition/definition levels encoding: {}", thriftToString(encoding));
}
}
std::unique_ptr<PageDecoder> makeDictionaryIndicesDecoder(parq::Encoding::type encoding, size_t dictionary_size, std::span<const char> data)
{
switch (encoding)
{
case parq::Encoding::RLE_DICTIONARY: return std::make_unique<BitPackedRLEDecoder<UInt32>>(data, dictionary_size, /*has_header_byte=*/ true);
default: throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected dictionary indices encoding: {}", thriftToString(encoding));
}
}
void Dictionary::reset()
{
mode = Mode::Uninitialized;
data = {};
col.reset();
offsets.clear();
offsets.shrink_to_fit();
decompressed_buf.clear();
decompressed_buf.shrink_to_fit();
}
bool Dictionary::isInitialized() const
{
return mode != Mode::Uninitialized;
}
double Dictionary::getAverageValueSize() const
{
switch (mode)
{
case Mode::FixedSize: return value_size;
case Mode::StringPlain: return std::max(0., double(data.size()) / std::max(offsets.size(), 1ul) - 4);
case Mode::Column: return double(col->byteSize()) / std::max(col->size(), 1ul);
case Mode::Uninitialized: break;
}
chassert(false);
return 0;
}
void Dictionary::decode(parq::Encoding::type encoding, const PageDecoderInfo & info, size_t num_values, std::span<const char> data_, const IDataType & raw_decoded_type)
{
chassert(mode == Mode::Uninitialized);
chassert(info.fixed_size_converter || info.string_converter);
if (encoding == parq::Encoding::PLAIN_DICTIONARY)
encoding = parq::Encoding::PLAIN;
count = num_values;
bool decode_generic = false;
if (encoding != parq::Encoding::PLAIN)
{
/// Parquet supports only PLAIN encoding for dictionaries, but we support any encoding
/// because it's easy (we need decode_generic code path anyway for ShortInt and Boolean).
decode_generic = true;
}
else if (info.fixed_size_converter && info.fixed_size_converter->isTrivial())
{
/// No decoding needed, we'll be just copying bytes from dictionary page directly.
mode = Mode::FixedSize;
value_size = info.fixed_size_converter->input_size;
data = data_;
}
else if (info.string_converter && info.string_converter->isTrivial())
{
mode = Mode::StringPlain;
data = data_;
offsets.resize(num_values);
const char * ptr = data.data();
const char * end = data.data() + data.size();
for (size_t i = 0; i < num_values; ++i)
{
UInt32 x;
memcpy(&x, ptr, 4); /// omitting range check because input is padded
size_t len = 4 + size_t(x);
if (len > size_t(end - ptr))
throw Exception(ErrorCodes::INCORRECT_DATA, "Encoded string is out of bounds");
ptr += len;
offsets[i] = ptr - data.data();
}
}
else
{
/// Values need to be converted, e.g. Decimal encoded as BYTE_ARRAY, or Int8 encoded as INT32.
decode_generic = true;
}
if (decode_generic)
{
auto decoder = info.makeDecoder(encoding, data_);
auto c = raw_decoded_type.createColumn();
c->reserve(num_values);
decoder->decode(num_values, *c);
col = std::move(c);
if (col->isFixedAndContiguous())
{
mode = Mode::FixedSize;
value_size = col->sizeOfValueIfFixed();
std::string_view s = col->getRawData();
data = std::span(s.data(), s.size());
chassert(data.size() == col->size() * value_size);
}
else
{
mode = Mode::Column;
}
}
chassert(mode != Mode::Uninitialized);
if (mode == Mode::FixedSize && data.size() != count * value_size)
throw Exception(ErrorCodes::INCORRECT_DATA, "Incorrect dictionary page size: {} != {} * {}", data.size(), count, value_size);
}
template<size_t value_size>
static void indexImpl(const PaddedPODArray<UInt32> & indexes, std::span<const char> data, std::span<char> to)
{
size_t size = indexes.size();
for (size_t i = 0; i < size; ++i)
memcpy(to.data() + i * value_size, data.data() + indexes[i] * value_size, value_size);
}
void Dictionary::index(const ColumnUInt32 & indexes_col, IColumn & out)
{
const PaddedPODArray<UInt32> & indexes = indexes_col.getData();
switch (mode)
{
case Mode::FixedSize:
{
auto to = out.insertRawUninitialized(indexes.size());
chassert(to.size() == value_size * indexes.size());
/// Short variable-length memcpy is very slow compared to a simple mov, so we dispatch
/// to specialized loops covering basic int types.
switch (value_size)
{
case 1: indexImpl<1>(indexes, data, to); break;
case 2: indexImpl<2>(indexes, data, to); break;
case 3: indexImpl<3>(indexes, data, to); break;
case 4: indexImpl<4>(indexes, data, to); break;
case 8: indexImpl<8>(indexes, data, to); break;
case 16: indexImpl<16>(indexes, data, to); break;
default:
for (size_t i = 0; i < indexes.size(); ++i)
memcpy(to.data() + i * value_size, data.data() + indexes[i] * value_size, value_size);
}
break;
}
case Mode::StringPlain: