-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathdecoder.cc
More file actions
2488 lines (2187 loc) · 95.3 KB
/
decoder.cc
File metadata and controls
2488 lines (2187 loc) · 95.3 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.
#include "parquet/encoding.h"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
#include "arrow/array.h"
#include "arrow/array/builder_binary.h"
#include "arrow/array/builder_dict.h"
#include "arrow/array/builder_primitive.h"
#include "arrow/type_traits.h"
#include "arrow/util/bit_block_counter.h"
#include "arrow/util/bit_run_reader.h"
#include "arrow/util/bit_stream_utils_internal.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/bitmap_ops.h"
#include "arrow/util/byte_stream_split_internal.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/endian.h"
#include "arrow/util/int_util_overflow.h"
#include "arrow/util/logging_internal.h"
#include "arrow/util/rle_encoding_internal.h"
#include "arrow/util/spaced_internal.h"
#include "arrow/util/ubsan.h"
#include "arrow/visit_data_inline.h"
#include "parquet/exception.h"
#include "parquet/platform.h"
#include "parquet/schema.h"
#include "parquet/types.h"
#ifdef _MSC_VER
// disable warning about inheritance via dominance in the diamond pattern
# pragma warning(disable : 4250)
#endif
namespace bit_util = arrow::bit_util;
using arrow::Status;
using arrow::VisitNullBitmapInline;
using arrow::internal::AddWithOverflow;
using arrow::internal::BitBlockCounter;
using arrow::internal::checked_cast;
using arrow::internal::VisitBitRuns;
using arrow::util::SafeLoad;
using arrow::util::SafeLoadAs;
namespace parquet {
namespace {
// A helper class to abstract away differences between EncodingTraits<DType>::Accumulator
// for ByteArrayType and FLBAType.
template <typename DType, typename ArrowType>
struct ArrowBinaryHelper;
template <>
struct ArrowBinaryHelper<ByteArrayType, ::arrow::BinaryType> {
using Accumulator = typename EncodingTraits<ByteArrayType>::Accumulator;
explicit ArrowBinaryHelper(Accumulator* acc)
: acc_(acc),
builder_(checked_cast<::arrow::BinaryBuilder*>(acc->builder.get())),
chunk_space_remaining_(::arrow::kBinaryMemoryLimit -
builder_->value_data_length()) {}
// Prepare will reserve the number of entries in the current chunk.
// If estimated_data_length is provided, it will also reserve the estimated data length.
Status Prepare(int64_t length, std::optional<int64_t> estimated_data_length = {}) {
entries_remaining_ = length;
RETURN_NOT_OK(ReserveInitialChunkData(estimated_data_length));
return Status::OK();
}
// If a new chunk is created and estimated_remaining_data_length is provided,
// it will also reserve the estimated data length for this chunk.
Status AppendValue(const uint8_t* data, int32_t length,
std::optional<int64_t> estimated_remaining_data_length = {}) {
DCHECK_GT(entries_remaining_, 0);
if (ARROW_PREDICT_FALSE(!CanFit(length))) {
// This element would exceed the capacity of a chunk
RETURN_NOT_OK(PushChunk());
// Reserve entries and data in new chunk
RETURN_NOT_OK(ReserveInitialChunkData(estimated_remaining_data_length));
}
chunk_space_remaining_ -= length;
--entries_remaining_;
if (estimated_remaining_data_length.has_value()) {
// Assume Prepare() was already called with an estimated_data_length
builder_->UnsafeAppend(data, length);
return Status::OK();
} else {
return builder_->Append(data, length);
}
}
void UnsafeAppendNull() {
DCHECK_GT(entries_remaining_, 0);
--entries_remaining_;
builder_->UnsafeAppendNull();
}
Status AppendNulls(int64_t length) {
DCHECK_GE(entries_remaining_, length);
entries_remaining_ -= length;
return builder_->AppendNulls(length);
}
private:
Status PushChunk() {
ARROW_ASSIGN_OR_RAISE(auto chunk, acc_->builder->Finish());
acc_->chunks.push_back(std::move(chunk));
chunk_space_remaining_ = ::arrow::kBinaryMemoryLimit;
return Status::OK();
}
Status ReserveInitialChunkData(std::optional<int64_t> estimated_remaining_data_length) {
RETURN_NOT_OK(builder_->Reserve(entries_remaining_));
if (estimated_remaining_data_length.has_value()) {
int64_t required_capacity =
std::min(*estimated_remaining_data_length, chunk_space_remaining_);
RETURN_NOT_OK(builder_->ReserveData(required_capacity));
}
return Status::OK();
}
bool CanFit(int64_t length) const { return length <= chunk_space_remaining_; }
Accumulator* acc_;
::arrow::BinaryBuilder* builder_;
int64_t entries_remaining_;
int64_t chunk_space_remaining_;
};
template <typename ArrowBinaryType>
struct ArrowBinaryHelper<ByteArrayType, ArrowBinaryType> {
using Accumulator = typename EncodingTraits<ByteArrayType>::Accumulator;
using BuilderType = typename ::arrow::TypeTraits<ArrowBinaryType>::BuilderType;
static constexpr bool kIsBinaryView =
::arrow::is_binary_view_like_type<ArrowBinaryType>::value;
explicit ArrowBinaryHelper(Accumulator* acc)
: builder_(checked_cast<BuilderType*>(acc->builder.get())) {}
// Prepare will reserve the number of entries in the current chunk.
// If estimated_data_length is provided, it will also reserve the estimated data length,
// and the caller should better call `UnsafeAppend` instead of `Append` to avoid
// double-checking the data length.
Status Prepare(int64_t length, std::optional<int64_t> estimated_data_length = {}) {
RETURN_NOT_OK(builder_->Reserve(length));
// Avoid reserving data when reading into a binary-view array, because many
// values may be very short and not require any heap storage, which would make
// the initial allocation wasteful.
if (!kIsBinaryView && estimated_data_length.has_value()) {
RETURN_NOT_OK(builder_->ReserveData(*estimated_data_length));
}
return Status::OK();
}
Status AppendValue(const uint8_t* data, int32_t length,
std::optional<int64_t> estimated_remaining_data_length = {}) {
if (!kIsBinaryView && estimated_remaining_data_length.has_value()) {
// Assume Prepare() was already called with an estimated_data_length
builder_->UnsafeAppend(data, length);
return Status::OK();
} else {
return builder_->Append(data, length);
}
}
void UnsafeAppendNull() { builder_->UnsafeAppendNull(); }
Status AppendNulls(int64_t length) { return builder_->AppendNulls(length); }
private:
BuilderType* builder_;
};
template <>
struct ArrowBinaryHelper<FLBAType, ::arrow::FixedSizeBinaryType> {
using Accumulator = typename EncodingTraits<FLBAType>::Accumulator;
explicit ArrowBinaryHelper(Accumulator* acc) : acc_(acc) {}
Status Prepare(int64_t length, std::optional<int64_t> estimated_data_length = {}) {
return acc_->Reserve(length);
}
Status AppendValue(const uint8_t* data, int32_t length,
std::optional<int64_t> estimated_remaining_data_length = {}) {
acc_->UnsafeAppend(data);
return Status::OK();
}
void UnsafeAppendNull() { acc_->UnsafeAppendNull(); }
Status AppendNulls(int64_t length) { return acc_->AppendNulls(length); }
private:
Accumulator* acc_;
};
// Call `func(&helper, args...)` where `helper` is a ArrowBinaryHelper<> instance
// suitable for the Parquet DType and accumulator `acc`.
template <typename DType, typename Function, typename... Args>
auto DispatchArrowBinaryHelper(typename EncodingTraits<DType>::Accumulator* acc,
int64_t length,
std::optional<int64_t> estimated_data_length,
Function&& func, Args&&... args) {
static_assert(std::is_same_v<DType, ByteArrayType> || std::is_same_v<DType, FLBAType>,
"unsupported DType");
if constexpr (std::is_same_v<DType, ByteArrayType>) {
switch (acc->builder->type()->id()) {
case ::arrow::Type::BINARY:
case ::arrow::Type::STRING: {
ArrowBinaryHelper<DType, ::arrow::BinaryType> helper(acc);
RETURN_NOT_OK(helper.Prepare(length, estimated_data_length));
return func(&helper, std::forward<Args>(args)...);
}
case ::arrow::Type::LARGE_BINARY:
case ::arrow::Type::LARGE_STRING: {
ArrowBinaryHelper<DType, ::arrow::LargeBinaryType> helper(acc);
RETURN_NOT_OK(helper.Prepare(length, estimated_data_length));
return func(&helper, std::forward<Args>(args)...);
}
case ::arrow::Type::BINARY_VIEW:
case ::arrow::Type::STRING_VIEW: {
ArrowBinaryHelper<DType, ::arrow::BinaryViewType> helper(acc);
RETURN_NOT_OK(helper.Prepare(length, estimated_data_length));
return func(&helper, std::forward<Args>(args)...);
}
default:
throw ParquetException(
"Unsupported Arrow builder type when reading from BYTE_ARRAY column: " +
acc->builder->type()->ToString());
}
} else {
ArrowBinaryHelper<DType, ::arrow::FixedSizeBinaryType> helper(acc);
RETURN_NOT_OK(helper.Prepare(length, estimated_data_length));
return func(&helper, std::forward<Args>(args)...);
}
}
void CheckPageLargeEnough(int64_t remaining_bytes, int32_t value_width,
int64_t num_values) {
if (remaining_bytes < value_width * num_values) {
ParquetException::EofException();
}
}
// Internal decoder class hierarchy
class DecoderImpl : virtual public Decoder {
public:
void SetData(int num_values, const uint8_t* data, int len) override {
num_values_ = num_values;
data_ = data;
len_ = len;
}
int values_left() const override { return num_values_; }
Encoding::type encoding() const override { return encoding_; }
protected:
DecoderImpl(const ColumnDescriptor* descr, Encoding::type encoding)
: descr_(descr), encoding_(encoding), num_values_(0), data_(NULLPTR), len_(0) {}
// For accessing type-specific metadata, like FIXED_LEN_BYTE_ARRAY
const ColumnDescriptor* descr_;
const Encoding::type encoding_;
int num_values_;
const uint8_t* data_;
int len_;
};
template <typename DType>
class TypedDecoderImpl : public DecoderImpl, virtual public TypedDecoder<DType> {
public:
using T = typename DType::c_type;
protected:
TypedDecoderImpl(const ColumnDescriptor* descr, Encoding::type encoding)
: DecoderImpl(descr, encoding) {
if constexpr (std::is_same_v<DType, FLBAType>) {
if (descr_ == nullptr) {
throw ParquetException(
"Must pass a ColumnDescriptor when creating a Decoder for "
"FIXED_LEN_BYTE_ARRAY");
}
type_length_ = descr_->type_length();
} else if constexpr (std::is_same_v<DType, ByteArrayType>) {
type_length_ = -1;
} else {
type_length_ = sizeof(T);
}
}
int DecodeSpaced(T* buffer, int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset) override {
if (null_count > 0) {
int values_to_read = num_values - null_count;
int values_read = this->Decode(buffer, values_to_read);
if (values_read != values_to_read) {
throw ParquetException("Number of values / definition_levels read did not match");
}
::arrow::util::internal::SpacedExpandRightward<T>(buffer, num_values, null_count,
valid_bits, valid_bits_offset);
return num_values;
} else {
return this->Decode(buffer, num_values);
}
}
int type_length_;
};
// ----------------------------------------------------------------------
// PLAIN decoder
template <typename DType>
class PlainDecoder : public TypedDecoderImpl<DType> {
public:
using T = typename DType::c_type;
explicit PlainDecoder(const ColumnDescriptor* descr)
: TypedDecoderImpl<DType>(descr, Encoding::PLAIN) {}
int Decode(T* buffer, int max_values) override;
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<DType>::Accumulator* builder) override;
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<DType>::DictAccumulator* builder) override;
};
template <>
int PlainDecoder<Int96Type>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<Int96Type>::Accumulator* builder) {
ParquetException::NYI("DecodeArrow not supported for Int96");
}
template <>
int PlainDecoder<Int96Type>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<Int96Type>::DictAccumulator* builder) {
ParquetException::NYI("DecodeArrow not supported for Int96");
}
template <>
int PlainDecoder<BooleanType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<BooleanType>::Accumulator* builder) {
ParquetException::NYI("BooleanType handled in concrete subclass");
}
template <>
int PlainDecoder<BooleanType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<BooleanType>::DictAccumulator* builder) {
ParquetException::NYI("dictionaries of BooleanType");
}
template <typename DType>
int PlainDecoder<DType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<DType>::Accumulator* builder) {
using value_type = typename DType::c_type;
constexpr int value_size = static_cast<int>(sizeof(value_type));
int values_decoded = num_values - null_count;
CheckPageLargeEnough(this->len_, value_size, values_decoded);
const uint8_t* data = this->data_;
PARQUET_THROW_NOT_OK(builder->Reserve(num_values));
PARQUET_THROW_NOT_OK(
VisitBitRuns(valid_bits, valid_bits_offset, num_values,
[&](int64_t position, int64_t run_length, bool is_valid) {
if (is_valid) {
#if ARROW_LITTLE_ENDIAN
RETURN_NOT_OK(builder->AppendValues(
reinterpret_cast<const value_type*>(data), run_length));
data += run_length * sizeof(value_type);
#else
// On big-endian systems, we need to byte-swap each value
// since Parquet data is stored in little-endian format
for (int64_t i = 0; i < run_length; ++i) {
value_type value = ::arrow::bit_util::FromLittleEndian(
SafeLoadAs<value_type>(data));
RETURN_NOT_OK(builder->Append(value));
data += sizeof(value_type);
}
#endif
} else {
RETURN_NOT_OK(builder->AppendNulls(run_length));
}
return Status::OK();
}));
this->data_ = data;
this->len_ -= sizeof(value_type) * values_decoded;
this->num_values_ -= values_decoded;
return values_decoded;
}
template <typename DType>
int PlainDecoder<DType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<DType>::DictAccumulator* builder) {
using value_type = typename DType::c_type;
constexpr int value_size = static_cast<int>(sizeof(value_type));
int values_decoded = num_values - null_count;
CheckPageLargeEnough(this->len_, value_size, values_decoded);
const uint8_t* data = this->data_;
PARQUET_THROW_NOT_OK(builder->Reserve(num_values));
VisitNullBitmapInline(
valid_bits, valid_bits_offset, num_values, null_count,
[&]() {
PARQUET_THROW_NOT_OK(builder->Append(SafeLoadAs<value_type>(data)));
data += sizeof(value_type);
},
[&]() { PARQUET_THROW_NOT_OK(builder->AppendNull()); });
this->data_ = data;
this->len_ -= sizeof(value_type) * values_decoded;
this->num_values_ -= values_decoded;
return values_decoded;
}
// Decode routine templated on C++ type rather than type enum
template <typename T>
inline int DecodePlain(const uint8_t* data, int64_t data_size, int num_values,
int type_length, T* out) {
int64_t bytes_to_decode = num_values * static_cast<int64_t>(sizeof(T));
if (bytes_to_decode > data_size || bytes_to_decode > INT_MAX) {
ParquetException::EofException();
}
// If bytes_to_decode == 0, data could be null
if (bytes_to_decode > 0) {
#if ARROW_LITTLE_ENDIAN
memcpy(out, data, static_cast<size_t>(bytes_to_decode));
#else
// On big-endian systems, we need to byte-swap each value
// since Parquet data is stored in little-endian format.
// Only apply to integer and floating-point types that have FromLittleEndian support.
if constexpr (std::is_same_v<T, int32_t> || std::is_same_v<T, uint32_t> ||
std::is_same_v<T, int64_t> || std::is_same_v<T, uint64_t> ||
std::is_same_v<T, float> || std::is_same_v<T, double>) {
for (int i = 0; i < num_values; ++i) {
out[i] = ::arrow::bit_util::FromLittleEndian(SafeLoadAs<T>(data));
data += sizeof(T);
}
} else {
// For other types (bool, Int96, etc.), just do memcpy
memcpy(out, data, static_cast<size_t>(bytes_to_decode));
}
#endif
}
return static_cast<int>(bytes_to_decode);
}
// Template specialization for BYTE_ARRAY. The written values do not own their
// own data.
static inline int64_t ReadByteArray(const uint8_t* data, int64_t data_size,
ByteArray* out) {
if (ARROW_PREDICT_FALSE(data_size < 4)) {
ParquetException::EofException();
}
const int32_t len = ::arrow::bit_util::FromLittleEndian(SafeLoadAs<int32_t>(data));
if (len < 0) {
throw ParquetException("Invalid BYTE_ARRAY value");
}
const int64_t consumed_length = static_cast<int64_t>(len) + 4;
if (ARROW_PREDICT_FALSE(data_size < consumed_length)) {
ParquetException::EofException();
}
*out = ByteArray{static_cast<uint32_t>(len), data + 4};
return consumed_length;
}
template <>
inline int DecodePlain<ByteArray>(const uint8_t* data, int64_t data_size, int num_values,
int type_length, ByteArray* out) {
int bytes_decoded = 0;
for (int i = 0; i < num_values; ++i) {
const auto increment = ReadByteArray(data, data_size, out + i);
if (ARROW_PREDICT_FALSE(increment > INT_MAX - bytes_decoded)) {
throw ParquetException("BYTE_ARRAY chunk too large");
}
data += increment;
data_size -= increment;
bytes_decoded += static_cast<int>(increment);
}
return bytes_decoded;
}
// Template specialization for FIXED_LEN_BYTE_ARRAY. The written values do not
// own their own data.
template <>
inline int DecodePlain<FixedLenByteArray>(const uint8_t* data, int64_t data_size,
int num_values, int type_length,
FixedLenByteArray* out) {
int64_t bytes_to_decode = static_cast<int64_t>(type_length) * num_values;
if (bytes_to_decode > data_size || bytes_to_decode > INT_MAX) {
ParquetException::EofException();
}
for (int i = 0; i < num_values; ++i) {
out[i].ptr = data + i * static_cast<int64_t>(type_length);
}
return static_cast<int>(bytes_to_decode);
}
template <typename DType>
int PlainDecoder<DType>::Decode(T* buffer, int max_values) {
max_values = std::min(max_values, this->num_values_);
int bytes_consumed =
DecodePlain<T>(this->data_, this->len_, max_values, this->type_length_, buffer);
this->data_ += bytes_consumed;
this->len_ -= bytes_consumed;
this->num_values_ -= max_values;
return max_values;
}
// PLAIN decoder implementation for BOOLEAN
class PlainBooleanDecoder : public TypedDecoderImpl<BooleanType>, public BooleanDecoder {
public:
explicit PlainBooleanDecoder(const ColumnDescriptor* descr);
void SetData(int num_values, const uint8_t* data, int len) override;
// Two flavors of bool decoding
int Decode(uint8_t* buffer, int max_values) override;
int Decode(bool* buffer, int max_values) override;
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<BooleanType>::Accumulator* out) override;
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<BooleanType>::DictAccumulator* out) override;
private:
std::unique_ptr<::arrow::bit_util::BitReader> bit_reader_;
int total_num_values_{0};
};
PlainBooleanDecoder::PlainBooleanDecoder(const ColumnDescriptor* descr)
: TypedDecoderImpl<BooleanType>(descr, Encoding::PLAIN) {}
void PlainBooleanDecoder::SetData(int num_values, const uint8_t* data, int len) {
DecoderImpl::SetData(num_values, data, len);
total_num_values_ = num_values;
bit_reader_ = std::make_unique<bit_util::BitReader>(data, len);
}
int PlainBooleanDecoder::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<BooleanType>::Accumulator* builder) {
int values_decoded = num_values - null_count;
if (ARROW_PREDICT_FALSE(num_values_ < values_decoded)) {
// A too large `num_values` was requested.
ParquetException::EofException(
"A too large `num_values` was requested in PlainBooleanDecoder: remain " +
std::to_string(num_values_) + ", requested: " + std::to_string(values_decoded));
}
if (ARROW_PREDICT_FALSE(!bit_reader_->Advance(values_decoded))) {
ParquetException::EofException("PlainDecoder doesn't have enough values in page");
}
if (null_count == 0) {
// FastPath: can copy the data directly
PARQUET_THROW_NOT_OK(builder->AppendValues(data_, values_decoded, NULLPTR,
total_num_values_ - num_values_));
} else {
// Handle nulls by BitBlockCounter
PARQUET_THROW_NOT_OK(builder->Reserve(num_values));
BitBlockCounter bit_counter(valid_bits, valid_bits_offset, num_values);
int64_t value_position = 0;
int64_t valid_bits_offset_position = valid_bits_offset;
int64_t previous_value_offset = total_num_values_ - num_values_;
while (value_position < num_values) {
auto block = bit_counter.NextWord();
if (block.AllSet()) {
// GH-40978: We don't have UnsafeAppendValues for booleans currently,
// so using `AppendValues` here.
PARQUET_THROW_NOT_OK(
builder->AppendValues(data_, block.length, NULLPTR, previous_value_offset));
previous_value_offset += block.length;
} else if (block.NoneSet()) {
// GH-40978: We don't have UnsafeAppendNulls for booleans currently,
// so using `AppendNulls` here.
PARQUET_THROW_NOT_OK(builder->AppendNulls(block.length));
} else {
for (int64_t i = 0; i < block.length; ++i) {
if (bit_util::GetBit(valid_bits, valid_bits_offset_position + i)) {
bool value = bit_util::GetBit(data_, previous_value_offset);
builder->UnsafeAppend(value);
previous_value_offset += 1;
} else {
builder->UnsafeAppendNull();
}
}
}
value_position += block.length;
valid_bits_offset_position += block.length;
}
}
num_values_ -= values_decoded;
return values_decoded;
}
inline int PlainBooleanDecoder::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<BooleanType>::DictAccumulator* builder) {
ParquetException::NYI("dictionaries of BooleanType");
}
int PlainBooleanDecoder::Decode(uint8_t* buffer, int max_values) {
max_values = std::min(max_values, num_values_);
if (ARROW_PREDICT_FALSE(!bit_reader_->Advance(max_values))) {
ParquetException::EofException();
}
// Copy the data directly
// Parquet's boolean encoding is bit-packed using LSB. So
// we can directly copy the data to the buffer.
::arrow::internal::CopyBitmap(this->data_, /*offset=*/total_num_values_ - num_values_,
/*length=*/max_values, /*dest=*/buffer,
/*dest_offset=*/0);
num_values_ -= max_values;
return max_values;
}
int PlainBooleanDecoder::Decode(bool* buffer, int max_values) {
max_values = std::min(max_values, num_values_);
if (bit_reader_->GetBatch(1, buffer, max_values) != max_values) {
ParquetException::EofException();
}
num_values_ -= max_values;
return max_values;
}
// PLAIN decoder implementation for FIXED_LEN_BYTE_ARRAY and BYTE_ARRAY
template <>
inline int PlainDecoder<ByteArrayType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<ByteArrayType>::Accumulator* builder) {
ParquetException::NYI();
}
template <>
inline int PlainDecoder<ByteArrayType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<ByteArrayType>::DictAccumulator* builder) {
ParquetException::NYI();
}
template <>
inline int PlainDecoder<FLBAType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<FLBAType>::Accumulator* builder) {
const int byte_width = this->type_length_;
const int values_decoded = num_values - null_count;
CheckPageLargeEnough(len_, byte_width, values_decoded);
PARQUET_THROW_NOT_OK(builder->Reserve(num_values));
// 1. Copy directly into the FixedSizeBinary data buffer, packed to the right.
uint8_t* decode_out = builder->GetMutableValue(builder->length() + null_count);
memcpy(decode_out, data_, values_decoded * byte_width);
// 2. Expand the values into their final positions.
if (null_count == 0) {
// No expansion required, and no need to append the bitmap
builder->UnsafeAdvance(num_values);
} else {
::arrow::util::internal::SpacedExpandLeftward(
builder->GetMutableValue(builder->length()), byte_width, num_values, null_count,
valid_bits, valid_bits_offset);
builder->UnsafeAdvance(num_values, valid_bits, valid_bits_offset);
}
data_ += byte_width * values_decoded;
num_values_ -= values_decoded;
len_ -= byte_width * values_decoded;
return values_decoded;
}
template <>
inline int PlainDecoder<FLBAType>::DecodeArrow(
int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset,
typename EncodingTraits<FLBAType>::DictAccumulator* builder) {
const int byte_width = this->type_length_;
const int values_decoded = num_values - null_count;
CheckPageLargeEnough(len_, byte_width, values_decoded);
PARQUET_THROW_NOT_OK(builder->Reserve(num_values));
PARQUET_THROW_NOT_OK(
VisitBitRuns(valid_bits, valid_bits_offset, num_values,
[&](int64_t position, int64_t run_length, bool is_valid) {
if (is_valid) {
for (int64_t i = 0; i < run_length; ++i) {
RETURN_NOT_OK(builder->Append(data_));
}
data_ += run_length * byte_width;
} else {
RETURN_NOT_OK(builder->AppendNulls(run_length));
}
return Status::OK();
}));
num_values_ -= values_decoded;
len_ -= byte_width * values_decoded;
return values_decoded;
}
class PlainByteArrayDecoder : public PlainDecoder<ByteArrayType> {
public:
using Base = PlainDecoder<ByteArrayType>;
using Base::DecodeSpaced;
using Base::PlainDecoder;
// ----------------------------------------------------------------------
// Dictionary read paths
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
::arrow::BinaryDictionary32Builder* builder) override {
int result = 0;
PARQUET_THROW_NOT_OK(DecodeArrow(num_values, null_count, valid_bits,
valid_bits_offset, builder, &result));
return result;
}
// ----------------------------------------------------------------------
// Optimized dense binary read paths
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<ByteArrayType>::Accumulator* out) override {
int result = 0;
PARQUET_THROW_NOT_OK(DecodeArrowDense(num_values, null_count, valid_bits,
valid_bits_offset, out, &result));
return result;
}
private:
Status DecodeArrowDense(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<ByteArrayType>::Accumulator* out,
int* out_values_decoded) {
// We're going to decode `num_values - null_count` PLAIN values,
// and each value has a 4-byte length header that doesn't count for the
// Arrow binary data length.
int64_t estimated_data_length = len_ - 4 * (num_values - null_count);
if (ARROW_PREDICT_FALSE(estimated_data_length < 0)) {
return Status::Invalid("Invalid or truncated PLAIN-encoded BYTE_ARRAY data");
}
auto visit_binary_helper = [&](auto* helper) {
int values_decoded = 0;
auto visit_run = [&](int64_t position, int64_t run_length, bool is_valid) {
if (is_valid) {
for (int64_t i = 0; i < run_length; ++i) {
// We ensure `len_` is sufficient thanks to:
// 1. the initial `estimated_data_length` check above,
// 2. the running `value_len > estimated_data_length` check below.
// This precondition follows from those two checks.
DCHECK_GE(len_, 4);
auto value_len =
::arrow::bit_util::FromLittleEndian(SafeLoadAs<int32_t>(data_));
// This check also ensures that `value_len <= len_ - 4` due to the way
// `estimated_data_length` is computed.
if (ARROW_PREDICT_FALSE(value_len < 0 || value_len > estimated_data_length)) {
return Status::Invalid(
"Invalid or truncated PLAIN-encoded BYTE_ARRAY data");
}
RETURN_NOT_OK(
helper->AppendValue(data_ + 4, value_len, estimated_data_length));
auto increment = value_len + 4;
data_ += increment;
len_ -= increment;
estimated_data_length -= value_len;
DCHECK_GE(estimated_data_length, 0);
}
values_decoded += static_cast<int>(run_length);
DCHECK_LE(values_decoded, num_values);
return Status::OK();
} else {
return helper->AppendNulls(run_length);
}
};
RETURN_NOT_OK(
VisitBitRuns(valid_bits, valid_bits_offset, num_values, std::move(visit_run)));
num_values_ -= values_decoded;
*out_values_decoded = values_decoded;
return Status::OK();
};
return DispatchArrowBinaryHelper<ByteArrayType>(
out, num_values, estimated_data_length, visit_binary_helper);
}
template <typename BuilderType>
Status DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset, BuilderType* builder,
int* out_values_decoded) {
RETURN_NOT_OK(builder->Reserve(num_values));
int values_decoded = 0;
RETURN_NOT_OK(VisitBitRuns(
valid_bits, valid_bits_offset, num_values,
[&](int64_t position, int64_t run_length, bool is_valid) {
if (is_valid) {
for (int64_t i = 0; i < run_length; ++i) {
if (ARROW_PREDICT_FALSE(len_ < 4)) {
return Status::Invalid(
"Invalid or truncated PLAIN-encoded BYTE_ARRAY data");
}
auto value_len =
::arrow::bit_util::FromLittleEndian(SafeLoadAs<int32_t>(data_));
if (ARROW_PREDICT_FALSE(value_len < 0 || value_len > len_ - 4)) {
return Status::Invalid(
"Invalid or truncated PLAIN-encoded BYTE_ARRAY data");
}
RETURN_NOT_OK(builder->Append(data_ + 4, value_len));
auto increment = value_len + 4;
data_ += increment;
len_ -= increment;
}
values_decoded += static_cast<int>(run_length);
return Status::OK();
} else {
return builder->AppendNulls(run_length);
}
}));
num_values_ -= values_decoded;
*out_values_decoded = values_decoded;
return Status::OK();
}
};
class PlainFLBADecoder : public PlainDecoder<FLBAType>, public FLBADecoder {
public:
using Base = PlainDecoder<FLBAType>;
using Base::PlainDecoder;
};
// ----------------------------------------------------------------------
// Dictionary decoding
template <typename Type>
class DictDecoderImpl : public TypedDecoderImpl<Type>, public DictDecoder<Type> {
public:
typedef typename Type::c_type T;
// Initializes the dictionary with values from 'dictionary'. The data in
// dictionary is not guaranteed to persist in memory after this call so the
// dictionary decoder needs to copy the data out if necessary.
explicit DictDecoderImpl(const ColumnDescriptor* descr,
MemoryPool* pool = ::arrow::default_memory_pool())
: TypedDecoderImpl<Type>(descr, Encoding::RLE_DICTIONARY),
dictionary_(AllocateBuffer(pool, 0)),
dictionary_length_(0),
byte_array_data_(AllocateBuffer(pool, 0)),
byte_array_offsets_(AllocateBuffer(pool, 0)),
indices_scratch_space_(AllocateBuffer(pool, 0)) {}
// Perform type-specific initialization
void SetDict(TypedDecoder<Type>* dictionary) override;
void SetData(int num_values, const uint8_t* data, int len) override {
this->num_values_ = num_values;
if (len == 0) {
// Initialize dummy decoder to avoid crashes later on
idx_decoder_ =
::arrow::util::RleBitPackedDecoder<int32_t>(data, len, /*bit_width=*/1);
return;
}
uint8_t bit_width = *data;
if (ARROW_PREDICT_FALSE(bit_width > 32)) {
throw ParquetException("Invalid or corrupted bit_width " +
std::to_string(bit_width) + ". Maximum allowed is 32.");
}
idx_decoder_ = ::arrow::util::RleBitPackedDecoder<int32_t>(++data, --len, bit_width);
}
int Decode(T* buffer, int num_values) override {
num_values = std::min(num_values, this->num_values_);
int decoded_values = idx_decoder_.GetBatchWithDict(
dictionary_->data_as<T>(), dictionary_length_, buffer, num_values);
if (decoded_values != num_values) {
ParquetException::EofException();
}
this->num_values_ -= num_values;
return num_values;
}
int DecodeSpaced(T* buffer, int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset) override {
num_values = std::min(num_values, this->num_values_);
if (num_values != idx_decoder_.GetBatchWithDictSpaced(
dictionary_->data_as<T>(), dictionary_length_, buffer,
num_values, null_count, valid_bits, valid_bits_offset)) {
ParquetException::EofException();
}
this->num_values_ -= num_values;
return num_values;
}
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<Type>::Accumulator* out) override;
int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<Type>::DictAccumulator* out) override;
void InsertDictionary(::arrow::ArrayBuilder* builder) override;
int DecodeIndicesSpaced(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
::arrow::ArrayBuilder* builder) override {
if (num_values > 0) {
// TODO(wesm): Refactor to batch reads for improved memory use. It is not
// trivial because the null_count is relative to the entire bitmap
PARQUET_THROW_NOT_OK(indices_scratch_space_->TypedResize<int32_t>(
num_values, /*shrink_to_fit=*/false));
}
auto indices_buffer = indices_scratch_space_->mutable_data_as<int32_t>();
if (num_values != idx_decoder_.GetBatchSpaced(num_values, null_count, valid_bits,
valid_bits_offset, indices_buffer)) {
ParquetException::EofException();
}
// XXX(wesm): Cannot append "valid bits" directly to the builder
std::vector<uint8_t> valid_bytes(num_values, 0);
size_t i = 0;
VisitNullBitmapInline(
valid_bits, valid_bits_offset, num_values, null_count,
[&]() { valid_bytes[i++] = 1; }, [&]() { ++i; });
auto binary_builder = checked_cast<::arrow::BinaryDictionary32Builder*>(builder);
PARQUET_THROW_NOT_OK(
binary_builder->AppendIndices(indices_buffer, num_values, valid_bytes.data()));
this->num_values_ -= num_values - null_count;
return num_values - null_count;
}
int DecodeIndices(int num_values, ::arrow::ArrayBuilder* builder) override {
num_values = std::min(num_values, this->num_values_);
if (num_values > 0) {
// TODO(wesm): Refactor to batch reads for improved memory use. This is
// relatively simple here because we don't have to do any bookkeeping of
// nulls
PARQUET_THROW_NOT_OK(indices_scratch_space_->TypedResize<int32_t>(
num_values, /*shrink_to_fit=*/false));
}