applied-ai-018 commited on
Commit
287adac
·
verified ·
1 Parent(s): 8179f69

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_base.h +285 -0
  3. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_binary.h +329 -0
  4. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_decimal.h +72 -0
  5. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_dict.h +182 -0
  6. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_nested.h +863 -0
  7. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_primitive.h +202 -0
  8. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_run_end.h +133 -0
  9. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_adaptive.h +215 -0
  10. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_base.h +370 -0
  11. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_binary.h +971 -0
  12. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_decimal.h +102 -0
  13. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_dict.h +737 -0
  14. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_nested.h +839 -0
  15. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_primitive.h +555 -0
  16. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_run_end.h +303 -0
  17. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_time.h +66 -0
  18. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_union.h +254 -0
  19. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/concatenate.h +37 -0
  20. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/data.h +621 -0
  21. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/diff.h +76 -0
  22. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/util.h +90 -0
  23. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/validate.h +56 -0
  24. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server.h +328 -0
  25. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/flight/test_util.h +264 -0
  26. env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/flight/transport.h +302 -0
  27. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.h +20 -0
  28. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.h +35 -0
  29. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.h +21 -0
  30. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.h +25 -0
  31. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.h +379 -0
  32. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.h +184 -0
  33. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.h +524 -0
  34. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.h +180 -0
  35. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter.h +363 -0
  36. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter_reader.h +68 -0
  37. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/column_page.h +171 -0
  38. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/column_scanner.h +264 -0
  39. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.h +469 -0
  40. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.h +154 -0
  41. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.h +510 -0
  42. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.h +57 -0
  43. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_wrapper.h +84 -0
  44. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_system_key_material_store.h +89 -0
  45. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_encryption_key.h +57 -0
  46. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_metadata.h +91 -0
  47. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_toolkit.h +106 -0
  48. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client.h +93 -0
  49. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client_factory.h +38 -0
  50. env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/local_wrap_kms_client.h +94 -0
.gitattributes CHANGED
@@ -184,3 +184,4 @@ env-llmeval/lib/python3.10/site-packages/pyarrow/libparquet.so.1500 filter=lfs d
184
  env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1500 filter=lfs diff=lfs merge=lfs -text
185
  env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_substrait.so.1500 filter=lfs diff=lfs merge=lfs -text
186
  env-llmeval/lib/python3.10/site-packages/pyarrow/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
184
  env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1500 filter=lfs diff=lfs merge=lfs -text
185
  env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_substrait.so.1500 filter=lfs diff=lfs merge=lfs -text
186
  env-llmeval/lib/python3.10/site-packages/pyarrow/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
187
+ env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_flight.so.1500 filter=lfs diff=lfs merge=lfs -text
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_base.h ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <iosfwd>
22
+ #include <memory>
23
+ #include <string>
24
+ #include <vector>
25
+
26
+ #include "arrow/array/data.h"
27
+ #include "arrow/buffer.h"
28
+ #include "arrow/compare.h"
29
+ #include "arrow/result.h"
30
+ #include "arrow/status.h"
31
+ #include "arrow/type.h"
32
+ #include "arrow/util/bit_util.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+ #include "arrow/visitor.h"
36
+
37
+ namespace arrow {
38
+
39
+ // ----------------------------------------------------------------------
40
+ // User array accessor types
41
+
42
+ /// \brief Array base type
43
+ /// Immutable data array with some logical type and some length.
44
+ ///
45
+ /// Any memory is owned by the respective Buffer instance (or its parents).
46
+ ///
47
+ /// The base class is only required to have a null bitmap buffer if the null
48
+ /// count is greater than 0
49
+ ///
50
+ /// If known, the null count can be provided in the base Array constructor. If
51
+ /// the null count is not known, pass -1 to indicate that the null count is to
52
+ /// be computed on the first call to null_count()
53
+ class ARROW_EXPORT Array {
54
+ public:
55
+ virtual ~Array() = default;
56
+
57
+ /// \brief Return true if value at index is null. Does not boundscheck
58
+ bool IsNull(int64_t i) const { return !IsValid(i); }
59
+
60
+ /// \brief Return true if value at index is valid (not null). Does not
61
+ /// boundscheck
62
+ bool IsValid(int64_t i) const {
63
+ if (null_bitmap_data_ != NULLPTR) {
64
+ return bit_util::GetBit(null_bitmap_data_, i + data_->offset);
65
+ }
66
+ // Dispatching with a few conditionals like this makes IsNull more
67
+ // efficient for how it is used in practice. Making IsNull virtual
68
+ // would add a vtable lookup to every call and prevent inlining +
69
+ // a potential inner-branch removal.
70
+ if (type_id() == Type::SPARSE_UNION) {
71
+ return !internal::IsNullSparseUnion(*data_, i);
72
+ }
73
+ if (type_id() == Type::DENSE_UNION) {
74
+ return !internal::IsNullDenseUnion(*data_, i);
75
+ }
76
+ if (type_id() == Type::RUN_END_ENCODED) {
77
+ return !internal::IsNullRunEndEncoded(*data_, i);
78
+ }
79
+ return data_->null_count != data_->length;
80
+ }
81
+
82
+ /// \brief Return a Scalar containing the value of this array at i
83
+ Result<std::shared_ptr<Scalar>> GetScalar(int64_t i) const;
84
+
85
+ /// Size in the number of elements this array contains.
86
+ int64_t length() const { return data_->length; }
87
+
88
+ /// A relative position into another array's data, to enable zero-copy
89
+ /// slicing. This value defaults to zero
90
+ int64_t offset() const { return data_->offset; }
91
+
92
+ /// The number of null entries in the array. If the null count was not known
93
+ /// at time of construction (and set to a negative value), then the null
94
+ /// count will be computed and cached on the first invocation of this
95
+ /// function
96
+ int64_t null_count() const;
97
+
98
+ /// \brief Computes the logical null count for arrays of all types including
99
+ /// those that do not have a validity bitmap like union and run-end encoded
100
+ /// arrays
101
+ ///
102
+ /// If the array has a validity bitmap, this function behaves the same as
103
+ /// null_count(). For types that have no validity bitmap, this function will
104
+ /// recompute the null count every time it is called.
105
+ ///
106
+ /// \see GetNullCount
107
+ int64_t ComputeLogicalNullCount() const;
108
+
109
+ const std::shared_ptr<DataType>& type() const { return data_->type; }
110
+ Type::type type_id() const { return data_->type->id(); }
111
+
112
+ /// Buffer for the validity (null) bitmap, if any. Note that Union types
113
+ /// never have a null bitmap.
114
+ ///
115
+ /// Note that for `null_count == 0` or for null type, this will be null.
116
+ /// This buffer does not account for any slice offset
117
+ const std::shared_ptr<Buffer>& null_bitmap() const { return data_->buffers[0]; }
118
+
119
+ /// Raw pointer to the null bitmap.
120
+ ///
121
+ /// Note that for `null_count == 0` or for null type, this will be null.
122
+ /// This buffer does not account for any slice offset
123
+ const uint8_t* null_bitmap_data() const { return null_bitmap_data_; }
124
+
125
+ /// Equality comparison with another array
126
+ bool Equals(const Array& arr, const EqualOptions& = EqualOptions::Defaults()) const;
127
+ bool Equals(const std::shared_ptr<Array>& arr,
128
+ const EqualOptions& = EqualOptions::Defaults()) const;
129
+
130
+ /// \brief Return the formatted unified diff of arrow::Diff between this
131
+ /// Array and another Array
132
+ std::string Diff(const Array& other) const;
133
+
134
+ /// Approximate equality comparison with another array
135
+ ///
136
+ /// epsilon is only used if this is FloatArray or DoubleArray
137
+ bool ApproxEquals(const std::shared_ptr<Array>& arr,
138
+ const EqualOptions& = EqualOptions::Defaults()) const;
139
+ bool ApproxEquals(const Array& arr,
140
+ const EqualOptions& = EqualOptions::Defaults()) const;
141
+
142
+ /// Compare if the range of slots specified are equal for the given array and
143
+ /// this array. end_idx exclusive. This methods does not bounds check.
144
+ bool RangeEquals(int64_t start_idx, int64_t end_idx, int64_t other_start_idx,
145
+ const Array& other,
146
+ const EqualOptions& = EqualOptions::Defaults()) const;
147
+ bool RangeEquals(int64_t start_idx, int64_t end_idx, int64_t other_start_idx,
148
+ const std::shared_ptr<Array>& other,
149
+ const EqualOptions& = EqualOptions::Defaults()) const;
150
+ bool RangeEquals(const Array& other, int64_t start_idx, int64_t end_idx,
151
+ int64_t other_start_idx,
152
+ const EqualOptions& = EqualOptions::Defaults()) const;
153
+ bool RangeEquals(const std::shared_ptr<Array>& other, int64_t start_idx,
154
+ int64_t end_idx, int64_t other_start_idx,
155
+ const EqualOptions& = EqualOptions::Defaults()) const;
156
+
157
+ /// \brief Apply the ArrayVisitor::Visit() method specialized to the array type
158
+ Status Accept(ArrayVisitor* visitor) const;
159
+
160
+ /// Construct a zero-copy view of this array with the given type.
161
+ ///
162
+ /// This method checks if the types are layout-compatible.
163
+ /// Nested types are traversed in depth-first order. Data buffers must have
164
+ /// the same item sizes, even though the logical types may be different.
165
+ /// An error is returned if the types are not layout-compatible.
166
+ Result<std::shared_ptr<Array>> View(const std::shared_ptr<DataType>& type) const;
167
+
168
+ /// Construct a zero-copy slice of the array with the indicated offset and
169
+ /// length
170
+ ///
171
+ /// \param[in] offset the position of the first element in the constructed
172
+ /// slice
173
+ /// \param[in] length the length of the slice. If there are not enough
174
+ /// elements in the array, the length will be adjusted accordingly
175
+ ///
176
+ /// \return a new object wrapped in std::shared_ptr<Array>
177
+ std::shared_ptr<Array> Slice(int64_t offset, int64_t length) const;
178
+
179
+ /// Slice from offset until end of the array
180
+ std::shared_ptr<Array> Slice(int64_t offset) const;
181
+
182
+ /// Input-checking variant of Array::Slice
183
+ Result<std::shared_ptr<Array>> SliceSafe(int64_t offset, int64_t length) const;
184
+ /// Input-checking variant of Array::Slice
185
+ Result<std::shared_ptr<Array>> SliceSafe(int64_t offset) const;
186
+
187
+ const std::shared_ptr<ArrayData>& data() const { return data_; }
188
+
189
+ int num_fields() const { return static_cast<int>(data_->child_data.size()); }
190
+
191
+ /// \return PrettyPrint representation of array suitable for debugging
192
+ std::string ToString() const;
193
+
194
+ /// \brief Perform cheap validation checks to determine obvious inconsistencies
195
+ /// within the array's internal data.
196
+ ///
197
+ /// This is O(k) where k is the number of descendents.
198
+ ///
199
+ /// \return Status
200
+ Status Validate() const;
201
+
202
+ /// \brief Perform extensive validation checks to determine inconsistencies
203
+ /// within the array's internal data.
204
+ ///
205
+ /// This is potentially O(k*n) where k is the number of descendents and n
206
+ /// is the array length.
207
+ ///
208
+ /// \return Status
209
+ Status ValidateFull() const;
210
+
211
+ protected:
212
+ Array() = default;
213
+ ARROW_DEFAULT_MOVE_AND_ASSIGN(Array);
214
+
215
+ std::shared_ptr<ArrayData> data_;
216
+ const uint8_t* null_bitmap_data_ = NULLPTR;
217
+
218
+ /// Protected method for constructors
219
+ void SetData(const std::shared_ptr<ArrayData>& data) {
220
+ if (data->buffers.size() > 0) {
221
+ null_bitmap_data_ = data->GetValuesSafe<uint8_t>(0, /*offset=*/0);
222
+ } else {
223
+ null_bitmap_data_ = NULLPTR;
224
+ }
225
+ data_ = data;
226
+ }
227
+
228
+ private:
229
+ ARROW_DISALLOW_COPY_AND_ASSIGN(Array);
230
+
231
+ ARROW_FRIEND_EXPORT friend void PrintTo(const Array& x, std::ostream* os);
232
+ };
233
+
234
+ static inline std::ostream& operator<<(std::ostream& os, const Array& x) {
235
+ os << x.ToString();
236
+ return os;
237
+ }
238
+
239
+ /// Base class for non-nested arrays
240
+ class ARROW_EXPORT FlatArray : public Array {
241
+ protected:
242
+ using Array::Array;
243
+ };
244
+
245
+ /// Base class for arrays of fixed-size logical types
246
+ class ARROW_EXPORT PrimitiveArray : public FlatArray {
247
+ public:
248
+ PrimitiveArray(const std::shared_ptr<DataType>& type, int64_t length,
249
+ const std::shared_ptr<Buffer>& data,
250
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
251
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
252
+
253
+ /// Does not account for any slice offset
254
+ const std::shared_ptr<Buffer>& values() const { return data_->buffers[1]; }
255
+
256
+ protected:
257
+ PrimitiveArray() : raw_values_(NULLPTR) {}
258
+
259
+ void SetData(const std::shared_ptr<ArrayData>& data) {
260
+ this->Array::SetData(data);
261
+ raw_values_ = data->GetValuesSafe<uint8_t>(1, /*offset=*/0);
262
+ }
263
+
264
+ explicit PrimitiveArray(const std::shared_ptr<ArrayData>& data) { SetData(data); }
265
+
266
+ const uint8_t* raw_values_;
267
+ };
268
+
269
+ /// Degenerate null type Array
270
+ class ARROW_EXPORT NullArray : public FlatArray {
271
+ public:
272
+ using TypeClass = NullType;
273
+
274
+ explicit NullArray(const std::shared_ptr<ArrayData>& data) { SetData(data); }
275
+ explicit NullArray(int64_t length);
276
+
277
+ private:
278
+ void SetData(const std::shared_ptr<ArrayData>& data) {
279
+ null_bitmap_data_ = NULLPTR;
280
+ data->null_count = data->length;
281
+ data_ = data;
282
+ }
283
+ };
284
+
285
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_binary.h ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Array accessor classes for Binary, LargeBinart, String, LargeString,
19
+ // FixedSizeBinary
20
+
21
+ #pragma once
22
+
23
+ #include <cstdint>
24
+ #include <memory>
25
+ #include <optional>
26
+ #include <string>
27
+ #include <string_view>
28
+ #include <vector>
29
+
30
+ #include "arrow/array/array_base.h"
31
+ #include "arrow/array/data.h"
32
+ #include "arrow/buffer.h"
33
+ #include "arrow/stl_iterator.h"
34
+ #include "arrow/type.h"
35
+ #include "arrow/util/checked_cast.h"
36
+ #include "arrow/util/macros.h"
37
+ #include "arrow/util/visibility.h"
38
+
39
+ namespace arrow {
40
+
41
+ /// \addtogroup binary-arrays
42
+ ///
43
+ /// @{
44
+
45
+ // ----------------------------------------------------------------------
46
+ // Binary and String
47
+
48
+ /// Base class for variable-sized binary arrays, regardless of offset size
49
+ /// and logical interpretation.
50
+ template <typename TYPE>
51
+ class BaseBinaryArray : public FlatArray {
52
+ public:
53
+ using TypeClass = TYPE;
54
+ using offset_type = typename TypeClass::offset_type;
55
+ using IteratorType = stl::ArrayIterator<BaseBinaryArray<TYPE>>;
56
+
57
+ /// Return the pointer to the given elements bytes
58
+ // XXX should GetValue(int64_t i) return a string_view?
59
+ const uint8_t* GetValue(int64_t i, offset_type* out_length) const {
60
+ // Account for base offset
61
+ i += data_->offset;
62
+ const offset_type pos = raw_value_offsets_[i];
63
+ *out_length = raw_value_offsets_[i + 1] - pos;
64
+ return raw_data_ + pos;
65
+ }
66
+
67
+ /// \brief Get binary value as a string_view
68
+ ///
69
+ /// \param i the value index
70
+ /// \return the view over the selected value
71
+ std::string_view GetView(int64_t i) const {
72
+ // Account for base offset
73
+ i += data_->offset;
74
+ const offset_type pos = raw_value_offsets_[i];
75
+ return std::string_view(reinterpret_cast<const char*>(raw_data_ + pos),
76
+ raw_value_offsets_[i + 1] - pos);
77
+ }
78
+
79
+ std::optional<std::string_view> operator[](int64_t i) const {
80
+ return *IteratorType(*this, i);
81
+ }
82
+
83
+ /// \brief Get binary value as a string_view
84
+ /// Provided for consistency with other arrays.
85
+ ///
86
+ /// \param i the value index
87
+ /// \return the view over the selected value
88
+ std::string_view Value(int64_t i) const { return GetView(i); }
89
+
90
+ /// \brief Get binary value as a std::string
91
+ ///
92
+ /// \param i the value index
93
+ /// \return the value copied into a std::string
94
+ std::string GetString(int64_t i) const { return std::string(GetView(i)); }
95
+
96
+ /// Note that this buffer does not account for any slice offset
97
+ std::shared_ptr<Buffer> value_offsets() const { return data_->buffers[1]; }
98
+
99
+ /// Note that this buffer does not account for any slice offset
100
+ std::shared_ptr<Buffer> value_data() const { return data_->buffers[2]; }
101
+
102
+ const offset_type* raw_value_offsets() const {
103
+ return raw_value_offsets_ + data_->offset;
104
+ }
105
+
106
+ const uint8_t* raw_data() const { return raw_data_; }
107
+
108
+ /// \brief Return the data buffer absolute offset of the data for the value
109
+ /// at the passed index.
110
+ ///
111
+ /// Does not perform boundschecking
112
+ offset_type value_offset(int64_t i) const {
113
+ return raw_value_offsets_[i + data_->offset];
114
+ }
115
+
116
+ /// \brief Return the length of the data for the value at the passed index.
117
+ ///
118
+ /// Does not perform boundschecking
119
+ offset_type value_length(int64_t i) const {
120
+ i += data_->offset;
121
+ return raw_value_offsets_[i + 1] - raw_value_offsets_[i];
122
+ }
123
+
124
+ /// \brief Return the total length of the memory in the data buffer
125
+ /// referenced by this array. If the array has been sliced then this may be
126
+ /// less than the size of the data buffer (data_->buffers[2]).
127
+ offset_type total_values_length() const {
128
+ if (data_->length > 0) {
129
+ return raw_value_offsets_[data_->length + data_->offset] -
130
+ raw_value_offsets_[data_->offset];
131
+ } else {
132
+ return 0;
133
+ }
134
+ }
135
+
136
+ IteratorType begin() const { return IteratorType(*this); }
137
+
138
+ IteratorType end() const { return IteratorType(*this, length()); }
139
+
140
+ protected:
141
+ // For subclasses
142
+ BaseBinaryArray() = default;
143
+
144
+ // Protected method for constructors
145
+ void SetData(const std::shared_ptr<ArrayData>& data) {
146
+ this->Array::SetData(data);
147
+ raw_value_offsets_ = data->GetValuesSafe<offset_type>(1, /*offset=*/0);
148
+ raw_data_ = data->GetValuesSafe<uint8_t>(2, /*offset=*/0);
149
+ }
150
+
151
+ const offset_type* raw_value_offsets_ = NULLPTR;
152
+ const uint8_t* raw_data_ = NULLPTR;
153
+ };
154
+
155
+ /// Concrete Array class for variable-size binary data
156
+ class ARROW_EXPORT BinaryArray : public BaseBinaryArray<BinaryType> {
157
+ public:
158
+ explicit BinaryArray(const std::shared_ptr<ArrayData>& data);
159
+
160
+ BinaryArray(int64_t length, const std::shared_ptr<Buffer>& value_offsets,
161
+ const std::shared_ptr<Buffer>& data,
162
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
163
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
164
+
165
+ protected:
166
+ // For subclasses such as StringArray
167
+ BinaryArray() : BaseBinaryArray() {}
168
+ };
169
+
170
+ /// Concrete Array class for variable-size string (utf-8) data
171
+ class ARROW_EXPORT StringArray : public BinaryArray {
172
+ public:
173
+ using TypeClass = StringType;
174
+
175
+ explicit StringArray(const std::shared_ptr<ArrayData>& data);
176
+
177
+ StringArray(int64_t length, const std::shared_ptr<Buffer>& value_offsets,
178
+ const std::shared_ptr<Buffer>& data,
179
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
180
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
181
+
182
+ /// \brief Validate that this array contains only valid UTF8 entries
183
+ ///
184
+ /// This check is also implied by ValidateFull()
185
+ Status ValidateUTF8() const;
186
+ };
187
+
188
+ /// Concrete Array class for large variable-size binary data
189
+ class ARROW_EXPORT LargeBinaryArray : public BaseBinaryArray<LargeBinaryType> {
190
+ public:
191
+ explicit LargeBinaryArray(const std::shared_ptr<ArrayData>& data);
192
+
193
+ LargeBinaryArray(int64_t length, const std::shared_ptr<Buffer>& value_offsets,
194
+ const std::shared_ptr<Buffer>& data,
195
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
196
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
197
+
198
+ protected:
199
+ // For subclasses such as LargeStringArray
200
+ LargeBinaryArray() : BaseBinaryArray() {}
201
+ };
202
+
203
+ /// Concrete Array class for large variable-size string (utf-8) data
204
+ class ARROW_EXPORT LargeStringArray : public LargeBinaryArray {
205
+ public:
206
+ using TypeClass = LargeStringType;
207
+
208
+ explicit LargeStringArray(const std::shared_ptr<ArrayData>& data);
209
+
210
+ LargeStringArray(int64_t length, const std::shared_ptr<Buffer>& value_offsets,
211
+ const std::shared_ptr<Buffer>& data,
212
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
213
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
214
+
215
+ /// \brief Validate that this array contains only valid UTF8 entries
216
+ ///
217
+ /// This check is also implied by ValidateFull()
218
+ Status ValidateUTF8() const;
219
+ };
220
+
221
+ // ----------------------------------------------------------------------
222
+ // BinaryView and StringView
223
+
224
+ /// Concrete Array class for variable-size binary view data using the
225
+ /// BinaryViewType::c_type struct to reference in-line or out-of-line string values
226
+ class ARROW_EXPORT BinaryViewArray : public FlatArray {
227
+ public:
228
+ using TypeClass = BinaryViewType;
229
+ using IteratorType = stl::ArrayIterator<BinaryViewArray>;
230
+ using c_type = BinaryViewType::c_type;
231
+
232
+ explicit BinaryViewArray(std::shared_ptr<ArrayData> data);
233
+
234
+ BinaryViewArray(std::shared_ptr<DataType> type, int64_t length,
235
+ std::shared_ptr<Buffer> views, BufferVector data_buffers,
236
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
237
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
238
+
239
+ // For API compatibility with BinaryArray etc.
240
+ std::string_view GetView(int64_t i) const;
241
+ std::string GetString(int64_t i) const { return std::string{GetView(i)}; }
242
+
243
+ const auto& values() const { return data_->buffers[1]; }
244
+ const c_type* raw_values() const { return raw_values_; }
245
+
246
+ std::optional<std::string_view> operator[](int64_t i) const {
247
+ return *IteratorType(*this, i);
248
+ }
249
+
250
+ IteratorType begin() const { return IteratorType(*this); }
251
+ IteratorType end() const { return IteratorType(*this, length()); }
252
+
253
+ protected:
254
+ using FlatArray::FlatArray;
255
+
256
+ void SetData(std::shared_ptr<ArrayData> data) {
257
+ FlatArray::SetData(std::move(data));
258
+ raw_values_ = data_->GetValuesSafe<c_type>(1);
259
+ }
260
+
261
+ const c_type* raw_values_;
262
+ };
263
+
264
+ /// Concrete Array class for variable-size string view (utf-8) data using
265
+ /// BinaryViewType::c_type to reference in-line or out-of-line string values
266
+ class ARROW_EXPORT StringViewArray : public BinaryViewArray {
267
+ public:
268
+ using TypeClass = StringViewType;
269
+
270
+ explicit StringViewArray(std::shared_ptr<ArrayData> data);
271
+
272
+ using BinaryViewArray::BinaryViewArray;
273
+
274
+ /// \brief Validate that this array contains only valid UTF8 entries
275
+ ///
276
+ /// This check is also implied by ValidateFull()
277
+ Status ValidateUTF8() const;
278
+ };
279
+
280
+ // ----------------------------------------------------------------------
281
+ // Fixed width binary
282
+
283
+ /// Concrete Array class for fixed-size binary data
284
+ class ARROW_EXPORT FixedSizeBinaryArray : public PrimitiveArray {
285
+ public:
286
+ using TypeClass = FixedSizeBinaryType;
287
+ using IteratorType = stl::ArrayIterator<FixedSizeBinaryArray>;
288
+
289
+ explicit FixedSizeBinaryArray(const std::shared_ptr<ArrayData>& data);
290
+
291
+ FixedSizeBinaryArray(const std::shared_ptr<DataType>& type, int64_t length,
292
+ const std::shared_ptr<Buffer>& data,
293
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
294
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
295
+
296
+ const uint8_t* GetValue(int64_t i) const;
297
+ const uint8_t* Value(int64_t i) const { return GetValue(i); }
298
+
299
+ std::string_view GetView(int64_t i) const {
300
+ return std::string_view(reinterpret_cast<const char*>(GetValue(i)), byte_width());
301
+ }
302
+
303
+ std::optional<std::string_view> operator[](int64_t i) const {
304
+ return *IteratorType(*this, i);
305
+ }
306
+
307
+ std::string GetString(int64_t i) const { return std::string(GetView(i)); }
308
+
309
+ int32_t byte_width() const { return byte_width_; }
310
+
311
+ const uint8_t* raw_values() const { return raw_values_ + data_->offset * byte_width_; }
312
+
313
+ IteratorType begin() const { return IteratorType(*this); }
314
+
315
+ IteratorType end() const { return IteratorType(*this, length()); }
316
+
317
+ protected:
318
+ void SetData(const std::shared_ptr<ArrayData>& data) {
319
+ this->PrimitiveArray::SetData(data);
320
+ byte_width_ =
321
+ internal::checked_cast<const FixedSizeBinaryType&>(*type()).byte_width();
322
+ }
323
+
324
+ int32_t byte_width_;
325
+ };
326
+
327
+ /// @}
328
+
329
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_decimal.h ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+ #include <string>
23
+
24
+ #include "arrow/array/array_binary.h"
25
+ #include "arrow/array/data.h"
26
+ #include "arrow/type.h"
27
+ #include "arrow/util/visibility.h"
28
+
29
+ namespace arrow {
30
+
31
+ /// \addtogroup numeric-arrays
32
+ ///
33
+ /// @{
34
+
35
+ // ----------------------------------------------------------------------
36
+ // Decimal128Array
37
+
38
+ /// Concrete Array class for 128-bit decimal data
39
+ class ARROW_EXPORT Decimal128Array : public FixedSizeBinaryArray {
40
+ public:
41
+ using TypeClass = Decimal128Type;
42
+
43
+ using FixedSizeBinaryArray::FixedSizeBinaryArray;
44
+
45
+ /// \brief Construct Decimal128Array from ArrayData instance
46
+ explicit Decimal128Array(const std::shared_ptr<ArrayData>& data);
47
+
48
+ std::string FormatValue(int64_t i) const;
49
+ };
50
+
51
+ // Backward compatibility
52
+ using DecimalArray = Decimal128Array;
53
+
54
+ // ----------------------------------------------------------------------
55
+ // Decimal256Array
56
+
57
+ /// Concrete Array class for 256-bit decimal data
58
+ class ARROW_EXPORT Decimal256Array : public FixedSizeBinaryArray {
59
+ public:
60
+ using TypeClass = Decimal256Type;
61
+
62
+ using FixedSizeBinaryArray::FixedSizeBinaryArray;
63
+
64
+ /// \brief Construct Decimal256Array from ArrayData instance
65
+ explicit Decimal256Array(const std::shared_ptr<ArrayData>& data);
66
+
67
+ std::string FormatValue(int64_t i) const;
68
+ };
69
+
70
+ /// @}
71
+
72
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_dict.h ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+
23
+ #include "arrow/array/array_base.h"
24
+ #include "arrow/array/data.h"
25
+ #include "arrow/result.h"
26
+ #include "arrow/status.h"
27
+ #include "arrow/type.h"
28
+ #include "arrow/util/macros.h"
29
+ #include "arrow/util/visibility.h"
30
+
31
+ namespace arrow {
32
+
33
+ // ----------------------------------------------------------------------
34
+ // DictionaryArray
35
+
36
+ /// \brief Array type for dictionary-encoded data with a
37
+ /// data-dependent dictionary
38
+ ///
39
+ /// A dictionary array contains an array of non-negative integers (the
40
+ /// "dictionary indices") along with a data type containing a "dictionary"
41
+ /// corresponding to the distinct values represented in the data.
42
+ ///
43
+ /// For example, the array
44
+ ///
45
+ /// ["foo", "bar", "foo", "bar", "foo", "bar"]
46
+ ///
47
+ /// with dictionary ["bar", "foo"], would have dictionary array representation
48
+ ///
49
+ /// indices: [1, 0, 1, 0, 1, 0]
50
+ /// dictionary: ["bar", "foo"]
51
+ ///
52
+ /// The indices in principle may be any integer type.
53
+ class ARROW_EXPORT DictionaryArray : public Array {
54
+ public:
55
+ using TypeClass = DictionaryType;
56
+
57
+ explicit DictionaryArray(const std::shared_ptr<ArrayData>& data);
58
+
59
+ DictionaryArray(const std::shared_ptr<DataType>& type,
60
+ const std::shared_ptr<Array>& indices,
61
+ const std::shared_ptr<Array>& dictionary);
62
+
63
+ /// \brief Construct DictionaryArray from dictionary and indices
64
+ /// array and validate
65
+ ///
66
+ /// This function does the validation of the indices and input type. It checks if
67
+ /// all indices are non-negative and smaller than the size of the dictionary.
68
+ ///
69
+ /// \param[in] type a dictionary type
70
+ /// \param[in] dictionary the dictionary with same value type as the
71
+ /// type object
72
+ /// \param[in] indices an array of non-negative integers smaller than the
73
+ /// size of the dictionary
74
+ static Result<std::shared_ptr<Array>> FromArrays(
75
+ const std::shared_ptr<DataType>& type, const std::shared_ptr<Array>& indices,
76
+ const std::shared_ptr<Array>& dictionary);
77
+
78
+ static Result<std::shared_ptr<Array>> FromArrays(
79
+ const std::shared_ptr<Array>& indices, const std::shared_ptr<Array>& dictionary) {
80
+ return FromArrays(::arrow::dictionary(indices->type(), dictionary->type()), indices,
81
+ dictionary);
82
+ }
83
+
84
+ /// \brief Transpose this DictionaryArray
85
+ ///
86
+ /// This method constructs a new dictionary array with the given dictionary
87
+ /// type, transposing indices using the transpose map. The type and the
88
+ /// transpose map are typically computed using DictionaryUnifier.
89
+ ///
90
+ /// \param[in] type the new type object
91
+ /// \param[in] dictionary the new dictionary
92
+ /// \param[in] transpose_map transposition array of this array's indices
93
+ /// into the target array's indices
94
+ /// \param[in] pool a pool to allocate the array data from
95
+ Result<std::shared_ptr<Array>> Transpose(
96
+ const std::shared_ptr<DataType>& type, const std::shared_ptr<Array>& dictionary,
97
+ const int32_t* transpose_map, MemoryPool* pool = default_memory_pool()) const;
98
+
99
+ Result<std::shared_ptr<Array>> Compact(MemoryPool* pool = default_memory_pool()) const;
100
+
101
+ /// \brief Determine whether dictionary arrays may be compared without unification
102
+ bool CanCompareIndices(const DictionaryArray& other) const;
103
+
104
+ /// \brief Return the dictionary for this array, which is stored as
105
+ /// a member of the ArrayData internal structure
106
+ const std::shared_ptr<Array>& dictionary() const;
107
+ const std::shared_ptr<Array>& indices() const;
108
+
109
+ /// \brief Return the ith value of indices, cast to int64_t. Not recommended
110
+ /// for use in performance-sensitive code. Does not validate whether the
111
+ /// value is null or out-of-bounds.
112
+ int64_t GetValueIndex(int64_t i) const;
113
+
114
+ const DictionaryType* dict_type() const { return dict_type_; }
115
+
116
+ private:
117
+ void SetData(const std::shared_ptr<ArrayData>& data);
118
+ const DictionaryType* dict_type_;
119
+ std::shared_ptr<Array> indices_;
120
+
121
+ // Lazily initialized when invoking dictionary()
122
+ mutable std::shared_ptr<Array> dictionary_;
123
+ };
124
+
125
+ /// \brief Helper class for incremental dictionary unification
126
+ class ARROW_EXPORT DictionaryUnifier {
127
+ public:
128
+ virtual ~DictionaryUnifier() = default;
129
+
130
+ /// \brief Construct a DictionaryUnifier
131
+ /// \param[in] value_type the data type of the dictionaries
132
+ /// \param[in] pool MemoryPool to use for memory allocations
133
+ static Result<std::unique_ptr<DictionaryUnifier>> Make(
134
+ std::shared_ptr<DataType> value_type, MemoryPool* pool = default_memory_pool());
135
+
136
+ /// \brief Unify dictionaries accross array chunks
137
+ ///
138
+ /// The dictionaries in the array chunks will be unified, their indices
139
+ /// accordingly transposed.
140
+ ///
141
+ /// Only dictionaries with a primitive value type are currently supported.
142
+ /// However, dictionaries nested inside a more complex type are correctly unified.
143
+ static Result<std::shared_ptr<ChunkedArray>> UnifyChunkedArray(
144
+ const std::shared_ptr<ChunkedArray>& array,
145
+ MemoryPool* pool = default_memory_pool());
146
+
147
+ /// \brief Unify dictionaries accross the chunks of each table column
148
+ ///
149
+ /// The dictionaries in each table column will be unified, their indices
150
+ /// accordingly transposed.
151
+ ///
152
+ /// Only dictionaries with a primitive value type are currently supported.
153
+ /// However, dictionaries nested inside a more complex type are correctly unified.
154
+ static Result<std::shared_ptr<Table>> UnifyTable(
155
+ const Table& table, MemoryPool* pool = default_memory_pool());
156
+
157
+ /// \brief Append dictionary to the internal memo
158
+ virtual Status Unify(const Array& dictionary) = 0;
159
+
160
+ /// \brief Append dictionary and compute transpose indices
161
+ /// \param[in] dictionary the dictionary values to unify
162
+ /// \param[out] out_transpose a Buffer containing computed transpose indices
163
+ /// as int32_t values equal in length to the passed dictionary. The value in
164
+ /// each slot corresponds to the new index value for each original index
165
+ /// for a DictionaryArray with the old dictionary
166
+ virtual Status Unify(const Array& dictionary,
167
+ std::shared_ptr<Buffer>* out_transpose) = 0;
168
+
169
+ /// \brief Return a result DictionaryType with the smallest possible index
170
+ /// type to accommodate the unified dictionary. The unifier cannot be used
171
+ /// after this is called
172
+ virtual Status GetResult(std::shared_ptr<DataType>* out_type,
173
+ std::shared_ptr<Array>* out_dict) = 0;
174
+
175
+ /// \brief Return a unified dictionary with the given index type. If
176
+ /// the index type is not large enough then an invalid status will be returned.
177
+ /// The unifier cannot be used after this is called
178
+ virtual Status GetResultWithIndexType(const std::shared_ptr<DataType>& index_type,
179
+ std::shared_ptr<Array>* out_dict) = 0;
180
+ };
181
+
182
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_nested.h ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Array accessor classes for List, LargeList, ListView, LargeListView, FixedSizeList,
19
+ // Map, Struct, and Union
20
+
21
+ #pragma once
22
+
23
+ #include <cstdint>
24
+ #include <memory>
25
+ #include <string>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ #include "arrow/array/array_base.h"
30
+ #include "arrow/array/data.h"
31
+ #include "arrow/result.h"
32
+ #include "arrow/status.h"
33
+ #include "arrow/type.h"
34
+ #include "arrow/type_fwd.h"
35
+ #include "arrow/util/checked_cast.h"
36
+ #include "arrow/util/macros.h"
37
+ #include "arrow/util/visibility.h"
38
+
39
+ namespace arrow {
40
+
41
+ /// \addtogroup nested-arrays
42
+ ///
43
+ /// @{
44
+
45
+ // ----------------------------------------------------------------------
46
+ // VarLengthListLikeArray
47
+
48
+ template <typename TYPE>
49
+ class VarLengthListLikeArray;
50
+
51
+ namespace internal {
52
+
53
+ // Private helper for [Large]List[View]Array::SetData.
54
+ // Unfortunately, trying to define VarLengthListLikeArray::SetData outside of this header
55
+ // doesn't play well with MSVC.
56
+ template <typename TYPE>
57
+ void SetListData(VarLengthListLikeArray<TYPE>* self,
58
+ const std::shared_ptr<ArrayData>& data,
59
+ Type::type expected_type_id = TYPE::type_id);
60
+
61
+ } // namespace internal
62
+
63
+ /// Base class for variable-sized list and list-view arrays, regardless of offset size.
64
+ template <typename TYPE>
65
+ class VarLengthListLikeArray : public Array {
66
+ public:
67
+ using TypeClass = TYPE;
68
+ using offset_type = typename TypeClass::offset_type;
69
+
70
+ const TypeClass* var_length_list_like_type() const { return this->list_type_; }
71
+
72
+ /// \brief Return array object containing the list's values
73
+ ///
74
+ /// Note that this buffer does not account for any slice offset or length.
75
+ const std::shared_ptr<Array>& values() const { return values_; }
76
+
77
+ /// Note that this buffer does not account for any slice offset or length.
78
+ const std::shared_ptr<Buffer>& value_offsets() const { return data_->buffers[1]; }
79
+
80
+ const std::shared_ptr<DataType>& value_type() const { return list_type_->value_type(); }
81
+
82
+ /// Return pointer to raw value offsets accounting for any slice offset
83
+ const offset_type* raw_value_offsets() const {
84
+ return raw_value_offsets_ + data_->offset;
85
+ }
86
+
87
+ // The following functions will not perform boundschecking
88
+
89
+ offset_type value_offset(int64_t i) const {
90
+ return raw_value_offsets_[i + data_->offset];
91
+ }
92
+
93
+ /// \brief Return the size of the value at a particular index
94
+ ///
95
+ /// Since non-empty null lists and list-views are possible, avoid calling this
96
+ /// function when the list at slot i is null.
97
+ ///
98
+ /// \pre IsValid(i)
99
+ virtual offset_type value_length(int64_t i) const = 0;
100
+
101
+ /// \pre IsValid(i)
102
+ std::shared_ptr<Array> value_slice(int64_t i) const {
103
+ return values_->Slice(value_offset(i), value_length(i));
104
+ }
105
+
106
+ protected:
107
+ friend void internal::SetListData<TYPE>(VarLengthListLikeArray<TYPE>* self,
108
+ const std::shared_ptr<ArrayData>& data,
109
+ Type::type expected_type_id);
110
+
111
+ const TypeClass* list_type_ = NULLPTR;
112
+ std::shared_ptr<Array> values_;
113
+ const offset_type* raw_value_offsets_ = NULLPTR;
114
+ };
115
+
116
+ // ----------------------------------------------------------------------
117
+ // ListArray / LargeListArray
118
+
119
+ template <typename TYPE>
120
+ class BaseListArray : public VarLengthListLikeArray<TYPE> {
121
+ public:
122
+ using TypeClass = TYPE;
123
+ using offset_type = typename TYPE::offset_type;
124
+
125
+ const TypeClass* list_type() const { return this->var_length_list_like_type(); }
126
+
127
+ /// \brief Return the size of the value at a particular index
128
+ ///
129
+ /// Since non-empty null lists are possible, avoid calling this
130
+ /// function when the list at slot i is null.
131
+ ///
132
+ /// \pre IsValid(i)
133
+ offset_type value_length(int64_t i) const final {
134
+ i += this->data_->offset;
135
+ return this->raw_value_offsets_[i + 1] - this->raw_value_offsets_[i];
136
+ }
137
+ };
138
+
139
+ /// Concrete Array class for list data
140
+ class ARROW_EXPORT ListArray : public BaseListArray<ListType> {
141
+ public:
142
+ explicit ListArray(std::shared_ptr<ArrayData> data);
143
+
144
+ ListArray(std::shared_ptr<DataType> type, int64_t length,
145
+ std::shared_ptr<Buffer> value_offsets, std::shared_ptr<Array> values,
146
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
147
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
148
+
149
+ /// \brief Construct ListArray from array of offsets and child value array
150
+ ///
151
+ /// This function does the bare minimum of validation of the offsets and
152
+ /// input types, and will allocate a new offsets array if necessary (i.e. if
153
+ /// the offsets contain any nulls). If the offsets do not have nulls, they
154
+ /// are assumed to be well-formed.
155
+ ///
156
+ /// If a null_bitmap is not provided, the nulls will be inferred from the offsets'
157
+ /// null bitmap. But if a null_bitmap is provided, the offsets array can't have nulls.
158
+ ///
159
+ /// And when a null_bitmap is provided, the offsets array cannot be a slice (i.e. an
160
+ /// array with offset() > 0).
161
+ ///
162
+ /// \param[in] offsets Array containing n + 1 offsets encoding length and
163
+ /// size. Must be of int32 type
164
+ /// \param[in] values Array containing list values
165
+ /// \param[in] pool MemoryPool in case new offsets array needs to be
166
+ /// allocated because of null values
167
+ /// \param[in] null_bitmap Optional validity bitmap
168
+ /// \param[in] null_count Optional null count in null_bitmap
169
+ static Result<std::shared_ptr<ListArray>> FromArrays(
170
+ const Array& offsets, const Array& values, MemoryPool* pool = default_memory_pool(),
171
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
172
+ int64_t null_count = kUnknownNullCount);
173
+
174
+ static Result<std::shared_ptr<ListArray>> FromArrays(
175
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& values,
176
+ MemoryPool* pool = default_memory_pool(),
177
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
178
+ int64_t null_count = kUnknownNullCount);
179
+
180
+ /// \brief Build a ListArray from a ListViewArray
181
+ static Result<std::shared_ptr<ListArray>> FromListView(const ListViewArray& source,
182
+ MemoryPool* pool);
183
+
184
+ /// \brief Return an Array that is a concatenation of the lists in this array.
185
+ ///
186
+ /// Note that it's different from `values()` in that it takes into
187
+ /// consideration of this array's offsets as well as null elements backed
188
+ /// by non-empty lists (they are skipped, thus copying may be needed).
189
+ Result<std::shared_ptr<Array>> Flatten(
190
+ MemoryPool* memory_pool = default_memory_pool()) const;
191
+
192
+ /// \brief Return list offsets as an Int32Array
193
+ ///
194
+ /// The returned array will not have a validity bitmap, so you cannot expect
195
+ /// to pass it to ListArray::FromArrays() and get back the same list array
196
+ /// if the original one has nulls.
197
+ std::shared_ptr<Array> offsets() const;
198
+
199
+ protected:
200
+ // This constructor defers SetData to a derived array class
201
+ ListArray() = default;
202
+
203
+ void SetData(const std::shared_ptr<ArrayData>& data);
204
+ };
205
+
206
+ /// Concrete Array class for large list data (with 64-bit offsets)
207
+ class ARROW_EXPORT LargeListArray : public BaseListArray<LargeListType> {
208
+ public:
209
+ explicit LargeListArray(const std::shared_ptr<ArrayData>& data);
210
+
211
+ LargeListArray(const std::shared_ptr<DataType>& type, int64_t length,
212
+ const std::shared_ptr<Buffer>& value_offsets,
213
+ const std::shared_ptr<Array>& values,
214
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
215
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
216
+
217
+ /// \brief Construct LargeListArray from array of offsets and child value array
218
+ ///
219
+ /// This function does the bare minimum of validation of the offsets and
220
+ /// input types, and will allocate a new offsets array if necessary (i.e. if
221
+ /// the offsets contain any nulls). If the offsets do not have nulls, they
222
+ /// are assumed to be well-formed.
223
+ ///
224
+ /// If a null_bitmap is not provided, the nulls will be inferred from the offsets'
225
+ /// null bitmap. But if a null_bitmap is provided, the offsets array can't have nulls.
226
+ ///
227
+ /// And when a null_bitmap is provided, the offsets array cannot be a slice (i.e. an
228
+ /// array with offset() > 0).
229
+ ///
230
+ /// \param[in] offsets Array containing n + 1 offsets encoding length and
231
+ /// size. Must be of int64 type
232
+ /// \param[in] values Array containing list values
233
+ /// \param[in] pool MemoryPool in case new offsets array needs to be
234
+ /// allocated because of null values
235
+ /// \param[in] null_bitmap Optional validity bitmap
236
+ /// \param[in] null_count Optional null count in null_bitmap
237
+ static Result<std::shared_ptr<LargeListArray>> FromArrays(
238
+ const Array& offsets, const Array& values, MemoryPool* pool = default_memory_pool(),
239
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
240
+ int64_t null_count = kUnknownNullCount);
241
+
242
+ static Result<std::shared_ptr<LargeListArray>> FromArrays(
243
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& values,
244
+ MemoryPool* pool = default_memory_pool(),
245
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
246
+ int64_t null_count = kUnknownNullCount);
247
+
248
+ /// \brief Build a LargeListArray from a LargeListViewArray
249
+ static Result<std::shared_ptr<LargeListArray>> FromListView(
250
+ const LargeListViewArray& source, MemoryPool* pool);
251
+
252
+ /// \brief Return an Array that is a concatenation of the lists in this array.
253
+ ///
254
+ /// Note that it's different from `values()` in that it takes into
255
+ /// consideration of this array's offsets as well as null elements backed
256
+ /// by non-empty lists (they are skipped, thus copying may be needed).
257
+ Result<std::shared_ptr<Array>> Flatten(
258
+ MemoryPool* memory_pool = default_memory_pool()) const;
259
+
260
+ /// \brief Return list offsets as an Int64Array
261
+ std::shared_ptr<Array> offsets() const;
262
+
263
+ protected:
264
+ void SetData(const std::shared_ptr<ArrayData>& data);
265
+ };
266
+
267
+ // ----------------------------------------------------------------------
268
+ // ListViewArray / LargeListViewArray
269
+
270
+ template <typename TYPE>
271
+ class BaseListViewArray : public VarLengthListLikeArray<TYPE> {
272
+ public:
273
+ using TypeClass = TYPE;
274
+ using offset_type = typename TYPE::offset_type;
275
+
276
+ const TypeClass* list_view_type() const { return this->var_length_list_like_type(); }
277
+
278
+ /// \brief Note that this buffer does not account for any slice offset or length.
279
+ const std::shared_ptr<Buffer>& value_sizes() const { return this->data_->buffers[2]; }
280
+
281
+ /// \brief Return pointer to raw value offsets accounting for any slice offset
282
+ const offset_type* raw_value_sizes() const {
283
+ return raw_value_sizes_ + this->data_->offset;
284
+ }
285
+
286
+ /// \brief Return the size of the value at a particular index
287
+ ///
288
+ /// This should not be called if the list-view at slot i is null.
289
+ /// The returned size in those cases could be any value from 0 to the
290
+ /// length of the child values array.
291
+ ///
292
+ /// \pre IsValid(i)
293
+ offset_type value_length(int64_t i) const final {
294
+ return this->raw_value_sizes_[i + this->data_->offset];
295
+ }
296
+
297
+ protected:
298
+ const offset_type* raw_value_sizes_ = NULLPTR;
299
+ };
300
+
301
+ /// \brief Concrete Array class for list-view data
302
+ class ARROW_EXPORT ListViewArray : public BaseListViewArray<ListViewType> {
303
+ public:
304
+ explicit ListViewArray(std::shared_ptr<ArrayData> data);
305
+
306
+ ListViewArray(std::shared_ptr<DataType> type, int64_t length,
307
+ std::shared_ptr<Buffer> value_offsets,
308
+ std::shared_ptr<Buffer> value_sizes, std::shared_ptr<Array> values,
309
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
310
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
311
+
312
+ /// \brief Construct ListViewArray from array of offsets, sizes, and child
313
+ /// value array
314
+ ///
315
+ /// Construct a ListViewArray using buffers from offsets and sizes arrays
316
+ /// that project views into the child values array.
317
+ ///
318
+ /// This function does the bare minimum of validation of the offsets/sizes and
319
+ /// input types. The offset and length of the offsets and sizes arrays must
320
+ /// match and that will be checked, but their contents will be assumed to be
321
+ /// well-formed.
322
+ ///
323
+ /// If a null_bitmap is not provided, the nulls will be inferred from the
324
+ /// offsets's null bitmap. But if a null_bitmap is provided, the offsets array
325
+ /// can't have nulls.
326
+ ///
327
+ /// And when a null_bitmap is provided, neither the offsets or sizes array can be a
328
+ /// slice (i.e. an array with offset() > 0).
329
+ ///
330
+ /// \param[in] offsets An array of int32 offsets into the values array. NULL values are
331
+ /// supported if the corresponding values in sizes is NULL or 0.
332
+ /// \param[in] sizes An array containing the int32 sizes of every view. NULL values are
333
+ /// taken to represent a NULL list-view in the array being created.
334
+ /// \param[in] values Array containing list values
335
+ /// \param[in] pool MemoryPool
336
+ /// \param[in] null_bitmap Optional validity bitmap
337
+ /// \param[in] null_count Optional null count in null_bitmap
338
+ static Result<std::shared_ptr<ListViewArray>> FromArrays(
339
+ const Array& offsets, const Array& sizes, const Array& values,
340
+ MemoryPool* pool = default_memory_pool(),
341
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
342
+ int64_t null_count = kUnknownNullCount);
343
+
344
+ static Result<std::shared_ptr<ListViewArray>> FromArrays(
345
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& sizes,
346
+ const Array& values, MemoryPool* pool = default_memory_pool(),
347
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
348
+ int64_t null_count = kUnknownNullCount);
349
+
350
+ /// \brief Build a ListViewArray from a ListArray
351
+ static Result<std::shared_ptr<ListViewArray>> FromList(const ListArray& list_array,
352
+ MemoryPool* pool);
353
+
354
+ /// \brief Return an Array that is a concatenation of the list-views in this array.
355
+ ///
356
+ /// Note that it's different from `values()` in that it takes into
357
+ /// consideration this array's offsets (which can be in any order)
358
+ /// and sizes. Nulls are skipped.
359
+ ///
360
+ /// This function invokes Concatenate() if list-views are non-contiguous. It
361
+ /// will try to minimize the number of array slices passed to Concatenate() by
362
+ /// maximizing the size of each slice (containing as many contiguous
363
+ /// list-views as possible).
364
+ Result<std::shared_ptr<Array>> Flatten(
365
+ MemoryPool* memory_pool = default_memory_pool()) const;
366
+
367
+ /// \brief Return list-view offsets as an Int32Array
368
+ ///
369
+ /// The returned array will not have a validity bitmap, so you cannot expect
370
+ /// to pass it to ListArray::FromArrays() and get back the same list array
371
+ /// if the original one has nulls.
372
+ std::shared_ptr<Array> offsets() const;
373
+
374
+ /// \brief Return list-view sizes as an Int32Array
375
+ ///
376
+ /// The returned array will not have a validity bitmap, so you cannot expect
377
+ /// to pass it to ListViewArray::FromArrays() and get back the same list
378
+ /// array if the original one has nulls.
379
+ std::shared_ptr<Array> sizes() const;
380
+
381
+ protected:
382
+ // This constructor defers SetData to a derived array class
383
+ ListViewArray() = default;
384
+
385
+ void SetData(const std::shared_ptr<ArrayData>& data);
386
+ };
387
+
388
+ /// \brief Concrete Array class for large list-view data (with 64-bit offsets
389
+ /// and sizes)
390
+ class ARROW_EXPORT LargeListViewArray : public BaseListViewArray<LargeListViewType> {
391
+ public:
392
+ explicit LargeListViewArray(std::shared_ptr<ArrayData> data);
393
+
394
+ LargeListViewArray(std::shared_ptr<DataType> type, int64_t length,
395
+ std::shared_ptr<Buffer> value_offsets,
396
+ std::shared_ptr<Buffer> value_sizes, std::shared_ptr<Array> values,
397
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
398
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
399
+
400
+ /// \brief Construct LargeListViewArray from array of offsets, sizes, and child
401
+ /// value array
402
+ ///
403
+ /// Construct an LargeListViewArray using buffers from offsets and sizes arrays
404
+ /// that project views into the values array.
405
+ ///
406
+ /// This function does the bare minimum of validation of the offsets/sizes and
407
+ /// input types. The offset and length of the offsets and sizes arrays must
408
+ /// match and that will be checked, but their contents will be assumed to be
409
+ /// well-formed.
410
+ ///
411
+ /// If a null_bitmap is not provided, the nulls will be inferred from the offsets' or
412
+ /// sizes' null bitmap. Only one of these two is allowed to have a null bitmap. But if a
413
+ /// null_bitmap is provided, the offsets array and the sizes array can't have nulls.
414
+ ///
415
+ /// And when a null_bitmap is provided, neither the offsets or sizes array can be a
416
+ /// slice (i.e. an array with offset() > 0).
417
+ ///
418
+ /// \param[in] offsets An array of int64 offsets into the values array. NULL values are
419
+ /// supported if the corresponding values in sizes is NULL or 0.
420
+ /// \param[in] sizes An array containing the int64 sizes of every view. NULL values are
421
+ /// taken to represent a NULL list-view in the array being created.
422
+ /// \param[in] values Array containing list values
423
+ /// \param[in] pool MemoryPool
424
+ /// \param[in] null_bitmap Optional validity bitmap
425
+ /// \param[in] null_count Optional null count in null_bitmap
426
+ static Result<std::shared_ptr<LargeListViewArray>> FromArrays(
427
+ const Array& offsets, const Array& sizes, const Array& values,
428
+ MemoryPool* pool = default_memory_pool(),
429
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
430
+ int64_t null_count = kUnknownNullCount);
431
+
432
+ static Result<std::shared_ptr<LargeListViewArray>> FromArrays(
433
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& sizes,
434
+ const Array& values, MemoryPool* pool = default_memory_pool(),
435
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
436
+ int64_t null_count = kUnknownNullCount);
437
+
438
+ /// \brief Build a LargeListViewArray from a LargeListArray
439
+ static Result<std::shared_ptr<LargeListViewArray>> FromList(
440
+ const LargeListArray& list_array, MemoryPool* pool);
441
+
442
+ /// \brief Return an Array that is a concatenation of the large list-views in this
443
+ /// array.
444
+ ///
445
+ /// Note that it's different from `values()` in that it takes into
446
+ /// consideration this array's offsets (which can be in any order)
447
+ /// and sizes. Nulls are skipped.
448
+ Result<std::shared_ptr<Array>> Flatten(
449
+ MemoryPool* memory_pool = default_memory_pool()) const;
450
+
451
+ /// \brief Return list-view offsets as an Int64Array
452
+ ///
453
+ /// The returned array will not have a validity bitmap, so you cannot expect
454
+ /// to pass it to LargeListArray::FromArrays() and get back the same list array
455
+ /// if the original one has nulls.
456
+ std::shared_ptr<Array> offsets() const;
457
+
458
+ /// \brief Return list-view sizes as an Int64Array
459
+ ///
460
+ /// The returned array will not have a validity bitmap, so you cannot expect
461
+ /// to pass it to LargeListViewArray::FromArrays() and get back the same list
462
+ /// array if the original one has nulls.
463
+ std::shared_ptr<Array> sizes() const;
464
+
465
+ protected:
466
+ // This constructor defers SetData to a derived array class
467
+ LargeListViewArray() = default;
468
+
469
+ void SetData(const std::shared_ptr<ArrayData>& data);
470
+ };
471
+
472
+ // ----------------------------------------------------------------------
473
+ // MapArray
474
+
475
+ /// Concrete Array class for map data
476
+ ///
477
+ /// NB: "value" in this context refers to a pair of a key and the corresponding item
478
+ class ARROW_EXPORT MapArray : public ListArray {
479
+ public:
480
+ using TypeClass = MapType;
481
+
482
+ explicit MapArray(const std::shared_ptr<ArrayData>& data);
483
+
484
+ MapArray(const std::shared_ptr<DataType>& type, int64_t length,
485
+ const std::shared_ptr<Buffer>& value_offsets,
486
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
487
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
488
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
489
+
490
+ MapArray(const std::shared_ptr<DataType>& type, int64_t length, BufferVector buffers,
491
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
492
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
493
+
494
+ MapArray(const std::shared_ptr<DataType>& type, int64_t length,
495
+ const std::shared_ptr<Buffer>& value_offsets,
496
+ const std::shared_ptr<Array>& values,
497
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
498
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
499
+
500
+ /// \brief Construct MapArray from array of offsets and child key, item arrays
501
+ ///
502
+ /// This function does the bare minimum of validation of the offsets and
503
+ /// input types, and will allocate a new offsets array if necessary (i.e. if
504
+ /// the offsets contain any nulls). If the offsets do not have nulls, they
505
+ /// are assumed to be well-formed
506
+ ///
507
+ /// \param[in] offsets Array containing n + 1 offsets encoding length and
508
+ /// size. Must be of int32 type
509
+ /// \param[in] keys Array containing key values
510
+ /// \param[in] items Array containing item values
511
+ /// \param[in] pool MemoryPool in case new offsets array needs to be
512
+ /// allocated because of null values
513
+ static Result<std::shared_ptr<Array>> FromArrays(
514
+ const std::shared_ptr<Array>& offsets, const std::shared_ptr<Array>& keys,
515
+ const std::shared_ptr<Array>& items, MemoryPool* pool = default_memory_pool());
516
+
517
+ static Result<std::shared_ptr<Array>> FromArrays(
518
+ std::shared_ptr<DataType> type, const std::shared_ptr<Array>& offsets,
519
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
520
+ MemoryPool* pool = default_memory_pool());
521
+
522
+ const MapType* map_type() const { return map_type_; }
523
+
524
+ /// \brief Return array object containing all map keys
525
+ const std::shared_ptr<Array>& keys() const { return keys_; }
526
+
527
+ /// \brief Return array object containing all mapped items
528
+ const std::shared_ptr<Array>& items() const { return items_; }
529
+
530
+ /// Validate child data before constructing the actual MapArray.
531
+ static Status ValidateChildData(
532
+ const std::vector<std::shared_ptr<ArrayData>>& child_data);
533
+
534
+ protected:
535
+ void SetData(const std::shared_ptr<ArrayData>& data);
536
+
537
+ static Result<std::shared_ptr<Array>> FromArraysInternal(
538
+ std::shared_ptr<DataType> type, const std::shared_ptr<Array>& offsets,
539
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
540
+ MemoryPool* pool);
541
+
542
+ private:
543
+ const MapType* map_type_;
544
+ std::shared_ptr<Array> keys_, items_;
545
+ };
546
+
547
+ // ----------------------------------------------------------------------
548
+ // FixedSizeListArray
549
+
550
+ /// Concrete Array class for fixed size list data
551
+ class ARROW_EXPORT FixedSizeListArray : public Array {
552
+ public:
553
+ using TypeClass = FixedSizeListType;
554
+ using offset_type = TypeClass::offset_type;
555
+
556
+ explicit FixedSizeListArray(const std::shared_ptr<ArrayData>& data);
557
+
558
+ FixedSizeListArray(const std::shared_ptr<DataType>& type, int64_t length,
559
+ const std::shared_ptr<Array>& values,
560
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
561
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
562
+
563
+ const FixedSizeListType* list_type() const;
564
+
565
+ /// \brief Return array object containing the list's values
566
+ const std::shared_ptr<Array>& values() const;
567
+
568
+ const std::shared_ptr<DataType>& value_type() const;
569
+
570
+ // The following functions will not perform boundschecking
571
+ int64_t value_offset(int64_t i) const {
572
+ i += data_->offset;
573
+ return list_size_ * i;
574
+ }
575
+ /// \brief Return the fixed-size of the values
576
+ ///
577
+ /// No matter the value of the index parameter, the result is the same.
578
+ /// So even when the value at slot i is null, this function will return a
579
+ /// non-zero size.
580
+ ///
581
+ /// \pre IsValid(i)
582
+ int32_t value_length(int64_t i = 0) const {
583
+ ARROW_UNUSED(i);
584
+ return list_size_;
585
+ }
586
+ /// \pre IsValid(i)
587
+ std::shared_ptr<Array> value_slice(int64_t i) const {
588
+ return values_->Slice(value_offset(i), value_length(i));
589
+ }
590
+
591
+ /// \brief Return an Array that is a concatenation of the lists in this array.
592
+ ///
593
+ /// Note that it's different from `values()` in that it takes into
594
+ /// consideration null elements (they are skipped, thus copying may be needed).
595
+ Result<std::shared_ptr<Array>> Flatten(
596
+ MemoryPool* memory_pool = default_memory_pool()) const;
597
+
598
+ /// \brief Construct FixedSizeListArray from child value array and value_length
599
+ ///
600
+ /// \param[in] values Array containing list values
601
+ /// \param[in] list_size The fixed length of each list
602
+ /// \param[in] null_bitmap Optional validity bitmap
603
+ /// \param[in] null_count Optional null count in null_bitmap
604
+ /// \return Will have length equal to values.length() / list_size
605
+ static Result<std::shared_ptr<Array>> FromArrays(
606
+ const std::shared_ptr<Array>& values, int32_t list_size,
607
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
608
+ int64_t null_count = kUnknownNullCount);
609
+
610
+ /// \brief Construct FixedSizeListArray from child value array and type
611
+ ///
612
+ /// \param[in] values Array containing list values
613
+ /// \param[in] type The fixed sized list type
614
+ /// \param[in] null_bitmap Optional validity bitmap
615
+ /// \param[in] null_count Optional null count in null_bitmap
616
+ /// \return Will have length equal to values.length() / type.list_size()
617
+ static Result<std::shared_ptr<Array>> FromArrays(
618
+ const std::shared_ptr<Array>& values, std::shared_ptr<DataType> type,
619
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
620
+ int64_t null_count = kUnknownNullCount);
621
+
622
+ protected:
623
+ void SetData(const std::shared_ptr<ArrayData>& data);
624
+ int32_t list_size_;
625
+
626
+ private:
627
+ std::shared_ptr<Array> values_;
628
+ };
629
+
630
+ // ----------------------------------------------------------------------
631
+ // Struct
632
+
633
+ /// Concrete Array class for struct data
634
+ class ARROW_EXPORT StructArray : public Array {
635
+ public:
636
+ using TypeClass = StructType;
637
+
638
+ explicit StructArray(const std::shared_ptr<ArrayData>& data);
639
+
640
+ StructArray(const std::shared_ptr<DataType>& type, int64_t length,
641
+ const std::vector<std::shared_ptr<Array>>& children,
642
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
643
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
644
+
645
+ /// \brief Return a StructArray from child arrays and field names.
646
+ ///
647
+ /// The length and data type are automatically inferred from the arguments.
648
+ /// There should be at least one child array.
649
+ static Result<std::shared_ptr<StructArray>> Make(
650
+ const ArrayVector& children, const std::vector<std::string>& field_names,
651
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
652
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
653
+
654
+ /// \brief Return a StructArray from child arrays and fields.
655
+ ///
656
+ /// The length is automatically inferred from the arguments.
657
+ /// There should be at least one child array. This method does not
658
+ /// check that field types and child array types are consistent.
659
+ static Result<std::shared_ptr<StructArray>> Make(
660
+ const ArrayVector& children, const FieldVector& fields,
661
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
662
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
663
+
664
+ const StructType* struct_type() const;
665
+
666
+ // Return a shared pointer in case the requestor desires to share ownership
667
+ // with this array. The returned array has its offset, length and null
668
+ // count adjusted.
669
+ const std::shared_ptr<Array>& field(int pos) const;
670
+
671
+ const ArrayVector& fields() const;
672
+
673
+ /// Returns null if name not found
674
+ std::shared_ptr<Array> GetFieldByName(const std::string& name) const;
675
+
676
+ /// Indicate if field named `name` can be found unambiguously in the struct.
677
+ Status CanReferenceFieldByName(const std::string& name) const;
678
+
679
+ /// Indicate if fields named `names` can be found unambiguously in the struct.
680
+ Status CanReferenceFieldsByNames(const std::vector<std::string>& names) const;
681
+
682
+ /// \brief Flatten this array as a vector of arrays, one for each field
683
+ ///
684
+ /// \param[in] pool The pool to allocate null bitmaps from, if necessary
685
+ Result<ArrayVector> Flatten(MemoryPool* pool = default_memory_pool()) const;
686
+
687
+ /// \brief Get one of the child arrays, combining its null bitmap
688
+ /// with the parent struct array's bitmap.
689
+ ///
690
+ /// \param[in] index Which child array to get
691
+ /// \param[in] pool The pool to allocate null bitmaps from, if necessary
692
+ Result<std::shared_ptr<Array>> GetFlattenedField(
693
+ int index, MemoryPool* pool = default_memory_pool()) const;
694
+
695
+ private:
696
+ // For caching boxed child data
697
+ // XXX This is not handled in a thread-safe manner.
698
+ mutable ArrayVector boxed_fields_;
699
+ };
700
+
701
+ // ----------------------------------------------------------------------
702
+ // Union
703
+
704
+ /// Base class for SparseUnionArray and DenseUnionArray
705
+ class ARROW_EXPORT UnionArray : public Array {
706
+ public:
707
+ using type_code_t = int8_t;
708
+
709
+ /// Note that this buffer does not account for any slice offset
710
+ const std::shared_ptr<Buffer>& type_codes() const { return data_->buffers[1]; }
711
+
712
+ const type_code_t* raw_type_codes() const { return raw_type_codes_ + data_->offset; }
713
+
714
+ /// The logical type code of the value at index.
715
+ type_code_t type_code(int64_t i) const { return raw_type_codes_[i + data_->offset]; }
716
+
717
+ /// The physical child id containing value at index.
718
+ int child_id(int64_t i) const {
719
+ return union_type_->child_ids()[raw_type_codes_[i + data_->offset]];
720
+ }
721
+
722
+ const UnionType* union_type() const { return union_type_; }
723
+
724
+ UnionMode::type mode() const { return union_type_->mode(); }
725
+
726
+ /// \brief Return the given field as an individual array.
727
+ ///
728
+ /// For sparse unions, the returned array has its offset, length and null
729
+ /// count adjusted.
730
+ std::shared_ptr<Array> field(int pos) const;
731
+
732
+ protected:
733
+ void SetData(std::shared_ptr<ArrayData> data);
734
+
735
+ const type_code_t* raw_type_codes_;
736
+ const UnionType* union_type_;
737
+
738
+ // For caching boxed child data
739
+ mutable std::vector<std::shared_ptr<Array>> boxed_fields_;
740
+ };
741
+
742
+ /// Concrete Array class for sparse union data
743
+ class ARROW_EXPORT SparseUnionArray : public UnionArray {
744
+ public:
745
+ using TypeClass = SparseUnionType;
746
+
747
+ explicit SparseUnionArray(std::shared_ptr<ArrayData> data);
748
+
749
+ SparseUnionArray(std::shared_ptr<DataType> type, int64_t length, ArrayVector children,
750
+ std::shared_ptr<Buffer> type_ids, int64_t offset = 0);
751
+
752
+ /// \brief Construct SparseUnionArray from type_ids and children
753
+ ///
754
+ /// This function does the bare minimum of validation of the input types.
755
+ ///
756
+ /// \param[in] type_ids An array of logical type ids for the union type
757
+ /// \param[in] children Vector of children Arrays containing the data for each type.
758
+ /// \param[in] type_codes Vector of type codes.
759
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids, ArrayVector children,
760
+ std::vector<type_code_t> type_codes) {
761
+ return Make(std::move(type_ids), std::move(children), std::vector<std::string>{},
762
+ std::move(type_codes));
763
+ }
764
+
765
+ /// \brief Construct SparseUnionArray with custom field names from type_ids and children
766
+ ///
767
+ /// This function does the bare minimum of validation of the input types.
768
+ ///
769
+ /// \param[in] type_ids An array of logical type ids for the union type
770
+ /// \param[in] children Vector of children Arrays containing the data for each type.
771
+ /// \param[in] field_names Vector of strings containing the name of each field.
772
+ /// \param[in] type_codes Vector of type codes.
773
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids, ArrayVector children,
774
+ std::vector<std::string> field_names = {},
775
+ std::vector<type_code_t> type_codes = {});
776
+
777
+ const SparseUnionType* union_type() const {
778
+ return internal::checked_cast<const SparseUnionType*>(union_type_);
779
+ }
780
+
781
+ /// \brief Get one of the child arrays, adjusting its null bitmap
782
+ /// where the union array type code does not match.
783
+ ///
784
+ /// \param[in] index Which child array to get (i.e. the physical index, not the type
785
+ /// code) \param[in] pool The pool to allocate null bitmaps from, if necessary
786
+ Result<std::shared_ptr<Array>> GetFlattenedField(
787
+ int index, MemoryPool* pool = default_memory_pool()) const;
788
+
789
+ protected:
790
+ void SetData(std::shared_ptr<ArrayData> data);
791
+ };
792
+
793
+ /// \brief Concrete Array class for dense union data
794
+ ///
795
+ /// Note that union types do not have a validity bitmap
796
+ class ARROW_EXPORT DenseUnionArray : public UnionArray {
797
+ public:
798
+ using TypeClass = DenseUnionType;
799
+
800
+ explicit DenseUnionArray(const std::shared_ptr<ArrayData>& data);
801
+
802
+ DenseUnionArray(std::shared_ptr<DataType> type, int64_t length, ArrayVector children,
803
+ std::shared_ptr<Buffer> type_ids,
804
+ std::shared_ptr<Buffer> value_offsets = NULLPTR, int64_t offset = 0);
805
+
806
+ /// \brief Construct DenseUnionArray from type_ids, value_offsets, and children
807
+ ///
808
+ /// This function does the bare minimum of validation of the offsets and
809
+ /// input types.
810
+ ///
811
+ /// \param[in] type_ids An array of logical type ids for the union type
812
+ /// \param[in] value_offsets An array of signed int32 values indicating the
813
+ /// relative offset into the respective child array for the type in a given slot.
814
+ /// The respective offsets for each child value array must be in order / increasing.
815
+ /// \param[in] children Vector of children Arrays containing the data for each type.
816
+ /// \param[in] type_codes Vector of type codes.
817
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids,
818
+ const Array& value_offsets,
819
+ ArrayVector children,
820
+ std::vector<type_code_t> type_codes) {
821
+ return Make(type_ids, value_offsets, std::move(children), std::vector<std::string>{},
822
+ std::move(type_codes));
823
+ }
824
+
825
+ /// \brief Construct DenseUnionArray with custom field names from type_ids,
826
+ /// value_offsets, and children
827
+ ///
828
+ /// This function does the bare minimum of validation of the offsets and
829
+ /// input types.
830
+ ///
831
+ /// \param[in] type_ids An array of logical type ids for the union type
832
+ /// \param[in] value_offsets An array of signed int32 values indicating the
833
+ /// relative offset into the respective child array for the type in a given slot.
834
+ /// The respective offsets for each child value array must be in order / increasing.
835
+ /// \param[in] children Vector of children Arrays containing the data for each type.
836
+ /// \param[in] field_names Vector of strings containing the name of each field.
837
+ /// \param[in] type_codes Vector of type codes.
838
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids,
839
+ const Array& value_offsets,
840
+ ArrayVector children,
841
+ std::vector<std::string> field_names = {},
842
+ std::vector<type_code_t> type_codes = {});
843
+
844
+ const DenseUnionType* union_type() const {
845
+ return internal::checked_cast<const DenseUnionType*>(union_type_);
846
+ }
847
+
848
+ /// Note that this buffer does not account for any slice offset
849
+ const std::shared_ptr<Buffer>& value_offsets() const { return data_->buffers[2]; }
850
+
851
+ int32_t value_offset(int64_t i) const { return raw_value_offsets_[i + data_->offset]; }
852
+
853
+ const int32_t* raw_value_offsets() const { return raw_value_offsets_ + data_->offset; }
854
+
855
+ protected:
856
+ const int32_t* raw_value_offsets_;
857
+
858
+ void SetData(const std::shared_ptr<ArrayData>& data);
859
+ };
860
+
861
+ /// @}
862
+
863
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_primitive.h ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Array accessor types for primitive/C-type-based arrays, such as numbers,
19
+ // boolean, and temporal types.
20
+
21
+ #pragma once
22
+
23
+ #include <cstdint>
24
+ #include <memory>
25
+
26
+ #include "arrow/array/array_base.h"
27
+ #include "arrow/array/data.h"
28
+ #include "arrow/stl_iterator.h"
29
+ #include "arrow/type.h"
30
+ #include "arrow/type_fwd.h" // IWYU pragma: export
31
+ #include "arrow/type_traits.h"
32
+ #include "arrow/util/bit_util.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ /// Concrete Array class for boolean data
39
+ class ARROW_EXPORT BooleanArray : public PrimitiveArray {
40
+ public:
41
+ using TypeClass = BooleanType;
42
+ using IteratorType = stl::ArrayIterator<BooleanArray>;
43
+
44
+ explicit BooleanArray(const std::shared_ptr<ArrayData>& data);
45
+
46
+ BooleanArray(int64_t length, const std::shared_ptr<Buffer>& data,
47
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
48
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
49
+
50
+ bool Value(int64_t i) const {
51
+ return bit_util::GetBit(reinterpret_cast<const uint8_t*>(raw_values_),
52
+ i + data_->offset);
53
+ }
54
+
55
+ bool GetView(int64_t i) const { return Value(i); }
56
+
57
+ std::optional<bool> operator[](int64_t i) const { return *IteratorType(*this, i); }
58
+
59
+ /// \brief Return the number of false (0) values among the valid
60
+ /// values. Result is not cached.
61
+ int64_t false_count() const;
62
+
63
+ /// \brief Return the number of true (1) values among the valid
64
+ /// values. Result is not cached.
65
+ int64_t true_count() const;
66
+
67
+ IteratorType begin() const { return IteratorType(*this); }
68
+
69
+ IteratorType end() const { return IteratorType(*this, length()); }
70
+
71
+ protected:
72
+ using PrimitiveArray::PrimitiveArray;
73
+ };
74
+
75
+ /// \addtogroup numeric-arrays
76
+ ///
77
+ /// @{
78
+
79
+ /// \brief Concrete Array class for numeric data with a corresponding C type
80
+ ///
81
+ /// This class is templated on the corresponding DataType subclass for the
82
+ /// given data, for example NumericArray<Int8Type> or NumericArray<Date32Type>.
83
+ ///
84
+ /// Note that convenience aliases are available for all accepted types
85
+ /// (for example Int8Array for NumericArray<Int8Type>).
86
+ template <typename TYPE>
87
+ class NumericArray : public PrimitiveArray {
88
+ public:
89
+ using TypeClass = TYPE;
90
+ using value_type = typename TypeClass::c_type;
91
+ using IteratorType = stl::ArrayIterator<NumericArray<TYPE>>;
92
+
93
+ explicit NumericArray(const std::shared_ptr<ArrayData>& data) : PrimitiveArray(data) {}
94
+
95
+ // Only enable this constructor without a type argument for types without additional
96
+ // metadata
97
+ template <typename T1 = TYPE>
98
+ NumericArray(enable_if_parameter_free<T1, int64_t> length,
99
+ const std::shared_ptr<Buffer>& data,
100
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
101
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0)
102
+ : PrimitiveArray(TypeTraits<T1>::type_singleton(), length, data, null_bitmap,
103
+ null_count, offset) {}
104
+
105
+ const value_type* raw_values() const {
106
+ return reinterpret_cast<const value_type*>(raw_values_) + data_->offset;
107
+ }
108
+
109
+ value_type Value(int64_t i) const { return raw_values()[i]; }
110
+
111
+ // For API compatibility with BinaryArray etc.
112
+ value_type GetView(int64_t i) const { return Value(i); }
113
+
114
+ std::optional<value_type> operator[](int64_t i) const {
115
+ return *IteratorType(*this, i);
116
+ }
117
+
118
+ IteratorType begin() const { return IteratorType(*this); }
119
+
120
+ IteratorType end() const { return IteratorType(*this, length()); }
121
+
122
+ protected:
123
+ using PrimitiveArray::PrimitiveArray;
124
+ };
125
+
126
+ /// DayTimeArray
127
+ /// ---------------------
128
+ /// \brief Array of Day and Millisecond values.
129
+ class ARROW_EXPORT DayTimeIntervalArray : public PrimitiveArray {
130
+ public:
131
+ using TypeClass = DayTimeIntervalType;
132
+ using IteratorType = stl::ArrayIterator<DayTimeIntervalArray>;
133
+
134
+ explicit DayTimeIntervalArray(const std::shared_ptr<ArrayData>& data);
135
+
136
+ DayTimeIntervalArray(const std::shared_ptr<DataType>& type, int64_t length,
137
+ const std::shared_ptr<Buffer>& data,
138
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
139
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
140
+
141
+ DayTimeIntervalArray(int64_t length, const std::shared_ptr<Buffer>& data,
142
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
143
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
144
+
145
+ TypeClass::DayMilliseconds GetValue(int64_t i) const;
146
+ TypeClass::DayMilliseconds Value(int64_t i) const { return GetValue(i); }
147
+
148
+ // For compatibility with Take kernel.
149
+ TypeClass::DayMilliseconds GetView(int64_t i) const { return GetValue(i); }
150
+
151
+ IteratorType begin() const { return IteratorType(*this); }
152
+
153
+ IteratorType end() const { return IteratorType(*this, length()); }
154
+
155
+ std::optional<TypeClass::DayMilliseconds> operator[](int64_t i) const {
156
+ return *IteratorType(*this, i);
157
+ }
158
+
159
+ int32_t byte_width() const { return sizeof(TypeClass::DayMilliseconds); }
160
+
161
+ const uint8_t* raw_values() const { return raw_values_ + data_->offset * byte_width(); }
162
+ };
163
+
164
+ /// \brief Array of Month, Day and nanosecond values.
165
+ class ARROW_EXPORT MonthDayNanoIntervalArray : public PrimitiveArray {
166
+ public:
167
+ using TypeClass = MonthDayNanoIntervalType;
168
+ using IteratorType = stl::ArrayIterator<MonthDayNanoIntervalArray>;
169
+
170
+ explicit MonthDayNanoIntervalArray(const std::shared_ptr<ArrayData>& data);
171
+
172
+ MonthDayNanoIntervalArray(const std::shared_ptr<DataType>& type, int64_t length,
173
+ const std::shared_ptr<Buffer>& data,
174
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
175
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
176
+
177
+ MonthDayNanoIntervalArray(int64_t length, const std::shared_ptr<Buffer>& data,
178
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
179
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
180
+
181
+ TypeClass::MonthDayNanos GetValue(int64_t i) const;
182
+ TypeClass::MonthDayNanos Value(int64_t i) const { return GetValue(i); }
183
+
184
+ // For compatibility with Take kernel.
185
+ TypeClass::MonthDayNanos GetView(int64_t i) const { return GetValue(i); }
186
+
187
+ IteratorType begin() const { return IteratorType(*this); }
188
+
189
+ IteratorType end() const { return IteratorType(*this, length()); }
190
+
191
+ std::optional<TypeClass::MonthDayNanos> operator[](int64_t i) const {
192
+ return *IteratorType(*this, i);
193
+ }
194
+
195
+ int32_t byte_width() const { return sizeof(TypeClass::MonthDayNanos); }
196
+
197
+ const uint8_t* raw_values() const { return raw_values_ + data_->offset * byte_width(); }
198
+ };
199
+
200
+ /// @}
201
+
202
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_run_end.h ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Array accessor classes run-end encoded arrays
19
+
20
+ #pragma once
21
+
22
+ #include <cstdint>
23
+ #include <memory>
24
+ #include <string>
25
+ #include <utility>
26
+ #include <vector>
27
+
28
+ #include "arrow/array/array_base.h"
29
+ #include "arrow/array/data.h"
30
+ #include "arrow/result.h"
31
+ #include "arrow/status.h"
32
+ #include "arrow/type.h"
33
+ #include "arrow/type_fwd.h"
34
+ #include "arrow/util/checked_cast.h"
35
+ #include "arrow/util/macros.h"
36
+ #include "arrow/util/visibility.h"
37
+
38
+ namespace arrow {
39
+
40
+ /// \addtogroup run-end-encoded-arrays
41
+ ///
42
+ /// @{
43
+
44
+ // ----------------------------------------------------------------------
45
+ // RunEndEncoded
46
+
47
+ /// \brief Array type for run-end encoded data
48
+ class ARROW_EXPORT RunEndEncodedArray : public Array {
49
+ private:
50
+ std::shared_ptr<Array> run_ends_array_;
51
+ std::shared_ptr<Array> values_array_;
52
+
53
+ public:
54
+ using TypeClass = RunEndEncodedType;
55
+
56
+ explicit RunEndEncodedArray(const std::shared_ptr<ArrayData>& data);
57
+
58
+ /// \brief Construct a RunEndEncodedArray from all parameters
59
+ ///
60
+ /// The length and offset parameters refer to the dimensions of the logical
61
+ /// array which is the array we would get after expanding all the runs into
62
+ /// repeated values. As such, length can be much greater than the lenght of
63
+ /// the child run_ends and values arrays.
64
+ RunEndEncodedArray(const std::shared_ptr<DataType>& type, int64_t length,
65
+ const std::shared_ptr<Array>& run_ends,
66
+ const std::shared_ptr<Array>& values, int64_t offset = 0);
67
+
68
+ /// \brief Construct a RunEndEncodedArray from all parameters
69
+ ///
70
+ /// The length and offset parameters refer to the dimensions of the logical
71
+ /// array which is the array we would get after expanding all the runs into
72
+ /// repeated values. As such, length can be much greater than the lenght of
73
+ /// the child run_ends and values arrays.
74
+ static Result<std::shared_ptr<RunEndEncodedArray>> Make(
75
+ const std::shared_ptr<DataType>& type, int64_t logical_length,
76
+ const std::shared_ptr<Array>& run_ends, const std::shared_ptr<Array>& values,
77
+ int64_t logical_offset = 0);
78
+
79
+ /// \brief Construct a RunEndEncodedArray from values and run ends arrays
80
+ ///
81
+ /// The data type is automatically inferred from the arguments.
82
+ /// The run_ends and values arrays must have the same length.
83
+ static Result<std::shared_ptr<RunEndEncodedArray>> Make(
84
+ int64_t logical_length, const std::shared_ptr<Array>& run_ends,
85
+ const std::shared_ptr<Array>& values, int64_t logical_offset = 0);
86
+
87
+ protected:
88
+ void SetData(const std::shared_ptr<ArrayData>& data);
89
+
90
+ public:
91
+ /// \brief Returns an array holding the logical indexes of each run-end
92
+ ///
93
+ /// The physical offset to the array is applied.
94
+ const std::shared_ptr<Array>& run_ends() const { return run_ends_array_; }
95
+
96
+ /// \brief Returns an array holding the values of each run
97
+ ///
98
+ /// The physical offset to the array is applied.
99
+ const std::shared_ptr<Array>& values() const { return values_array_; }
100
+
101
+ /// \brief Returns an array holding the logical indexes of each run end
102
+ ///
103
+ /// If a non-zero logical offset is set, this function allocates a new
104
+ /// array and rewrites all the run end values to be relative to the logical
105
+ /// offset and cuts the end of the array to the logical length.
106
+ Result<std::shared_ptr<Array>> LogicalRunEnds(MemoryPool* pool) const;
107
+
108
+ /// \brief Returns an array holding the values of each run
109
+ ///
110
+ /// If a non-zero logical offset is set, this function allocates a new
111
+ /// array containing only the values within the logical range.
112
+ std::shared_ptr<Array> LogicalValues() const;
113
+
114
+ /// \brief Find the physical offset of this REE array
115
+ ///
116
+ /// This function uses binary-search, so it has a O(log N) cost.
117
+ int64_t FindPhysicalOffset() const;
118
+
119
+ /// \brief Find the physical length of this REE array
120
+ ///
121
+ /// The physical length of an REE is the number of physical values (and
122
+ /// run-ends) necessary to represent the logical range of values from offset
123
+ /// to length.
124
+ ///
125
+ /// Avoid calling this function if the physical length can be estabilished in
126
+ /// some other way (e.g. when iterating over the runs sequentially until the
127
+ /// end). This function uses binary-search, so it has a O(log N) cost.
128
+ int64_t FindPhysicalLength() const;
129
+ };
130
+
131
+ /// @}
132
+
133
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_adaptive.h ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <cstring>
22
+ #include <memory>
23
+ #include <type_traits>
24
+
25
+ #include "arrow/array/builder_base.h"
26
+ #include "arrow/buffer.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+ #include "arrow/util/macros.h"
30
+ #include "arrow/util/visibility.h"
31
+
32
+ namespace arrow {
33
+
34
+ /// \addtogroup numeric-builders
35
+ ///
36
+ /// @{
37
+
38
+ namespace internal {
39
+
40
+ class ARROW_EXPORT AdaptiveIntBuilderBase : public ArrayBuilder {
41
+ public:
42
+ AdaptiveIntBuilderBase(uint8_t start_int_size, MemoryPool* pool,
43
+ int64_t alignment = kDefaultBufferAlignment);
44
+
45
+ explicit AdaptiveIntBuilderBase(MemoryPool* pool,
46
+ int64_t alignment = kDefaultBufferAlignment)
47
+ : AdaptiveIntBuilderBase(sizeof(uint8_t), pool, alignment) {}
48
+
49
+ /// \brief Append multiple nulls
50
+ /// \param[in] length the number of nulls to append
51
+ Status AppendNulls(int64_t length) final {
52
+ ARROW_RETURN_NOT_OK(CommitPendingData());
53
+ if (ARROW_PREDICT_TRUE(length > 0)) {
54
+ ARROW_RETURN_NOT_OK(Reserve(length));
55
+ memset(data_->mutable_data() + length_ * int_size_, 0, int_size_ * length);
56
+ UnsafeSetNull(length);
57
+ }
58
+ return Status::OK();
59
+ }
60
+
61
+ Status AppendNull() final {
62
+ pending_data_[pending_pos_] = 0;
63
+ pending_valid_[pending_pos_] = 0;
64
+ pending_has_nulls_ = true;
65
+ ++pending_pos_;
66
+ ++length_;
67
+ ++null_count_;
68
+
69
+ if (ARROW_PREDICT_FALSE(pending_pos_ >= pending_size_)) {
70
+ return CommitPendingData();
71
+ }
72
+ return Status::OK();
73
+ }
74
+
75
+ Status AppendEmptyValues(int64_t length) final {
76
+ ARROW_RETURN_NOT_OK(CommitPendingData());
77
+ if (ARROW_PREDICT_TRUE(length > 0)) {
78
+ ARROW_RETURN_NOT_OK(Reserve(length));
79
+ memset(data_->mutable_data() + length_ * int_size_, 0, int_size_ * length);
80
+ UnsafeSetNotNull(length);
81
+ }
82
+ return Status::OK();
83
+ }
84
+
85
+ Status AppendEmptyValue() final {
86
+ pending_data_[pending_pos_] = 0;
87
+ pending_valid_[pending_pos_] = 1;
88
+ ++pending_pos_;
89
+ ++length_;
90
+
91
+ if (ARROW_PREDICT_FALSE(pending_pos_ >= pending_size_)) {
92
+ return CommitPendingData();
93
+ }
94
+ return Status::OK();
95
+ }
96
+
97
+ void Reset() override;
98
+ Status Resize(int64_t capacity) override;
99
+
100
+ protected:
101
+ Status AppendInternal(const uint64_t val) {
102
+ pending_data_[pending_pos_] = val;
103
+ pending_valid_[pending_pos_] = 1;
104
+ ++pending_pos_;
105
+ ++length_;
106
+
107
+ if (ARROW_PREDICT_FALSE(pending_pos_ >= pending_size_)) {
108
+ return CommitPendingData();
109
+ }
110
+ return Status::OK();
111
+ }
112
+
113
+ virtual Status CommitPendingData() = 0;
114
+
115
+ template <typename new_type, typename old_type>
116
+ typename std::enable_if<sizeof(old_type) >= sizeof(new_type), Status>::type
117
+ ExpandIntSizeInternal();
118
+ template <typename new_type, typename old_type>
119
+ typename std::enable_if<(sizeof(old_type) < sizeof(new_type)), Status>::type
120
+ ExpandIntSizeInternal();
121
+
122
+ std::shared_ptr<ResizableBuffer> data_;
123
+ uint8_t* raw_data_ = NULLPTR;
124
+
125
+ const uint8_t start_int_size_;
126
+ uint8_t int_size_;
127
+
128
+ static constexpr int32_t pending_size_ = 1024;
129
+ uint8_t pending_valid_[pending_size_];
130
+ uint64_t pending_data_[pending_size_];
131
+ int32_t pending_pos_ = 0;
132
+ bool pending_has_nulls_ = false;
133
+ };
134
+
135
+ } // namespace internal
136
+
137
+ class ARROW_EXPORT AdaptiveUIntBuilder : public internal::AdaptiveIntBuilderBase {
138
+ public:
139
+ explicit AdaptiveUIntBuilder(uint8_t start_int_size,
140
+ MemoryPool* pool = default_memory_pool());
141
+
142
+ explicit AdaptiveUIntBuilder(MemoryPool* pool = default_memory_pool())
143
+ : AdaptiveUIntBuilder(sizeof(uint8_t), pool) {}
144
+
145
+ using internal::AdaptiveIntBuilderBase::Reset;
146
+
147
+ /// Scalar append
148
+ Status Append(const uint64_t val) { return AppendInternal(val); }
149
+
150
+ /// \brief Append a sequence of elements in one shot
151
+ /// \param[in] values a contiguous C array of values
152
+ /// \param[in] length the number of values to append
153
+ /// \param[in] valid_bytes an optional sequence of bytes where non-zero
154
+ /// indicates a valid (non-null) value
155
+ /// \return Status
156
+ Status AppendValues(const uint64_t* values, int64_t length,
157
+ const uint8_t* valid_bytes = NULLPTR);
158
+
159
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
160
+
161
+ std::shared_ptr<DataType> type() const override;
162
+
163
+ protected:
164
+ Status CommitPendingData() override;
165
+ Status ExpandIntSize(uint8_t new_int_size);
166
+
167
+ Status AppendValuesInternal(const uint64_t* values, int64_t length,
168
+ const uint8_t* valid_bytes);
169
+
170
+ template <typename new_type>
171
+ Status ExpandIntSizeN();
172
+ };
173
+
174
+ class ARROW_EXPORT AdaptiveIntBuilder : public internal::AdaptiveIntBuilderBase {
175
+ public:
176
+ explicit AdaptiveIntBuilder(uint8_t start_int_size,
177
+ MemoryPool* pool = default_memory_pool(),
178
+ int64_t alignment = kDefaultBufferAlignment);
179
+
180
+ explicit AdaptiveIntBuilder(MemoryPool* pool = default_memory_pool(),
181
+ int64_t alignment = kDefaultBufferAlignment)
182
+ : AdaptiveIntBuilder(sizeof(uint8_t), pool, alignment) {}
183
+
184
+ using internal::AdaptiveIntBuilderBase::Reset;
185
+
186
+ /// Scalar append
187
+ Status Append(const int64_t val) { return AppendInternal(static_cast<uint64_t>(val)); }
188
+
189
+ /// \brief Append a sequence of elements in one shot
190
+ /// \param[in] values a contiguous C array of values
191
+ /// \param[in] length the number of values to append
192
+ /// \param[in] valid_bytes an optional sequence of bytes where non-zero
193
+ /// indicates a valid (non-null) value
194
+ /// \return Status
195
+ Status AppendValues(const int64_t* values, int64_t length,
196
+ const uint8_t* valid_bytes = NULLPTR);
197
+
198
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
199
+
200
+ std::shared_ptr<DataType> type() const override;
201
+
202
+ protected:
203
+ Status CommitPendingData() override;
204
+ Status ExpandIntSize(uint8_t new_int_size);
205
+
206
+ Status AppendValuesInternal(const int64_t* values, int64_t length,
207
+ const uint8_t* valid_bytes);
208
+
209
+ template <typename new_type>
210
+ Status ExpandIntSizeN();
211
+ };
212
+
213
+ /// @}
214
+
215
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_base.h ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <algorithm> // IWYU pragma: keep
21
+ #include <cstdint>
22
+ #include <limits>
23
+ #include <memory>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #include "arrow/array/array_base.h"
28
+ #include "arrow/array/array_primitive.h"
29
+ #include "arrow/buffer.h"
30
+ #include "arrow/buffer_builder.h"
31
+ #include "arrow/result.h"
32
+ #include "arrow/status.h"
33
+ #include "arrow/type_fwd.h"
34
+ #include "arrow/util/macros.h"
35
+ #include "arrow/util/visibility.h"
36
+
37
+ namespace arrow {
38
+
39
+ namespace internal {
40
+
41
+ template <class Builder, class V>
42
+ class ArrayBuilderExtraOps {
43
+ public:
44
+ /// \brief Append a value from an optional or null if it has no value.
45
+ Status AppendOrNull(const std::optional<V>& value) {
46
+ auto* self = static_cast<Builder*>(this);
47
+ return value.has_value() ? self->Append(*value) : self->AppendNull();
48
+ }
49
+
50
+ /// \brief Append a value from an optional or null if it has no value.
51
+ ///
52
+ /// Unsafe methods don't check existing size.
53
+ void UnsafeAppendOrNull(const std::optional<V>& value) {
54
+ auto* self = static_cast<Builder*>(this);
55
+ return value.has_value() ? self->UnsafeAppend(*value) : self->UnsafeAppendNull();
56
+ }
57
+ };
58
+
59
+ } // namespace internal
60
+
61
+ /// \defgroup numeric-builders Concrete builder subclasses for numeric types
62
+ /// @{
63
+ /// @}
64
+
65
+ /// \defgroup temporal-builders Concrete builder subclasses for temporal types
66
+ /// @{
67
+ /// @}
68
+
69
+ /// \defgroup binary-builders Concrete builder subclasses for binary types
70
+ /// @{
71
+ /// @}
72
+
73
+ /// \defgroup nested-builders Concrete builder subclasses for nested types
74
+ /// @{
75
+ /// @}
76
+
77
+ /// \defgroup dictionary-builders Concrete builder subclasses for dictionary types
78
+ /// @{
79
+ /// @}
80
+
81
+ /// \defgroup run-end-encoded-builders Concrete builder subclasses for run-end encoded
82
+ /// arrays
83
+ /// @{
84
+ /// @}
85
+
86
+ constexpr int64_t kMinBuilderCapacity = 1 << 5;
87
+ constexpr int64_t kListMaximumElements = std::numeric_limits<int32_t>::max() - 1;
88
+
89
+ /// Base class for all data array builders.
90
+ ///
91
+ /// This class provides a facilities for incrementally building the null bitmap
92
+ /// (see Append methods) and as a side effect the current number of slots and
93
+ /// the null count.
94
+ ///
95
+ /// \note Users are expected to use builders as one of the concrete types below.
96
+ /// For example, ArrayBuilder* pointing to BinaryBuilder should be downcast before use.
97
+ class ARROW_EXPORT ArrayBuilder {
98
+ public:
99
+ explicit ArrayBuilder(MemoryPool* pool, int64_t alignment = kDefaultBufferAlignment)
100
+ : pool_(pool), alignment_(alignment), null_bitmap_builder_(pool, alignment) {}
101
+
102
+ ARROW_DEFAULT_MOVE_AND_ASSIGN(ArrayBuilder);
103
+
104
+ virtual ~ArrayBuilder() = default;
105
+
106
+ /// For nested types. Since the objects are owned by this class instance, we
107
+ /// skip shared pointers and just return a raw pointer
108
+ ArrayBuilder* child(int i) { return children_[i].get(); }
109
+
110
+ const std::shared_ptr<ArrayBuilder>& child_builder(int i) const { return children_[i]; }
111
+
112
+ int num_children() const { return static_cast<int>(children_.size()); }
113
+
114
+ virtual int64_t length() const { return length_; }
115
+ int64_t null_count() const { return null_count_; }
116
+ int64_t capacity() const { return capacity_; }
117
+
118
+ /// \brief Ensure that enough memory has been allocated to fit the indicated
119
+ /// number of total elements in the builder, including any that have already
120
+ /// been appended. Does not account for reallocations that may be due to
121
+ /// variable size data, like binary values. To make space for incremental
122
+ /// appends, use Reserve instead.
123
+ ///
124
+ /// \param[in] capacity the minimum number of total array values to
125
+ /// accommodate. Must be greater than the current capacity.
126
+ /// \return Status
127
+ virtual Status Resize(int64_t capacity);
128
+
129
+ /// \brief Ensure that there is enough space allocated to append the indicated
130
+ /// number of elements without any further reallocation. Overallocation is
131
+ /// used in order to minimize the impact of incremental Reserve() calls.
132
+ /// Note that additional_capacity is relative to the current number of elements
133
+ /// rather than to the current capacity, so calls to Reserve() which are not
134
+ /// interspersed with addition of new elements may not increase the capacity.
135
+ ///
136
+ /// \param[in] additional_capacity the number of additional array values
137
+ /// \return Status
138
+ Status Reserve(int64_t additional_capacity) {
139
+ auto current_capacity = capacity();
140
+ auto min_capacity = length() + additional_capacity;
141
+ if (min_capacity <= current_capacity) return Status::OK();
142
+
143
+ // leave growth factor up to BufferBuilder
144
+ auto new_capacity = BufferBuilder::GrowByFactor(current_capacity, min_capacity);
145
+ return Resize(new_capacity);
146
+ }
147
+
148
+ /// Reset the builder.
149
+ virtual void Reset();
150
+
151
+ /// \brief Append a null value to builder
152
+ virtual Status AppendNull() = 0;
153
+ /// \brief Append a number of null values to builder
154
+ virtual Status AppendNulls(int64_t length) = 0;
155
+
156
+ /// \brief Append a non-null value to builder
157
+ ///
158
+ /// The appended value is an implementation detail, but the corresponding
159
+ /// memory slot is guaranteed to be initialized.
160
+ /// This method is useful when appending a null value to a parent nested type.
161
+ virtual Status AppendEmptyValue() = 0;
162
+
163
+ /// \brief Append a number of non-null values to builder
164
+ ///
165
+ /// The appended values are an implementation detail, but the corresponding
166
+ /// memory slot is guaranteed to be initialized.
167
+ /// This method is useful when appending null values to a parent nested type.
168
+ virtual Status AppendEmptyValues(int64_t length) = 0;
169
+
170
+ /// \brief Append a value from a scalar
171
+ Status AppendScalar(const Scalar& scalar) { return AppendScalar(scalar, 1); }
172
+ virtual Status AppendScalar(const Scalar& scalar, int64_t n_repeats);
173
+ virtual Status AppendScalars(const ScalarVector& scalars);
174
+
175
+ /// \brief Append a range of values from an array.
176
+ ///
177
+ /// The given array must be the same type as the builder.
178
+ virtual Status AppendArraySlice(const ArraySpan& array, int64_t offset,
179
+ int64_t length) {
180
+ return Status::NotImplemented("AppendArraySlice for builder for ", *type());
181
+ }
182
+
183
+ /// \brief Return result of builder as an internal generic ArrayData
184
+ /// object. Resets builder except for dictionary builder
185
+ ///
186
+ /// \param[out] out the finalized ArrayData object
187
+ /// \return Status
188
+ virtual Status FinishInternal(std::shared_ptr<ArrayData>* out) = 0;
189
+
190
+ /// \brief Return result of builder as an Array object.
191
+ ///
192
+ /// The builder is reset except for DictionaryBuilder.
193
+ ///
194
+ /// \param[out] out the finalized Array object
195
+ /// \return Status
196
+ Status Finish(std::shared_ptr<Array>* out);
197
+
198
+ /// \brief Return result of builder as an Array object.
199
+ ///
200
+ /// The builder is reset except for DictionaryBuilder.
201
+ ///
202
+ /// \return The finalized Array object
203
+ Result<std::shared_ptr<Array>> Finish();
204
+
205
+ /// \brief Return the type of the built Array
206
+ virtual std::shared_ptr<DataType> type() const = 0;
207
+
208
+ protected:
209
+ /// Append to null bitmap
210
+ Status AppendToBitmap(bool is_valid);
211
+
212
+ /// Vector append. Treat each zero byte as a null. If valid_bytes is null
213
+ /// assume all of length bits are valid.
214
+ Status AppendToBitmap(const uint8_t* valid_bytes, int64_t length);
215
+
216
+ /// Uniform append. Append N times the same validity bit.
217
+ Status AppendToBitmap(int64_t num_bits, bool value);
218
+
219
+ /// Set the next length bits to not null (i.e. valid).
220
+ Status SetNotNull(int64_t length);
221
+
222
+ // Unsafe operations (don't check capacity/don't resize)
223
+
224
+ void UnsafeAppendNull() { UnsafeAppendToBitmap(false); }
225
+
226
+ // Append to null bitmap, update the length
227
+ void UnsafeAppendToBitmap(bool is_valid) {
228
+ null_bitmap_builder_.UnsafeAppend(is_valid);
229
+ ++length_;
230
+ if (!is_valid) ++null_count_;
231
+ }
232
+
233
+ // Vector append. Treat each zero byte as a nullzero. If valid_bytes is null
234
+ // assume all of length bits are valid.
235
+ void UnsafeAppendToBitmap(const uint8_t* valid_bytes, int64_t length) {
236
+ if (valid_bytes == NULLPTR) {
237
+ return UnsafeSetNotNull(length);
238
+ }
239
+ null_bitmap_builder_.UnsafeAppend(valid_bytes, length);
240
+ length_ += length;
241
+ null_count_ = null_bitmap_builder_.false_count();
242
+ }
243
+
244
+ // Vector append. Copy from a given bitmap. If bitmap is null assume
245
+ // all of length bits are valid.
246
+ void UnsafeAppendToBitmap(const uint8_t* bitmap, int64_t offset, int64_t length) {
247
+ if (bitmap == NULLPTR) {
248
+ return UnsafeSetNotNull(length);
249
+ }
250
+ null_bitmap_builder_.UnsafeAppend(bitmap, offset, length);
251
+ length_ += length;
252
+ null_count_ = null_bitmap_builder_.false_count();
253
+ }
254
+
255
+ // Append the same validity value a given number of times.
256
+ void UnsafeAppendToBitmap(const int64_t num_bits, bool value) {
257
+ if (value) {
258
+ UnsafeSetNotNull(num_bits);
259
+ } else {
260
+ UnsafeSetNull(num_bits);
261
+ }
262
+ }
263
+
264
+ void UnsafeAppendToBitmap(const std::vector<bool>& is_valid);
265
+
266
+ // Set the next validity bits to not null (i.e. valid).
267
+ void UnsafeSetNotNull(int64_t length);
268
+
269
+ // Set the next validity bits to null (i.e. invalid).
270
+ void UnsafeSetNull(int64_t length);
271
+
272
+ static Status TrimBuffer(const int64_t bytes_filled, ResizableBuffer* buffer);
273
+
274
+ /// \brief Finish to an array of the specified ArrayType
275
+ template <typename ArrayType>
276
+ Status FinishTyped(std::shared_ptr<ArrayType>* out) {
277
+ std::shared_ptr<Array> out_untyped;
278
+ ARROW_RETURN_NOT_OK(Finish(&out_untyped));
279
+ *out = std::static_pointer_cast<ArrayType>(std::move(out_untyped));
280
+ return Status::OK();
281
+ }
282
+
283
+ // Check the requested capacity for validity
284
+ Status CheckCapacity(int64_t new_capacity) {
285
+ if (ARROW_PREDICT_FALSE(new_capacity < 0)) {
286
+ return Status::Invalid(
287
+ "Resize capacity must be positive (requested: ", new_capacity, ")");
288
+ }
289
+
290
+ if (ARROW_PREDICT_FALSE(new_capacity < length_)) {
291
+ return Status::Invalid("Resize cannot downsize (requested: ", new_capacity,
292
+ ", current length: ", length_, ")");
293
+ }
294
+
295
+ return Status::OK();
296
+ }
297
+
298
+ // Check for array type
299
+ Status CheckArrayType(const std::shared_ptr<DataType>& expected_type,
300
+ const Array& array, const char* message);
301
+ Status CheckArrayType(Type::type expected_type, const Array& array,
302
+ const char* message);
303
+
304
+ MemoryPool* pool_;
305
+ int64_t alignment_;
306
+
307
+ TypedBufferBuilder<bool> null_bitmap_builder_;
308
+ int64_t null_count_ = 0;
309
+
310
+ // Array length, so far. Also, the index of the next element to be added
311
+ int64_t length_ = 0;
312
+ int64_t capacity_ = 0;
313
+
314
+ // Child value array builders. These are owned by this class
315
+ std::vector<std::shared_ptr<ArrayBuilder>> children_;
316
+
317
+ private:
318
+ ARROW_DISALLOW_COPY_AND_ASSIGN(ArrayBuilder);
319
+ };
320
+
321
+ /// \brief Construct an empty ArrayBuilder corresponding to the data
322
+ /// type
323
+ /// \param[in] pool the MemoryPool to use for allocations
324
+ /// \param[in] type the data type to create the builder for
325
+ /// \param[out] out the created ArrayBuilder
326
+ ARROW_EXPORT
327
+ Status MakeBuilder(MemoryPool* pool, const std::shared_ptr<DataType>& type,
328
+ std::unique_ptr<ArrayBuilder>* out);
329
+
330
+ inline Result<std::unique_ptr<ArrayBuilder>> MakeBuilder(
331
+ const std::shared_ptr<DataType>& type, MemoryPool* pool = default_memory_pool()) {
332
+ std::unique_ptr<ArrayBuilder> out;
333
+ ARROW_RETURN_NOT_OK(MakeBuilder(pool, type, &out));
334
+ return std::move(out);
335
+ }
336
+
337
+ /// \brief Construct an empty ArrayBuilder corresponding to the data
338
+ /// type, where any top-level or nested dictionary builders return the
339
+ /// exact index type specified by the type.
340
+ ARROW_EXPORT
341
+ Status MakeBuilderExactIndex(MemoryPool* pool, const std::shared_ptr<DataType>& type,
342
+ std::unique_ptr<ArrayBuilder>* out);
343
+
344
+ inline Result<std::unique_ptr<ArrayBuilder>> MakeBuilderExactIndex(
345
+ const std::shared_ptr<DataType>& type, MemoryPool* pool = default_memory_pool()) {
346
+ std::unique_ptr<ArrayBuilder> out;
347
+ ARROW_RETURN_NOT_OK(MakeBuilderExactIndex(pool, type, &out));
348
+ return std::move(out);
349
+ }
350
+
351
+ /// \brief Construct an empty DictionaryBuilder initialized optionally
352
+ /// with a pre-existing dictionary
353
+ /// \param[in] pool the MemoryPool to use for allocations
354
+ /// \param[in] type the dictionary type to create the builder for
355
+ /// \param[in] dictionary the initial dictionary, if any. May be nullptr
356
+ /// \param[out] out the created ArrayBuilder
357
+ ARROW_EXPORT
358
+ Status MakeDictionaryBuilder(MemoryPool* pool, const std::shared_ptr<DataType>& type,
359
+ const std::shared_ptr<Array>& dictionary,
360
+ std::unique_ptr<ArrayBuilder>* out);
361
+
362
+ inline Result<std::unique_ptr<ArrayBuilder>> MakeDictionaryBuilder(
363
+ const std::shared_ptr<DataType>& type, const std::shared_ptr<Array>& dictionary,
364
+ MemoryPool* pool = default_memory_pool()) {
365
+ std::unique_ptr<ArrayBuilder> out;
366
+ ARROW_RETURN_NOT_OK(MakeDictionaryBuilder(pool, type, dictionary, &out));
367
+ return std::move(out);
368
+ }
369
+
370
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_binary.h ADDED
@@ -0,0 +1,971 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <array>
21
+ #include <cstddef>
22
+ #include <cstdint>
23
+ #include <cstring>
24
+ #include <limits>
25
+ #include <memory>
26
+ #include <numeric>
27
+ #include <string>
28
+ #include <string_view>
29
+ #include <vector>
30
+
31
+ #include "arrow/array/array_base.h"
32
+ #include "arrow/array/array_binary.h"
33
+ #include "arrow/array/builder_base.h"
34
+ #include "arrow/array/data.h"
35
+ #include "arrow/buffer.h"
36
+ #include "arrow/buffer_builder.h"
37
+ #include "arrow/status.h"
38
+ #include "arrow/type.h"
39
+ #include "arrow/util/binary_view_util.h"
40
+ #include "arrow/util/macros.h"
41
+ #include "arrow/util/visibility.h"
42
+
43
+ namespace arrow {
44
+
45
+ /// \addtogroup binary-builders
46
+ ///
47
+ /// @{
48
+
49
+ // ----------------------------------------------------------------------
50
+ // Binary and String
51
+
52
+ template <typename TYPE>
53
+ class BaseBinaryBuilder
54
+ : public ArrayBuilder,
55
+ public internal::ArrayBuilderExtraOps<BaseBinaryBuilder<TYPE>, std::string_view> {
56
+ public:
57
+ using TypeClass = TYPE;
58
+ using offset_type = typename TypeClass::offset_type;
59
+
60
+ explicit BaseBinaryBuilder(MemoryPool* pool = default_memory_pool(),
61
+ int64_t alignment = kDefaultBufferAlignment)
62
+ : ArrayBuilder(pool, alignment),
63
+ offsets_builder_(pool, alignment),
64
+ value_data_builder_(pool, alignment) {}
65
+
66
+ BaseBinaryBuilder(const std::shared_ptr<DataType>& type, MemoryPool* pool)
67
+ : BaseBinaryBuilder(pool) {}
68
+
69
+ Status Append(const uint8_t* value, offset_type length) {
70
+ ARROW_RETURN_NOT_OK(Reserve(1));
71
+ UnsafeAppendNextOffset();
72
+ // Safety check for UBSAN.
73
+ if (ARROW_PREDICT_TRUE(length > 0)) {
74
+ ARROW_RETURN_NOT_OK(ValidateOverflow(length));
75
+ ARROW_RETURN_NOT_OK(value_data_builder_.Append(value, length));
76
+ }
77
+
78
+ UnsafeAppendToBitmap(true);
79
+ return Status::OK();
80
+ }
81
+
82
+ Status Append(const char* value, offset_type length) {
83
+ return Append(reinterpret_cast<const uint8_t*>(value), length);
84
+ }
85
+
86
+ Status Append(std::string_view value) {
87
+ return Append(value.data(), static_cast<offset_type>(value.size()));
88
+ }
89
+
90
+ /// Extend the last appended value by appending more data at the end
91
+ ///
92
+ /// Unlike Append, this does not create a new offset.
93
+ Status ExtendCurrent(const uint8_t* value, offset_type length) {
94
+ // Safety check for UBSAN.
95
+ if (ARROW_PREDICT_TRUE(length > 0)) {
96
+ ARROW_RETURN_NOT_OK(ValidateOverflow(length));
97
+ ARROW_RETURN_NOT_OK(value_data_builder_.Append(value, length));
98
+ }
99
+ return Status::OK();
100
+ }
101
+
102
+ Status ExtendCurrent(std::string_view value) {
103
+ return ExtendCurrent(reinterpret_cast<const uint8_t*>(value.data()),
104
+ static_cast<offset_type>(value.size()));
105
+ }
106
+
107
+ Status AppendNulls(int64_t length) final {
108
+ const int64_t num_bytes = value_data_builder_.length();
109
+ ARROW_RETURN_NOT_OK(Reserve(length));
110
+ for (int64_t i = 0; i < length; ++i) {
111
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(num_bytes));
112
+ }
113
+ UnsafeAppendToBitmap(length, false);
114
+ return Status::OK();
115
+ }
116
+
117
+ Status AppendNull() final {
118
+ ARROW_RETURN_NOT_OK(Reserve(1));
119
+ UnsafeAppendNextOffset();
120
+ UnsafeAppendToBitmap(false);
121
+ return Status::OK();
122
+ }
123
+
124
+ Status AppendEmptyValue() final {
125
+ ARROW_RETURN_NOT_OK(Reserve(1));
126
+ UnsafeAppendNextOffset();
127
+ UnsafeAppendToBitmap(true);
128
+ return Status::OK();
129
+ }
130
+
131
+ Status AppendEmptyValues(int64_t length) final {
132
+ const int64_t num_bytes = value_data_builder_.length();
133
+ ARROW_RETURN_NOT_OK(Reserve(length));
134
+ for (int64_t i = 0; i < length; ++i) {
135
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(num_bytes));
136
+ }
137
+ UnsafeAppendToBitmap(length, true);
138
+ return Status::OK();
139
+ }
140
+
141
+ /// \brief Append without checking capacity
142
+ ///
143
+ /// Offsets and data should have been presized using Reserve() and
144
+ /// ReserveData(), respectively.
145
+ void UnsafeAppend(const uint8_t* value, offset_type length) {
146
+ UnsafeAppendNextOffset();
147
+ value_data_builder_.UnsafeAppend(value, length);
148
+ UnsafeAppendToBitmap(true);
149
+ }
150
+
151
+ void UnsafeAppend(const char* value, offset_type length) {
152
+ UnsafeAppend(reinterpret_cast<const uint8_t*>(value), length);
153
+ }
154
+
155
+ void UnsafeAppend(const std::string& value) {
156
+ UnsafeAppend(value.c_str(), static_cast<offset_type>(value.size()));
157
+ }
158
+
159
+ void UnsafeAppend(std::string_view value) {
160
+ UnsafeAppend(value.data(), static_cast<offset_type>(value.size()));
161
+ }
162
+
163
+ /// Like ExtendCurrent, but do not check capacity
164
+ void UnsafeExtendCurrent(const uint8_t* value, offset_type length) {
165
+ value_data_builder_.UnsafeAppend(value, length);
166
+ }
167
+
168
+ void UnsafeExtendCurrent(std::string_view value) {
169
+ UnsafeExtendCurrent(reinterpret_cast<const uint8_t*>(value.data()),
170
+ static_cast<offset_type>(value.size()));
171
+ }
172
+
173
+ void UnsafeAppendNull() {
174
+ const int64_t num_bytes = value_data_builder_.length();
175
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(num_bytes));
176
+ UnsafeAppendToBitmap(false);
177
+ }
178
+
179
+ void UnsafeAppendEmptyValue() {
180
+ const int64_t num_bytes = value_data_builder_.length();
181
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(num_bytes));
182
+ UnsafeAppendToBitmap(true);
183
+ }
184
+
185
+ /// \brief Append a sequence of strings in one shot.
186
+ ///
187
+ /// \param[in] values a vector of strings
188
+ /// \param[in] valid_bytes an optional sequence of bytes where non-zero
189
+ /// indicates a valid (non-null) value
190
+ /// \return Status
191
+ Status AppendValues(const std::vector<std::string>& values,
192
+ const uint8_t* valid_bytes = NULLPTR) {
193
+ std::size_t total_length = std::accumulate(
194
+ values.begin(), values.end(), 0ULL,
195
+ [](uint64_t sum, const std::string& str) { return sum + str.size(); });
196
+ ARROW_RETURN_NOT_OK(Reserve(values.size()));
197
+ ARROW_RETURN_NOT_OK(ReserveData(total_length));
198
+
199
+ if (valid_bytes != NULLPTR) {
200
+ for (std::size_t i = 0; i < values.size(); ++i) {
201
+ UnsafeAppendNextOffset();
202
+ if (valid_bytes[i]) {
203
+ value_data_builder_.UnsafeAppend(
204
+ reinterpret_cast<const uint8_t*>(values[i].data()), values[i].size());
205
+ }
206
+ }
207
+ } else {
208
+ for (const auto& value : values) {
209
+ UnsafeAppendNextOffset();
210
+ value_data_builder_.UnsafeAppend(reinterpret_cast<const uint8_t*>(value.data()),
211
+ value.size());
212
+ }
213
+ }
214
+
215
+ UnsafeAppendToBitmap(valid_bytes, values.size());
216
+ return Status::OK();
217
+ }
218
+
219
+ /// \brief Append a sequence of nul-terminated strings in one shot.
220
+ /// If one of the values is NULL, it is processed as a null
221
+ /// value even if the corresponding valid_bytes entry is 1.
222
+ ///
223
+ /// \param[in] values a contiguous C array of nul-terminated char *
224
+ /// \param[in] length the number of values to append
225
+ /// \param[in] valid_bytes an optional sequence of bytes where non-zero
226
+ /// indicates a valid (non-null) value
227
+ /// \return Status
228
+ Status AppendValues(const char** values, int64_t length,
229
+ const uint8_t* valid_bytes = NULLPTR) {
230
+ std::size_t total_length = 0;
231
+ std::vector<std::size_t> value_lengths(length);
232
+ bool have_null_value = false;
233
+ for (int64_t i = 0; i < length; ++i) {
234
+ if (values[i] != NULLPTR) {
235
+ auto value_length = strlen(values[i]);
236
+ value_lengths[i] = value_length;
237
+ total_length += value_length;
238
+ } else {
239
+ have_null_value = true;
240
+ }
241
+ }
242
+ ARROW_RETURN_NOT_OK(Reserve(length));
243
+ ARROW_RETURN_NOT_OK(ReserveData(total_length));
244
+
245
+ if (valid_bytes) {
246
+ int64_t valid_bytes_offset = 0;
247
+ for (int64_t i = 0; i < length; ++i) {
248
+ UnsafeAppendNextOffset();
249
+ if (valid_bytes[i]) {
250
+ if (values[i]) {
251
+ value_data_builder_.UnsafeAppend(reinterpret_cast<const uint8_t*>(values[i]),
252
+ value_lengths[i]);
253
+ } else {
254
+ UnsafeAppendToBitmap(valid_bytes + valid_bytes_offset,
255
+ i - valid_bytes_offset);
256
+ UnsafeAppendToBitmap(false);
257
+ valid_bytes_offset = i + 1;
258
+ }
259
+ }
260
+ }
261
+ UnsafeAppendToBitmap(valid_bytes + valid_bytes_offset, length - valid_bytes_offset);
262
+ } else {
263
+ if (have_null_value) {
264
+ std::vector<uint8_t> valid_vector(length, 0);
265
+ for (int64_t i = 0; i < length; ++i) {
266
+ UnsafeAppendNextOffset();
267
+ if (values[i]) {
268
+ value_data_builder_.UnsafeAppend(reinterpret_cast<const uint8_t*>(values[i]),
269
+ value_lengths[i]);
270
+ valid_vector[i] = 1;
271
+ }
272
+ }
273
+ UnsafeAppendToBitmap(valid_vector.data(), length);
274
+ } else {
275
+ for (int64_t i = 0; i < length; ++i) {
276
+ UnsafeAppendNextOffset();
277
+ value_data_builder_.UnsafeAppend(reinterpret_cast<const uint8_t*>(values[i]),
278
+ value_lengths[i]);
279
+ }
280
+ UnsafeAppendToBitmap(NULLPTR, length);
281
+ }
282
+ }
283
+ return Status::OK();
284
+ }
285
+
286
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
287
+ int64_t length) override {
288
+ auto bitmap = array.GetValues<uint8_t>(0, 0);
289
+ auto offsets = array.GetValues<offset_type>(1);
290
+ auto data = array.GetValues<uint8_t>(2, 0);
291
+ auto total_length = offsets[offset + length] - offsets[offset];
292
+ ARROW_RETURN_NOT_OK(Reserve(length));
293
+ ARROW_RETURN_NOT_OK(ReserveData(total_length));
294
+ for (int64_t i = 0; i < length; i++) {
295
+ if (!bitmap || bit_util::GetBit(bitmap, array.offset + offset + i)) {
296
+ const offset_type start = offsets[offset + i];
297
+ const offset_type end = offsets[offset + i + 1];
298
+ UnsafeAppend(data + start, end - start);
299
+ } else {
300
+ UnsafeAppendNull();
301
+ }
302
+ }
303
+ return Status::OK();
304
+ }
305
+
306
+ void Reset() override {
307
+ ArrayBuilder::Reset();
308
+ offsets_builder_.Reset();
309
+ value_data_builder_.Reset();
310
+ }
311
+
312
+ Status ValidateOverflow(int64_t new_bytes) {
313
+ auto new_size = value_data_builder_.length() + new_bytes;
314
+ if (ARROW_PREDICT_FALSE(new_size > memory_limit())) {
315
+ return Status::CapacityError("array cannot contain more than ", memory_limit(),
316
+ " bytes, have ", new_size);
317
+ } else {
318
+ return Status::OK();
319
+ }
320
+ }
321
+
322
+ Status Resize(int64_t capacity) override {
323
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
324
+ // One more than requested for offsets
325
+ ARROW_RETURN_NOT_OK(offsets_builder_.Resize(capacity + 1));
326
+ return ArrayBuilder::Resize(capacity);
327
+ }
328
+
329
+ /// \brief Ensures there is enough allocated capacity to append the indicated
330
+ /// number of bytes to the value data buffer without additional allocations
331
+ Status ReserveData(int64_t elements) {
332
+ ARROW_RETURN_NOT_OK(ValidateOverflow(elements));
333
+ return value_data_builder_.Reserve(elements);
334
+ }
335
+
336
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
337
+ // Write final offset (values length)
338
+ ARROW_RETURN_NOT_OK(AppendNextOffset());
339
+
340
+ // These buffers' padding zeroed by BufferBuilder
341
+ std::shared_ptr<Buffer> offsets, value_data, null_bitmap;
342
+ ARROW_RETURN_NOT_OK(offsets_builder_.Finish(&offsets));
343
+ ARROW_RETURN_NOT_OK(value_data_builder_.Finish(&value_data));
344
+ ARROW_RETURN_NOT_OK(null_bitmap_builder_.Finish(&null_bitmap));
345
+
346
+ *out = ArrayData::Make(type(), length_, {null_bitmap, offsets, value_data},
347
+ null_count_, 0);
348
+ Reset();
349
+ return Status::OK();
350
+ }
351
+
352
+ /// \return data pointer of the value date builder
353
+ const uint8_t* value_data() const { return value_data_builder_.data(); }
354
+ /// \return size of values buffer so far
355
+ int64_t value_data_length() const { return value_data_builder_.length(); }
356
+ /// \return capacity of values buffer
357
+ int64_t value_data_capacity() const { return value_data_builder_.capacity(); }
358
+
359
+ /// \return data pointer of the value date builder
360
+ const offset_type* offsets_data() const { return offsets_builder_.data(); }
361
+
362
+ /// Temporary access to a value.
363
+ ///
364
+ /// This pointer becomes invalid on the next modifying operation.
365
+ const uint8_t* GetValue(int64_t i, offset_type* out_length) const {
366
+ const offset_type* offsets = offsets_builder_.data();
367
+ const auto offset = offsets[i];
368
+ if (i == (length_ - 1)) {
369
+ *out_length = static_cast<offset_type>(value_data_builder_.length()) - offset;
370
+ } else {
371
+ *out_length = offsets[i + 1] - offset;
372
+ }
373
+ return value_data_builder_.data() + offset;
374
+ }
375
+
376
+ offset_type offset(int64_t i) const { return offsets_data()[i]; }
377
+
378
+ /// Temporary access to a value.
379
+ ///
380
+ /// This view becomes invalid on the next modifying operation.
381
+ std::string_view GetView(int64_t i) const {
382
+ offset_type value_length;
383
+ const uint8_t* value_data = GetValue(i, &value_length);
384
+ return std::string_view(reinterpret_cast<const char*>(value_data), value_length);
385
+ }
386
+
387
+ // Cannot make this a static attribute because of linking issues
388
+ static constexpr int64_t memory_limit() {
389
+ return std::numeric_limits<offset_type>::max() - 1;
390
+ }
391
+
392
+ protected:
393
+ TypedBufferBuilder<offset_type> offsets_builder_;
394
+ TypedBufferBuilder<uint8_t> value_data_builder_;
395
+
396
+ Status AppendNextOffset() {
397
+ const int64_t num_bytes = value_data_builder_.length();
398
+ return offsets_builder_.Append(static_cast<offset_type>(num_bytes));
399
+ }
400
+
401
+ void UnsafeAppendNextOffset() {
402
+ const int64_t num_bytes = value_data_builder_.length();
403
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(num_bytes));
404
+ }
405
+ };
406
+
407
+ /// \class BinaryBuilder
408
+ /// \brief Builder class for variable-length binary data
409
+ class ARROW_EXPORT BinaryBuilder : public BaseBinaryBuilder<BinaryType> {
410
+ public:
411
+ using BaseBinaryBuilder::BaseBinaryBuilder;
412
+
413
+ /// \cond FALSE
414
+ using ArrayBuilder::Finish;
415
+ /// \endcond
416
+
417
+ Status Finish(std::shared_ptr<BinaryArray>* out) { return FinishTyped(out); }
418
+
419
+ std::shared_ptr<DataType> type() const override { return binary(); }
420
+ };
421
+
422
+ /// \class StringBuilder
423
+ /// \brief Builder class for UTF8 strings
424
+ class ARROW_EXPORT StringBuilder : public BinaryBuilder {
425
+ public:
426
+ using BinaryBuilder::BinaryBuilder;
427
+
428
+ /// \cond FALSE
429
+ using ArrayBuilder::Finish;
430
+ /// \endcond
431
+
432
+ Status Finish(std::shared_ptr<StringArray>* out) { return FinishTyped(out); }
433
+
434
+ std::shared_ptr<DataType> type() const override { return utf8(); }
435
+ };
436
+
437
+ /// \class LargeBinaryBuilder
438
+ /// \brief Builder class for large variable-length binary data
439
+ class ARROW_EXPORT LargeBinaryBuilder : public BaseBinaryBuilder<LargeBinaryType> {
440
+ public:
441
+ using BaseBinaryBuilder::BaseBinaryBuilder;
442
+
443
+ /// \cond FALSE
444
+ using ArrayBuilder::Finish;
445
+ /// \endcond
446
+
447
+ Status Finish(std::shared_ptr<LargeBinaryArray>* out) { return FinishTyped(out); }
448
+
449
+ std::shared_ptr<DataType> type() const override { return large_binary(); }
450
+ };
451
+
452
+ /// \class LargeStringBuilder
453
+ /// \brief Builder class for large UTF8 strings
454
+ class ARROW_EXPORT LargeStringBuilder : public LargeBinaryBuilder {
455
+ public:
456
+ using LargeBinaryBuilder::LargeBinaryBuilder;
457
+
458
+ /// \cond FALSE
459
+ using ArrayBuilder::Finish;
460
+ /// \endcond
461
+
462
+ Status Finish(std::shared_ptr<LargeStringArray>* out) { return FinishTyped(out); }
463
+
464
+ std::shared_ptr<DataType> type() const override { return large_utf8(); }
465
+ };
466
+
467
+ // ----------------------------------------------------------------------
468
+ // BinaryViewBuilder, StringViewBuilder
469
+ //
470
+ // These builders do not support building raw pointer view arrays.
471
+
472
+ namespace internal {
473
+
474
+ // We allocate medium-sized memory chunks and accumulate data in those, which
475
+ // may result in some waste if there are many large-ish strings. If a string
476
+ // comes along that does not fit into a block, we allocate a new block and
477
+ // write into that.
478
+ //
479
+ // Later we can implement optimizations to continuing filling underfull blocks
480
+ // after encountering a large string that required allocating a new block.
481
+ class ARROW_EXPORT StringHeapBuilder {
482
+ public:
483
+ static constexpr int64_t kDefaultBlocksize = 32 << 10; // 32KB
484
+
485
+ StringHeapBuilder(MemoryPool* pool, int64_t alignment)
486
+ : pool_(pool), alignment_(alignment) {}
487
+
488
+ void SetBlockSize(int64_t blocksize) { blocksize_ = blocksize; }
489
+
490
+ using c_type = BinaryViewType::c_type;
491
+
492
+ template <bool Safe>
493
+ std::conditional_t<Safe, Result<c_type>, c_type> Append(const uint8_t* value,
494
+ int64_t length) {
495
+ if (length <= BinaryViewType::kInlineSize) {
496
+ return util::ToInlineBinaryView(value, static_cast<int32_t>(length));
497
+ }
498
+
499
+ if constexpr (Safe) {
500
+ ARROW_RETURN_NOT_OK(Reserve(length));
501
+ }
502
+
503
+ auto v =
504
+ util::ToBinaryView(value, static_cast<int32_t>(length),
505
+ static_cast<int32_t>(blocks_.size() - 1), current_offset_);
506
+
507
+ memcpy(current_out_buffer_, value, static_cast<size_t>(length));
508
+ current_out_buffer_ += length;
509
+ current_remaining_bytes_ -= length;
510
+ current_offset_ += static_cast<int32_t>(length);
511
+ return v;
512
+ }
513
+
514
+ static constexpr int64_t ValueSizeLimit() {
515
+ return std::numeric_limits<int32_t>::max();
516
+ }
517
+
518
+ /// \brief Ensure that the indicated number of bytes can be appended via
519
+ /// UnsafeAppend operations without the need to allocate more memory
520
+ Status Reserve(int64_t num_bytes) {
521
+ if (ARROW_PREDICT_FALSE(num_bytes > ValueSizeLimit())) {
522
+ return Status::CapacityError(
523
+ "BinaryView or StringView elements cannot reference "
524
+ "strings larger than 2GB");
525
+ }
526
+ if (num_bytes > current_remaining_bytes_) {
527
+ ARROW_RETURN_NOT_OK(FinishLastBlock());
528
+ current_remaining_bytes_ = num_bytes > blocksize_ ? num_bytes : blocksize_;
529
+ ARROW_ASSIGN_OR_RAISE(
530
+ std::shared_ptr<ResizableBuffer> new_block,
531
+ AllocateResizableBuffer(current_remaining_bytes_, alignment_, pool_));
532
+ current_offset_ = 0;
533
+ current_out_buffer_ = new_block->mutable_data();
534
+ blocks_.emplace_back(std::move(new_block));
535
+ }
536
+ return Status::OK();
537
+ }
538
+
539
+ void Reset() {
540
+ current_offset_ = 0;
541
+ current_out_buffer_ = NULLPTR;
542
+ current_remaining_bytes_ = 0;
543
+ blocks_.clear();
544
+ }
545
+
546
+ int64_t current_remaining_bytes() const { return current_remaining_bytes_; }
547
+
548
+ Result<std::vector<std::shared_ptr<ResizableBuffer>>> Finish() {
549
+ if (!blocks_.empty()) {
550
+ ARROW_RETURN_NOT_OK(FinishLastBlock());
551
+ }
552
+ current_offset_ = 0;
553
+ current_out_buffer_ = NULLPTR;
554
+ current_remaining_bytes_ = 0;
555
+ return std::move(blocks_);
556
+ }
557
+
558
+ private:
559
+ Status FinishLastBlock() {
560
+ if (current_remaining_bytes_ > 0) {
561
+ // Avoid leaking uninitialized bytes from the allocator
562
+ ARROW_RETURN_NOT_OK(
563
+ blocks_.back()->Resize(blocks_.back()->size() - current_remaining_bytes_,
564
+ /*shrink_to_fit=*/true));
565
+ blocks_.back()->ZeroPadding();
566
+ }
567
+ return Status::OK();
568
+ }
569
+
570
+ MemoryPool* pool_;
571
+ int64_t alignment_;
572
+ int64_t blocksize_ = kDefaultBlocksize;
573
+ std::vector<std::shared_ptr<ResizableBuffer>> blocks_;
574
+
575
+ int32_t current_offset_ = 0;
576
+ uint8_t* current_out_buffer_ = NULLPTR;
577
+ int64_t current_remaining_bytes_ = 0;
578
+ };
579
+
580
+ } // namespace internal
581
+
582
+ class ARROW_EXPORT BinaryViewBuilder : public ArrayBuilder {
583
+ public:
584
+ using TypeClass = BinaryViewType;
585
+
586
+ // this constructor provided for MakeBuilder compatibility
587
+ BinaryViewBuilder(const std::shared_ptr<DataType>&, MemoryPool* pool);
588
+
589
+ explicit BinaryViewBuilder(MemoryPool* pool = default_memory_pool(),
590
+ int64_t alignment = kDefaultBufferAlignment)
591
+ : ArrayBuilder(pool, alignment),
592
+ data_builder_(pool, alignment),
593
+ data_heap_builder_(pool, alignment) {}
594
+
595
+ /// Set the size for future preallocated data buffers.
596
+ ///
597
+ /// The default size is 32KB, so after each 32KB of string data appended to the builder
598
+ /// a new data buffer will be allocated. Adjust this to a larger value to decrease the
599
+ /// frequency of allocation, or to a smaller value to lower the overhead of each
600
+ /// allocation.
601
+ void SetBlockSize(int64_t blocksize) { data_heap_builder_.SetBlockSize(blocksize); }
602
+
603
+ /// The number of bytes which can be appended to this builder without allocating another
604
+ /// data buffer.
605
+ int64_t current_block_bytes_remaining() const {
606
+ return data_heap_builder_.current_remaining_bytes();
607
+ }
608
+
609
+ Status Append(const uint8_t* value, int64_t length) {
610
+ ARROW_RETURN_NOT_OK(Reserve(1));
611
+ UnsafeAppendToBitmap(true);
612
+ ARROW_ASSIGN_OR_RAISE(auto v,
613
+ data_heap_builder_.Append</*Safe=*/true>(value, length));
614
+ data_builder_.UnsafeAppend(v);
615
+ return Status::OK();
616
+ }
617
+
618
+ Status Append(const char* value, int64_t length) {
619
+ return Append(reinterpret_cast<const uint8_t*>(value), length);
620
+ }
621
+
622
+ Status Append(std::string_view value) {
623
+ return Append(value.data(), static_cast<int64_t>(value.size()));
624
+ }
625
+
626
+ /// \brief Append without checking capacity
627
+ ///
628
+ /// Builder should have been presized using Reserve() and ReserveData(),
629
+ /// respectively, and the value must not be larger than 2GB
630
+ void UnsafeAppend(const uint8_t* value, int64_t length) {
631
+ UnsafeAppendToBitmap(true);
632
+ auto v = data_heap_builder_.Append</*Safe=*/false>(value, length);
633
+ data_builder_.UnsafeAppend(v);
634
+ }
635
+
636
+ void UnsafeAppend(const char* value, int64_t length) {
637
+ UnsafeAppend(reinterpret_cast<const uint8_t*>(value), length);
638
+ }
639
+
640
+ void UnsafeAppend(const std::string& value) {
641
+ UnsafeAppend(value.c_str(), static_cast<int64_t>(value.size()));
642
+ }
643
+
644
+ void UnsafeAppend(std::string_view value) {
645
+ UnsafeAppend(value.data(), static_cast<int64_t>(value.size()));
646
+ }
647
+
648
+ /// \brief Ensures there is enough allocated available capacity in the
649
+ /// out-of-line data heap to append the indicated number of bytes without
650
+ /// additional allocations
651
+ Status ReserveData(int64_t length);
652
+
653
+ Status AppendNulls(int64_t length) final {
654
+ ARROW_RETURN_NOT_OK(Reserve(length));
655
+ data_builder_.UnsafeAppend(length, BinaryViewType::c_type{});
656
+ UnsafeSetNull(length);
657
+ return Status::OK();
658
+ }
659
+
660
+ /// \brief Append a single null element
661
+ Status AppendNull() final {
662
+ ARROW_RETURN_NOT_OK(Reserve(1));
663
+ data_builder_.UnsafeAppend(BinaryViewType::c_type{});
664
+ UnsafeAppendToBitmap(false);
665
+ return Status::OK();
666
+ }
667
+
668
+ /// \brief Append a empty element (length-0 inline string)
669
+ Status AppendEmptyValue() final {
670
+ ARROW_RETURN_NOT_OK(Reserve(1));
671
+ data_builder_.UnsafeAppend(BinaryViewType::c_type{});
672
+ UnsafeAppendToBitmap(true);
673
+ return Status::OK();
674
+ }
675
+
676
+ /// \brief Append several empty elements
677
+ Status AppendEmptyValues(int64_t length) final {
678
+ ARROW_RETURN_NOT_OK(Reserve(length));
679
+ data_builder_.UnsafeAppend(length, BinaryViewType::c_type{});
680
+ UnsafeSetNotNull(length);
681
+ return Status::OK();
682
+ }
683
+
684
+ void UnsafeAppendNull() {
685
+ data_builder_.UnsafeAppend(BinaryViewType::c_type{});
686
+ UnsafeAppendToBitmap(false);
687
+ }
688
+
689
+ void UnsafeAppendEmptyValue() {
690
+ data_builder_.UnsafeAppend(BinaryViewType::c_type{});
691
+ UnsafeAppendToBitmap(true);
692
+ }
693
+
694
+ /// \brief Append a slice of a BinaryViewArray passed as an ArraySpan. Copies
695
+ /// the underlying out-of-line string memory to avoid memory lifetime issues
696
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
697
+ int64_t length) override;
698
+
699
+ void Reset() override;
700
+
701
+ Status Resize(int64_t capacity) override {
702
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
703
+ capacity = std::max(capacity, kMinBuilderCapacity);
704
+ ARROW_RETURN_NOT_OK(data_builder_.Resize(capacity));
705
+ return ArrayBuilder::Resize(capacity);
706
+ }
707
+
708
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
709
+
710
+ std::shared_ptr<DataType> type() const override { return binary_view(); }
711
+
712
+ protected:
713
+ TypedBufferBuilder<BinaryViewType::c_type> data_builder_;
714
+
715
+ // Accumulates out-of-line data in fixed-size chunks which are then attached
716
+ // to the resulting ArrayData
717
+ internal::StringHeapBuilder data_heap_builder_;
718
+ };
719
+
720
+ class ARROW_EXPORT StringViewBuilder : public BinaryViewBuilder {
721
+ public:
722
+ using BinaryViewBuilder::BinaryViewBuilder;
723
+ std::shared_ptr<DataType> type() const override { return utf8_view(); }
724
+ };
725
+
726
+ // ----------------------------------------------------------------------
727
+ // FixedSizeBinaryBuilder
728
+
729
+ class ARROW_EXPORT FixedSizeBinaryBuilder : public ArrayBuilder {
730
+ public:
731
+ using TypeClass = FixedSizeBinaryType;
732
+
733
+ explicit FixedSizeBinaryBuilder(const std::shared_ptr<DataType>& type,
734
+ MemoryPool* pool = default_memory_pool(),
735
+ int64_t alignment = kDefaultBufferAlignment);
736
+
737
+ Status Append(const uint8_t* value) {
738
+ ARROW_RETURN_NOT_OK(Reserve(1));
739
+ UnsafeAppend(value);
740
+ return Status::OK();
741
+ }
742
+
743
+ Status Append(const char* value) {
744
+ return Append(reinterpret_cast<const uint8_t*>(value));
745
+ }
746
+
747
+ Status Append(std::string_view view) {
748
+ ARROW_RETURN_NOT_OK(Reserve(1));
749
+ UnsafeAppend(view);
750
+ return Status::OK();
751
+ }
752
+
753
+ Status Append(const std::string& s) {
754
+ ARROW_RETURN_NOT_OK(Reserve(1));
755
+ UnsafeAppend(s);
756
+ return Status::OK();
757
+ }
758
+
759
+ Status Append(const Buffer& s) {
760
+ ARROW_RETURN_NOT_OK(Reserve(1));
761
+ UnsafeAppend(s);
762
+ return Status::OK();
763
+ }
764
+
765
+ Status Append(const std::shared_ptr<Buffer>& s) { return Append(*s); }
766
+
767
+ template <size_t NBYTES>
768
+ Status Append(const std::array<uint8_t, NBYTES>& value) {
769
+ ARROW_RETURN_NOT_OK(Reserve(1));
770
+ UnsafeAppend(
771
+ std::string_view(reinterpret_cast<const char*>(value.data()), value.size()));
772
+ return Status::OK();
773
+ }
774
+
775
+ Status AppendValues(const uint8_t* data, int64_t length,
776
+ const uint8_t* valid_bytes = NULLPTR);
777
+
778
+ Status AppendValues(const uint8_t* data, int64_t length, const uint8_t* validity,
779
+ int64_t bitmap_offset);
780
+
781
+ Status AppendNull() final;
782
+ Status AppendNulls(int64_t length) final;
783
+
784
+ Status AppendEmptyValue() final;
785
+ Status AppendEmptyValues(int64_t length) final;
786
+
787
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
788
+ int64_t length) override {
789
+ return AppendValues(
790
+ array.GetValues<uint8_t>(1, 0) + ((array.offset + offset) * byte_width_), length,
791
+ array.GetValues<uint8_t>(0, 0), array.offset + offset);
792
+ }
793
+
794
+ void UnsafeAppend(const uint8_t* value) {
795
+ UnsafeAppendToBitmap(true);
796
+ if (ARROW_PREDICT_TRUE(byte_width_ > 0)) {
797
+ byte_builder_.UnsafeAppend(value, byte_width_);
798
+ }
799
+ }
800
+
801
+ void UnsafeAppend(const char* value) {
802
+ UnsafeAppend(reinterpret_cast<const uint8_t*>(value));
803
+ }
804
+
805
+ void UnsafeAppend(std::string_view value) {
806
+ #ifndef NDEBUG
807
+ CheckValueSize(static_cast<size_t>(value.size()));
808
+ #endif
809
+ UnsafeAppend(reinterpret_cast<const uint8_t*>(value.data()));
810
+ }
811
+
812
+ void UnsafeAppend(const Buffer& s) { UnsafeAppend(std::string_view{s}); }
813
+
814
+ void UnsafeAppend(const std::shared_ptr<Buffer>& s) { UnsafeAppend(*s); }
815
+
816
+ void UnsafeAppendNull() {
817
+ UnsafeAppendToBitmap(false);
818
+ byte_builder_.UnsafeAppend(/*num_copies=*/byte_width_, 0);
819
+ }
820
+
821
+ Status ValidateOverflow(int64_t new_bytes) const {
822
+ auto new_size = byte_builder_.length() + new_bytes;
823
+ if (ARROW_PREDICT_FALSE(new_size > memory_limit())) {
824
+ return Status::CapacityError("array cannot contain more than ", memory_limit(),
825
+ " bytes, have ", new_size);
826
+ } else {
827
+ return Status::OK();
828
+ }
829
+ }
830
+
831
+ /// \brief Ensures there is enough allocated capacity to append the indicated
832
+ /// number of bytes to the value data buffer without additional allocations
833
+ Status ReserveData(int64_t elements) {
834
+ ARROW_RETURN_NOT_OK(ValidateOverflow(elements));
835
+ return byte_builder_.Reserve(elements);
836
+ }
837
+
838
+ void Reset() override;
839
+ Status Resize(int64_t capacity) override;
840
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
841
+
842
+ /// \cond FALSE
843
+ using ArrayBuilder::Finish;
844
+ /// \endcond
845
+
846
+ Status Finish(std::shared_ptr<FixedSizeBinaryArray>* out) { return FinishTyped(out); }
847
+
848
+ /// \return size of values buffer so far
849
+ int64_t value_data_length() const { return byte_builder_.length(); }
850
+
851
+ int32_t byte_width() const { return byte_width_; }
852
+
853
+ /// Temporary access to a value.
854
+ ///
855
+ /// This pointer becomes invalid on the next modifying operation.
856
+ const uint8_t* GetValue(int64_t i) const;
857
+
858
+ /// Temporary access to a value.
859
+ ///
860
+ /// This view becomes invalid on the next modifying operation.
861
+ std::string_view GetView(int64_t i) const;
862
+
863
+ static constexpr int64_t memory_limit() {
864
+ return std::numeric_limits<int64_t>::max() - 1;
865
+ }
866
+
867
+ std::shared_ptr<DataType> type() const override {
868
+ return fixed_size_binary(byte_width_);
869
+ }
870
+
871
+ protected:
872
+ int32_t byte_width_;
873
+ BufferBuilder byte_builder_;
874
+
875
+ /// Temporary access to a value.
876
+ ///
877
+ /// This pointer becomes invalid on the next modifying operation.
878
+ uint8_t* GetMutableValue(int64_t i) {
879
+ uint8_t* data_ptr = byte_builder_.mutable_data();
880
+ return data_ptr + i * byte_width_;
881
+ }
882
+
883
+ void CheckValueSize(int64_t size);
884
+ };
885
+
886
+ /// @}
887
+
888
+ // ----------------------------------------------------------------------
889
+ // Chunked builders: build a sequence of BinaryArray or StringArray that are
890
+ // limited to a particular size (to the upper limit of 2GB)
891
+
892
+ namespace internal {
893
+
894
+ class ARROW_EXPORT ChunkedBinaryBuilder {
895
+ public:
896
+ explicit ChunkedBinaryBuilder(int32_t max_chunk_value_length,
897
+ MemoryPool* pool = default_memory_pool());
898
+
899
+ ChunkedBinaryBuilder(int32_t max_chunk_value_length, int32_t max_chunk_length,
900
+ MemoryPool* pool = default_memory_pool());
901
+
902
+ virtual ~ChunkedBinaryBuilder() = default;
903
+
904
+ Status Append(const uint8_t* value, int32_t length) {
905
+ if (ARROW_PREDICT_FALSE(length + builder_->value_data_length() >
906
+ max_chunk_value_length_)) {
907
+ if (builder_->value_data_length() == 0) {
908
+ // The current item is larger than max_chunk_size_;
909
+ // this chunk will be oversize and hold *only* this item
910
+ ARROW_RETURN_NOT_OK(builder_->Append(value, length));
911
+ return NextChunk();
912
+ }
913
+ // The current item would cause builder_->value_data_length() to exceed
914
+ // max_chunk_size_, so finish this chunk and append the current item to the next
915
+ // chunk
916
+ ARROW_RETURN_NOT_OK(NextChunk());
917
+ return Append(value, length);
918
+ }
919
+
920
+ if (ARROW_PREDICT_FALSE(builder_->length() == max_chunk_length_)) {
921
+ // The current item would cause builder_->length() to exceed max_chunk_length_, so
922
+ // finish this chunk and append the current item to the next chunk
923
+ ARROW_RETURN_NOT_OK(NextChunk());
924
+ }
925
+
926
+ return builder_->Append(value, length);
927
+ }
928
+
929
+ Status Append(std::string_view value) {
930
+ return Append(reinterpret_cast<const uint8_t*>(value.data()),
931
+ static_cast<int32_t>(value.size()));
932
+ }
933
+
934
+ Status AppendNull() {
935
+ if (ARROW_PREDICT_FALSE(builder_->length() == max_chunk_length_)) {
936
+ ARROW_RETURN_NOT_OK(NextChunk());
937
+ }
938
+ return builder_->AppendNull();
939
+ }
940
+
941
+ Status Reserve(int64_t values);
942
+
943
+ virtual Status Finish(ArrayVector* out);
944
+
945
+ protected:
946
+ Status NextChunk();
947
+
948
+ // maximum total character data size per chunk
949
+ int64_t max_chunk_value_length_;
950
+
951
+ // maximum elements allowed per chunk
952
+ int64_t max_chunk_length_ = kListMaximumElements;
953
+
954
+ // when Reserve() would cause builder_ to exceed its max_chunk_length_,
955
+ // add to extra_capacity_ instead and wait to reserve until the next chunk
956
+ int64_t extra_capacity_ = 0;
957
+
958
+ std::unique_ptr<BinaryBuilder> builder_;
959
+ std::vector<std::shared_ptr<Array>> chunks_;
960
+ };
961
+
962
+ class ARROW_EXPORT ChunkedStringBuilder : public ChunkedBinaryBuilder {
963
+ public:
964
+ using ChunkedBinaryBuilder::ChunkedBinaryBuilder;
965
+
966
+ Status Finish(ArrayVector* out) override;
967
+ };
968
+
969
+ } // namespace internal
970
+
971
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_decimal.h ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+
22
+ #include "arrow/array/array_decimal.h"
23
+ #include "arrow/array/builder_base.h"
24
+ #include "arrow/array/builder_binary.h"
25
+ #include "arrow/array/data.h"
26
+ #include "arrow/status.h"
27
+ #include "arrow/type.h"
28
+ #include "arrow/util/visibility.h"
29
+
30
+ namespace arrow {
31
+
32
+ /// \addtogroup numeric-builders
33
+ ///
34
+ /// @{
35
+
36
+ class ARROW_EXPORT Decimal128Builder : public FixedSizeBinaryBuilder {
37
+ public:
38
+ using TypeClass = Decimal128Type;
39
+ using ValueType = Decimal128;
40
+
41
+ explicit Decimal128Builder(const std::shared_ptr<DataType>& type,
42
+ MemoryPool* pool = default_memory_pool(),
43
+ int64_t alignment = kDefaultBufferAlignment);
44
+
45
+ using FixedSizeBinaryBuilder::Append;
46
+ using FixedSizeBinaryBuilder::AppendValues;
47
+ using FixedSizeBinaryBuilder::Reset;
48
+
49
+ Status Append(Decimal128 val);
50
+ void UnsafeAppend(Decimal128 val);
51
+ void UnsafeAppend(std::string_view val);
52
+
53
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
54
+
55
+ /// \cond FALSE
56
+ using ArrayBuilder::Finish;
57
+ /// \endcond
58
+
59
+ Status Finish(std::shared_ptr<Decimal128Array>* out) { return FinishTyped(out); }
60
+
61
+ std::shared_ptr<DataType> type() const override { return decimal_type_; }
62
+
63
+ protected:
64
+ std::shared_ptr<Decimal128Type> decimal_type_;
65
+ };
66
+
67
+ class ARROW_EXPORT Decimal256Builder : public FixedSizeBinaryBuilder {
68
+ public:
69
+ using TypeClass = Decimal256Type;
70
+ using ValueType = Decimal256;
71
+
72
+ explicit Decimal256Builder(const std::shared_ptr<DataType>& type,
73
+ MemoryPool* pool = default_memory_pool(),
74
+ int64_t alignment = kDefaultBufferAlignment);
75
+
76
+ using FixedSizeBinaryBuilder::Append;
77
+ using FixedSizeBinaryBuilder::AppendValues;
78
+ using FixedSizeBinaryBuilder::Reset;
79
+
80
+ Status Append(const Decimal256& val);
81
+ void UnsafeAppend(const Decimal256& val);
82
+ void UnsafeAppend(std::string_view val);
83
+
84
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
85
+
86
+ /// \cond FALSE
87
+ using ArrayBuilder::Finish;
88
+ /// \endcond
89
+
90
+ Status Finish(std::shared_ptr<Decimal256Array>* out) { return FinishTyped(out); }
91
+
92
+ std::shared_ptr<DataType> type() const override { return decimal_type_; }
93
+
94
+ protected:
95
+ std::shared_ptr<Decimal256Type> decimal_type_;
96
+ };
97
+
98
+ using DecimalBuilder = Decimal128Builder;
99
+
100
+ /// @}
101
+
102
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_dict.h ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <algorithm>
21
+ #include <cstdint>
22
+ #include <memory>
23
+ #include <type_traits>
24
+
25
+ #include "arrow/array/array_base.h"
26
+ #include "arrow/array/array_binary.h"
27
+ #include "arrow/array/builder_adaptive.h" // IWYU pragma: export
28
+ #include "arrow/array/builder_base.h" // IWYU pragma: export
29
+ #include "arrow/array/builder_primitive.h" // IWYU pragma: export
30
+ #include "arrow/array/data.h"
31
+ #include "arrow/array/util.h"
32
+ #include "arrow/scalar.h"
33
+ #include "arrow/status.h"
34
+ #include "arrow/type.h"
35
+ #include "arrow/type_traits.h"
36
+ #include "arrow/util/bit_block_counter.h"
37
+ #include "arrow/util/checked_cast.h"
38
+ #include "arrow/util/decimal.h"
39
+ #include "arrow/util/macros.h"
40
+ #include "arrow/util/visibility.h"
41
+
42
+ namespace arrow {
43
+
44
+ // ----------------------------------------------------------------------
45
+ // Dictionary builder
46
+
47
+ namespace internal {
48
+
49
+ template <typename T, typename Enable = void>
50
+ struct DictionaryValue {
51
+ using type = typename T::c_type;
52
+ using PhysicalType = T;
53
+ };
54
+
55
+ template <typename T>
56
+ struct DictionaryValue<T, enable_if_base_binary<T>> {
57
+ using type = std::string_view;
58
+ using PhysicalType =
59
+ typename std::conditional<std::is_same<typename T::offset_type, int32_t>::value,
60
+ BinaryType, LargeBinaryType>::type;
61
+ };
62
+
63
+ template <typename T>
64
+ struct DictionaryValue<T, enable_if_binary_view_like<T>> {
65
+ using type = std::string_view;
66
+ using PhysicalType = BinaryViewType;
67
+ };
68
+
69
+ template <typename T>
70
+ struct DictionaryValue<T, enable_if_fixed_size_binary<T>> {
71
+ using type = std::string_view;
72
+ using PhysicalType = BinaryType;
73
+ };
74
+
75
+ class ARROW_EXPORT DictionaryMemoTable {
76
+ public:
77
+ DictionaryMemoTable(MemoryPool* pool, const std::shared_ptr<DataType>& type);
78
+ DictionaryMemoTable(MemoryPool* pool, const std::shared_ptr<Array>& dictionary);
79
+ ~DictionaryMemoTable();
80
+
81
+ Status GetArrayData(int64_t start_offset, std::shared_ptr<ArrayData>* out);
82
+
83
+ /// \brief Insert new memo values
84
+ Status InsertValues(const Array& values);
85
+
86
+ int32_t size() const;
87
+
88
+ template <typename T>
89
+ Status GetOrInsert(typename DictionaryValue<T>::type value, int32_t* out) {
90
+ // We want to keep the DictionaryMemoTable implementation private, also we can't
91
+ // use extern template classes because of compiler issues (MinGW?). Instead,
92
+ // we expose explicit function overrides for each supported physical type.
93
+ const typename DictionaryValue<T>::PhysicalType* physical_type = NULLPTR;
94
+ return GetOrInsert(physical_type, value, out);
95
+ }
96
+
97
+ private:
98
+ Status GetOrInsert(const BooleanType*, bool value, int32_t* out);
99
+ Status GetOrInsert(const Int8Type*, int8_t value, int32_t* out);
100
+ Status GetOrInsert(const Int16Type*, int16_t value, int32_t* out);
101
+ Status GetOrInsert(const Int32Type*, int32_t value, int32_t* out);
102
+ Status GetOrInsert(const Int64Type*, int64_t value, int32_t* out);
103
+ Status GetOrInsert(const UInt8Type*, uint8_t value, int32_t* out);
104
+ Status GetOrInsert(const UInt16Type*, uint16_t value, int32_t* out);
105
+ Status GetOrInsert(const UInt32Type*, uint32_t value, int32_t* out);
106
+ Status GetOrInsert(const UInt64Type*, uint64_t value, int32_t* out);
107
+ Status GetOrInsert(const DurationType*, int64_t value, int32_t* out);
108
+ Status GetOrInsert(const TimestampType*, int64_t value, int32_t* out);
109
+ Status GetOrInsert(const Date32Type*, int32_t value, int32_t* out);
110
+ Status GetOrInsert(const Date64Type*, int64_t value, int32_t* out);
111
+ Status GetOrInsert(const Time32Type*, int32_t value, int32_t* out);
112
+ Status GetOrInsert(const Time64Type*, int64_t value, int32_t* out);
113
+ Status GetOrInsert(const MonthDayNanoIntervalType*,
114
+ MonthDayNanoIntervalType::MonthDayNanos value, int32_t* out);
115
+ Status GetOrInsert(const DayTimeIntervalType*,
116
+ DayTimeIntervalType::DayMilliseconds value, int32_t* out);
117
+ Status GetOrInsert(const MonthIntervalType*, int32_t value, int32_t* out);
118
+ Status GetOrInsert(const FloatType*, float value, int32_t* out);
119
+ Status GetOrInsert(const DoubleType*, double value, int32_t* out);
120
+
121
+ Status GetOrInsert(const BinaryType*, std::string_view value, int32_t* out);
122
+ Status GetOrInsert(const LargeBinaryType*, std::string_view value, int32_t* out);
123
+ Status GetOrInsert(const BinaryViewType*, std::string_view value, int32_t* out);
124
+
125
+ class DictionaryMemoTableImpl;
126
+ std::unique_ptr<DictionaryMemoTableImpl> impl_;
127
+ };
128
+
129
+ } // namespace internal
130
+
131
+ /// \addtogroup dictionary-builders
132
+ ///
133
+ /// @{
134
+
135
+ namespace internal {
136
+
137
+ /// \brief Array builder for created encoded DictionaryArray from
138
+ /// dense array
139
+ ///
140
+ /// Unlike other builders, dictionary builder does not completely
141
+ /// reset the state on Finish calls.
142
+ template <typename BuilderType, typename T>
143
+ class DictionaryBuilderBase : public ArrayBuilder {
144
+ public:
145
+ using TypeClass = DictionaryType;
146
+ using Value = typename DictionaryValue<T>::type;
147
+
148
+ // WARNING: the type given below is the value type, not the DictionaryType.
149
+ // The DictionaryType is instantiated on the Finish() call.
150
+ template <typename B = BuilderType, typename T1 = T>
151
+ DictionaryBuilderBase(uint8_t start_int_size,
152
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value &&
153
+ !is_fixed_size_binary_type<T1>::value,
154
+ const std::shared_ptr<DataType>&>
155
+ value_type,
156
+ MemoryPool* pool = default_memory_pool(),
157
+ int64_t alignment = kDefaultBufferAlignment)
158
+ : ArrayBuilder(pool, alignment),
159
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
160
+ delta_offset_(0),
161
+ byte_width_(-1),
162
+ indices_builder_(start_int_size, pool, alignment),
163
+ value_type_(value_type) {}
164
+
165
+ template <typename T1 = T>
166
+ explicit DictionaryBuilderBase(
167
+ enable_if_t<!is_fixed_size_binary_type<T1>::value, const std::shared_ptr<DataType>&>
168
+ value_type,
169
+ MemoryPool* pool = default_memory_pool(),
170
+ int64_t alignment = kDefaultBufferAlignment)
171
+ : ArrayBuilder(pool, alignment),
172
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
173
+ delta_offset_(0),
174
+ byte_width_(-1),
175
+ indices_builder_(pool, alignment),
176
+ value_type_(value_type) {}
177
+
178
+ template <typename T1 = T>
179
+ explicit DictionaryBuilderBase(
180
+ const std::shared_ptr<DataType>& index_type,
181
+ enable_if_t<!is_fixed_size_binary_type<T1>::value, const std::shared_ptr<DataType>&>
182
+ value_type,
183
+ MemoryPool* pool = default_memory_pool(),
184
+ int64_t alignment = kDefaultBufferAlignment)
185
+ : ArrayBuilder(pool, alignment),
186
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
187
+ delta_offset_(0),
188
+ byte_width_(-1),
189
+ indices_builder_(index_type, pool, alignment),
190
+ value_type_(value_type) {}
191
+
192
+ template <typename B = BuilderType, typename T1 = T>
193
+ DictionaryBuilderBase(uint8_t start_int_size,
194
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value &&
195
+ is_fixed_size_binary_type<T1>::value,
196
+ const std::shared_ptr<DataType>&>
197
+ value_type,
198
+ MemoryPool* pool = default_memory_pool(),
199
+ int64_t alignment = kDefaultBufferAlignment)
200
+ : ArrayBuilder(pool, alignment),
201
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
202
+ delta_offset_(0),
203
+ byte_width_(static_cast<const T1&>(*value_type).byte_width()),
204
+ indices_builder_(start_int_size, pool, alignment),
205
+ value_type_(value_type) {}
206
+
207
+ template <typename T1 = T>
208
+ explicit DictionaryBuilderBase(
209
+ enable_if_fixed_size_binary<T1, const std::shared_ptr<DataType>&> value_type,
210
+ MemoryPool* pool = default_memory_pool(),
211
+ int64_t alignment = kDefaultBufferAlignment)
212
+ : ArrayBuilder(pool, alignment),
213
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
214
+ delta_offset_(0),
215
+ byte_width_(static_cast<const T1&>(*value_type).byte_width()),
216
+ indices_builder_(pool, alignment),
217
+ value_type_(value_type) {}
218
+
219
+ template <typename T1 = T>
220
+ explicit DictionaryBuilderBase(
221
+ const std::shared_ptr<DataType>& index_type,
222
+ enable_if_fixed_size_binary<T1, const std::shared_ptr<DataType>&> value_type,
223
+ MemoryPool* pool = default_memory_pool(),
224
+ int64_t alignment = kDefaultBufferAlignment)
225
+ : ArrayBuilder(pool, alignment),
226
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
227
+ delta_offset_(0),
228
+ byte_width_(static_cast<const T1&>(*value_type).byte_width()),
229
+ indices_builder_(index_type, pool, alignment),
230
+ value_type_(value_type) {}
231
+
232
+ template <typename T1 = T>
233
+ explicit DictionaryBuilderBase(
234
+ enable_if_parameter_free<T1, MemoryPool*> pool = default_memory_pool())
235
+ : DictionaryBuilderBase<BuilderType, T1>(TypeTraits<T1>::type_singleton(), pool) {}
236
+
237
+ // This constructor doesn't check for errors. Use InsertMemoValues instead.
238
+ explicit DictionaryBuilderBase(const std::shared_ptr<Array>& dictionary,
239
+ MemoryPool* pool = default_memory_pool(),
240
+ int64_t alignment = kDefaultBufferAlignment)
241
+ : ArrayBuilder(pool, alignment),
242
+ memo_table_(new internal::DictionaryMemoTable(pool, dictionary)),
243
+ delta_offset_(0),
244
+ byte_width_(-1),
245
+ indices_builder_(pool, alignment),
246
+ value_type_(dictionary->type()) {}
247
+
248
+ ~DictionaryBuilderBase() override = default;
249
+
250
+ /// \brief The current number of entries in the dictionary
251
+ int64_t dictionary_length() const { return memo_table_->size(); }
252
+
253
+ /// \brief The value byte width (for FixedSizeBinaryType)
254
+ template <typename T1 = T>
255
+ enable_if_fixed_size_binary<T1, int32_t> byte_width() const {
256
+ return byte_width_;
257
+ }
258
+
259
+ /// \brief Append a scalar value
260
+ Status Append(Value value) {
261
+ ARROW_RETURN_NOT_OK(Reserve(1));
262
+
263
+ int32_t memo_index;
264
+ ARROW_RETURN_NOT_OK(memo_table_->GetOrInsert<T>(value, &memo_index));
265
+ ARROW_RETURN_NOT_OK(indices_builder_.Append(memo_index));
266
+ length_ += 1;
267
+
268
+ return Status::OK();
269
+ }
270
+
271
+ /// \brief Append a fixed-width string (only for FixedSizeBinaryType)
272
+ template <typename T1 = T>
273
+ enable_if_fixed_size_binary<T1, Status> Append(const uint8_t* value) {
274
+ return Append(std::string_view(reinterpret_cast<const char*>(value), byte_width_));
275
+ }
276
+
277
+ /// \brief Append a fixed-width string (only for FixedSizeBinaryType)
278
+ template <typename T1 = T>
279
+ enable_if_fixed_size_binary<T1, Status> Append(const char* value) {
280
+ return Append(std::string_view(value, byte_width_));
281
+ }
282
+
283
+ /// \brief Append a string (only for binary types)
284
+ template <typename T1 = T>
285
+ enable_if_binary_like<T1, Status> Append(const uint8_t* value, int32_t length) {
286
+ return Append(reinterpret_cast<const char*>(value), length);
287
+ }
288
+
289
+ /// \brief Append a string (only for binary types)
290
+ template <typename T1 = T>
291
+ enable_if_binary_like<T1, Status> Append(const char* value, int32_t length) {
292
+ return Append(std::string_view(value, length));
293
+ }
294
+
295
+ /// \brief Append a string (only for string types)
296
+ template <typename T1 = T>
297
+ enable_if_string_like<T1, Status> Append(const char* value, int32_t length) {
298
+ return Append(std::string_view(value, length));
299
+ }
300
+
301
+ /// \brief Append a decimal (only for Decimal128Type)
302
+ template <typename T1 = T>
303
+ enable_if_decimal128<T1, Status> Append(const Decimal128& value) {
304
+ uint8_t data[16];
305
+ value.ToBytes(data);
306
+ return Append(data, 16);
307
+ }
308
+
309
+ /// \brief Append a decimal (only for Decimal128Type)
310
+ template <typename T1 = T>
311
+ enable_if_decimal256<T1, Status> Append(const Decimal256& value) {
312
+ uint8_t data[32];
313
+ value.ToBytes(data);
314
+ return Append(data, 32);
315
+ }
316
+
317
+ /// \brief Append a scalar null value
318
+ Status AppendNull() final {
319
+ length_ += 1;
320
+ null_count_ += 1;
321
+
322
+ return indices_builder_.AppendNull();
323
+ }
324
+
325
+ Status AppendNulls(int64_t length) final {
326
+ length_ += length;
327
+ null_count_ += length;
328
+
329
+ return indices_builder_.AppendNulls(length);
330
+ }
331
+
332
+ Status AppendEmptyValue() final {
333
+ length_ += 1;
334
+
335
+ return indices_builder_.AppendEmptyValue();
336
+ }
337
+
338
+ Status AppendEmptyValues(int64_t length) final {
339
+ length_ += length;
340
+
341
+ return indices_builder_.AppendEmptyValues(length);
342
+ }
343
+
344
+ Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override {
345
+ if (!scalar.is_valid) return AppendNulls(n_repeats);
346
+
347
+ const auto& dict_ty = internal::checked_cast<const DictionaryType&>(*scalar.type);
348
+ const DictionaryScalar& dict_scalar =
349
+ internal::checked_cast<const DictionaryScalar&>(scalar);
350
+ const auto& dict = internal::checked_cast<const typename TypeTraits<T>::ArrayType&>(
351
+ *dict_scalar.value.dictionary);
352
+ ARROW_RETURN_NOT_OK(Reserve(n_repeats));
353
+ switch (dict_ty.index_type()->id()) {
354
+ case Type::UINT8:
355
+ return AppendScalarImpl<UInt8Type>(dict, *dict_scalar.value.index, n_repeats);
356
+ case Type::INT8:
357
+ return AppendScalarImpl<Int8Type>(dict, *dict_scalar.value.index, n_repeats);
358
+ case Type::UINT16:
359
+ return AppendScalarImpl<UInt16Type>(dict, *dict_scalar.value.index, n_repeats);
360
+ case Type::INT16:
361
+ return AppendScalarImpl<Int16Type>(dict, *dict_scalar.value.index, n_repeats);
362
+ case Type::UINT32:
363
+ return AppendScalarImpl<UInt32Type>(dict, *dict_scalar.value.index, n_repeats);
364
+ case Type::INT32:
365
+ return AppendScalarImpl<Int32Type>(dict, *dict_scalar.value.index, n_repeats);
366
+ case Type::UINT64:
367
+ return AppendScalarImpl<UInt64Type>(dict, *dict_scalar.value.index, n_repeats);
368
+ case Type::INT64:
369
+ return AppendScalarImpl<Int64Type>(dict, *dict_scalar.value.index, n_repeats);
370
+ default:
371
+ return Status::TypeError("Invalid index type: ", dict_ty);
372
+ }
373
+ return Status::OK();
374
+ }
375
+
376
+ Status AppendScalars(const ScalarVector& scalars) override {
377
+ for (const auto& scalar : scalars) {
378
+ ARROW_RETURN_NOT_OK(AppendScalar(*scalar, /*n_repeats=*/1));
379
+ }
380
+ return Status::OK();
381
+ }
382
+
383
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length) final {
384
+ // Visit the indices and insert the unpacked values.
385
+ const auto& dict_ty = internal::checked_cast<const DictionaryType&>(*array.type);
386
+ // See if possible to avoid using ToArrayData here
387
+ const typename TypeTraits<T>::ArrayType dict(array.dictionary().ToArrayData());
388
+ ARROW_RETURN_NOT_OK(Reserve(length));
389
+ switch (dict_ty.index_type()->id()) {
390
+ case Type::UINT8:
391
+ return AppendArraySliceImpl<uint8_t>(dict, array, offset, length);
392
+ case Type::INT8:
393
+ return AppendArraySliceImpl<int8_t>(dict, array, offset, length);
394
+ case Type::UINT16:
395
+ return AppendArraySliceImpl<uint16_t>(dict, array, offset, length);
396
+ case Type::INT16:
397
+ return AppendArraySliceImpl<int16_t>(dict, array, offset, length);
398
+ case Type::UINT32:
399
+ return AppendArraySliceImpl<uint32_t>(dict, array, offset, length);
400
+ case Type::INT32:
401
+ return AppendArraySliceImpl<int32_t>(dict, array, offset, length);
402
+ case Type::UINT64:
403
+ return AppendArraySliceImpl<uint64_t>(dict, array, offset, length);
404
+ case Type::INT64:
405
+ return AppendArraySliceImpl<int64_t>(dict, array, offset, length);
406
+ default:
407
+ return Status::TypeError("Invalid index type: ", dict_ty);
408
+ }
409
+ return Status::OK();
410
+ }
411
+
412
+ /// \brief Insert values into the dictionary's memo, but do not append any
413
+ /// indices. Can be used to initialize a new builder with known dictionary
414
+ /// values
415
+ /// \param[in] values dictionary values to add to memo. Type must match
416
+ /// builder type
417
+ Status InsertMemoValues(const Array& values) {
418
+ return memo_table_->InsertValues(values);
419
+ }
420
+
421
+ /// \brief Append a whole dense array to the builder
422
+ template <typename T1 = T>
423
+ enable_if_t<!is_fixed_size_binary_type<T1>::value, Status> AppendArray(
424
+ const Array& array) {
425
+ using ArrayType = typename TypeTraits<T>::ArrayType;
426
+
427
+ #ifndef NDEBUG
428
+ ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType(
429
+ value_type_, array, "Wrong value type of array to be appended"));
430
+ #endif
431
+
432
+ const auto& concrete_array = static_cast<const ArrayType&>(array);
433
+ for (int64_t i = 0; i < array.length(); i++) {
434
+ if (array.IsNull(i)) {
435
+ ARROW_RETURN_NOT_OK(AppendNull());
436
+ } else {
437
+ ARROW_RETURN_NOT_OK(Append(concrete_array.GetView(i)));
438
+ }
439
+ }
440
+ return Status::OK();
441
+ }
442
+
443
+ template <typename T1 = T>
444
+ enable_if_fixed_size_binary<T1, Status> AppendArray(const Array& array) {
445
+ #ifndef NDEBUG
446
+ ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType(
447
+ value_type_, array, "Wrong value type of array to be appended"));
448
+ #endif
449
+
450
+ const auto& concrete_array = static_cast<const FixedSizeBinaryArray&>(array);
451
+ for (int64_t i = 0; i < array.length(); i++) {
452
+ if (array.IsNull(i)) {
453
+ ARROW_RETURN_NOT_OK(AppendNull());
454
+ } else {
455
+ ARROW_RETURN_NOT_OK(Append(concrete_array.GetValue(i)));
456
+ }
457
+ }
458
+ return Status::OK();
459
+ }
460
+
461
+ void Reset() override {
462
+ // Perform a partial reset. Call ResetFull to also reset the accumulated
463
+ // dictionary values
464
+ ArrayBuilder::Reset();
465
+ indices_builder_.Reset();
466
+ }
467
+
468
+ /// \brief Reset and also clear accumulated dictionary values in memo table
469
+ void ResetFull() {
470
+ Reset();
471
+ memo_table_.reset(new internal::DictionaryMemoTable(pool_, value_type_));
472
+ }
473
+
474
+ Status Resize(int64_t capacity) override {
475
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
476
+ capacity = std::max(capacity, kMinBuilderCapacity);
477
+ ARROW_RETURN_NOT_OK(indices_builder_.Resize(capacity));
478
+ capacity_ = indices_builder_.capacity();
479
+ return Status::OK();
480
+ }
481
+
482
+ /// \brief Return dictionary indices and a delta dictionary since the last
483
+ /// time that Finish or FinishDelta were called, and reset state of builder
484
+ /// (except the memo table)
485
+ Status FinishDelta(std::shared_ptr<Array>* out_indices,
486
+ std::shared_ptr<Array>* out_delta) {
487
+ std::shared_ptr<ArrayData> indices_data;
488
+ std::shared_ptr<ArrayData> delta_data;
489
+ ARROW_RETURN_NOT_OK(FinishWithDictOffset(delta_offset_, &indices_data, &delta_data));
490
+ *out_indices = MakeArray(indices_data);
491
+ *out_delta = MakeArray(delta_data);
492
+ return Status::OK();
493
+ }
494
+
495
+ /// \cond FALSE
496
+ using ArrayBuilder::Finish;
497
+ /// \endcond
498
+
499
+ Status Finish(std::shared_ptr<DictionaryArray>* out) { return FinishTyped(out); }
500
+
501
+ std::shared_ptr<DataType> type() const override {
502
+ return ::arrow::dictionary(indices_builder_.type(), value_type_);
503
+ }
504
+
505
+ protected:
506
+ template <typename c_type>
507
+ Status AppendArraySliceImpl(const typename TypeTraits<T>::ArrayType& dict,
508
+ const ArraySpan& array, int64_t offset, int64_t length) {
509
+ const c_type* values = array.GetValues<c_type>(1) + offset;
510
+ return VisitBitBlocks(
511
+ array.buffers[0].data, array.offset + offset, length,
512
+ [&](const int64_t position) {
513
+ const int64_t index = static_cast<int64_t>(values[position]);
514
+ if (dict.IsValid(index)) {
515
+ return Append(dict.GetView(index));
516
+ }
517
+ return AppendNull();
518
+ },
519
+ [&]() { return AppendNull(); });
520
+ }
521
+
522
+ template <typename IndexType>
523
+ Status AppendScalarImpl(const typename TypeTraits<T>::ArrayType& dict,
524
+ const Scalar& index_scalar, int64_t n_repeats) {
525
+ using ScalarType = typename TypeTraits<IndexType>::ScalarType;
526
+ const auto index = internal::checked_cast<const ScalarType&>(index_scalar).value;
527
+ if (index_scalar.is_valid && dict.IsValid(index)) {
528
+ const auto& value = dict.GetView(index);
529
+ for (int64_t i = 0; i < n_repeats; i++) {
530
+ ARROW_RETURN_NOT_OK(Append(value));
531
+ }
532
+ return Status::OK();
533
+ }
534
+ return AppendNulls(n_repeats);
535
+ }
536
+
537
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
538
+ std::shared_ptr<ArrayData> dictionary;
539
+ ARROW_RETURN_NOT_OK(FinishWithDictOffset(/*offset=*/0, out, &dictionary));
540
+
541
+ // Set type of array data to the right dictionary type
542
+ (*out)->type = type();
543
+ (*out)->dictionary = dictionary;
544
+ return Status::OK();
545
+ }
546
+
547
+ Status FinishWithDictOffset(int64_t dict_offset,
548
+ std::shared_ptr<ArrayData>* out_indices,
549
+ std::shared_ptr<ArrayData>* out_dictionary) {
550
+ // Finalize indices array
551
+ ARROW_RETURN_NOT_OK(indices_builder_.FinishInternal(out_indices));
552
+
553
+ // Generate dictionary array from hash table contents
554
+ ARROW_RETURN_NOT_OK(memo_table_->GetArrayData(dict_offset, out_dictionary));
555
+ delta_offset_ = memo_table_->size();
556
+
557
+ // Update internals for further uses of this DictionaryBuilder
558
+ ArrayBuilder::Reset();
559
+ return Status::OK();
560
+ }
561
+
562
+ std::unique_ptr<DictionaryMemoTable> memo_table_;
563
+
564
+ // The size of the dictionary memo at last invocation of Finish, to use in
565
+ // FinishDelta for computing dictionary deltas
566
+ int32_t delta_offset_;
567
+
568
+ // Only used for FixedSizeBinaryType
569
+ int32_t byte_width_;
570
+
571
+ BuilderType indices_builder_;
572
+ std::shared_ptr<DataType> value_type_;
573
+ };
574
+
575
+ template <typename BuilderType>
576
+ class DictionaryBuilderBase<BuilderType, NullType> : public ArrayBuilder {
577
+ public:
578
+ template <typename B = BuilderType>
579
+ DictionaryBuilderBase(
580
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value, uint8_t>
581
+ start_int_size,
582
+ const std::shared_ptr<DataType>& value_type,
583
+ MemoryPool* pool = default_memory_pool())
584
+ : ArrayBuilder(pool), indices_builder_(start_int_size, pool) {}
585
+
586
+ explicit DictionaryBuilderBase(const std::shared_ptr<DataType>& value_type,
587
+ MemoryPool* pool = default_memory_pool())
588
+ : ArrayBuilder(pool), indices_builder_(pool) {}
589
+
590
+ explicit DictionaryBuilderBase(const std::shared_ptr<DataType>& index_type,
591
+ const std::shared_ptr<DataType>& value_type,
592
+ MemoryPool* pool = default_memory_pool())
593
+ : ArrayBuilder(pool), indices_builder_(index_type, pool) {}
594
+
595
+ template <typename B = BuilderType>
596
+ explicit DictionaryBuilderBase(
597
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value, uint8_t>
598
+ start_int_size,
599
+ MemoryPool* pool = default_memory_pool())
600
+ : ArrayBuilder(pool), indices_builder_(start_int_size, pool) {}
601
+
602
+ explicit DictionaryBuilderBase(MemoryPool* pool = default_memory_pool())
603
+ : ArrayBuilder(pool), indices_builder_(pool) {}
604
+
605
+ explicit DictionaryBuilderBase(const std::shared_ptr<Array>& dictionary,
606
+ MemoryPool* pool = default_memory_pool())
607
+ : ArrayBuilder(pool), indices_builder_(pool) {}
608
+
609
+ /// \brief Append a scalar null value
610
+ Status AppendNull() final {
611
+ length_ += 1;
612
+ null_count_ += 1;
613
+
614
+ return indices_builder_.AppendNull();
615
+ }
616
+
617
+ Status AppendNulls(int64_t length) final {
618
+ length_ += length;
619
+ null_count_ += length;
620
+
621
+ return indices_builder_.AppendNulls(length);
622
+ }
623
+
624
+ Status AppendEmptyValue() final {
625
+ length_ += 1;
626
+
627
+ return indices_builder_.AppendEmptyValue();
628
+ }
629
+
630
+ Status AppendEmptyValues(int64_t length) final {
631
+ length_ += length;
632
+
633
+ return indices_builder_.AppendEmptyValues(length);
634
+ }
635
+
636
+ /// \brief Append a whole dense array to the builder
637
+ Status AppendArray(const Array& array) {
638
+ #ifndef NDEBUG
639
+ ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType(
640
+ Type::NA, array, "Wrong value type of array to be appended"));
641
+ #endif
642
+ for (int64_t i = 0; i < array.length(); i++) {
643
+ ARROW_RETURN_NOT_OK(AppendNull());
644
+ }
645
+ return Status::OK();
646
+ }
647
+
648
+ Status Resize(int64_t capacity) override {
649
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
650
+ capacity = std::max(capacity, kMinBuilderCapacity);
651
+
652
+ ARROW_RETURN_NOT_OK(indices_builder_.Resize(capacity));
653
+ capacity_ = indices_builder_.capacity();
654
+ return Status::OK();
655
+ }
656
+
657
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
658
+ ARROW_RETURN_NOT_OK(indices_builder_.FinishInternal(out));
659
+ (*out)->type = dictionary((*out)->type, null());
660
+ (*out)->dictionary = NullArray(0).data();
661
+ return Status::OK();
662
+ }
663
+
664
+ /// \cond FALSE
665
+ using ArrayBuilder::Finish;
666
+ /// \endcond
667
+
668
+ Status Finish(std::shared_ptr<DictionaryArray>* out) { return FinishTyped(out); }
669
+
670
+ std::shared_ptr<DataType> type() const override {
671
+ return ::arrow::dictionary(indices_builder_.type(), null());
672
+ }
673
+
674
+ protected:
675
+ BuilderType indices_builder_;
676
+ };
677
+
678
+ } // namespace internal
679
+
680
+ /// \brief A DictionaryArray builder that uses AdaptiveIntBuilder to return the
681
+ /// smallest index size that can accommodate the dictionary indices
682
+ template <typename T>
683
+ class DictionaryBuilder : public internal::DictionaryBuilderBase<AdaptiveIntBuilder, T> {
684
+ public:
685
+ using BASE = internal::DictionaryBuilderBase<AdaptiveIntBuilder, T>;
686
+ using BASE::BASE;
687
+
688
+ /// \brief Append dictionary indices directly without modifying memo
689
+ ///
690
+ /// NOTE: Experimental API
691
+ Status AppendIndices(const int64_t* values, int64_t length,
692
+ const uint8_t* valid_bytes = NULLPTR) {
693
+ int64_t null_count_before = this->indices_builder_.null_count();
694
+ ARROW_RETURN_NOT_OK(this->indices_builder_.AppendValues(values, length, valid_bytes));
695
+ this->capacity_ = this->indices_builder_.capacity();
696
+ this->length_ += length;
697
+ this->null_count_ += this->indices_builder_.null_count() - null_count_before;
698
+ return Status::OK();
699
+ }
700
+ };
701
+
702
+ /// \brief A DictionaryArray builder that always returns int32 dictionary
703
+ /// indices so that data cast to dictionary form will have a consistent index
704
+ /// type, e.g. for creating a ChunkedArray
705
+ template <typename T>
706
+ class Dictionary32Builder : public internal::DictionaryBuilderBase<Int32Builder, T> {
707
+ public:
708
+ using BASE = internal::DictionaryBuilderBase<Int32Builder, T>;
709
+ using BASE::BASE;
710
+
711
+ /// \brief Append dictionary indices directly without modifying memo
712
+ ///
713
+ /// NOTE: Experimental API
714
+ Status AppendIndices(const int32_t* values, int64_t length,
715
+ const uint8_t* valid_bytes = NULLPTR) {
716
+ int64_t null_count_before = this->indices_builder_.null_count();
717
+ ARROW_RETURN_NOT_OK(this->indices_builder_.AppendValues(values, length, valid_bytes));
718
+ this->capacity_ = this->indices_builder_.capacity();
719
+ this->length_ += length;
720
+ this->null_count_ += this->indices_builder_.null_count() - null_count_before;
721
+ return Status::OK();
722
+ }
723
+ };
724
+
725
+ // ----------------------------------------------------------------------
726
+ // Binary / Unicode builders
727
+ // (compatibility aliases; those used to be derived classes with additional
728
+ // Append() overloads, but they have been folded into DictionaryBuilderBase)
729
+
730
+ using BinaryDictionaryBuilder = DictionaryBuilder<BinaryType>;
731
+ using StringDictionaryBuilder = DictionaryBuilder<StringType>;
732
+ using BinaryDictionary32Builder = Dictionary32Builder<BinaryType>;
733
+ using StringDictionary32Builder = Dictionary32Builder<StringType>;
734
+
735
+ /// @}
736
+
737
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_nested.h ADDED
@@ -0,0 +1,839 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <limits>
22
+ #include <memory>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "arrow/array/array_nested.h"
27
+ #include "arrow/array/builder_base.h"
28
+ #include "arrow/array/data.h"
29
+ #include "arrow/buffer.h"
30
+ #include "arrow/buffer_builder.h"
31
+ #include "arrow/status.h"
32
+ #include "arrow/type.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ /// \addtogroup nested-builders
39
+ ///
40
+ /// @{
41
+
42
+ // ----------------------------------------------------------------------
43
+ // VarLengthListLikeBuilder
44
+
45
+ template <typename TYPE>
46
+ class ARROW_EXPORT VarLengthListLikeBuilder : public ArrayBuilder {
47
+ public:
48
+ using TypeClass = TYPE;
49
+ using offset_type = typename TypeClass::offset_type;
50
+
51
+ /// Use this constructor to incrementally build the value array along with offsets and
52
+ /// null bitmap.
53
+ VarLengthListLikeBuilder(MemoryPool* pool,
54
+ std::shared_ptr<ArrayBuilder> const& value_builder,
55
+ const std::shared_ptr<DataType>& type,
56
+ int64_t alignment = kDefaultBufferAlignment)
57
+ : ArrayBuilder(pool, alignment),
58
+ offsets_builder_(pool, alignment),
59
+ value_builder_(value_builder),
60
+ value_field_(type->field(0)->WithType(NULLPTR)) {}
61
+
62
+ VarLengthListLikeBuilder(MemoryPool* pool,
63
+ std::shared_ptr<ArrayBuilder> const& value_builder,
64
+ int64_t alignment = kDefaultBufferAlignment)
65
+ : VarLengthListLikeBuilder(pool, value_builder,
66
+ std::make_shared<TYPE>(value_builder->type()),
67
+ alignment) {}
68
+
69
+ ~VarLengthListLikeBuilder() override = default;
70
+
71
+ Status Resize(int64_t capacity) override {
72
+ if (ARROW_PREDICT_FALSE(capacity > maximum_elements())) {
73
+ return Status::CapacityError(type_name(),
74
+ " array cannot reserve space for more than ",
75
+ maximum_elements(), " got ", capacity);
76
+ }
77
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
78
+
79
+ // One more than requested for list offsets
80
+ const int64_t offsets_capacity =
81
+ is_list_view(TYPE::type_id) ? capacity : capacity + 1;
82
+ ARROW_RETURN_NOT_OK(offsets_builder_.Resize(offsets_capacity));
83
+ return ArrayBuilder::Resize(capacity);
84
+ }
85
+
86
+ void Reset() override {
87
+ ArrayBuilder::Reset();
88
+ offsets_builder_.Reset();
89
+ value_builder_->Reset();
90
+ }
91
+
92
+ /// \brief Start a new variable-length list slot
93
+ ///
94
+ /// This function should be called before appending elements to the
95
+ /// value builder. Elements appended to the value builder before this function
96
+ /// is called for the first time, will not be members of any list value.
97
+ ///
98
+ /// After this function is called, list_length elements SHOULD be appended to
99
+ /// the values builder. If this contract is violated, the behavior is defined by
100
+ /// the concrete builder implementation and SHOULD NOT be relied upon unless
101
+ /// the caller is specifically building a [Large]List or [Large]ListView array.
102
+ ///
103
+ /// For [Large]List arrays, the list slot length will be the number of elements
104
+ /// appended to the values builder before the next call to Append* or Finish. For
105
+ /// [Large]ListView arrays, the list slot length will be exactly list_length, but if
106
+ /// Append* is called before at least list_length elements are appended to the values
107
+ /// builder, the current list slot will share elements with the next list
108
+ /// slots or an invalid [Large]ListView array will be generated because there
109
+ /// aren't enough elements in the values builder to fill the list slots.
110
+ ///
111
+ /// If you're building a [Large]List and don't need to be compatible
112
+ /// with [Large]ListView, then `BaseListBuilder::Append(bool is_valid)`
113
+ /// is a simpler API.
114
+ ///
115
+ /// \pre if is_valid is false, list_length MUST be 0
116
+ /// \param is_valid Whether the new list slot is valid
117
+ /// \param list_length The number of elements in the list
118
+ Status Append(bool is_valid, int64_t list_length) {
119
+ ARROW_RETURN_NOT_OK(Reserve(1));
120
+ assert(is_valid || list_length == 0);
121
+ UnsafeAppendToBitmap(is_valid);
122
+ UnsafeAppendDimensions(/*offset=*/value_builder_->length(), /*size=*/list_length);
123
+ return Status::OK();
124
+ }
125
+
126
+ Status AppendNull() final {
127
+ // Append() a null list slot with list_length=0.
128
+ //
129
+ // When building [Large]List arrays, elements being appended to the values builder
130
+ // before the next call to Append* or Finish will extend the list slot length, but
131
+ // that is totally fine because list arrays admit non-empty null list slots.
132
+ //
133
+ // In the case of [Large]ListViews that's not a problem either because the
134
+ // list slot length remains zero.
135
+ return Append(false, 0);
136
+ }
137
+
138
+ Status AppendNulls(int64_t length) final {
139
+ ARROW_RETURN_NOT_OK(Reserve(length));
140
+ UnsafeAppendToBitmap(length, false);
141
+ UnsafeAppendEmptyDimensions(/*num_values=*/length);
142
+ return Status::OK();
143
+ }
144
+
145
+ /// \brief Append an empty list slot
146
+ ///
147
+ /// \post Another call to Append* or Finish should be made before appending to
148
+ /// the values builder to ensure list slot remains empty
149
+ Status AppendEmptyValue() final { return Append(true, 0); }
150
+
151
+ /// \brief Append an empty list slot
152
+ ///
153
+ /// \post Another call to Append* or Finish should be made before appending to
154
+ /// the values builder to ensure the last list slot remains empty
155
+ Status AppendEmptyValues(int64_t length) final {
156
+ ARROW_RETURN_NOT_OK(Reserve(length));
157
+ UnsafeAppendToBitmap(length, true);
158
+ UnsafeAppendEmptyDimensions(/*num_values=*/length);
159
+ return Status::OK();
160
+ }
161
+
162
+ /// \brief Vector append
163
+ ///
164
+ /// For list-array builders, the sizes are inferred from the offsets.
165
+ /// BaseListBuilder<T> provides an implementation that doesn't take sizes, but
166
+ /// this virtual function allows dispatching calls to both list-array and
167
+ /// list-view-array builders (which need the sizes)
168
+ ///
169
+ /// \param offsets The offsets of the variable-length lists
170
+ /// \param sizes The sizes of the variable-length lists
171
+ /// \param length The number of offsets, sizes, and validity bits to append
172
+ /// \param valid_bytes If passed, valid_bytes is of equal length to values,
173
+ /// and any zero byte will be considered as a null for that slot
174
+ virtual Status AppendValues(const offset_type* offsets, const offset_type* sizes,
175
+ int64_t length, const uint8_t* valid_bytes) = 0;
176
+
177
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
178
+ int64_t length) override {
179
+ const offset_type* offsets = array.GetValues<offset_type>(1);
180
+ [[maybe_unused]] const offset_type* sizes = NULLPTR;
181
+ if constexpr (is_list_view(TYPE::type_id)) {
182
+ sizes = array.GetValues<offset_type>(2);
183
+ }
184
+ const bool all_valid = !array.MayHaveLogicalNulls();
185
+ const uint8_t* validity = array.HasValidityBitmap() ? array.buffers[0].data : NULLPTR;
186
+ ARROW_RETURN_NOT_OK(Reserve(length));
187
+ for (int64_t row = offset; row < offset + length; row++) {
188
+ const bool is_valid =
189
+ all_valid || (validity && bit_util::GetBit(validity, array.offset + row)) ||
190
+ array.IsValid(row);
191
+ int64_t size = 0;
192
+ if (is_valid) {
193
+ if constexpr (is_list_view(TYPE::type_id)) {
194
+ size = sizes[row];
195
+ } else {
196
+ size = offsets[row + 1] - offsets[row];
197
+ }
198
+ }
199
+ UnsafeAppendToBitmap(is_valid);
200
+ UnsafeAppendDimensions(/*offset=*/value_builder_->length(), size);
201
+ if (is_valid) {
202
+ ARROW_RETURN_NOT_OK(
203
+ value_builder_->AppendArraySlice(array.child_data[0], offsets[row], size));
204
+ }
205
+ }
206
+ return Status::OK();
207
+ }
208
+
209
+ Status ValidateOverflow(int64_t new_elements) const {
210
+ auto new_length = value_builder_->length() + new_elements;
211
+ if (ARROW_PREDICT_FALSE(new_length > maximum_elements())) {
212
+ return Status::CapacityError(type_name(), " array cannot contain more than ",
213
+ maximum_elements(), " elements, have ", new_elements);
214
+ } else {
215
+ return Status::OK();
216
+ }
217
+ }
218
+
219
+ ArrayBuilder* value_builder() const { return value_builder_.get(); }
220
+
221
+ // Cannot make this a static attribute because of linking issues
222
+ static constexpr int64_t maximum_elements() {
223
+ return std::numeric_limits<offset_type>::max() - 1;
224
+ }
225
+
226
+ std::shared_ptr<DataType> type() const override {
227
+ return std::make_shared<TYPE>(value_field_->WithType(value_builder_->type()));
228
+ }
229
+
230
+ private:
231
+ static constexpr const char* type_name() {
232
+ if constexpr (is_list_view(TYPE::type_id)) {
233
+ return "ListView";
234
+ } else {
235
+ return "List";
236
+ }
237
+ }
238
+
239
+ protected:
240
+ /// \brief Append dimensions for num_values empty list slots.
241
+ ///
242
+ /// ListViewBuilder overrides this to also append the sizes.
243
+ virtual void UnsafeAppendEmptyDimensions(int64_t num_values) {
244
+ const int64_t offset = value_builder_->length();
245
+ for (int64_t i = 0; i < num_values; ++i) {
246
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(offset));
247
+ }
248
+ }
249
+
250
+ /// \brief Append dimensions for a single list slot.
251
+ ///
252
+ /// ListViewBuilder overrides this to also append the size.
253
+ virtual void UnsafeAppendDimensions(int64_t offset, int64_t size) {
254
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(offset));
255
+ }
256
+
257
+ TypedBufferBuilder<offset_type> offsets_builder_;
258
+ std::shared_ptr<ArrayBuilder> value_builder_;
259
+ std::shared_ptr<Field> value_field_;
260
+ };
261
+
262
+ // ----------------------------------------------------------------------
263
+ // ListBuilder / LargeListBuilder
264
+
265
+ template <typename TYPE>
266
+ class ARROW_EXPORT BaseListBuilder : public VarLengthListLikeBuilder<TYPE> {
267
+ private:
268
+ using BASE = VarLengthListLikeBuilder<TYPE>;
269
+
270
+ public:
271
+ using TypeClass = TYPE;
272
+ using offset_type = typename BASE::offset_type;
273
+
274
+ using BASE::BASE;
275
+
276
+ using BASE::Append;
277
+
278
+ ~BaseListBuilder() override = default;
279
+
280
+ /// \brief Start a new variable-length list slot
281
+ ///
282
+ /// This function should be called before beginning to append elements to the
283
+ /// value builder
284
+ Status Append(bool is_valid = true) {
285
+ // The value_length parameter to BASE::Append(bool, int64_t) is ignored when
286
+ // building a list array, so we can pass 0 here.
287
+ return BASE::Append(is_valid, 0);
288
+ }
289
+
290
+ /// \brief Vector append
291
+ ///
292
+ /// If passed, valid_bytes is of equal length to values, and any zero byte
293
+ /// will be considered as a null for that slot
294
+ Status AppendValues(const offset_type* offsets, int64_t length,
295
+ const uint8_t* valid_bytes = NULLPTR) {
296
+ ARROW_RETURN_NOT_OK(this->Reserve(length));
297
+ this->UnsafeAppendToBitmap(valid_bytes, length);
298
+ this->offsets_builder_.UnsafeAppend(offsets, length);
299
+ return Status::OK();
300
+ }
301
+
302
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
303
+ int64_t length, const uint8_t* valid_bytes) final {
304
+ // Offsets are assumed to be valid, but the first length-1 sizes have to be
305
+ // consistent with the offsets to partially rule out the possibility that the
306
+ // caller is passing sizes that could work if building a list-view, but don't
307
+ // work on building a list that requires offsets to be non-decreasing.
308
+ //
309
+ // CAUTION: the last size element (`sizes[length - 1]`) is not
310
+ // validated and could be inconsistent with the offsets given in a
311
+ // subsequent call to AppendValues.
312
+ #ifndef NDEBUG
313
+ if (sizes) {
314
+ for (int64_t i = 0; i < length - 1; ++i) {
315
+ if (ARROW_PREDICT_FALSE(offsets[i] != offsets[i + 1] - sizes[i])) {
316
+ if (!valid_bytes || valid_bytes[i]) {
317
+ return Status::Invalid(
318
+ "BaseListBuilder: sizes are inconsistent with offsets provided");
319
+ }
320
+ }
321
+ }
322
+ }
323
+ #endif
324
+ return AppendValues(offsets, length, valid_bytes);
325
+ }
326
+
327
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
328
+ int64_t length) {
329
+ return AppendValues(offsets, sizes, length, /*valid_bytes=*/NULLPTR);
330
+ }
331
+
332
+ Status AppendNextOffset() {
333
+ ARROW_RETURN_NOT_OK(this->ValidateOverflow(0));
334
+ const int64_t num_values = this->value_builder_->length();
335
+ return this->offsets_builder_.Append(static_cast<offset_type>(num_values));
336
+ }
337
+
338
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
339
+ ARROW_RETURN_NOT_OK(AppendNextOffset());
340
+
341
+ // Offset padding zeroed by BufferBuilder
342
+ std::shared_ptr<Buffer> offsets;
343
+ std::shared_ptr<Buffer> null_bitmap;
344
+ ARROW_RETURN_NOT_OK(this->offsets_builder_.Finish(&offsets));
345
+ ARROW_RETURN_NOT_OK(this->null_bitmap_builder_.Finish(&null_bitmap));
346
+
347
+ if (this->value_builder_->length() == 0) {
348
+ // Try to make sure we get a non-null values buffer (ARROW-2744)
349
+ ARROW_RETURN_NOT_OK(this->value_builder_->Resize(0));
350
+ }
351
+
352
+ std::shared_ptr<ArrayData> items;
353
+ ARROW_RETURN_NOT_OK(this->value_builder_->FinishInternal(&items));
354
+
355
+ *out = ArrayData::Make(this->type(), this->length_,
356
+ {std::move(null_bitmap), std::move(offsets)},
357
+ {std::move(items)}, this->null_count_);
358
+ this->Reset();
359
+ return Status::OK();
360
+ }
361
+ };
362
+
363
+ /// \class ListBuilder
364
+ /// \brief Builder class for variable-length list array value types
365
+ ///
366
+ /// To use this class, you must append values to the child array builder and use
367
+ /// the Append function to delimit each distinct list value (once the values
368
+ /// have been appended to the child array) or use the bulk API to append
369
+ /// a sequence of offsets and null values.
370
+ ///
371
+ /// A note on types. Per arrow/type.h all types in the c++ implementation are
372
+ /// logical so even though this class always builds list array, this can
373
+ /// represent multiple different logical types. If no logical type is provided
374
+ /// at construction time, the class defaults to List<T> where t is taken from the
375
+ /// value_builder/values that the object is constructed with.
376
+ class ARROW_EXPORT ListBuilder : public BaseListBuilder<ListType> {
377
+ public:
378
+ using BaseListBuilder::BaseListBuilder;
379
+
380
+ /// \cond FALSE
381
+ using ArrayBuilder::Finish;
382
+ /// \endcond
383
+
384
+ Status Finish(std::shared_ptr<ListArray>* out) { return FinishTyped(out); }
385
+ };
386
+
387
+ /// \class LargeListBuilder
388
+ /// \brief Builder class for large variable-length list array value types
389
+ ///
390
+ /// Like ListBuilder, but to create large list arrays (with 64-bit offsets).
391
+ class ARROW_EXPORT LargeListBuilder : public BaseListBuilder<LargeListType> {
392
+ public:
393
+ using BaseListBuilder::BaseListBuilder;
394
+
395
+ /// \cond FALSE
396
+ using ArrayBuilder::Finish;
397
+ /// \endcond
398
+
399
+ Status Finish(std::shared_ptr<LargeListArray>* out) { return FinishTyped(out); }
400
+ };
401
+
402
+ // ----------------------------------------------------------------------
403
+ // ListViewBuilder / LargeListViewBuilder
404
+
405
+ template <typename TYPE>
406
+ class ARROW_EXPORT BaseListViewBuilder : public VarLengthListLikeBuilder<TYPE> {
407
+ private:
408
+ using BASE = VarLengthListLikeBuilder<TYPE>;
409
+
410
+ public:
411
+ using TypeClass = TYPE;
412
+ using offset_type = typename BASE::offset_type;
413
+
414
+ using BASE::BASE;
415
+
416
+ ~BaseListViewBuilder() override = default;
417
+
418
+ Status Resize(int64_t capacity) override {
419
+ ARROW_RETURN_NOT_OK(BASE::Resize(capacity));
420
+ return sizes_builder_.Resize(capacity);
421
+ }
422
+
423
+ void Reset() override {
424
+ BASE::Reset();
425
+ sizes_builder_.Reset();
426
+ }
427
+
428
+ /// \brief Vector append
429
+ ///
430
+ /// If passed, valid_bytes is of equal length to values, and any zero byte
431
+ /// will be considered as a null for that slot
432
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
433
+ int64_t length, const uint8_t* valid_bytes) final {
434
+ ARROW_RETURN_NOT_OK(this->Reserve(length));
435
+ this->UnsafeAppendToBitmap(valid_bytes, length);
436
+ this->offsets_builder_.UnsafeAppend(offsets, length);
437
+ this->sizes_builder_.UnsafeAppend(sizes, length);
438
+ return Status::OK();
439
+ }
440
+
441
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
442
+ int64_t length) {
443
+ return AppendValues(offsets, sizes, length, /*valid_bytes=*/NULLPTR);
444
+ }
445
+
446
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
447
+ // Offset and sizes padding zeroed by BufferBuilder
448
+ std::shared_ptr<Buffer> null_bitmap;
449
+ std::shared_ptr<Buffer> offsets;
450
+ std::shared_ptr<Buffer> sizes;
451
+ ARROW_RETURN_NOT_OK(this->null_bitmap_builder_.Finish(&null_bitmap));
452
+ ARROW_RETURN_NOT_OK(this->offsets_builder_.Finish(&offsets));
453
+ ARROW_RETURN_NOT_OK(this->sizes_builder_.Finish(&sizes));
454
+
455
+ if (this->value_builder_->length() == 0) {
456
+ // Try to make sure we get a non-null values buffer (ARROW-2744)
457
+ ARROW_RETURN_NOT_OK(this->value_builder_->Resize(0));
458
+ }
459
+
460
+ std::shared_ptr<ArrayData> items;
461
+ ARROW_RETURN_NOT_OK(this->value_builder_->FinishInternal(&items));
462
+
463
+ *out = ArrayData::Make(this->type(), this->length_,
464
+ {std::move(null_bitmap), std::move(offsets), std::move(sizes)},
465
+ {std::move(items)}, this->null_count_);
466
+ this->Reset();
467
+ return Status::OK();
468
+ }
469
+
470
+ protected:
471
+ void UnsafeAppendEmptyDimensions(int64_t num_values) override {
472
+ for (int64_t i = 0; i < num_values; ++i) {
473
+ this->offsets_builder_.UnsafeAppend(0);
474
+ }
475
+ for (int64_t i = 0; i < num_values; ++i) {
476
+ this->sizes_builder_.UnsafeAppend(0);
477
+ }
478
+ }
479
+
480
+ void UnsafeAppendDimensions(int64_t offset, int64_t size) override {
481
+ this->offsets_builder_.UnsafeAppend(static_cast<offset_type>(offset));
482
+ this->sizes_builder_.UnsafeAppend(static_cast<offset_type>(size));
483
+ }
484
+
485
+ private:
486
+ TypedBufferBuilder<offset_type> sizes_builder_;
487
+ };
488
+
489
+ class ARROW_EXPORT ListViewBuilder final : public BaseListViewBuilder<ListViewType> {
490
+ public:
491
+ using BaseListViewBuilder::BaseListViewBuilder;
492
+
493
+ /// \cond FALSE
494
+ using ArrayBuilder::Finish;
495
+ /// \endcond
496
+
497
+ Status Finish(std::shared_ptr<ListViewArray>* out) { return FinishTyped(out); }
498
+ };
499
+
500
+ class ARROW_EXPORT LargeListViewBuilder final
501
+ : public BaseListViewBuilder<LargeListViewType> {
502
+ public:
503
+ using BaseListViewBuilder::BaseListViewBuilder;
504
+
505
+ /// \cond FALSE
506
+ using ArrayBuilder::Finish;
507
+ /// \endcond
508
+
509
+ Status Finish(std::shared_ptr<LargeListViewArray>* out) { return FinishTyped(out); }
510
+ };
511
+
512
+ // ----------------------------------------------------------------------
513
+ // Map builder
514
+
515
+ /// \class MapBuilder
516
+ /// \brief Builder class for arrays of variable-size maps
517
+ ///
518
+ /// To use this class, you must append values to the key and item array builders
519
+ /// and use the Append function to delimit each distinct map (once the keys and items
520
+ /// have been appended) or use the bulk API to append a sequence of offsets and null
521
+ /// maps.
522
+ ///
523
+ /// Key uniqueness and ordering are not validated.
524
+ class ARROW_EXPORT MapBuilder : public ArrayBuilder {
525
+ public:
526
+ /// Use this constructor to define the built array's type explicitly. If key_builder
527
+ /// or item_builder has indeterminate type, this builder will also.
528
+ MapBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& key_builder,
529
+ const std::shared_ptr<ArrayBuilder>& item_builder,
530
+ const std::shared_ptr<DataType>& type);
531
+
532
+ /// Use this constructor to infer the built array's type. If key_builder or
533
+ /// item_builder has indeterminate type, this builder will also.
534
+ MapBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& key_builder,
535
+ const std::shared_ptr<ArrayBuilder>& item_builder, bool keys_sorted = false);
536
+
537
+ MapBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& item_builder,
538
+ const std::shared_ptr<DataType>& type);
539
+
540
+ Status Resize(int64_t capacity) override;
541
+ void Reset() override;
542
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
543
+
544
+ /// \cond FALSE
545
+ using ArrayBuilder::Finish;
546
+ /// \endcond
547
+
548
+ Status Finish(std::shared_ptr<MapArray>* out) { return FinishTyped(out); }
549
+
550
+ /// \brief Vector append
551
+ ///
552
+ /// If passed, valid_bytes is of equal length to values, and any zero byte
553
+ /// will be considered as a null for that slot
554
+ Status AppendValues(const int32_t* offsets, int64_t length,
555
+ const uint8_t* valid_bytes = NULLPTR);
556
+
557
+ /// \brief Start a new variable-length map slot
558
+ ///
559
+ /// This function should be called before beginning to append elements to the
560
+ /// key and item builders
561
+ Status Append();
562
+
563
+ Status AppendNull() final;
564
+
565
+ Status AppendNulls(int64_t length) final;
566
+
567
+ Status AppendEmptyValue() final;
568
+
569
+ Status AppendEmptyValues(int64_t length) final;
570
+
571
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
572
+ int64_t length) override {
573
+ const int32_t* offsets = array.GetValues<int32_t>(1);
574
+ const bool all_valid = !array.MayHaveLogicalNulls();
575
+ const uint8_t* validity = array.HasValidityBitmap() ? array.buffers[0].data : NULLPTR;
576
+ for (int64_t row = offset; row < offset + length; row++) {
577
+ const bool is_valid =
578
+ all_valid || (validity && bit_util::GetBit(validity, array.offset + row)) ||
579
+ array.IsValid(row);
580
+ if (is_valid) {
581
+ ARROW_RETURN_NOT_OK(Append());
582
+ const int64_t slot_length = offsets[row + 1] - offsets[row];
583
+ // Add together the inner StructArray offset to the Map/List offset
584
+ int64_t key_value_offset = array.child_data[0].offset + offsets[row];
585
+ ARROW_RETURN_NOT_OK(key_builder_->AppendArraySlice(
586
+ array.child_data[0].child_data[0], key_value_offset, slot_length));
587
+ ARROW_RETURN_NOT_OK(item_builder_->AppendArraySlice(
588
+ array.child_data[0].child_data[1], key_value_offset, slot_length));
589
+ } else {
590
+ ARROW_RETURN_NOT_OK(AppendNull());
591
+ }
592
+ }
593
+ return Status::OK();
594
+ }
595
+
596
+ /// \brief Get builder to append keys.
597
+ ///
598
+ /// Append a key with this builder should be followed by appending
599
+ /// an item or null value with item_builder().
600
+ ArrayBuilder* key_builder() const { return key_builder_.get(); }
601
+
602
+ /// \brief Get builder to append items
603
+ ///
604
+ /// Appending an item with this builder should have been preceded
605
+ /// by appending a key with key_builder().
606
+ ArrayBuilder* item_builder() const { return item_builder_.get(); }
607
+
608
+ /// \brief Get builder to add Map entries as struct values.
609
+ ///
610
+ /// This is used instead of key_builder()/item_builder() and allows
611
+ /// the Map to be built as a list of struct values.
612
+ ArrayBuilder* value_builder() const { return list_builder_->value_builder(); }
613
+
614
+ std::shared_ptr<DataType> type() const override {
615
+ // Key and Item builder may update types, but they don't contain the field names,
616
+ // so we need to reconstruct the type. (See ARROW-13735.)
617
+ return std::make_shared<MapType>(
618
+ field(entries_name_,
619
+ struct_({field(key_name_, key_builder_->type(), false),
620
+ field(item_name_, item_builder_->type(), item_nullable_)}),
621
+ false),
622
+ keys_sorted_);
623
+ }
624
+
625
+ Status ValidateOverflow(int64_t new_elements) {
626
+ return list_builder_->ValidateOverflow(new_elements);
627
+ }
628
+
629
+ protected:
630
+ inline Status AdjustStructBuilderLength();
631
+
632
+ protected:
633
+ bool keys_sorted_ = false;
634
+ bool item_nullable_ = false;
635
+ std::string entries_name_;
636
+ std::string key_name_;
637
+ std::string item_name_;
638
+ std::shared_ptr<ListBuilder> list_builder_;
639
+ std::shared_ptr<ArrayBuilder> key_builder_;
640
+ std::shared_ptr<ArrayBuilder> item_builder_;
641
+ };
642
+
643
+ // ----------------------------------------------------------------------
644
+ // FixedSizeList builder
645
+
646
+ /// \class FixedSizeListBuilder
647
+ /// \brief Builder class for fixed-length list array value types
648
+ class ARROW_EXPORT FixedSizeListBuilder : public ArrayBuilder {
649
+ public:
650
+ /// Use this constructor to define the built array's type explicitly. If value_builder
651
+ /// has indeterminate type, this builder will also.
652
+ FixedSizeListBuilder(MemoryPool* pool,
653
+ std::shared_ptr<ArrayBuilder> const& value_builder,
654
+ int32_t list_size);
655
+
656
+ /// Use this constructor to infer the built array's type. If value_builder has
657
+ /// indeterminate type, this builder will also.
658
+ FixedSizeListBuilder(MemoryPool* pool,
659
+ std::shared_ptr<ArrayBuilder> const& value_builder,
660
+ const std::shared_ptr<DataType>& type);
661
+
662
+ Status Resize(int64_t capacity) override;
663
+ void Reset() override;
664
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
665
+
666
+ /// \cond FALSE
667
+ using ArrayBuilder::Finish;
668
+ /// \endcond
669
+
670
+ Status Finish(std::shared_ptr<FixedSizeListArray>* out) { return FinishTyped(out); }
671
+
672
+ /// \brief Append a valid fixed length list.
673
+ ///
674
+ /// This function affects only the validity bitmap; the child values must be appended
675
+ /// using the child array builder.
676
+ Status Append();
677
+
678
+ /// \brief Vector append
679
+ ///
680
+ /// If passed, valid_bytes wil be read and any zero byte
681
+ /// will cause the corresponding slot to be null
682
+ ///
683
+ /// This function affects only the validity bitmap; the child values must be appended
684
+ /// using the child array builder. This includes appending nulls for null lists.
685
+ /// XXX this restriction is confusing, should this method be omitted?
686
+ Status AppendValues(int64_t length, const uint8_t* valid_bytes = NULLPTR);
687
+
688
+ /// \brief Append a null fixed length list.
689
+ ///
690
+ /// The child array builder will have the appropriate number of nulls appended
691
+ /// automatically.
692
+ Status AppendNull() final;
693
+
694
+ /// \brief Append length null fixed length lists.
695
+ ///
696
+ /// The child array builder will have the appropriate number of nulls appended
697
+ /// automatically.
698
+ Status AppendNulls(int64_t length) final;
699
+
700
+ Status ValidateOverflow(int64_t new_elements);
701
+
702
+ Status AppendEmptyValue() final;
703
+
704
+ Status AppendEmptyValues(int64_t length) final;
705
+
706
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length) final {
707
+ const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR;
708
+ for (int64_t row = offset; row < offset + length; row++) {
709
+ if (!validity || bit_util::GetBit(validity, array.offset + row)) {
710
+ ARROW_RETURN_NOT_OK(value_builder_->AppendArraySlice(
711
+ array.child_data[0], list_size_ * (array.offset + row), list_size_));
712
+ ARROW_RETURN_NOT_OK(Append());
713
+ } else {
714
+ ARROW_RETURN_NOT_OK(AppendNull());
715
+ }
716
+ }
717
+ return Status::OK();
718
+ }
719
+
720
+ ArrayBuilder* value_builder() const { return value_builder_.get(); }
721
+
722
+ std::shared_ptr<DataType> type() const override {
723
+ return fixed_size_list(value_field_->WithType(value_builder_->type()), list_size_);
724
+ }
725
+
726
+ // Cannot make this a static attribute because of linking issues
727
+ static constexpr int64_t maximum_elements() {
728
+ return std::numeric_limits<FixedSizeListType::offset_type>::max() - 1;
729
+ }
730
+
731
+ protected:
732
+ std::shared_ptr<Field> value_field_;
733
+ const int32_t list_size_;
734
+ std::shared_ptr<ArrayBuilder> value_builder_;
735
+ };
736
+
737
+ // ----------------------------------------------------------------------
738
+ // Struct
739
+
740
+ // ---------------------------------------------------------------------------------
741
+ // StructArray builder
742
+ /// Append, Resize and Reserve methods are acting on StructBuilder.
743
+ /// Please make sure all these methods of all child-builders' are consistently
744
+ /// called to maintain data-structure consistency.
745
+ class ARROW_EXPORT StructBuilder : public ArrayBuilder {
746
+ public:
747
+ /// If any of field_builders has indeterminate type, this builder will also
748
+ StructBuilder(const std::shared_ptr<DataType>& type, MemoryPool* pool,
749
+ std::vector<std::shared_ptr<ArrayBuilder>> field_builders);
750
+
751
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
752
+
753
+ /// \cond FALSE
754
+ using ArrayBuilder::Finish;
755
+ /// \endcond
756
+
757
+ Status Finish(std::shared_ptr<StructArray>* out) { return FinishTyped(out); }
758
+
759
+ /// Null bitmap is of equal length to every child field, and any zero byte
760
+ /// will be considered as a null for that field, but users must using app-
761
+ /// end methods or advance methods of the child builders' independently to
762
+ /// insert data.
763
+ Status AppendValues(int64_t length, const uint8_t* valid_bytes) {
764
+ ARROW_RETURN_NOT_OK(Reserve(length));
765
+ UnsafeAppendToBitmap(valid_bytes, length);
766
+ return Status::OK();
767
+ }
768
+
769
+ /// Append an element to the Struct. All child-builders' Append method must
770
+ /// be called independently to maintain data-structure consistency.
771
+ Status Append(bool is_valid = true) {
772
+ ARROW_RETURN_NOT_OK(Reserve(1));
773
+ UnsafeAppendToBitmap(is_valid);
774
+ return Status::OK();
775
+ }
776
+
777
+ /// \brief Append a null value. Automatically appends an empty value to each child
778
+ /// builder.
779
+ Status AppendNull() final {
780
+ for (const auto& field : children_) {
781
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValue());
782
+ }
783
+ return Append(false);
784
+ }
785
+
786
+ /// \brief Append multiple null values. Automatically appends empty values to each
787
+ /// child builder.
788
+ Status AppendNulls(int64_t length) final {
789
+ for (const auto& field : children_) {
790
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValues(length));
791
+ }
792
+ ARROW_RETURN_NOT_OK(Reserve(length));
793
+ UnsafeAppendToBitmap(length, false);
794
+ return Status::OK();
795
+ }
796
+
797
+ Status AppendEmptyValue() final {
798
+ for (const auto& field : children_) {
799
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValue());
800
+ }
801
+ return Append(true);
802
+ }
803
+
804
+ Status AppendEmptyValues(int64_t length) final {
805
+ for (const auto& field : children_) {
806
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValues(length));
807
+ }
808
+ ARROW_RETURN_NOT_OK(Reserve(length));
809
+ UnsafeAppendToBitmap(length, true);
810
+ return Status::OK();
811
+ }
812
+
813
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
814
+ int64_t length) override {
815
+ for (int i = 0; static_cast<size_t>(i) < children_.size(); i++) {
816
+ ARROW_RETURN_NOT_OK(children_[i]->AppendArraySlice(array.child_data[i],
817
+ array.offset + offset, length));
818
+ }
819
+ const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR;
820
+ ARROW_RETURN_NOT_OK(Reserve(length));
821
+ UnsafeAppendToBitmap(validity, array.offset + offset, length);
822
+ return Status::OK();
823
+ }
824
+
825
+ void Reset() override;
826
+
827
+ ArrayBuilder* field_builder(int i) const { return children_[i].get(); }
828
+
829
+ int num_fields() const { return static_cast<int>(children_.size()); }
830
+
831
+ std::shared_ptr<DataType> type() const override;
832
+
833
+ private:
834
+ std::shared_ptr<DataType> type_;
835
+ };
836
+
837
+ /// @}
838
+
839
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_primitive.h ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <algorithm>
21
+ #include <memory>
22
+ #include <vector>
23
+
24
+ #include "arrow/array/builder_base.h"
25
+ #include "arrow/array/data.h"
26
+ #include "arrow/result.h"
27
+ #include "arrow/type.h"
28
+ #include "arrow/type_traits.h"
29
+
30
+ namespace arrow {
31
+
32
+ class ARROW_EXPORT NullBuilder : public ArrayBuilder {
33
+ public:
34
+ explicit NullBuilder(MemoryPool* pool = default_memory_pool(),
35
+ int64_t alignment = kDefaultBufferAlignment)
36
+ : ArrayBuilder(pool) {}
37
+ explicit NullBuilder(const std::shared_ptr<DataType>& type,
38
+ MemoryPool* pool = default_memory_pool(),
39
+ int64_t alignment = kDefaultBufferAlignment)
40
+ : NullBuilder(pool, alignment) {}
41
+
42
+ /// \brief Append the specified number of null elements
43
+ Status AppendNulls(int64_t length) final {
44
+ if (length < 0) return Status::Invalid("length must be positive");
45
+ null_count_ += length;
46
+ length_ += length;
47
+ return Status::OK();
48
+ }
49
+
50
+ /// \brief Append a single null element
51
+ Status AppendNull() final { return AppendNulls(1); }
52
+
53
+ Status AppendEmptyValues(int64_t length) final { return AppendNulls(length); }
54
+
55
+ Status AppendEmptyValue() final { return AppendEmptyValues(1); }
56
+
57
+ Status Append(std::nullptr_t) { return AppendNull(); }
58
+
59
+ Status AppendArraySlice(const ArraySpan&, int64_t, int64_t length) override {
60
+ return AppendNulls(length);
61
+ }
62
+
63
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
64
+
65
+ /// \cond FALSE
66
+ using ArrayBuilder::Finish;
67
+ /// \endcond
68
+
69
+ std::shared_ptr<DataType> type() const override { return null(); }
70
+
71
+ Status Finish(std::shared_ptr<NullArray>* out) { return FinishTyped(out); }
72
+ };
73
+
74
+ /// \addtogroup numeric-builders
75
+ ///
76
+ /// @{
77
+
78
+ /// Base class for all Builders that emit an Array of a scalar numerical type.
79
+ template <typename T>
80
+ class NumericBuilder
81
+ : public ArrayBuilder,
82
+ public internal::ArrayBuilderExtraOps<NumericBuilder<T>, typename T::c_type> {
83
+ public:
84
+ using TypeClass = T;
85
+ using value_type = typename T::c_type;
86
+ using ArrayType = typename TypeTraits<T>::ArrayType;
87
+
88
+ template <typename T1 = T>
89
+ explicit NumericBuilder(
90
+ enable_if_parameter_free<T1, MemoryPool*> pool = default_memory_pool(),
91
+ int64_t alignment = kDefaultBufferAlignment)
92
+ : ArrayBuilder(pool, alignment),
93
+ type_(TypeTraits<T>::type_singleton()),
94
+ data_builder_(pool, alignment) {}
95
+
96
+ NumericBuilder(const std::shared_ptr<DataType>& type, MemoryPool* pool,
97
+ int64_t alignment = kDefaultBufferAlignment)
98
+ : ArrayBuilder(pool, alignment), type_(type), data_builder_(pool, alignment) {}
99
+
100
+ /// Append a single scalar and increase the size if necessary.
101
+ Status Append(const value_type val) {
102
+ ARROW_RETURN_NOT_OK(ArrayBuilder::Reserve(1));
103
+ UnsafeAppend(val);
104
+ return Status::OK();
105
+ }
106
+
107
+ /// Write nulls as uint8_t* (0 value indicates null) into pre-allocated memory
108
+ /// The memory at the corresponding data slot is set to 0 to prevent
109
+ /// uninitialized memory access
110
+ Status AppendNulls(int64_t length) final {
111
+ ARROW_RETURN_NOT_OK(Reserve(length));
112
+ data_builder_.UnsafeAppend(length, value_type{}); // zero
113
+ UnsafeSetNull(length);
114
+ return Status::OK();
115
+ }
116
+
117
+ /// \brief Append a single null element
118
+ Status AppendNull() final {
119
+ ARROW_RETURN_NOT_OK(Reserve(1));
120
+ data_builder_.UnsafeAppend(value_type{}); // zero
121
+ UnsafeAppendToBitmap(false);
122
+ return Status::OK();
123
+ }
124
+
125
+ /// \brief Append a empty element
126
+ Status AppendEmptyValue() final {
127
+ ARROW_RETURN_NOT_OK(Reserve(1));
128
+ data_builder_.UnsafeAppend(value_type{}); // zero
129
+ UnsafeAppendToBitmap(true);
130
+ return Status::OK();
131
+ }
132
+
133
+ /// \brief Append several empty elements
134
+ Status AppendEmptyValues(int64_t length) final {
135
+ ARROW_RETURN_NOT_OK(Reserve(length));
136
+ data_builder_.UnsafeAppend(length, value_type{}); // zero
137
+ UnsafeSetNotNull(length);
138
+ return Status::OK();
139
+ }
140
+
141
+ value_type GetValue(int64_t index) const { return data_builder_.data()[index]; }
142
+
143
+ void Reset() override {
144
+ data_builder_.Reset();
145
+ ArrayBuilder::Reset();
146
+ }
147
+
148
+ Status Resize(int64_t capacity) override {
149
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
150
+ capacity = std::max(capacity, kMinBuilderCapacity);
151
+ ARROW_RETURN_NOT_OK(data_builder_.Resize(capacity));
152
+ return ArrayBuilder::Resize(capacity);
153
+ }
154
+
155
+ value_type operator[](int64_t index) const { return GetValue(index); }
156
+
157
+ value_type& operator[](int64_t index) {
158
+ return reinterpret_cast<value_type*>(data_builder_.mutable_data())[index];
159
+ }
160
+
161
+ /// \brief Append a sequence of elements in one shot
162
+ /// \param[in] values a contiguous C array of values
163
+ /// \param[in] length the number of values to append
164
+ /// \param[in] valid_bytes an optional sequence of bytes where non-zero
165
+ /// indicates a valid (non-null) value
166
+ /// \return Status
167
+ Status AppendValues(const value_type* values, int64_t length,
168
+ const uint8_t* valid_bytes = NULLPTR) {
169
+ ARROW_RETURN_NOT_OK(Reserve(length));
170
+ data_builder_.UnsafeAppend(values, length);
171
+ // length_ is update by these
172
+ ArrayBuilder::UnsafeAppendToBitmap(valid_bytes, length);
173
+ return Status::OK();
174
+ }
175
+
176
+ /// \brief Append a sequence of elements in one shot
177
+ /// \param[in] values a contiguous C array of values
178
+ /// \param[in] length the number of values to append
179
+ /// \param[in] bitmap a validity bitmap to copy (may be null)
180
+ /// \param[in] bitmap_offset an offset into the validity bitmap
181
+ /// \return Status
182
+ Status AppendValues(const value_type* values, int64_t length, const uint8_t* bitmap,
183
+ int64_t bitmap_offset) {
184
+ ARROW_RETURN_NOT_OK(Reserve(length));
185
+ data_builder_.UnsafeAppend(values, length);
186
+ // length_ is update by these
187
+ ArrayBuilder::UnsafeAppendToBitmap(bitmap, bitmap_offset, length);
188
+ return Status::OK();
189
+ }
190
+
191
+ /// \brief Append a sequence of elements in one shot
192
+ /// \param[in] values a contiguous C array of values
193
+ /// \param[in] length the number of values to append
194
+ /// \param[in] is_valid an std::vector<bool> indicating valid (1) or null
195
+ /// (0). Equal in length to values
196
+ /// \return Status
197
+ Status AppendValues(const value_type* values, int64_t length,
198
+ const std::vector<bool>& is_valid) {
199
+ ARROW_RETURN_NOT_OK(Reserve(length));
200
+ data_builder_.UnsafeAppend(values, length);
201
+ // length_ is update by these
202
+ ArrayBuilder::UnsafeAppendToBitmap(is_valid);
203
+ return Status::OK();
204
+ }
205
+
206
+ /// \brief Append a sequence of elements in one shot
207
+ /// \param[in] values a std::vector of values
208
+ /// \param[in] is_valid an std::vector<bool> indicating valid (1) or null
209
+ /// (0). Equal in length to values
210
+ /// \return Status
211
+ Status AppendValues(const std::vector<value_type>& values,
212
+ const std::vector<bool>& is_valid) {
213
+ return AppendValues(values.data(), static_cast<int64_t>(values.size()), is_valid);
214
+ }
215
+
216
+ /// \brief Append a sequence of elements in one shot
217
+ /// \param[in] values a std::vector of values
218
+ /// \return Status
219
+ Status AppendValues(const std::vector<value_type>& values) {
220
+ return AppendValues(values.data(), static_cast<int64_t>(values.size()));
221
+ }
222
+
223
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
224
+ ARROW_ASSIGN_OR_RAISE(auto null_bitmap,
225
+ null_bitmap_builder_.FinishWithLength(length_));
226
+ ARROW_ASSIGN_OR_RAISE(auto data, data_builder_.FinishWithLength(length_));
227
+ *out = ArrayData::Make(type(), length_, {null_bitmap, data}, null_count_);
228
+ capacity_ = length_ = null_count_ = 0;
229
+ return Status::OK();
230
+ }
231
+
232
+ /// \cond FALSE
233
+ using ArrayBuilder::Finish;
234
+ /// \endcond
235
+
236
+ Status Finish(std::shared_ptr<ArrayType>* out) { return FinishTyped(out); }
237
+
238
+ /// \brief Append a sequence of elements in one shot
239
+ /// \param[in] values_begin InputIterator to the beginning of the values
240
+ /// \param[in] values_end InputIterator pointing to the end of the values
241
+ /// \return Status
242
+ template <typename ValuesIter>
243
+ Status AppendValues(ValuesIter values_begin, ValuesIter values_end) {
244
+ int64_t length = static_cast<int64_t>(std::distance(values_begin, values_end));
245
+ ARROW_RETURN_NOT_OK(Reserve(length));
246
+ data_builder_.UnsafeAppend(values_begin, values_end);
247
+ // this updates the length_
248
+ UnsafeSetNotNull(length);
249
+ return Status::OK();
250
+ }
251
+
252
+ /// \brief Append a sequence of elements in one shot, with a specified nullmap
253
+ /// \param[in] values_begin InputIterator to the beginning of the values
254
+ /// \param[in] values_end InputIterator pointing to the end of the values
255
+ /// \param[in] valid_begin InputIterator with elements indication valid(1)
256
+ /// or null(0) values.
257
+ /// \return Status
258
+ template <typename ValuesIter, typename ValidIter>
259
+ enable_if_t<!std::is_pointer<ValidIter>::value, Status> AppendValues(
260
+ ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) {
261
+ static_assert(!internal::is_null_pointer<ValidIter>::value,
262
+ "Don't pass a NULLPTR directly as valid_begin, use the 2-argument "
263
+ "version instead");
264
+ int64_t length = static_cast<int64_t>(std::distance(values_begin, values_end));
265
+ ARROW_RETURN_NOT_OK(Reserve(length));
266
+ data_builder_.UnsafeAppend(values_begin, values_end);
267
+ null_bitmap_builder_.UnsafeAppend<true>(
268
+ length, [&valid_begin]() -> bool { return *valid_begin++; });
269
+ length_ = null_bitmap_builder_.length();
270
+ null_count_ = null_bitmap_builder_.false_count();
271
+ return Status::OK();
272
+ }
273
+
274
+ // Same as above, with a pointer type ValidIter
275
+ template <typename ValuesIter, typename ValidIter>
276
+ enable_if_t<std::is_pointer<ValidIter>::value, Status> AppendValues(
277
+ ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) {
278
+ int64_t length = static_cast<int64_t>(std::distance(values_begin, values_end));
279
+ ARROW_RETURN_NOT_OK(Reserve(length));
280
+ data_builder_.UnsafeAppend(values_begin, values_end);
281
+ // this updates the length_
282
+ if (valid_begin == NULLPTR) {
283
+ UnsafeSetNotNull(length);
284
+ } else {
285
+ null_bitmap_builder_.UnsafeAppend<true>(
286
+ length, [&valid_begin]() -> bool { return *valid_begin++; });
287
+ length_ = null_bitmap_builder_.length();
288
+ null_count_ = null_bitmap_builder_.false_count();
289
+ }
290
+
291
+ return Status::OK();
292
+ }
293
+
294
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
295
+ int64_t length) override {
296
+ return AppendValues(array.GetValues<value_type>(1) + offset, length,
297
+ array.GetValues<uint8_t>(0, 0), array.offset + offset);
298
+ }
299
+
300
+ /// Append a single scalar under the assumption that the underlying Buffer is
301
+ /// large enough.
302
+ ///
303
+ /// This method does not capacity-check; make sure to call Reserve
304
+ /// beforehand.
305
+ void UnsafeAppend(const value_type val) {
306
+ ArrayBuilder::UnsafeAppendToBitmap(true);
307
+ data_builder_.UnsafeAppend(val);
308
+ }
309
+
310
+ void UnsafeAppendNull() {
311
+ ArrayBuilder::UnsafeAppendToBitmap(false);
312
+ data_builder_.UnsafeAppend(value_type{}); // zero
313
+ }
314
+
315
+ std::shared_ptr<DataType> type() const override { return type_; }
316
+
317
+ protected:
318
+ std::shared_ptr<DataType> type_;
319
+ TypedBufferBuilder<value_type> data_builder_;
320
+ };
321
+
322
+ // Builders
323
+
324
+ using UInt8Builder = NumericBuilder<UInt8Type>;
325
+ using UInt16Builder = NumericBuilder<UInt16Type>;
326
+ using UInt32Builder = NumericBuilder<UInt32Type>;
327
+ using UInt64Builder = NumericBuilder<UInt64Type>;
328
+
329
+ using Int8Builder = NumericBuilder<Int8Type>;
330
+ using Int16Builder = NumericBuilder<Int16Type>;
331
+ using Int32Builder = NumericBuilder<Int32Type>;
332
+ using Int64Builder = NumericBuilder<Int64Type>;
333
+
334
+ using HalfFloatBuilder = NumericBuilder<HalfFloatType>;
335
+ using FloatBuilder = NumericBuilder<FloatType>;
336
+ using DoubleBuilder = NumericBuilder<DoubleType>;
337
+
338
+ /// @}
339
+
340
+ /// \addtogroup temporal-builders
341
+ ///
342
+ /// @{
343
+
344
+ using Date32Builder = NumericBuilder<Date32Type>;
345
+ using Date64Builder = NumericBuilder<Date64Type>;
346
+ using Time32Builder = NumericBuilder<Time32Type>;
347
+ using Time64Builder = NumericBuilder<Time64Type>;
348
+ using TimestampBuilder = NumericBuilder<TimestampType>;
349
+ using MonthIntervalBuilder = NumericBuilder<MonthIntervalType>;
350
+ using DurationBuilder = NumericBuilder<DurationType>;
351
+
352
+ /// @}
353
+
354
+ class ARROW_EXPORT BooleanBuilder
355
+ : public ArrayBuilder,
356
+ public internal::ArrayBuilderExtraOps<BooleanBuilder, bool> {
357
+ public:
358
+ using TypeClass = BooleanType;
359
+ using value_type = bool;
360
+
361
+ explicit BooleanBuilder(MemoryPool* pool = default_memory_pool(),
362
+ int64_t alignment = kDefaultBufferAlignment);
363
+
364
+ BooleanBuilder(const std::shared_ptr<DataType>& type,
365
+ MemoryPool* pool = default_memory_pool(),
366
+ int64_t alignment = kDefaultBufferAlignment);
367
+
368
+ /// Write nulls as uint8_t* (0 value indicates null) into pre-allocated memory
369
+ Status AppendNulls(int64_t length) final {
370
+ ARROW_RETURN_NOT_OK(Reserve(length));
371
+ data_builder_.UnsafeAppend(length, false);
372
+ UnsafeSetNull(length);
373
+ return Status::OK();
374
+ }
375
+
376
+ Status AppendNull() final {
377
+ ARROW_RETURN_NOT_OK(Reserve(1));
378
+ UnsafeAppendNull();
379
+ return Status::OK();
380
+ }
381
+
382
+ Status AppendEmptyValue() final {
383
+ ARROW_RETURN_NOT_OK(Reserve(1));
384
+ data_builder_.UnsafeAppend(false);
385
+ UnsafeSetNotNull(1);
386
+ return Status::OK();
387
+ }
388
+
389
+ Status AppendEmptyValues(int64_t length) final {
390
+ ARROW_RETURN_NOT_OK(Reserve(length));
391
+ data_builder_.UnsafeAppend(length, false);
392
+ UnsafeSetNotNull(length);
393
+ return Status::OK();
394
+ }
395
+
396
+ /// Scalar append
397
+ Status Append(const bool val) {
398
+ ARROW_RETURN_NOT_OK(Reserve(1));
399
+ UnsafeAppend(val);
400
+ return Status::OK();
401
+ }
402
+
403
+ Status Append(const uint8_t val) { return Append(val != 0); }
404
+
405
+ /// Scalar append, without checking for capacity
406
+ void UnsafeAppend(const bool val) {
407
+ data_builder_.UnsafeAppend(val);
408
+ UnsafeAppendToBitmap(true);
409
+ }
410
+
411
+ void UnsafeAppendNull() {
412
+ data_builder_.UnsafeAppend(false);
413
+ UnsafeAppendToBitmap(false);
414
+ }
415
+
416
+ void UnsafeAppend(const uint8_t val) { UnsafeAppend(val != 0); }
417
+
418
+ /// \brief Append a sequence of elements in one shot
419
+ /// \param[in] values a contiguous array of bytes (non-zero is 1)
420
+ /// \param[in] length the number of values to append
421
+ /// \param[in] valid_bytes an optional sequence of bytes where non-zero
422
+ /// indicates a valid (non-null) value
423
+ /// \return Status
424
+ Status AppendValues(const uint8_t* values, int64_t length,
425
+ const uint8_t* valid_bytes = NULLPTR);
426
+
427
+ /// \brief Append a sequence of elements in one shot
428
+ /// \param[in] values a bitmap of values
429
+ /// \param[in] length the number of values to append
430
+ /// \param[in] validity a validity bitmap to copy (may be null)
431
+ /// \param[in] offset an offset into the values and validity bitmaps
432
+ /// \return Status
433
+ Status AppendValues(const uint8_t* values, int64_t length, const uint8_t* validity,
434
+ int64_t offset);
435
+
436
+ /// \brief Append a sequence of elements in one shot
437
+ /// \param[in] values a contiguous C array of values
438
+ /// \param[in] length the number of values to append
439
+ /// \param[in] is_valid an std::vector<bool> indicating valid (1) or null
440
+ /// (0). Equal in length to values
441
+ /// \return Status
442
+ Status AppendValues(const uint8_t* values, int64_t length,
443
+ const std::vector<bool>& is_valid);
444
+
445
+ /// \brief Append a sequence of elements in one shot
446
+ /// \param[in] values a std::vector of bytes
447
+ /// \param[in] is_valid an std::vector<bool> indicating valid (1) or null
448
+ /// (0). Equal in length to values
449
+ /// \return Status
450
+ Status AppendValues(const std::vector<uint8_t>& values,
451
+ const std::vector<bool>& is_valid);
452
+
453
+ /// \brief Append a sequence of elements in one shot
454
+ /// \param[in] values a std::vector of bytes
455
+ /// \return Status
456
+ Status AppendValues(const std::vector<uint8_t>& values);
457
+
458
+ /// \brief Append a sequence of elements in one shot
459
+ /// \param[in] values an std::vector<bool> indicating true (1) or false
460
+ /// \param[in] is_valid an std::vector<bool> indicating valid (1) or null
461
+ /// (0). Equal in length to values
462
+ /// \return Status
463
+ Status AppendValues(const std::vector<bool>& values, const std::vector<bool>& is_valid);
464
+
465
+ /// \brief Append a sequence of elements in one shot
466
+ /// \param[in] values an std::vector<bool> indicating true (1) or false
467
+ /// \return Status
468
+ Status AppendValues(const std::vector<bool>& values);
469
+
470
+ /// \brief Append a sequence of elements in one shot
471
+ /// \param[in] values_begin InputIterator to the beginning of the values
472
+ /// \param[in] values_end InputIterator pointing to the end of the values
473
+ /// or null(0) values
474
+ /// \return Status
475
+ template <typename ValuesIter>
476
+ Status AppendValues(ValuesIter values_begin, ValuesIter values_end) {
477
+ int64_t length = static_cast<int64_t>(std::distance(values_begin, values_end));
478
+ ARROW_RETURN_NOT_OK(Reserve(length));
479
+ data_builder_.UnsafeAppend<false>(
480
+ length, [&values_begin]() -> bool { return *values_begin++; });
481
+ // this updates length_
482
+ UnsafeSetNotNull(length);
483
+ return Status::OK();
484
+ }
485
+
486
+ /// \brief Append a sequence of elements in one shot, with a specified nullmap
487
+ /// \param[in] values_begin InputIterator to the beginning of the values
488
+ /// \param[in] values_end InputIterator pointing to the end of the values
489
+ /// \param[in] valid_begin InputIterator with elements indication valid(1)
490
+ /// or null(0) values
491
+ /// \return Status
492
+ template <typename ValuesIter, typename ValidIter>
493
+ enable_if_t<!std::is_pointer<ValidIter>::value, Status> AppendValues(
494
+ ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) {
495
+ static_assert(!internal::is_null_pointer<ValidIter>::value,
496
+ "Don't pass a NULLPTR directly as valid_begin, use the 2-argument "
497
+ "version instead");
498
+ int64_t length = static_cast<int64_t>(std::distance(values_begin, values_end));
499
+ ARROW_RETURN_NOT_OK(Reserve(length));
500
+
501
+ data_builder_.UnsafeAppend<false>(
502
+ length, [&values_begin]() -> bool { return *values_begin++; });
503
+ null_bitmap_builder_.UnsafeAppend<true>(
504
+ length, [&valid_begin]() -> bool { return *valid_begin++; });
505
+ length_ = null_bitmap_builder_.length();
506
+ null_count_ = null_bitmap_builder_.false_count();
507
+ return Status::OK();
508
+ }
509
+
510
+ // Same as above, for a pointer type ValidIter
511
+ template <typename ValuesIter, typename ValidIter>
512
+ enable_if_t<std::is_pointer<ValidIter>::value, Status> AppendValues(
513
+ ValuesIter values_begin, ValuesIter values_end, ValidIter valid_begin) {
514
+ int64_t length = static_cast<int64_t>(std::distance(values_begin, values_end));
515
+ ARROW_RETURN_NOT_OK(Reserve(length));
516
+ data_builder_.UnsafeAppend<false>(
517
+ length, [&values_begin]() -> bool { return *values_begin++; });
518
+
519
+ if (valid_begin == NULLPTR) {
520
+ UnsafeSetNotNull(length);
521
+ } else {
522
+ null_bitmap_builder_.UnsafeAppend<true>(
523
+ length, [&valid_begin]() -> bool { return *valid_begin++; });
524
+ }
525
+ length_ = null_bitmap_builder_.length();
526
+ null_count_ = null_bitmap_builder_.false_count();
527
+ return Status::OK();
528
+ }
529
+
530
+ Status AppendValues(int64_t length, bool value);
531
+
532
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
533
+ int64_t length) override {
534
+ return AppendValues(array.GetValues<uint8_t>(1, 0), length,
535
+ array.GetValues<uint8_t>(0, 0), array.offset + offset);
536
+ }
537
+
538
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
539
+
540
+ /// \cond FALSE
541
+ using ArrayBuilder::Finish;
542
+ /// \endcond
543
+
544
+ Status Finish(std::shared_ptr<BooleanArray>* out) { return FinishTyped(out); }
545
+
546
+ void Reset() override;
547
+ Status Resize(int64_t capacity) override;
548
+
549
+ std::shared_ptr<DataType> type() const override { return boolean(); }
550
+
551
+ protected:
552
+ TypedBufferBuilder<bool> data_builder_;
553
+ };
554
+
555
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_run_end.h ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <limits>
22
+ #include <memory>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "arrow/array.h"
27
+ #include "arrow/array/builder_base.h"
28
+
29
+ namespace arrow {
30
+
31
+ /// \addtogroup run-end-encoded-builders
32
+ ///
33
+ /// @{
34
+
35
+ namespace internal {
36
+
37
+ /// \brief An ArrayBuilder that deduplicates repeated values as they are
38
+ /// appended to the inner-ArrayBuilder and reports the length of the current run
39
+ /// of identical values.
40
+ ///
41
+ /// The following sequence of calls
42
+ ///
43
+ /// Append(2)
44
+ /// Append(2)
45
+ /// Append(2)
46
+ /// Append(7)
47
+ /// Append(7)
48
+ /// Append(2)
49
+ /// FinishInternal()
50
+ ///
51
+ /// will cause the inner-builder to receive only 3 Append calls
52
+ ///
53
+ /// Append(2)
54
+ /// Append(7)
55
+ /// Append(2)
56
+ /// FinishInternal()
57
+ ///
58
+ /// Note that values returned by length(), null_count() and capacity() are
59
+ /// related to the compressed array built by the inner-ArrayBuilder.
60
+ class RunCompressorBuilder : public ArrayBuilder {
61
+ public:
62
+ RunCompressorBuilder(MemoryPool* pool, std::shared_ptr<ArrayBuilder> inner_builder,
63
+ std::shared_ptr<DataType> type);
64
+
65
+ ~RunCompressorBuilder() override;
66
+
67
+ ARROW_DISALLOW_COPY_AND_ASSIGN(RunCompressorBuilder);
68
+
69
+ /// \brief Called right before a run is being closed
70
+ ///
71
+ /// Subclasses can override this function to perform an additional action when
72
+ /// a run is closed (i.e. run-length is known and value is appended to the
73
+ /// inner builder).
74
+ ///
75
+ /// \param value can be NULLPTR if closing a run of NULLs
76
+ /// \param length the greater than 0 length of the value run being closed
77
+ virtual Status WillCloseRun(const std::shared_ptr<const Scalar>& value,
78
+ int64_t length) {
79
+ return Status::OK();
80
+ }
81
+
82
+ /// \brief Called right before a run of empty values is being closed
83
+ ///
84
+ /// Subclasses can override this function to perform an additional action when
85
+ /// a run of empty values is appended (i.e. run-length is known and a single
86
+ /// empty value is appended to the inner builder).
87
+ ///
88
+ /// \param length the greater than 0 length of the value run being closed
89
+ virtual Status WillCloseRunOfEmptyValues(int64_t length) { return Status::OK(); }
90
+
91
+ /// \brief Allocate enough memory for a given number of array elements.
92
+ ///
93
+ /// NOTE: Conservatively resizing a run-length compressed array for a given
94
+ /// number of logical elements is not possible, since the physical length will
95
+ /// vary depending on the values to be appended in the future. But we can
96
+ /// pessimistically assume that each run will contain a single value and
97
+ /// allocate that number of runs.
98
+ Status Resize(int64_t capacity) override { return ResizePhysical(capacity); }
99
+
100
+ /// \brief Allocate enough memory for a given number of runs.
101
+ ///
102
+ /// Like Resize on non-encoded builders, it does not account for variable size
103
+ /// data.
104
+ Status ResizePhysical(int64_t capacity);
105
+
106
+ Status ReservePhysical(int64_t additional_capacity) {
107
+ return Reserve(additional_capacity);
108
+ }
109
+
110
+ void Reset() override;
111
+
112
+ Status AppendNull() final { return AppendNulls(1); }
113
+ Status AppendNulls(int64_t length) override;
114
+
115
+ Status AppendEmptyValue() final { return AppendEmptyValues(1); }
116
+ Status AppendEmptyValues(int64_t length) override;
117
+
118
+ Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override;
119
+ Status AppendScalars(const ScalarVector& scalars) override;
120
+
121
+ // AppendArraySlice() is not implemented.
122
+
123
+ /// \brief Append a slice of an array containing values from already
124
+ /// compressed runs.
125
+ ///
126
+ /// NOTE: WillCloseRun() is not called as the length of each run cannot be
127
+ /// determined at this point. Caller should ensure that !has_open_run() by
128
+ /// calling FinishCurrentRun() before calling this.
129
+ ///
130
+ /// Pre-condition: !has_open_run()
131
+ Status AppendRunCompressedArraySlice(const ArraySpan& array, int64_t offset,
132
+ int64_t length);
133
+
134
+ /// \brief Forces the closing of the current run if one is currently open.
135
+ ///
136
+ /// This can be called when one wants to ensure the current run will not be
137
+ /// extended. This may cause identical values to appear close to each other in
138
+ /// the underlying array (i.e. two runs that could be a single run) if more
139
+ /// values are appended after this is called.
140
+ ///
141
+ /// Finish() and FinishInternal() call this automatically.
142
+ virtual Status FinishCurrentRun();
143
+
144
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
145
+
146
+ ArrayBuilder& inner_builder() const { return *inner_builder_; }
147
+
148
+ std::shared_ptr<DataType> type() const override { return inner_builder_->type(); }
149
+
150
+ bool has_open_run() const { return current_run_length_ > 0; }
151
+ int64_t open_run_length() const { return current_run_length_; }
152
+
153
+ private:
154
+ inline void UpdateDimensions() {
155
+ capacity_ = inner_builder_->capacity();
156
+ length_ = inner_builder_->length();
157
+ null_count_ = inner_builder_->null_count();
158
+ }
159
+
160
+ private:
161
+ std::shared_ptr<ArrayBuilder> inner_builder_;
162
+ std::shared_ptr<const Scalar> current_value_ = NULLPTR;
163
+ int64_t current_run_length_ = 0;
164
+ };
165
+
166
+ } // namespace internal
167
+
168
+ // ----------------------------------------------------------------------
169
+ // RunEndEncoded builder
170
+
171
+ /// \brief Run-end encoded array builder.
172
+ ///
173
+ /// NOTE: the value returned by and capacity() is related to the
174
+ /// compressed array (physical) and not the decoded array (logical) that is
175
+ /// run-end encoded. null_count() always returns 0. length(), on the other hand,
176
+ /// returns the logical length of the run-end encoded array.
177
+ class ARROW_EXPORT RunEndEncodedBuilder : public ArrayBuilder {
178
+ private:
179
+ // An internal::RunCompressorBuilder that produces a run-end in the
180
+ // RunEndEncodedBuilder every time a value-run is closed.
181
+ class ValueRunBuilder : public internal::RunCompressorBuilder {
182
+ public:
183
+ ValueRunBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& value_builder,
184
+ const std::shared_ptr<DataType>& value_type,
185
+ RunEndEncodedBuilder& ree_builder);
186
+
187
+ ~ValueRunBuilder() override = default;
188
+
189
+ Status WillCloseRun(const std::shared_ptr<const Scalar>&, int64_t length) override {
190
+ return ree_builder_.CloseRun(length);
191
+ }
192
+
193
+ Status WillCloseRunOfEmptyValues(int64_t length) override {
194
+ return ree_builder_.CloseRun(length);
195
+ }
196
+
197
+ private:
198
+ RunEndEncodedBuilder& ree_builder_;
199
+ };
200
+
201
+ public:
202
+ RunEndEncodedBuilder(MemoryPool* pool,
203
+ const std::shared_ptr<ArrayBuilder>& run_end_builder,
204
+ const std::shared_ptr<ArrayBuilder>& value_builder,
205
+ std::shared_ptr<DataType> type);
206
+
207
+ /// \brief Allocate enough memory for a given number of array elements.
208
+ ///
209
+ /// NOTE: Conservatively resizing an REE for a given number of logical
210
+ /// elements is not possible, since the physical length will vary depending on
211
+ /// the values to be appended in the future. But we can pessimistically assume
212
+ /// that each run will contain a single value and allocate that number of
213
+ /// runs.
214
+ Status Resize(int64_t capacity) override { return ResizePhysical(capacity); }
215
+
216
+ /// \brief Allocate enough memory for a given number of runs.
217
+ Status ResizePhysical(int64_t capacity);
218
+
219
+ /// \brief Ensure that there is enough space allocated to append the indicated
220
+ /// number of run without any further reallocation. Overallocation is
221
+ /// used in order to minimize the impact of incremental ReservePhysical() calls.
222
+ /// Note that additional_capacity is relative to the current number of elements
223
+ /// rather than to the current capacity, so calls to Reserve() which are not
224
+ /// interspersed with addition of new elements may not increase the capacity.
225
+ ///
226
+ /// \param[in] additional_capacity the number of additional runs
227
+ /// \return Status
228
+ Status ReservePhysical(int64_t additional_capacity) {
229
+ return Reserve(additional_capacity);
230
+ }
231
+
232
+ void Reset() override;
233
+
234
+ Status AppendNull() final { return AppendNulls(1); }
235
+ Status AppendNulls(int64_t length) override;
236
+
237
+ Status AppendEmptyValue() final { return AppendEmptyValues(1); }
238
+ Status AppendEmptyValues(int64_t length) override;
239
+ Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override;
240
+ Status AppendScalars(const ScalarVector& scalars) override;
241
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
242
+ int64_t length) override;
243
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
244
+
245
+ /// \cond FALSE
246
+ using ArrayBuilder::Finish;
247
+ /// \endcond
248
+
249
+ Status Finish(std::shared_ptr<RunEndEncodedArray>* out) { return FinishTyped(out); }
250
+
251
+ /// \brief Forces the closing of the current run if one is currently open.
252
+ ///
253
+ /// This can be called when one wants to ensure the current run will not be
254
+ /// extended. This may cause identical values to appear close to each other in
255
+ /// the values array (i.e. two runs that could be a single run) if more
256
+ /// values are appended after this is called.
257
+ Status FinishCurrentRun();
258
+
259
+ std::shared_ptr<DataType> type() const override;
260
+
261
+ private:
262
+ /// \brief Update physical capacity and logical length
263
+ ///
264
+ /// \param committed_logical_length number of logical values that have been
265
+ /// committed to the values array
266
+ /// \param open_run_length number of logical values in the currently open run if any
267
+ inline void UpdateDimensions(int64_t committed_logical_length,
268
+ int64_t open_run_length) {
269
+ capacity_ = run_end_builder().capacity();
270
+ length_ = committed_logical_length + open_run_length;
271
+ committed_logical_length_ = committed_logical_length;
272
+ }
273
+
274
+ // Pre-condition: !value_run_builder_.has_open_run()
275
+ template <typename RunEndCType>
276
+ Status DoAppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length);
277
+
278
+ template <typename RunEndCType>
279
+ Status DoAppendRunEnd(int64_t run_end);
280
+
281
+ /// \brief Cast run_end to the appropriate type and appends it to the run_ends
282
+ /// array.
283
+ Status AppendRunEnd(int64_t run_end);
284
+
285
+ /// \brief Close a run by appending a value to the run_ends array and updating
286
+ /// length_ to reflect the new run.
287
+ ///
288
+ /// Pre-condition: run_length > 0.
289
+ [[nodiscard]] Status CloseRun(int64_t run_length);
290
+
291
+ ArrayBuilder& run_end_builder();
292
+ ArrayBuilder& value_builder();
293
+
294
+ private:
295
+ std::shared_ptr<RunEndEncodedType> type_;
296
+ ValueRunBuilder* value_run_builder_;
297
+ // The length not counting the current open run in the value_run_builder_
298
+ int64_t committed_logical_length_ = 0;
299
+ };
300
+
301
+ /// @}
302
+
303
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_time.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Contains declarations of time related Arrow builder types.
19
+
20
+ #pragma once
21
+
22
+ #include <memory>
23
+
24
+ #include "arrow/array/builder_base.h"
25
+ #include "arrow/array/builder_primitive.h"
26
+
27
+ namespace arrow {
28
+
29
+ /// \addtogroup temporal-builders
30
+ ///
31
+ /// @{
32
+
33
+ // TODO(ARROW-7938): this class is untested
34
+
35
+ class ARROW_EXPORT DayTimeIntervalBuilder : public NumericBuilder<DayTimeIntervalType> {
36
+ public:
37
+ using DayMilliseconds = DayTimeIntervalType::DayMilliseconds;
38
+
39
+ explicit DayTimeIntervalBuilder(MemoryPool* pool = default_memory_pool(),
40
+ int64_t alignment = kDefaultBufferAlignment)
41
+ : DayTimeIntervalBuilder(day_time_interval(), pool, alignment) {}
42
+
43
+ explicit DayTimeIntervalBuilder(std::shared_ptr<DataType> type,
44
+ MemoryPool* pool = default_memory_pool(),
45
+ int64_t alignment = kDefaultBufferAlignment)
46
+ : NumericBuilder<DayTimeIntervalType>(type, pool, alignment) {}
47
+ };
48
+
49
+ class ARROW_EXPORT MonthDayNanoIntervalBuilder
50
+ : public NumericBuilder<MonthDayNanoIntervalType> {
51
+ public:
52
+ using MonthDayNanos = MonthDayNanoIntervalType::MonthDayNanos;
53
+
54
+ explicit MonthDayNanoIntervalBuilder(MemoryPool* pool = default_memory_pool(),
55
+ int64_t alignment = kDefaultBufferAlignment)
56
+ : MonthDayNanoIntervalBuilder(month_day_nano_interval(), pool, alignment) {}
57
+
58
+ explicit MonthDayNanoIntervalBuilder(std::shared_ptr<DataType> type,
59
+ MemoryPool* pool = default_memory_pool(),
60
+ int64_t alignment = kDefaultBufferAlignment)
61
+ : NumericBuilder<MonthDayNanoIntervalType>(type, pool, alignment) {}
62
+ };
63
+
64
+ /// @}
65
+
66
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_union.h ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "arrow/array/array_nested.h"
26
+ #include "arrow/array/builder_base.h"
27
+ #include "arrow/array/data.h"
28
+ #include "arrow/buffer_builder.h"
29
+ #include "arrow/memory_pool.h"
30
+ #include "arrow/status.h"
31
+ #include "arrow/type.h"
32
+ #include "arrow/util/visibility.h"
33
+
34
+ namespace arrow {
35
+
36
+ /// \addtogroup nested-builders
37
+ ///
38
+ /// @{
39
+
40
+ /// \brief Base class for union array builds.
41
+ ///
42
+ /// Note that while we subclass ArrayBuilder, as union types do not have a
43
+ /// validity bitmap, the bitmap builder member of ArrayBuilder is not used.
44
+ class ARROW_EXPORT BasicUnionBuilder : public ArrayBuilder {
45
+ public:
46
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
47
+
48
+ /// \cond FALSE
49
+ using ArrayBuilder::Finish;
50
+ /// \endcond
51
+
52
+ Status Finish(std::shared_ptr<UnionArray>* out) { return FinishTyped(out); }
53
+
54
+ /// \brief Make a new child builder available to the UnionArray
55
+ ///
56
+ /// \param[in] new_child the child builder
57
+ /// \param[in] field_name the name of the field in the union array type
58
+ /// if type inference is used
59
+ /// \return child index, which is the "type" argument that needs
60
+ /// to be passed to the "Append" method to add a new element to
61
+ /// the union array.
62
+ int8_t AppendChild(const std::shared_ptr<ArrayBuilder>& new_child,
63
+ const std::string& field_name = "");
64
+
65
+ std::shared_ptr<DataType> type() const override;
66
+
67
+ int64_t length() const override { return types_builder_.length(); }
68
+
69
+ protected:
70
+ BasicUnionBuilder(MemoryPool* pool, int64_t alignment,
71
+ const std::vector<std::shared_ptr<ArrayBuilder>>& children,
72
+ const std::shared_ptr<DataType>& type);
73
+
74
+ int8_t NextTypeId();
75
+
76
+ std::vector<std::shared_ptr<Field>> child_fields_;
77
+ std::vector<int8_t> type_codes_;
78
+ UnionMode::type mode_;
79
+
80
+ std::vector<ArrayBuilder*> type_id_to_children_;
81
+ std::vector<int> type_id_to_child_id_;
82
+ // for all type_id < dense_type_id_, type_id_to_children_[type_id] != nullptr
83
+ int8_t dense_type_id_ = 0;
84
+ TypedBufferBuilder<int8_t> types_builder_;
85
+ };
86
+
87
+ /// \class DenseUnionBuilder
88
+ ///
89
+ /// This API is EXPERIMENTAL.
90
+ class ARROW_EXPORT DenseUnionBuilder : public BasicUnionBuilder {
91
+ public:
92
+ /// Use this constructor to initialize the UnionBuilder with no child builders,
93
+ /// allowing type to be inferred. You will need to call AppendChild for each of the
94
+ /// children builders you want to use.
95
+ explicit DenseUnionBuilder(MemoryPool* pool,
96
+ int64_t alignment = kDefaultBufferAlignment)
97
+ : BasicUnionBuilder(pool, alignment, {}, dense_union(FieldVector{})),
98
+ offsets_builder_(pool, alignment) {}
99
+
100
+ /// Use this constructor to specify the type explicitly.
101
+ /// You can still add child builders to the union after using this constructor
102
+ DenseUnionBuilder(MemoryPool* pool,
103
+ const std::vector<std::shared_ptr<ArrayBuilder>>& children,
104
+ const std::shared_ptr<DataType>& type,
105
+ int64_t alignment = kDefaultBufferAlignment)
106
+ : BasicUnionBuilder(pool, alignment, children, type),
107
+ offsets_builder_(pool, alignment) {}
108
+
109
+ Status AppendNull() final {
110
+ const int8_t first_child_code = type_codes_[0];
111
+ ArrayBuilder* child_builder = type_id_to_children_[first_child_code];
112
+ ARROW_RETURN_NOT_OK(types_builder_.Append(first_child_code));
113
+ ARROW_RETURN_NOT_OK(
114
+ offsets_builder_.Append(static_cast<int32_t>(child_builder->length())));
115
+ // Append a null arbitrarily to the first child
116
+ return child_builder->AppendNull();
117
+ }
118
+
119
+ Status AppendNulls(int64_t length) final {
120
+ const int8_t first_child_code = type_codes_[0];
121
+ ArrayBuilder* child_builder = type_id_to_children_[first_child_code];
122
+ ARROW_RETURN_NOT_OK(types_builder_.Append(length, first_child_code));
123
+ ARROW_RETURN_NOT_OK(
124
+ offsets_builder_.Append(length, static_cast<int32_t>(child_builder->length())));
125
+ // Append just a single null to the first child
126
+ return child_builder->AppendNull();
127
+ }
128
+
129
+ Status AppendEmptyValue() final {
130
+ const int8_t first_child_code = type_codes_[0];
131
+ ArrayBuilder* child_builder = type_id_to_children_[first_child_code];
132
+ ARROW_RETURN_NOT_OK(types_builder_.Append(first_child_code));
133
+ ARROW_RETURN_NOT_OK(
134
+ offsets_builder_.Append(static_cast<int32_t>(child_builder->length())));
135
+ // Append an empty value arbitrarily to the first child
136
+ return child_builder->AppendEmptyValue();
137
+ }
138
+
139
+ Status AppendEmptyValues(int64_t length) final {
140
+ const int8_t first_child_code = type_codes_[0];
141
+ ArrayBuilder* child_builder = type_id_to_children_[first_child_code];
142
+ ARROW_RETURN_NOT_OK(types_builder_.Append(length, first_child_code));
143
+ ARROW_RETURN_NOT_OK(
144
+ offsets_builder_.Append(length, static_cast<int32_t>(child_builder->length())));
145
+ // Append just a single empty value to the first child
146
+ return child_builder->AppendEmptyValue();
147
+ }
148
+
149
+ /// \brief Append an element to the UnionArray. This must be followed
150
+ /// by an append to the appropriate child builder.
151
+ ///
152
+ /// \param[in] next_type type_id of the child to which the next value will be appended.
153
+ ///
154
+ /// The corresponding child builder must be appended to independently after this method
155
+ /// is called.
156
+ Status Append(int8_t next_type) {
157
+ ARROW_RETURN_NOT_OK(types_builder_.Append(next_type));
158
+ if (type_id_to_children_[next_type]->length() == kListMaximumElements) {
159
+ return Status::CapacityError(
160
+ "a dense UnionArray cannot contain more than 2^31 - 1 elements from a single "
161
+ "child");
162
+ }
163
+ auto offset = static_cast<int32_t>(type_id_to_children_[next_type]->length());
164
+ return offsets_builder_.Append(offset);
165
+ }
166
+
167
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
168
+ int64_t length) override;
169
+
170
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
171
+
172
+ private:
173
+ TypedBufferBuilder<int32_t> offsets_builder_;
174
+ };
175
+
176
+ /// \class SparseUnionBuilder
177
+ ///
178
+ /// This API is EXPERIMENTAL.
179
+ class ARROW_EXPORT SparseUnionBuilder : public BasicUnionBuilder {
180
+ public:
181
+ /// Use this constructor to initialize the UnionBuilder with no child builders,
182
+ /// allowing type to be inferred. You will need to call AppendChild for each of the
183
+ /// children builders you want to use.
184
+ explicit SparseUnionBuilder(MemoryPool* pool,
185
+ int64_t alignment = kDefaultBufferAlignment)
186
+ : BasicUnionBuilder(pool, alignment, {}, sparse_union(FieldVector{})) {}
187
+
188
+ /// Use this constructor to specify the type explicitly.
189
+ /// You can still add child builders to the union after using this constructor
190
+ SparseUnionBuilder(MemoryPool* pool,
191
+ const std::vector<std::shared_ptr<ArrayBuilder>>& children,
192
+ const std::shared_ptr<DataType>& type,
193
+ int64_t alignment = kDefaultBufferAlignment)
194
+ : BasicUnionBuilder(pool, alignment, children, type) {}
195
+
196
+ /// \brief Append a null value.
197
+ ///
198
+ /// A null is appended to the first child, empty values to the other children.
199
+ Status AppendNull() final {
200
+ const auto first_child_code = type_codes_[0];
201
+ ARROW_RETURN_NOT_OK(types_builder_.Append(first_child_code));
202
+ ARROW_RETURN_NOT_OK(type_id_to_children_[first_child_code]->AppendNull());
203
+ for (int i = 1; i < static_cast<int>(type_codes_.size()); ++i) {
204
+ ARROW_RETURN_NOT_OK(type_id_to_children_[type_codes_[i]]->AppendEmptyValue());
205
+ }
206
+ return Status::OK();
207
+ }
208
+
209
+ /// \brief Append multiple null values.
210
+ ///
211
+ /// Nulls are appended to the first child, empty values to the other children.
212
+ Status AppendNulls(int64_t length) final {
213
+ const auto first_child_code = type_codes_[0];
214
+ ARROW_RETURN_NOT_OK(types_builder_.Append(length, first_child_code));
215
+ ARROW_RETURN_NOT_OK(type_id_to_children_[first_child_code]->AppendNulls(length));
216
+ for (int i = 1; i < static_cast<int>(type_codes_.size()); ++i) {
217
+ ARROW_RETURN_NOT_OK(
218
+ type_id_to_children_[type_codes_[i]]->AppendEmptyValues(length));
219
+ }
220
+ return Status::OK();
221
+ }
222
+
223
+ Status AppendEmptyValue() final {
224
+ ARROW_RETURN_NOT_OK(types_builder_.Append(type_codes_[0]));
225
+ for (int8_t code : type_codes_) {
226
+ ARROW_RETURN_NOT_OK(type_id_to_children_[code]->AppendEmptyValue());
227
+ }
228
+ return Status::OK();
229
+ }
230
+
231
+ Status AppendEmptyValues(int64_t length) final {
232
+ ARROW_RETURN_NOT_OK(types_builder_.Append(length, type_codes_[0]));
233
+ for (int8_t code : type_codes_) {
234
+ ARROW_RETURN_NOT_OK(type_id_to_children_[code]->AppendEmptyValues(length));
235
+ }
236
+ return Status::OK();
237
+ }
238
+
239
+ /// \brief Append an element to the UnionArray. This must be followed
240
+ /// by an append to the appropriate child builder.
241
+ ///
242
+ /// \param[in] next_type type_id of the child to which the next value will be appended.
243
+ ///
244
+ /// The corresponding child builder must be appended to independently after this method
245
+ /// is called, and all other child builders must have null or empty value appended.
246
+ Status Append(int8_t next_type) { return types_builder_.Append(next_type); }
247
+
248
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
249
+ int64_t length) override;
250
+ };
251
+
252
+ /// @}
253
+
254
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/concatenate.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+
22
+ #include "arrow/type_fwd.h"
23
+ #include "arrow/util/macros.h"
24
+ #include "arrow/util/visibility.h"
25
+
26
+ namespace arrow {
27
+
28
+ /// \brief Concatenate arrays
29
+ ///
30
+ /// \param[in] arrays a vector of arrays to be concatenated
31
+ /// \param[in] pool memory to store the result will be allocated from this memory pool
32
+ /// \return the concatenated array
33
+ ARROW_EXPORT
34
+ Result<std::shared_ptr<Array>> Concatenate(const ArrayVector& arrays,
35
+ MemoryPool* pool = default_memory_pool());
36
+
37
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/data.h ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <atomic> // IWYU pragma: export
21
+ #include <cassert>
22
+ #include <cstdint>
23
+ #include <memory>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #include "arrow/buffer.h"
28
+ #include "arrow/result.h"
29
+ #include "arrow/type.h"
30
+ #include "arrow/util/bit_util.h"
31
+ #include "arrow/util/macros.h"
32
+ #include "arrow/util/span.h"
33
+ #include "arrow/util/visibility.h"
34
+
35
+ namespace arrow {
36
+
37
+ class Array;
38
+ struct ArrayData;
39
+
40
+ namespace internal {
41
+ // ----------------------------------------------------------------------
42
+ // Null handling for types without a validity bitmap and the dictionary type
43
+
44
+ ARROW_EXPORT bool IsNullSparseUnion(const ArrayData& data, int64_t i);
45
+ ARROW_EXPORT bool IsNullDenseUnion(const ArrayData& data, int64_t i);
46
+ ARROW_EXPORT bool IsNullRunEndEncoded(const ArrayData& data, int64_t i);
47
+
48
+ ARROW_EXPORT bool UnionMayHaveLogicalNulls(const ArrayData& data);
49
+ ARROW_EXPORT bool RunEndEncodedMayHaveLogicalNulls(const ArrayData& data);
50
+ ARROW_EXPORT bool DictionaryMayHaveLogicalNulls(const ArrayData& data);
51
+ } // namespace internal
52
+
53
+ // When slicing, we do not know the null count of the sliced range without
54
+ // doing some computation. To avoid doing this eagerly, we set the null count
55
+ // to -1 (any negative number will do). When Array::null_count is called the
56
+ // first time, the null count will be computed. See ARROW-33
57
+ constexpr int64_t kUnknownNullCount = -1;
58
+
59
+ // ----------------------------------------------------------------------
60
+ // Generic array data container
61
+
62
+ /// \class ArrayData
63
+ /// \brief Mutable container for generic Arrow array data
64
+ ///
65
+ /// This data structure is a self-contained representation of the memory and
66
+ /// metadata inside an Arrow array data structure (called vectors in Java). The
67
+ /// classes arrow::Array and its subclasses provide strongly-typed accessors
68
+ /// with support for the visitor pattern and other affordances.
69
+ ///
70
+ /// This class is designed for easy internal data manipulation, analytical data
71
+ /// processing, and data transport to and from IPC messages. For example, we
72
+ /// could cast from int64 to float64 like so:
73
+ ///
74
+ /// Int64Array arr = GetMyData();
75
+ /// auto new_data = arr.data()->Copy();
76
+ /// new_data->type = arrow::float64();
77
+ /// DoubleArray double_arr(new_data);
78
+ ///
79
+ /// This object is also useful in an analytics setting where memory may be
80
+ /// reused. For example, if we had a group of operations all returning doubles,
81
+ /// say:
82
+ ///
83
+ /// Log(Sqrt(Expr(arr)))
84
+ ///
85
+ /// Then the low-level implementations of each of these functions could have
86
+ /// the signatures
87
+ ///
88
+ /// void Log(const ArrayData& values, ArrayData* out);
89
+ ///
90
+ /// As another example a function may consume one or more memory buffers in an
91
+ /// input array and replace them with newly-allocated data, changing the output
92
+ /// data type as well.
93
+ struct ARROW_EXPORT ArrayData {
94
+ ArrayData() = default;
95
+
96
+ ArrayData(std::shared_ptr<DataType> type, int64_t length,
97
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0)
98
+ : type(std::move(type)), length(length), null_count(null_count), offset(offset) {}
99
+
100
+ ArrayData(std::shared_ptr<DataType> type, int64_t length,
101
+ std::vector<std::shared_ptr<Buffer>> buffers,
102
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0)
103
+ : ArrayData(std::move(type), length, null_count, offset) {
104
+ this->buffers = std::move(buffers);
105
+ }
106
+
107
+ ArrayData(std::shared_ptr<DataType> type, int64_t length,
108
+ std::vector<std::shared_ptr<Buffer>> buffers,
109
+ std::vector<std::shared_ptr<ArrayData>> child_data,
110
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0)
111
+ : ArrayData(std::move(type), length, null_count, offset) {
112
+ this->buffers = std::move(buffers);
113
+ this->child_data = std::move(child_data);
114
+ }
115
+
116
+ static std::shared_ptr<ArrayData> Make(std::shared_ptr<DataType> type, int64_t length,
117
+ std::vector<std::shared_ptr<Buffer>> buffers,
118
+ int64_t null_count = kUnknownNullCount,
119
+ int64_t offset = 0);
120
+
121
+ static std::shared_ptr<ArrayData> Make(
122
+ std::shared_ptr<DataType> type, int64_t length,
123
+ std::vector<std::shared_ptr<Buffer>> buffers,
124
+ std::vector<std::shared_ptr<ArrayData>> child_data,
125
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
126
+
127
+ static std::shared_ptr<ArrayData> Make(
128
+ std::shared_ptr<DataType> type, int64_t length,
129
+ std::vector<std::shared_ptr<Buffer>> buffers,
130
+ std::vector<std::shared_ptr<ArrayData>> child_data,
131
+ std::shared_ptr<ArrayData> dictionary, int64_t null_count = kUnknownNullCount,
132
+ int64_t offset = 0);
133
+
134
+ static std::shared_ptr<ArrayData> Make(std::shared_ptr<DataType> type, int64_t length,
135
+ int64_t null_count = kUnknownNullCount,
136
+ int64_t offset = 0);
137
+
138
+ // Move constructor
139
+ ArrayData(ArrayData&& other) noexcept
140
+ : type(std::move(other.type)),
141
+ length(other.length),
142
+ offset(other.offset),
143
+ buffers(std::move(other.buffers)),
144
+ child_data(std::move(other.child_data)),
145
+ dictionary(std::move(other.dictionary)) {
146
+ SetNullCount(other.null_count);
147
+ }
148
+
149
+ // Copy constructor
150
+ ArrayData(const ArrayData& other) noexcept
151
+ : type(other.type),
152
+ length(other.length),
153
+ offset(other.offset),
154
+ buffers(other.buffers),
155
+ child_data(other.child_data),
156
+ dictionary(other.dictionary) {
157
+ SetNullCount(other.null_count);
158
+ }
159
+
160
+ // Move assignment
161
+ ArrayData& operator=(ArrayData&& other) {
162
+ type = std::move(other.type);
163
+ length = other.length;
164
+ SetNullCount(other.null_count);
165
+ offset = other.offset;
166
+ buffers = std::move(other.buffers);
167
+ child_data = std::move(other.child_data);
168
+ dictionary = std::move(other.dictionary);
169
+ return *this;
170
+ }
171
+
172
+ // Copy assignment
173
+ ArrayData& operator=(const ArrayData& other) {
174
+ type = other.type;
175
+ length = other.length;
176
+ SetNullCount(other.null_count);
177
+ offset = other.offset;
178
+ buffers = other.buffers;
179
+ child_data = other.child_data;
180
+ dictionary = other.dictionary;
181
+ return *this;
182
+ }
183
+
184
+ std::shared_ptr<ArrayData> Copy() const { return std::make_shared<ArrayData>(*this); }
185
+
186
+ bool IsNull(int64_t i) const { return !IsValid(i); }
187
+
188
+ bool IsValid(int64_t i) const {
189
+ if (buffers[0] != NULLPTR) {
190
+ return bit_util::GetBit(buffers[0]->data(), i + offset);
191
+ }
192
+ const auto type = this->type->id();
193
+ if (type == Type::SPARSE_UNION) {
194
+ return !internal::IsNullSparseUnion(*this, i);
195
+ }
196
+ if (type == Type::DENSE_UNION) {
197
+ return !internal::IsNullDenseUnion(*this, i);
198
+ }
199
+ if (type == Type::RUN_END_ENCODED) {
200
+ return !internal::IsNullRunEndEncoded(*this, i);
201
+ }
202
+ return null_count.load() != length;
203
+ }
204
+
205
+ // Access a buffer's data as a typed C pointer
206
+ template <typename T>
207
+ inline const T* GetValues(int i, int64_t absolute_offset) const {
208
+ if (buffers[i]) {
209
+ return reinterpret_cast<const T*>(buffers[i]->data()) + absolute_offset;
210
+ } else {
211
+ return NULLPTR;
212
+ }
213
+ }
214
+
215
+ template <typename T>
216
+ inline const T* GetValues(int i) const {
217
+ return GetValues<T>(i, offset);
218
+ }
219
+
220
+ // Like GetValues, but returns NULLPTR instead of aborting if the underlying
221
+ // buffer is not a CPU buffer.
222
+ template <typename T>
223
+ inline const T* GetValuesSafe(int i, int64_t absolute_offset) const {
224
+ if (buffers[i] && buffers[i]->is_cpu()) {
225
+ return reinterpret_cast<const T*>(buffers[i]->data()) + absolute_offset;
226
+ } else {
227
+ return NULLPTR;
228
+ }
229
+ }
230
+
231
+ template <typename T>
232
+ inline const T* GetValuesSafe(int i) const {
233
+ return GetValuesSafe<T>(i, offset);
234
+ }
235
+
236
+ // Access a buffer's data as a typed C pointer
237
+ template <typename T>
238
+ inline T* GetMutableValues(int i, int64_t absolute_offset) {
239
+ if (buffers[i]) {
240
+ return reinterpret_cast<T*>(buffers[i]->mutable_data()) + absolute_offset;
241
+ } else {
242
+ return NULLPTR;
243
+ }
244
+ }
245
+
246
+ template <typename T>
247
+ inline T* GetMutableValues(int i) {
248
+ return GetMutableValues<T>(i, offset);
249
+ }
250
+
251
+ /// \brief Construct a zero-copy slice of the data with the given offset and length
252
+ std::shared_ptr<ArrayData> Slice(int64_t offset, int64_t length) const;
253
+
254
+ /// \brief Input-checking variant of Slice
255
+ ///
256
+ /// An Invalid Status is returned if the requested slice falls out of bounds.
257
+ /// Note that unlike Slice, `length` isn't clamped to the available buffer size.
258
+ Result<std::shared_ptr<ArrayData>> SliceSafe(int64_t offset, int64_t length) const;
259
+
260
+ void SetNullCount(int64_t v) { null_count.store(v); }
261
+
262
+ /// \brief Return physical null count, or compute and set it if it's not known
263
+ int64_t GetNullCount() const;
264
+
265
+ /// \brief Return true if the data has a validity bitmap and the physical null
266
+ /// count is known to be non-zero or not yet known.
267
+ ///
268
+ /// Note that this is not the same as MayHaveLogicalNulls, which also checks
269
+ /// for the presence of nulls in child data for types like unions and run-end
270
+ /// encoded types.
271
+ ///
272
+ /// \see HasValidityBitmap
273
+ /// \see MayHaveLogicalNulls
274
+ bool MayHaveNulls() const {
275
+ // If an ArrayData is slightly malformed it may have kUnknownNullCount set
276
+ // but no buffer
277
+ return null_count.load() != 0 && buffers[0] != NULLPTR;
278
+ }
279
+
280
+ /// \brief Return true if the data has a validity bitmap
281
+ bool HasValidityBitmap() const { return buffers[0] != NULLPTR; }
282
+
283
+ /// \brief Return true if the validity bitmap may have 0's in it, or if the
284
+ /// child arrays (in the case of types without a validity bitmap) may have
285
+ /// nulls, or if the dictionary of dictionay array may have nulls.
286
+ ///
287
+ /// This is not a drop-in replacement for MayHaveNulls, as historically
288
+ /// MayHaveNulls() has been used to check for the presence of a validity
289
+ /// bitmap that needs to be checked.
290
+ ///
291
+ /// Code that previously used MayHaveNulls() and then dealt with the validity
292
+ /// bitmap directly can be fixed to handle all types correctly without
293
+ /// performance degradation when handling most types by adopting
294
+ /// HasValidityBitmap and MayHaveLogicalNulls.
295
+ ///
296
+ /// Before:
297
+ ///
298
+ /// uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR;
299
+ /// for (int64_t i = 0; i < array.length; ++i) {
300
+ /// if (validity && !bit_util::GetBit(validity, i)) {
301
+ /// continue; // skip a NULL
302
+ /// }
303
+ /// ...
304
+ /// }
305
+ ///
306
+ /// After:
307
+ ///
308
+ /// bool all_valid = !array.MayHaveLogicalNulls();
309
+ /// uint8_t* validity = array.HasValidityBitmap() ? array.buffers[0].data : NULLPTR;
310
+ /// for (int64_t i = 0; i < array.length; ++i) {
311
+ /// bool is_valid = all_valid ||
312
+ /// (validity && bit_util::GetBit(validity, i)) ||
313
+ /// array.IsValid(i);
314
+ /// if (!is_valid) {
315
+ /// continue; // skip a NULL
316
+ /// }
317
+ /// ...
318
+ /// }
319
+ bool MayHaveLogicalNulls() const {
320
+ if (buffers[0] != NULLPTR) {
321
+ return null_count.load() != 0;
322
+ }
323
+ const auto t = type->id();
324
+ if (t == Type::SPARSE_UNION || t == Type::DENSE_UNION) {
325
+ return internal::UnionMayHaveLogicalNulls(*this);
326
+ }
327
+ if (t == Type::RUN_END_ENCODED) {
328
+ return internal::RunEndEncodedMayHaveLogicalNulls(*this);
329
+ }
330
+ if (t == Type::DICTIONARY) {
331
+ return internal::DictionaryMayHaveLogicalNulls(*this);
332
+ }
333
+ return null_count.load() != 0;
334
+ }
335
+
336
+ /// \brief Computes the logical null count for arrays of all types including
337
+ /// those that do not have a validity bitmap like union and run-end encoded
338
+ /// arrays
339
+ ///
340
+ /// If the array has a validity bitmap, this function behaves the same as
341
+ /// GetNullCount. For types that have no validity bitmap, this function will
342
+ /// recompute the null count every time it is called.
343
+ ///
344
+ /// \see GetNullCount
345
+ int64_t ComputeLogicalNullCount() const;
346
+
347
+ std::shared_ptr<DataType> type;
348
+ int64_t length = 0;
349
+ mutable std::atomic<int64_t> null_count{0};
350
+ // The logical start point into the physical buffers (in values, not bytes).
351
+ // Note that, for child data, this must be *added* to the child data's own offset.
352
+ int64_t offset = 0;
353
+ std::vector<std::shared_ptr<Buffer>> buffers;
354
+ std::vector<std::shared_ptr<ArrayData>> child_data;
355
+
356
+ // The dictionary for this Array, if any. Only used for dictionary type
357
+ std::shared_ptr<ArrayData> dictionary;
358
+ };
359
+
360
+ /// \brief A non-owning Buffer reference
361
+ struct ARROW_EXPORT BufferSpan {
362
+ // It is the user of this class's responsibility to ensure that
363
+ // buffers that were const originally are not written to
364
+ // accidentally.
365
+ uint8_t* data = NULLPTR;
366
+ int64_t size = 0;
367
+ // Pointer back to buffer that owns this memory
368
+ const std::shared_ptr<Buffer>* owner = NULLPTR;
369
+
370
+ template <typename T>
371
+ const T* data_as() const {
372
+ return reinterpret_cast<const T*>(data);
373
+ }
374
+ template <typename T>
375
+ T* mutable_data_as() {
376
+ return reinterpret_cast<T*>(data);
377
+ }
378
+ };
379
+
380
+ /// \brief EXPERIMENTAL: A non-owning ArrayData reference that is cheaply
381
+ /// copyable and does not contain any shared_ptr objects. Do not use in public
382
+ /// APIs aside from compute kernels for now
383
+ struct ARROW_EXPORT ArraySpan {
384
+ const DataType* type = NULLPTR;
385
+ int64_t length = 0;
386
+ mutable int64_t null_count = kUnknownNullCount;
387
+ int64_t offset = 0;
388
+ BufferSpan buffers[3];
389
+
390
+ ArraySpan() = default;
391
+
392
+ explicit ArraySpan(const DataType* type, int64_t length) : type(type), length(length) {}
393
+
394
+ ArraySpan(const ArrayData& data) { // NOLINT implicit conversion
395
+ SetMembers(data);
396
+ }
397
+ explicit ArraySpan(const Scalar& data) { FillFromScalar(data); }
398
+
399
+ /// If dictionary-encoded, put dictionary in the first entry
400
+ std::vector<ArraySpan> child_data;
401
+
402
+ /// \brief Populate ArraySpan to look like an array of length 1 pointing at
403
+ /// the data members of a Scalar value
404
+ void FillFromScalar(const Scalar& value);
405
+
406
+ void SetMembers(const ArrayData& data);
407
+
408
+ void SetBuffer(int index, const std::shared_ptr<Buffer>& buffer) {
409
+ this->buffers[index].data = const_cast<uint8_t*>(buffer->data());
410
+ this->buffers[index].size = buffer->size();
411
+ this->buffers[index].owner = &buffer;
412
+ }
413
+
414
+ const ArraySpan& dictionary() const { return child_data[0]; }
415
+
416
+ /// \brief Return the number of buffers (out of 3) that are used to
417
+ /// constitute this array
418
+ int num_buffers() const;
419
+
420
+ // Access a buffer's data as a typed C pointer
421
+ template <typename T>
422
+ inline T* GetValues(int i, int64_t absolute_offset) {
423
+ return reinterpret_cast<T*>(buffers[i].data) + absolute_offset;
424
+ }
425
+
426
+ template <typename T>
427
+ inline T* GetValues(int i) {
428
+ return GetValues<T>(i, this->offset);
429
+ }
430
+
431
+ // Access a buffer's data as a typed C pointer
432
+ template <typename T>
433
+ inline const T* GetValues(int i, int64_t absolute_offset) const {
434
+ return reinterpret_cast<const T*>(buffers[i].data) + absolute_offset;
435
+ }
436
+
437
+ template <typename T>
438
+ inline const T* GetValues(int i) const {
439
+ return GetValues<T>(i, this->offset);
440
+ }
441
+
442
+ /// \brief Access a buffer's data as a span
443
+ ///
444
+ /// \param i The buffer index
445
+ /// \param length The required length (in number of typed values) of the requested span
446
+ /// \pre i > 0
447
+ /// \pre length <= the length of the buffer (in number of values) that's expected for
448
+ /// this array type
449
+ /// \return A span<const T> of the requested length
450
+ template <typename T>
451
+ util::span<const T> GetSpan(int i, int64_t length) const {
452
+ const int64_t buffer_length = buffers[i].size / static_cast<int64_t>(sizeof(T));
453
+ assert(i > 0 && length + offset <= buffer_length);
454
+ ARROW_UNUSED(buffer_length);
455
+ return util::span<const T>(buffers[i].data_as<T>() + this->offset, length);
456
+ }
457
+
458
+ /// \brief Access a buffer's data as a span
459
+ ///
460
+ /// \param i The buffer index
461
+ /// \param length The required length (in number of typed values) of the requested span
462
+ /// \pre i > 0
463
+ /// \pre length <= the length of the buffer (in number of values) that's expected for
464
+ /// this array type
465
+ /// \return A span<T> of the requested length
466
+ template <typename T>
467
+ util::span<T> GetSpan(int i, int64_t length) {
468
+ const int64_t buffer_length = buffers[i].size / static_cast<int64_t>(sizeof(T));
469
+ assert(i > 0 && length + offset <= buffer_length);
470
+ ARROW_UNUSED(buffer_length);
471
+ return util::span<T>(buffers[i].mutable_data_as<T>() + this->offset, length);
472
+ }
473
+
474
+ inline bool IsNull(int64_t i) const { return !IsValid(i); }
475
+
476
+ inline bool IsValid(int64_t i) const {
477
+ if (this->buffers[0].data != NULLPTR) {
478
+ return bit_util::GetBit(this->buffers[0].data, i + this->offset);
479
+ } else {
480
+ const auto type = this->type->id();
481
+ if (type == Type::SPARSE_UNION) {
482
+ return !IsNullSparseUnion(i);
483
+ }
484
+ if (type == Type::DENSE_UNION) {
485
+ return !IsNullDenseUnion(i);
486
+ }
487
+ if (type == Type::RUN_END_ENCODED) {
488
+ return !IsNullRunEndEncoded(i);
489
+ }
490
+ return this->null_count != this->length;
491
+ }
492
+ }
493
+
494
+ std::shared_ptr<ArrayData> ToArrayData() const;
495
+
496
+ std::shared_ptr<Array> ToArray() const;
497
+
498
+ std::shared_ptr<Buffer> GetBuffer(int index) const {
499
+ const BufferSpan& buf = this->buffers[index];
500
+ if (buf.owner) {
501
+ return *buf.owner;
502
+ } else if (buf.data != NULLPTR) {
503
+ // Buffer points to some memory without an owning buffer
504
+ return std::make_shared<Buffer>(buf.data, buf.size);
505
+ } else {
506
+ return NULLPTR;
507
+ }
508
+ }
509
+
510
+ void SetSlice(int64_t offset, int64_t length) {
511
+ this->offset = offset;
512
+ this->length = length;
513
+ if (this->type->id() == Type::NA) {
514
+ this->null_count = this->length;
515
+ } else if (this->MayHaveNulls()) {
516
+ this->null_count = kUnknownNullCount;
517
+ } else {
518
+ this->null_count = 0;
519
+ }
520
+ }
521
+
522
+ /// \brief Return physical null count, or compute and set it if it's not known
523
+ int64_t GetNullCount() const;
524
+
525
+ /// \brief Return true if the array has a validity bitmap and the physical null
526
+ /// count is known to be non-zero or not yet known
527
+ ///
528
+ /// Note that this is not the same as MayHaveLogicalNulls, which also checks
529
+ /// for the presence of nulls in child data for types like unions and run-end
530
+ /// encoded types.
531
+ ///
532
+ /// \see HasValidityBitmap
533
+ /// \see MayHaveLogicalNulls
534
+ bool MayHaveNulls() const {
535
+ // If an ArrayData is slightly malformed it may have kUnknownNullCount set
536
+ // but no buffer
537
+ return null_count != 0 && buffers[0].data != NULLPTR;
538
+ }
539
+
540
+ /// \brief Return true if the array has a validity bitmap
541
+ bool HasValidityBitmap() const { return buffers[0].data != NULLPTR; }
542
+
543
+ /// \brief Return true if the validity bitmap may have 0's in it, or if the
544
+ /// child arrays (in the case of types without a validity bitmap) may have
545
+ /// nulls, or if the dictionary of dictionay array may have nulls.
546
+ ///
547
+ /// \see ArrayData::MayHaveLogicalNulls
548
+ bool MayHaveLogicalNulls() const {
549
+ if (buffers[0].data != NULLPTR) {
550
+ return null_count != 0;
551
+ }
552
+ const auto t = type->id();
553
+ if (t == Type::SPARSE_UNION || t == Type::DENSE_UNION) {
554
+ return UnionMayHaveLogicalNulls();
555
+ }
556
+ if (t == Type::RUN_END_ENCODED) {
557
+ return RunEndEncodedMayHaveLogicalNulls();
558
+ }
559
+ if (t == Type::DICTIONARY) {
560
+ return DictionaryMayHaveLogicalNulls();
561
+ }
562
+ return null_count != 0;
563
+ }
564
+
565
+ /// \brief Compute the logical null count for arrays of all types including
566
+ /// those that do not have a validity bitmap like union and run-end encoded
567
+ /// arrays
568
+ ///
569
+ /// If the array has a validity bitmap, this function behaves the same as
570
+ /// GetNullCount. For types that have no validity bitmap, this function will
571
+ /// recompute the logical null count every time it is called.
572
+ ///
573
+ /// \see GetNullCount
574
+ int64_t ComputeLogicalNullCount() const;
575
+
576
+ /// Some DataTypes (StringView, BinaryView) may have an arbitrary number of variadic
577
+ /// buffers. Since ArraySpan only has 3 buffers, we pack the variadic buffers into
578
+ /// buffers[2]; IE buffers[2].data points to the first shared_ptr<Buffer> of the
579
+ /// variadic set and buffers[2].size is the number of variadic buffers times
580
+ /// sizeof(shared_ptr<Buffer>).
581
+ ///
582
+ /// \see HasVariadicBuffers
583
+ util::span<const std::shared_ptr<Buffer>> GetVariadicBuffers() const;
584
+ bool HasVariadicBuffers() const;
585
+
586
+ private:
587
+ ARROW_FRIEND_EXPORT friend bool internal::IsNullRunEndEncoded(const ArrayData& span,
588
+ int64_t i);
589
+
590
+ bool IsNullSparseUnion(int64_t i) const;
591
+ bool IsNullDenseUnion(int64_t i) const;
592
+
593
+ /// \brief Return true if the value at logical index i is null
594
+ ///
595
+ /// This function uses binary-search, so it has a O(log N) cost.
596
+ /// Iterating over the whole array and calling IsNull is O(N log N), so
597
+ /// for better performance it is recommended to use a
598
+ /// ree_util::RunEndEncodedArraySpan to iterate run by run instead.
599
+ bool IsNullRunEndEncoded(int64_t i) const;
600
+
601
+ bool UnionMayHaveLogicalNulls() const;
602
+ bool RunEndEncodedMayHaveLogicalNulls() const;
603
+ bool DictionaryMayHaveLogicalNulls() const;
604
+ };
605
+
606
+ namespace internal {
607
+
608
+ void FillZeroLengthArray(const DataType* type, ArraySpan* span);
609
+
610
+ /// Construct a zero-copy view of this ArrayData with the given type.
611
+ ///
612
+ /// This method checks if the types are layout-compatible.
613
+ /// Nested types are traversed in depth-first order. Data buffers must have
614
+ /// the same item sizes, even though the logical types may be different.
615
+ /// An error is returned if the types are not layout-compatible.
616
+ ARROW_EXPORT
617
+ Result<std::shared_ptr<ArrayData>> GetArrayView(const std::shared_ptr<ArrayData>& data,
618
+ const std::shared_ptr<DataType>& type);
619
+
620
+ } // namespace internal
621
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/diff.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <functional>
22
+ #include <iosfwd>
23
+ #include <memory>
24
+
25
+ #include "arrow/array/array_base.h"
26
+ #include "arrow/array/array_nested.h"
27
+ #include "arrow/result.h"
28
+ #include "arrow/status.h"
29
+ #include "arrow/type.h"
30
+ #include "arrow/util/visibility.h"
31
+
32
+ namespace arrow {
33
+
34
+ /// \brief Compare two arrays, returning an edit script which expresses the difference
35
+ /// between them
36
+ ///
37
+ /// An edit script is an array of struct(insert: bool, run_length: int64_t).
38
+ /// Each element of "insert" determines whether an element was inserted into (true)
39
+ /// or deleted from (false) base. Each insertion or deletion is followed by a run of
40
+ /// elements which are unchanged from base to target; the length of this run is stored
41
+ /// in "run_length". (Note that the edit script begins and ends with a run of shared
42
+ /// elements but both fields of the struct must have the same length. To accommodate this
43
+ /// the first element of "insert" should be ignored.)
44
+ ///
45
+ /// For example for base "hlloo" and target "hello", the edit script would be
46
+ /// [
47
+ /// {"insert": false, "run_length": 1}, // leading run of length 1 ("h")
48
+ /// {"insert": true, "run_length": 3}, // insert("e") then a run of length 3 ("llo")
49
+ /// {"insert": false, "run_length": 0} // delete("o") then an empty run
50
+ /// ]
51
+ ///
52
+ /// Diffing arrays containing nulls is not currently supported.
53
+ ///
54
+ /// \param[in] base baseline for comparison
55
+ /// \param[in] target an array of identical type to base whose elements differ from base's
56
+ /// \param[in] pool memory to store the result will be allocated from this memory pool
57
+ /// \return an edit script array which can be applied to base to produce target
58
+ ARROW_EXPORT
59
+ Result<std::shared_ptr<StructArray>> Diff(const Array& base, const Array& target,
60
+ MemoryPool* pool = default_memory_pool());
61
+
62
+ /// \brief visitor interface for easy traversal of an edit script
63
+ ///
64
+ /// visitor will be called for each hunk of insertions and deletions.
65
+ ARROW_EXPORT Status VisitEditScript(
66
+ const Array& edits,
67
+ const std::function<Status(int64_t delete_begin, int64_t delete_end,
68
+ int64_t insert_begin, int64_t insert_end)>& visitor);
69
+
70
+ /// \brief return a function which will format an edit script in unified
71
+ /// diff format to os, given base and target arrays of type
72
+ ARROW_EXPORT Result<
73
+ std::function<Status(const Array& edits, const Array& base, const Array& target)>>
74
+ MakeUnifiedDiffFormatter(const DataType& type, std::ostream* os);
75
+
76
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/util.h ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+ #include <vector>
23
+
24
+ #include "arrow/array/data.h"
25
+ #include "arrow/compare.h"
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+ #include "arrow/util/macros.h"
30
+ #include "arrow/util/visibility.h"
31
+
32
+ namespace arrow {
33
+
34
+ /// \brief Create a strongly-typed Array instance from generic ArrayData
35
+ /// \param[in] data the array contents
36
+ /// \return the resulting Array instance
37
+ ARROW_EXPORT
38
+ std::shared_ptr<Array> MakeArray(const std::shared_ptr<ArrayData>& data);
39
+
40
+ /// \brief Create a strongly-typed Array instance with all elements null
41
+ /// \param[in] type the array type
42
+ /// \param[in] length the array length
43
+ /// \param[in] pool the memory pool to allocate memory from
44
+ ARROW_EXPORT
45
+ Result<std::shared_ptr<Array>> MakeArrayOfNull(const std::shared_ptr<DataType>& type,
46
+ int64_t length,
47
+ MemoryPool* pool = default_memory_pool());
48
+
49
+ /// \brief Create an Array instance whose slots are the given scalar
50
+ /// \param[in] scalar the value with which to fill the array
51
+ /// \param[in] length the array length
52
+ /// \param[in] pool the memory pool to allocate memory from
53
+ ARROW_EXPORT
54
+ Result<std::shared_ptr<Array>> MakeArrayFromScalar(
55
+ const Scalar& scalar, int64_t length, MemoryPool* pool = default_memory_pool());
56
+
57
+ /// \brief Create an empty Array of a given type
58
+ ///
59
+ /// The output Array will be of the given type.
60
+ ///
61
+ /// \param[in] type the data type of the empty Array
62
+ /// \param[in] pool the memory pool to allocate memory from
63
+ /// \return the resulting Array
64
+ ARROW_EXPORT
65
+ Result<std::shared_ptr<Array>> MakeEmptyArray(std::shared_ptr<DataType> type,
66
+ MemoryPool* pool = default_memory_pool());
67
+
68
+ namespace internal {
69
+
70
+ /// \brief Swap endian of each element in a generic ArrayData
71
+ ///
72
+ /// As dictionaries are often shared between different arrays, dictionaries
73
+ /// are not swapped by this function and should be handled separately.
74
+ ///
75
+ /// \param[in] data the array contents
76
+ /// \param[in] pool the memory pool to allocate memory from
77
+ /// \return the resulting ArrayData whose elements were swapped
78
+ ARROW_EXPORT
79
+ Result<std::shared_ptr<ArrayData>> SwapEndianArrayData(
80
+ const std::shared_ptr<ArrayData>& data, MemoryPool* pool = default_memory_pool());
81
+
82
+ /// Given a number of ArrayVectors, treat each ArrayVector as the
83
+ /// chunks of a chunked array. Then rechunk each ArrayVector such that
84
+ /// all ArrayVectors are chunked identically. It is mandatory that
85
+ /// all ArrayVectors contain the same total number of elements.
86
+ ARROW_EXPORT
87
+ std::vector<ArrayVector> RechunkArraysConsistently(const std::vector<ArrayVector>&);
88
+
89
+ } // namespace internal
90
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/array/validate.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "arrow/status.h"
21
+ #include "arrow/type_fwd.h"
22
+ #include "arrow/util/visibility.h"
23
+
24
+ namespace arrow {
25
+ namespace internal {
26
+
27
+ // Internal functions implementing Array::Validate() and friends.
28
+
29
+ // O(1) array metadata validation
30
+
31
+ ARROW_EXPORT
32
+ Status ValidateArray(const Array& array);
33
+
34
+ ARROW_EXPORT
35
+ Status ValidateArray(const ArrayData& data);
36
+
37
+ // O(N) array data validation.
38
+ // Note that, starting from 7.0.0, "full" routines also validate metadata.
39
+ // Before, ValidateArray() needed to be called before ValidateArrayFull()
40
+ // to ensure metadata correctness, otherwise invalid memory accesses
41
+ // may occur.
42
+
43
+ ARROW_EXPORT
44
+ Status ValidateArrayFull(const Array& array);
45
+
46
+ ARROW_EXPORT
47
+ Status ValidateArrayFull(const ArrayData& data);
48
+
49
+ ARROW_EXPORT
50
+ Status ValidateUTF8(const Array& array);
51
+
52
+ ARROW_EXPORT
53
+ Status ValidateUTF8(const ArrayData& data);
54
+
55
+ } // namespace internal
56
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/flight/server.h ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Interfaces to use for defining Flight RPC servers. API should be considered
19
+ // experimental for now
20
+
21
+ #pragma once
22
+
23
+ #include <chrono>
24
+ #include <functional>
25
+ #include <memory>
26
+ #include <string>
27
+ #include <utility>
28
+ #include <vector>
29
+
30
+ #include "arrow/flight/server_auth.h"
31
+ #include "arrow/flight/type_fwd.h"
32
+ #include "arrow/flight/types.h" // IWYU pragma: keep
33
+ #include "arrow/flight/visibility.h" // IWYU pragma: keep
34
+ #include "arrow/ipc/dictionary.h"
35
+ #include "arrow/ipc/options.h"
36
+ #include "arrow/record_batch.h"
37
+
38
+ namespace arrow {
39
+
40
+ class Schema;
41
+ class Status;
42
+
43
+ namespace flight {
44
+
45
+ /// \brief Interface that produces a sequence of IPC payloads to be sent in
46
+ /// FlightData protobuf messages
47
+ class ARROW_FLIGHT_EXPORT FlightDataStream {
48
+ public:
49
+ virtual ~FlightDataStream();
50
+
51
+ virtual std::shared_ptr<Schema> schema() = 0;
52
+
53
+ /// \brief Compute FlightPayload containing serialized RecordBatch schema
54
+ virtual arrow::Result<FlightPayload> GetSchemaPayload() = 0;
55
+
56
+ // When the stream is completed, the last payload written will have null
57
+ // metadata
58
+ virtual arrow::Result<FlightPayload> Next() = 0;
59
+
60
+ virtual Status Close();
61
+ };
62
+
63
+ /// \brief A basic implementation of FlightDataStream that will provide
64
+ /// a sequence of FlightData messages to be written to a stream
65
+ class ARROW_FLIGHT_EXPORT RecordBatchStream : public FlightDataStream {
66
+ public:
67
+ /// \param[in] reader produces a sequence of record batches
68
+ /// \param[in] options IPC options for writing
69
+ explicit RecordBatchStream(
70
+ const std::shared_ptr<RecordBatchReader>& reader,
71
+ const ipc::IpcWriteOptions& options = ipc::IpcWriteOptions::Defaults());
72
+ ~RecordBatchStream() override;
73
+
74
+ // inherit deprecated API
75
+ using FlightDataStream::GetSchemaPayload;
76
+ using FlightDataStream::Next;
77
+
78
+ std::shared_ptr<Schema> schema() override;
79
+ arrow::Result<FlightPayload> GetSchemaPayload() override;
80
+
81
+ arrow::Result<FlightPayload> Next() override;
82
+ Status Close() override;
83
+
84
+ private:
85
+ class RecordBatchStreamImpl;
86
+ std::unique_ptr<RecordBatchStreamImpl> impl_;
87
+ };
88
+
89
+ /// \brief A reader for IPC payloads uploaded by a client. Also allows
90
+ /// reading application-defined metadata via the Flight protocol.
91
+ class ARROW_FLIGHT_EXPORT FlightMessageReader : public MetadataRecordBatchReader {
92
+ public:
93
+ /// \brief Get the descriptor for this upload.
94
+ virtual const FlightDescriptor& descriptor() const = 0;
95
+ };
96
+
97
+ /// \brief A writer for application-specific metadata sent back to the
98
+ /// client during an upload.
99
+ class ARROW_FLIGHT_EXPORT FlightMetadataWriter {
100
+ public:
101
+ virtual ~FlightMetadataWriter();
102
+ /// \brief Send a message to the client.
103
+ virtual Status WriteMetadata(const Buffer& app_metadata) = 0;
104
+ };
105
+
106
+ /// \brief A writer for IPC payloads to a client. Also allows sending
107
+ /// application-defined metadata via the Flight protocol.
108
+ ///
109
+ /// This class offers more control compared to FlightDataStream,
110
+ /// including the option to write metadata without data and the
111
+ /// ability to interleave reading and writing.
112
+ class ARROW_FLIGHT_EXPORT FlightMessageWriter : public MetadataRecordBatchWriter {
113
+ public:
114
+ virtual ~FlightMessageWriter() = default;
115
+ };
116
+
117
+ /// \brief Call state/contextual data.
118
+ class ARROW_FLIGHT_EXPORT ServerCallContext {
119
+ public:
120
+ virtual ~ServerCallContext() = default;
121
+ /// \brief The name of the authenticated peer (may be the empty string)
122
+ virtual const std::string& peer_identity() const = 0;
123
+ /// \brief The peer address (not validated)
124
+ virtual const std::string& peer() const = 0;
125
+ /// \brief Add a response header. This is only valid before the server
126
+ /// starts sending the response; generally this isn't an issue unless you
127
+ /// are implementing FlightDataStream, ResultStream, or similar interfaces
128
+ /// yourself, or during a DoExchange or DoPut.
129
+ virtual void AddHeader(const std::string& key, const std::string& value) const = 0;
130
+ /// \brief Add a response trailer. This is only valid before the server
131
+ /// sends the final status; generally this isn't an issue unless your RPC
132
+ /// handler launches a thread or similar.
133
+ virtual void AddTrailer(const std::string& key, const std::string& value) const = 0;
134
+ /// \brief Look up a middleware by key. Do not maintain a reference
135
+ /// to the object beyond the request body.
136
+ /// \return The middleware, or nullptr if not found.
137
+ virtual ServerMiddleware* GetMiddleware(const std::string& key) const = 0;
138
+ /// \brief Check if the current RPC has been cancelled (by the client, by
139
+ /// a network error, etc.).
140
+ virtual bool is_cancelled() const = 0;
141
+ /// \brief The headers sent by the client for this call.
142
+ virtual const CallHeaders& incoming_headers() const = 0;
143
+ };
144
+
145
+ class ARROW_FLIGHT_EXPORT FlightServerOptions {
146
+ public:
147
+ explicit FlightServerOptions(const Location& location_);
148
+
149
+ ~FlightServerOptions();
150
+
151
+ /// \brief The host & port (or domain socket path) to listen on.
152
+ /// Use port 0 to bind to an available port.
153
+ Location location;
154
+ /// \brief The authentication handler to use.
155
+ std::shared_ptr<ServerAuthHandler> auth_handler;
156
+ /// \brief A list of TLS certificate+key pairs to use.
157
+ std::vector<CertKeyPair> tls_certificates;
158
+ /// \brief Enable mTLS and require that the client present a certificate.
159
+ bool verify_client;
160
+ /// \brief If using mTLS, the PEM-encoded root certificate to use.
161
+ std::string root_certificates;
162
+ /// \brief A list of server middleware to apply, along with a key to
163
+ /// identify them by.
164
+ ///
165
+ /// Middleware are always applied in the order provided. Duplicate
166
+ /// keys are an error.
167
+ std::vector<std::pair<std::string, std::shared_ptr<ServerMiddlewareFactory>>>
168
+ middleware;
169
+
170
+ /// \brief An optional memory manager to control where to allocate incoming data.
171
+ std::shared_ptr<MemoryManager> memory_manager;
172
+
173
+ /// \brief A Flight implementation-specific callback to customize
174
+ /// transport-specific options.
175
+ ///
176
+ /// Not guaranteed to be called. The type of the parameter is
177
+ /// specific to the Flight implementation. Users should take care to
178
+ /// link to the same transport implementation as Flight to avoid
179
+ /// runtime problems. See "Using Arrow C++ in your own project" in
180
+ /// the documentation for more details.
181
+ std::function<void(void*)> builder_hook;
182
+ };
183
+
184
+ /// \brief Skeleton RPC server implementation which can be used to create
185
+ /// custom servers by implementing its abstract methods
186
+ class ARROW_FLIGHT_EXPORT FlightServerBase {
187
+ public:
188
+ FlightServerBase();
189
+ virtual ~FlightServerBase();
190
+
191
+ // Lifecycle methods.
192
+
193
+ /// \brief Initialize a Flight server listening at the given location.
194
+ /// This method must be called before any other method.
195
+ /// \param[in] options The configuration for this server.
196
+ Status Init(const FlightServerOptions& options);
197
+
198
+ /// \brief Get the port that the Flight server is listening on.
199
+ /// This method must only be called after Init(). Will return a
200
+ /// non-positive value if no port exists (e.g. when listening on a
201
+ /// domain socket).
202
+ int port() const;
203
+
204
+ /// \brief Get the address that the Flight server is listening on.
205
+ /// This method must only be called after Init().
206
+ Location location() const;
207
+
208
+ /// \brief Set the server to stop when receiving any of the given signal
209
+ /// numbers.
210
+ /// This method must be called before Serve().
211
+ Status SetShutdownOnSignals(const std::vector<int> sigs);
212
+
213
+ /// \brief Start serving.
214
+ /// This method blocks until the server shuts down.
215
+ ///
216
+ /// The server will start to shut down when either Shutdown() is called
217
+ /// or one of the signals registered in SetShutdownOnSignals() is received.
218
+ Status Serve();
219
+
220
+ /// \brief Query whether Serve() was interrupted by a signal.
221
+ /// This method must be called after Serve() has returned.
222
+ ///
223
+ /// \return int the signal number that interrupted Serve(), if any, otherwise 0
224
+ int GotSignal() const;
225
+
226
+ /// \brief Shut down the server, blocking until current requests finish.
227
+ ///
228
+ /// Can be called from a signal handler or another thread while Serve()
229
+ /// blocks. Optionally a deadline can be set. Once the deadline expires
230
+ /// server will wait until remaining running calls complete.
231
+ ///
232
+ /// Should only be called once.
233
+ Status Shutdown(const std::chrono::system_clock::time_point* deadline = NULLPTR);
234
+
235
+ /// \brief Block until server shuts down with Shutdown.
236
+ ///
237
+ /// Does not respond to signals like Serve().
238
+ Status Wait();
239
+
240
+ // Implement these methods to create your own server. The default
241
+ // implementations will return a not-implemented result to the client
242
+
243
+ /// \brief Retrieve a list of available fields given an optional opaque
244
+ /// criteria
245
+ /// \param[in] context The call context.
246
+ /// \param[in] criteria may be null
247
+ /// \param[out] listings the returned listings iterator
248
+ /// \return Status
249
+ virtual Status ListFlights(const ServerCallContext& context, const Criteria* criteria,
250
+ std::unique_ptr<FlightListing>* listings);
251
+
252
+ /// \brief Retrieve the schema and an access plan for the indicated
253
+ /// descriptor
254
+ /// \param[in] context The call context.
255
+ /// \param[in] request the dataset request, whether a named dataset or command
256
+ /// \param[out] info the returned flight info provider
257
+ /// \return Status
258
+ virtual Status GetFlightInfo(const ServerCallContext& context,
259
+ const FlightDescriptor& request,
260
+ std::unique_ptr<FlightInfo>* info);
261
+
262
+ /// \brief Retrieve the current status of the target query
263
+ /// \param[in] context The call context.
264
+ /// \param[in] request the dataset request or a descriptor returned by a
265
+ /// prior PollFlightInfo call
266
+ /// \param[out] info the returned retry info provider
267
+ /// \return Status
268
+ virtual Status PollFlightInfo(const ServerCallContext& context,
269
+ const FlightDescriptor& request,
270
+ std::unique_ptr<PollInfo>* info);
271
+
272
+ /// \brief Retrieve the schema for the indicated descriptor
273
+ /// \param[in] context The call context.
274
+ /// \param[in] request the dataset request, whether a named dataset or command
275
+ /// \param[out] schema the returned flight schema provider
276
+ /// \return Status
277
+ virtual Status GetSchema(const ServerCallContext& context,
278
+ const FlightDescriptor& request,
279
+ std::unique_ptr<SchemaResult>* schema);
280
+
281
+ /// \brief Get a stream of IPC payloads to put on the wire
282
+ /// \param[in] context The call context.
283
+ /// \param[in] request an opaque ticket
284
+ /// \param[out] stream the returned stream provider
285
+ /// \return Status
286
+ virtual Status DoGet(const ServerCallContext& context, const Ticket& request,
287
+ std::unique_ptr<FlightDataStream>* stream);
288
+
289
+ /// \brief Process a stream of IPC payloads sent from a client
290
+ /// \param[in] context The call context.
291
+ /// \param[in] reader a sequence of uploaded record batches
292
+ /// \param[in] writer send metadata back to the client
293
+ /// \return Status
294
+ virtual Status DoPut(const ServerCallContext& context,
295
+ std::unique_ptr<FlightMessageReader> reader,
296
+ std::unique_ptr<FlightMetadataWriter> writer);
297
+
298
+ /// \brief Process a bidirectional stream of IPC payloads
299
+ /// \param[in] context The call context.
300
+ /// \param[in] reader a sequence of uploaded record batches
301
+ /// \param[in] writer send data back to the client
302
+ /// \return Status
303
+ virtual Status DoExchange(const ServerCallContext& context,
304
+ std::unique_ptr<FlightMessageReader> reader,
305
+ std::unique_ptr<FlightMessageWriter> writer);
306
+
307
+ /// \brief Execute an action, return stream of zero or more results
308
+ /// \param[in] context The call context.
309
+ /// \param[in] action the action to execute, with type and body
310
+ /// \param[out] result the result iterator
311
+ /// \return Status
312
+ virtual Status DoAction(const ServerCallContext& context, const Action& action,
313
+ std::unique_ptr<ResultStream>* result);
314
+
315
+ /// \brief Retrieve the list of available actions
316
+ /// \param[in] context The call context.
317
+ /// \param[out] actions a vector of available action types
318
+ /// \return Status
319
+ virtual Status ListActions(const ServerCallContext& context,
320
+ std::vector<ActionType>* actions);
321
+
322
+ private:
323
+ struct Impl;
324
+ std::unique_ptr<Impl> impl_;
325
+ };
326
+
327
+ } // namespace flight
328
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/flight/test_util.h ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <gmock/gmock.h>
21
+ #include <gtest/gtest.h>
22
+
23
+ #include <cstdint>
24
+ #include <memory>
25
+ #include <string>
26
+ #include <thread>
27
+ #include <utility>
28
+ #include <vector>
29
+
30
+ #include "arrow/status.h"
31
+ #include "arrow/testing/gtest_util.h"
32
+ #include "arrow/testing/util.h"
33
+
34
+ #include "arrow/flight/client.h"
35
+ #include "arrow/flight/client_auth.h"
36
+ #include "arrow/flight/server.h"
37
+ #include "arrow/flight/server_auth.h"
38
+ #include "arrow/flight/types.h"
39
+ #include "arrow/flight/visibility.h"
40
+
41
+ namespace boost {
42
+ namespace process {
43
+
44
+ class child;
45
+
46
+ } // namespace process
47
+ } // namespace boost
48
+
49
+ namespace arrow {
50
+ namespace flight {
51
+
52
+ // ----------------------------------------------------------------------
53
+ // Helpers to compare values for equality
54
+
55
+ inline void AssertEqual(const FlightInfo& expected, const FlightInfo& actual) {
56
+ ipc::DictionaryMemo expected_memo;
57
+ ipc::DictionaryMemo actual_memo;
58
+ ASSERT_OK_AND_ASSIGN(auto ex_schema, expected.GetSchema(&expected_memo));
59
+ ASSERT_OK_AND_ASSIGN(auto actual_schema, actual.GetSchema(&actual_memo));
60
+
61
+ AssertSchemaEqual(*ex_schema, *actual_schema);
62
+ ASSERT_EQ(expected.total_records(), actual.total_records());
63
+ ASSERT_EQ(expected.total_bytes(), actual.total_bytes());
64
+
65
+ ASSERT_EQ(expected.descriptor(), actual.descriptor());
66
+ ASSERT_THAT(actual.endpoints(), ::testing::ContainerEq(expected.endpoints()));
67
+ }
68
+
69
+ // ----------------------------------------------------------------------
70
+ // Fixture to use for running test servers
71
+
72
+ class ARROW_FLIGHT_EXPORT TestServer {
73
+ public:
74
+ explicit TestServer(const std::string& executable_name)
75
+ : executable_name_(executable_name), port_(::arrow::GetListenPort()) {}
76
+ TestServer(const std::string& executable_name, int port)
77
+ : executable_name_(executable_name), port_(port) {}
78
+ TestServer(const std::string& executable_name, const std::string& unix_sock)
79
+ : executable_name_(executable_name), unix_sock_(unix_sock) {}
80
+
81
+ void Start(const std::vector<std::string>& extra_args);
82
+ void Start() { Start({}); }
83
+
84
+ int Stop();
85
+
86
+ bool IsRunning();
87
+
88
+ int port() const;
89
+ const std::string& unix_sock() const;
90
+
91
+ private:
92
+ std::string executable_name_;
93
+ int port_;
94
+ std::string unix_sock_;
95
+ std::shared_ptr<::boost::process::child> server_process_;
96
+ };
97
+
98
+ /// \brief Create a simple Flight server for testing
99
+ ARROW_FLIGHT_EXPORT
100
+ std::unique_ptr<FlightServerBase> ExampleTestServer();
101
+
102
+ // Helper to initialize a server and matching client with callbacks to
103
+ // populate options.
104
+ template <typename T, typename... Args>
105
+ Status MakeServer(const Location& location, std::unique_ptr<FlightServerBase>* server,
106
+ std::unique_ptr<FlightClient>* client,
107
+ std::function<Status(FlightServerOptions*)> make_server_options,
108
+ std::function<Status(FlightClientOptions*)> make_client_options,
109
+ Args&&... server_args) {
110
+ *server = std::make_unique<T>(std::forward<Args>(server_args)...);
111
+ FlightServerOptions server_options(location);
112
+ RETURN_NOT_OK(make_server_options(&server_options));
113
+ RETURN_NOT_OK((*server)->Init(server_options));
114
+ std::string uri =
115
+ location.scheme() + "://127.0.0.1:" + std::to_string((*server)->port());
116
+ ARROW_ASSIGN_OR_RAISE(auto real_location, Location::Parse(uri));
117
+ FlightClientOptions client_options = FlightClientOptions::Defaults();
118
+ RETURN_NOT_OK(make_client_options(&client_options));
119
+ return FlightClient::Connect(real_location, client_options).Value(client);
120
+ }
121
+
122
+ // Helper to initialize a server and matching client with callbacks to
123
+ // populate options.
124
+ template <typename T, typename... Args>
125
+ Status MakeServer(std::unique_ptr<FlightServerBase>* server,
126
+ std::unique_ptr<FlightClient>* client,
127
+ std::function<Status(FlightServerOptions*)> make_server_options,
128
+ std::function<Status(FlightClientOptions*)> make_client_options,
129
+ Args&&... server_args) {
130
+ ARROW_ASSIGN_OR_RAISE(auto location, Location::ForGrpcTcp("localhost", 0));
131
+ return MakeServer<T>(location, server, client, std::move(make_server_options),
132
+ std::move(make_client_options),
133
+ std::forward<Args>(server_args)...);
134
+ }
135
+
136
+ // ----------------------------------------------------------------------
137
+ // A FlightDataStream that numbers the record batches
138
+ /// \brief A basic implementation of FlightDataStream that will provide
139
+ /// a sequence of FlightData messages to be written to a stream
140
+ class ARROW_FLIGHT_EXPORT NumberingStream : public FlightDataStream {
141
+ public:
142
+ explicit NumberingStream(std::unique_ptr<FlightDataStream> stream);
143
+
144
+ std::shared_ptr<Schema> schema() override;
145
+ arrow::Result<FlightPayload> GetSchemaPayload() override;
146
+ arrow::Result<FlightPayload> Next() override;
147
+
148
+ private:
149
+ int counter_;
150
+ std::shared_ptr<FlightDataStream> stream_;
151
+ };
152
+
153
+ // ----------------------------------------------------------------------
154
+ // Example data for test-server and unit tests
155
+
156
+ ARROW_FLIGHT_EXPORT
157
+ std::shared_ptr<Schema> ExampleIntSchema();
158
+
159
+ ARROW_FLIGHT_EXPORT
160
+ std::shared_ptr<Schema> ExampleStringSchema();
161
+
162
+ ARROW_FLIGHT_EXPORT
163
+ std::shared_ptr<Schema> ExampleDictSchema();
164
+
165
+ ARROW_FLIGHT_EXPORT
166
+ std::shared_ptr<Schema> ExampleLargeSchema();
167
+
168
+ ARROW_FLIGHT_EXPORT
169
+ Status ExampleIntBatches(RecordBatchVector* out);
170
+
171
+ ARROW_FLIGHT_EXPORT
172
+ Status ExampleFloatBatches(RecordBatchVector* out);
173
+
174
+ ARROW_FLIGHT_EXPORT
175
+ Status ExampleDictBatches(RecordBatchVector* out);
176
+
177
+ ARROW_FLIGHT_EXPORT
178
+ Status ExampleNestedBatches(RecordBatchVector* out);
179
+
180
+ ARROW_FLIGHT_EXPORT
181
+ Status ExampleLargeBatches(RecordBatchVector* out);
182
+
183
+ ARROW_FLIGHT_EXPORT
184
+ arrow::Result<std::shared_ptr<RecordBatch>> VeryLargeBatch();
185
+
186
+ ARROW_FLIGHT_EXPORT
187
+ std::vector<FlightInfo> ExampleFlightInfo();
188
+
189
+ ARROW_FLIGHT_EXPORT
190
+ std::vector<ActionType> ExampleActionTypes();
191
+
192
+ ARROW_FLIGHT_EXPORT
193
+ FlightInfo MakeFlightInfo(const Schema& schema, const FlightDescriptor& descriptor,
194
+ const std::vector<FlightEndpoint>& endpoints,
195
+ int64_t total_records, int64_t total_bytes, bool ordered,
196
+ std::string app_metadata);
197
+
198
+ // ----------------------------------------------------------------------
199
+ // A pair of authentication handlers that check for a predefined password
200
+ // and set the peer identity to a predefined username.
201
+
202
+ class ARROW_FLIGHT_EXPORT TestServerAuthHandler : public ServerAuthHandler {
203
+ public:
204
+ explicit TestServerAuthHandler(const std::string& username,
205
+ const std::string& password);
206
+ ~TestServerAuthHandler() override;
207
+ Status Authenticate(const ServerCallContext& context, ServerAuthSender* outgoing,
208
+ ServerAuthReader* incoming) override;
209
+ Status IsValid(const ServerCallContext& context, const std::string& token,
210
+ std::string* peer_identity) override;
211
+
212
+ private:
213
+ std::string username_;
214
+ std::string password_;
215
+ };
216
+
217
+ class ARROW_FLIGHT_EXPORT TestServerBasicAuthHandler : public ServerAuthHandler {
218
+ public:
219
+ explicit TestServerBasicAuthHandler(const std::string& username,
220
+ const std::string& password);
221
+ ~TestServerBasicAuthHandler() override;
222
+ Status Authenticate(const ServerCallContext& context, ServerAuthSender* outgoing,
223
+ ServerAuthReader* incoming) override;
224
+ Status IsValid(const ServerCallContext& context, const std::string& token,
225
+ std::string* peer_identity) override;
226
+
227
+ private:
228
+ BasicAuth basic_auth_;
229
+ };
230
+
231
+ class ARROW_FLIGHT_EXPORT TestClientAuthHandler : public ClientAuthHandler {
232
+ public:
233
+ explicit TestClientAuthHandler(const std::string& username,
234
+ const std::string& password);
235
+ ~TestClientAuthHandler() override;
236
+ Status Authenticate(ClientAuthSender* outgoing, ClientAuthReader* incoming) override;
237
+ Status GetToken(std::string* token) override;
238
+
239
+ private:
240
+ std::string username_;
241
+ std::string password_;
242
+ };
243
+
244
+ class ARROW_FLIGHT_EXPORT TestClientBasicAuthHandler : public ClientAuthHandler {
245
+ public:
246
+ explicit TestClientBasicAuthHandler(const std::string& username,
247
+ const std::string& password);
248
+ ~TestClientBasicAuthHandler() override;
249
+ Status Authenticate(ClientAuthSender* outgoing, ClientAuthReader* incoming) override;
250
+ Status GetToken(std::string* token) override;
251
+
252
+ private:
253
+ BasicAuth basic_auth_;
254
+ std::string token_;
255
+ };
256
+
257
+ ARROW_FLIGHT_EXPORT
258
+ Status ExampleTlsCertificates(std::vector<CertKeyPair>* out);
259
+
260
+ ARROW_FLIGHT_EXPORT
261
+ Status ExampleTlsCertificateRoot(CertKeyPair* out);
262
+
263
+ } // namespace flight
264
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/flight/transport.h ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ /// \file
19
+ /// Internal (but not private) interface for implementing
20
+ /// alternate network transports in Flight.
21
+ ///
22
+ /// \warning EXPERIMENTAL. Subject to change.
23
+ ///
24
+ /// To implement a transport, implement ServerTransport and
25
+ /// ClientTransport, and register the desired URI schemes with
26
+ /// TransportRegistry. Flight takes care of most of the per-RPC
27
+ /// details; transports only handle connections and providing a I/O
28
+ /// stream implementation (TransportDataStream).
29
+ ///
30
+ /// On the server side:
31
+ ///
32
+ /// 1. Applications subclass FlightServerBase and override RPC handlers.
33
+ /// 2. FlightServerBase::Init will look up and create a ServerTransport
34
+ /// based on the scheme of the Location given to it.
35
+ /// 3. The ServerTransport will start the actual server. (For instance,
36
+ /// for gRPC, it creates a gRPC server and registers a gRPC service.)
37
+ /// That server will handle connections.
38
+ /// 4. The transport should forward incoming calls to the server to the RPC
39
+ /// handlers defined on ServerTransport, which implements the actual
40
+ /// RPC handler using the interfaces here. Any I/O the RPC handler needs
41
+ /// to do is managed by transport-specific implementations of
42
+ /// TransportDataStream.
43
+ /// 5. ServerTransport calls FlightServerBase for the actual application
44
+ /// logic.
45
+ ///
46
+ /// On the client side:
47
+ ///
48
+ /// 1. Applications create a FlightClient with a Location.
49
+ /// 2. FlightClient will look up and create a ClientTransport based on
50
+ /// the scheme of the Location given to it.
51
+ /// 3. When calling a method on FlightClient, FlightClient will delegate to
52
+ /// the ClientTransport. There is some indirection, e.g. for DoGet,
53
+ /// FlightClient only requests that the ClientTransport start the
54
+ /// call and provide it with an I/O stream. The "Flight implementation"
55
+ /// itself still lives in FlightClient.
56
+
57
+ #pragma once
58
+
59
+ #include <functional>
60
+ #include <memory>
61
+ #include <optional>
62
+ #include <string>
63
+ #include <utility>
64
+ #include <vector>
65
+
66
+ #include "arrow/flight/type_fwd.h"
67
+ #include "arrow/flight/types.h"
68
+ #include "arrow/flight/visibility.h"
69
+ #include "arrow/ipc/options.h"
70
+ #include "arrow/type_fwd.h"
71
+
72
+ namespace arrow {
73
+ namespace ipc {
74
+ class Message;
75
+ }
76
+ namespace flight {
77
+ class FlightStatusDetail;
78
+ namespace internal {
79
+
80
+ /// Internal, not user-visible type used for memory-efficient reads
81
+ struct FlightData {
82
+ /// Used only for puts, may be null
83
+ std::unique_ptr<FlightDescriptor> descriptor;
84
+
85
+ /// Non-length-prefixed Message header as described in format/Message.fbs
86
+ std::shared_ptr<Buffer> metadata;
87
+
88
+ /// Application-defined metadata
89
+ std::shared_ptr<Buffer> app_metadata;
90
+
91
+ /// Message body
92
+ std::shared_ptr<Buffer> body;
93
+
94
+ /// Open IPC message from the metadata and body
95
+ ::arrow::Result<std::unique_ptr<ipc::Message>> OpenMessage();
96
+ };
97
+
98
+ /// \brief A transport-specific interface for reading/writing Arrow data.
99
+ ///
100
+ /// New transports will implement this to read/write IPC payloads to
101
+ /// the underlying stream.
102
+ class ARROW_FLIGHT_EXPORT TransportDataStream {
103
+ public:
104
+ virtual ~TransportDataStream() = default;
105
+ /// \brief Attempt to read the next FlightData message.
106
+ ///
107
+ /// \return success true if data was populated, false if there was
108
+ /// an error. For clients, the error can be retrieved from
109
+ /// Finish(Status).
110
+ virtual bool ReadData(FlightData* data);
111
+ /// \brief Attempt to write a FlightPayload.
112
+ ///
113
+ /// \param[in] payload The data to write.
114
+ /// \return true if the message was accepted by the transport, false
115
+ /// if not (e.g. due to client/server disconnect), Status if there
116
+ /// was an error (e.g. with the payload itself).
117
+ virtual arrow::Result<bool> WriteData(const FlightPayload& payload);
118
+ /// \brief Indicate that there are no more writes on this stream.
119
+ ///
120
+ /// This is only a hint for the underlying transport and may not
121
+ /// actually do anything.
122
+ virtual Status WritesDone();
123
+ };
124
+
125
+ /// \brief A transport-specific interface for reading/writing Arrow
126
+ /// data for a client.
127
+ class ARROW_FLIGHT_EXPORT ClientDataStream : public TransportDataStream {
128
+ public:
129
+ /// \brief Attempt to read a non-data message.
130
+ ///
131
+ /// Only implemented for DoPut; mutually exclusive with
132
+ /// ReadData(FlightData*).
133
+ virtual bool ReadPutMetadata(std::shared_ptr<Buffer>* out);
134
+ /// \brief Attempt to cancel the call.
135
+ ///
136
+ /// This is only a hint and may not take effect immediately. The
137
+ /// client should still finish the call with Finish(Status) as usual.
138
+ virtual void TryCancel() {}
139
+ /// \brief Finish the call, reporting the server-sent status and/or
140
+ /// any client-side errors as appropriate.
141
+ ///
142
+ /// Implies WritesDone() and DoFinish().
143
+ ///
144
+ /// \param[in] st A client-side status to combine with the
145
+ /// server-side error. That is, if an error occurs on the
146
+ /// client-side, call Finish(Status) to finish the server-side
147
+ /// call, get the server-side status, and merge the statuses
148
+ /// together so context is not lost.
149
+ Status Finish(Status st);
150
+
151
+ protected:
152
+ /// \brief End the call, returning the final server status.
153
+ ///
154
+ /// For implementors: should imply WritesDone() (even if it does not
155
+ /// directly call it).
156
+ ///
157
+ /// Implies WritesDone().
158
+ virtual Status DoFinish() = 0;
159
+ };
160
+
161
+ /// An implementation of a Flight client for a particular transport.
162
+ ///
163
+ /// Transports should override the methods they are capable of
164
+ /// supporting. The default method implementations return an error.
165
+ class ARROW_FLIGHT_EXPORT ClientTransport {
166
+ public:
167
+ virtual ~ClientTransport() = default;
168
+
169
+ /// Initialize the client.
170
+ virtual Status Init(const FlightClientOptions& options, const Location& location,
171
+ const arrow::internal::Uri& uri) = 0;
172
+ /// Close the client. Once this returns, the client is no longer usable.
173
+ virtual Status Close() = 0;
174
+
175
+ virtual Status Authenticate(const FlightCallOptions& options,
176
+ std::unique_ptr<ClientAuthHandler> auth_handler);
177
+ virtual arrow::Result<std::pair<std::string, std::string>> AuthenticateBasicToken(
178
+ const FlightCallOptions& options, const std::string& username,
179
+ const std::string& password);
180
+ virtual Status DoAction(const FlightCallOptions& options, const Action& action,
181
+ std::unique_ptr<ResultStream>* results);
182
+ virtual Status ListActions(const FlightCallOptions& options,
183
+ std::vector<ActionType>* actions);
184
+ virtual Status GetFlightInfo(const FlightCallOptions& options,
185
+ const FlightDescriptor& descriptor,
186
+ std::unique_ptr<FlightInfo>* info);
187
+ virtual void GetFlightInfoAsync(const FlightCallOptions& options,
188
+ const FlightDescriptor& descriptor,
189
+ std::shared_ptr<AsyncListener<FlightInfo>> listener);
190
+ virtual Status PollFlightInfo(const FlightCallOptions& options,
191
+ const FlightDescriptor& descriptor,
192
+ std::unique_ptr<PollInfo>* info);
193
+ virtual arrow::Result<std::unique_ptr<SchemaResult>> GetSchema(
194
+ const FlightCallOptions& options, const FlightDescriptor& descriptor);
195
+ virtual Status ListFlights(const FlightCallOptions& options, const Criteria& criteria,
196
+ std::unique_ptr<FlightListing>* listing);
197
+ virtual Status DoGet(const FlightCallOptions& options, const Ticket& ticket,
198
+ std::unique_ptr<ClientDataStream>* stream);
199
+ virtual Status DoPut(const FlightCallOptions& options,
200
+ std::unique_ptr<ClientDataStream>* stream);
201
+ virtual Status DoExchange(const FlightCallOptions& options,
202
+ std::unique_ptr<ClientDataStream>* stream);
203
+
204
+ bool supports_async() const { return CheckAsyncSupport().ok(); }
205
+ virtual Status CheckAsyncSupport() const {
206
+ return Status::NotImplemented(
207
+ "this Flight transport does not support async operations");
208
+ }
209
+
210
+ static void SetAsyncRpc(AsyncListenerBase* listener, std::unique_ptr<AsyncRpc>&& rpc);
211
+ static AsyncRpc* GetAsyncRpc(AsyncListenerBase* listener);
212
+ static std::unique_ptr<AsyncRpc> ReleaseAsyncRpc(AsyncListenerBase* listener);
213
+ };
214
+
215
+ /// A registry of transport implementations.
216
+ class ARROW_FLIGHT_EXPORT TransportRegistry {
217
+ public:
218
+ using ClientFactory = std::function<arrow::Result<std::unique_ptr<ClientTransport>>()>;
219
+ using ServerFactory = std::function<arrow::Result<std::unique_ptr<ServerTransport>>(
220
+ FlightServerBase*, std::shared_ptr<MemoryManager> memory_manager)>;
221
+
222
+ TransportRegistry();
223
+ ~TransportRegistry();
224
+
225
+ arrow::Result<std::unique_ptr<ClientTransport>> MakeClient(
226
+ const std::string& scheme) const;
227
+ arrow::Result<std::unique_ptr<ServerTransport>> MakeServer(
228
+ const std::string& scheme, FlightServerBase* base,
229
+ std::shared_ptr<MemoryManager> memory_manager) const;
230
+
231
+ Status RegisterClient(const std::string& scheme, ClientFactory factory);
232
+ Status RegisterServer(const std::string& scheme, ServerFactory factory);
233
+
234
+ private:
235
+ class Impl;
236
+ std::unique_ptr<Impl> impl_;
237
+ };
238
+
239
+ /// \brief Get the registry of transport implementations.
240
+ ARROW_FLIGHT_EXPORT
241
+ TransportRegistry* GetDefaultTransportRegistry();
242
+
243
+ //------------------------------------------------------------
244
+ // Async APIs
245
+
246
+ /// \brief Transport-specific state for an async RPC.
247
+ ///
248
+ /// Transport implementations may subclass this to store their own
249
+ /// state, and stash an instance in a user-supplied AsyncListener via
250
+ /// ClientTransport::GetAsyncRpc and ClientTransport::SetAsyncRpc.
251
+ ///
252
+ /// This API is EXPERIMENTAL.
253
+ class ARROW_FLIGHT_EXPORT AsyncRpc {
254
+ public:
255
+ virtual ~AsyncRpc() = default;
256
+ /// \brief Request cancellation of the RPC.
257
+ virtual void TryCancel() {}
258
+
259
+ /// Only needed for DoPut/DoExchange
260
+ virtual void Begin(const FlightDescriptor& descriptor, std::shared_ptr<Schema> schema) {
261
+ }
262
+ /// Only needed for DoPut/DoExchange
263
+ virtual void Write(arrow::flight::FlightStreamChunk chunk) {}
264
+ /// Only needed for DoPut/DoExchange
265
+ virtual void DoneWriting() {}
266
+ };
267
+
268
+ //------------------------------------------------------------
269
+ // Error propagation helpers
270
+
271
+ /// \brief Abstract error status.
272
+ ///
273
+ /// Transport implementations may use side channels (e.g. HTTP
274
+ /// trailers) to convey additional information to reconstruct the
275
+ /// original C++ status for implementations that can use it.
276
+ struct ARROW_FLIGHT_EXPORT TransportStatus {
277
+ TransportStatusCode code;
278
+ std::string message;
279
+
280
+ /// \brief Convert a C++ status to an abstract transport status.
281
+ static TransportStatus FromStatus(const Status& arrow_status);
282
+
283
+ /// \brief Reconstruct a string-encoded TransportStatus.
284
+ static TransportStatus FromCodeStringAndMessage(const std::string& code_str,
285
+ std::string message);
286
+
287
+ /// \brief Convert an abstract transport status to a C++ status.
288
+ Status ToStatus() const;
289
+ };
290
+
291
+ /// \brief Convert the string representation of an Arrow status code
292
+ /// back to an Arrow status.
293
+ ARROW_FLIGHT_EXPORT
294
+ Status ReconstructStatus(const std::string& code_str, const Status& current_status,
295
+ std::optional<std::string> message,
296
+ std::optional<std::string> detail_message,
297
+ std::optional<std::string> detail_bin,
298
+ std::shared_ptr<FlightStatusDetail> detail);
299
+
300
+ } // namespace internal
301
+ } // namespace flight
302
+ } // namespace arrow
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "parquet/exception.h"
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ // Column reader API
21
+ #include "parquet/column_reader.h"
22
+ #include "parquet/column_scanner.h"
23
+ #include "parquet/exception.h"
24
+ #include "parquet/file_reader.h"
25
+ #include "parquet/metadata.h"
26
+ #include "parquet/platform.h"
27
+ #include "parquet/printer.h"
28
+ #include "parquet/properties.h"
29
+ #include "parquet/statistics.h"
30
+
31
+ // Schemas
32
+ #include "parquet/api/schema.h"
33
+
34
+ // IO
35
+ #include "parquet/api/io.h"
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ // Schemas
21
+ #include "parquet/schema.h"
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "parquet/api/io.h"
21
+ #include "parquet/api/schema.h"
22
+ #include "parquet/column_writer.h"
23
+ #include "parquet/exception.h"
24
+ #include "parquet/file_writer.h"
25
+ #include "parquet/statistics.h"
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.h ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ // N.B. we don't include async_generator.h as it's relatively heavy
22
+ #include <functional>
23
+ #include <memory>
24
+ #include <vector>
25
+
26
+ #include "parquet/file_reader.h"
27
+ #include "parquet/platform.h"
28
+ #include "parquet/properties.h"
29
+
30
+ namespace arrow {
31
+
32
+ class ChunkedArray;
33
+ class KeyValueMetadata;
34
+ class RecordBatchReader;
35
+ struct Scalar;
36
+ class Schema;
37
+ class Table;
38
+ class RecordBatch;
39
+
40
+ } // namespace arrow
41
+
42
+ namespace parquet {
43
+
44
+ class FileMetaData;
45
+ class SchemaDescriptor;
46
+
47
+ namespace arrow {
48
+
49
+ class ColumnChunkReader;
50
+ class ColumnReader;
51
+ struct SchemaManifest;
52
+ class RowGroupReader;
53
+
54
+ /// \brief Arrow read adapter class for deserializing Parquet files as Arrow row batches.
55
+ ///
56
+ /// This interfaces caters for different use cases and thus provides different
57
+ /// interfaces. In its most simplistic form, we cater for a user that wants to
58
+ /// read the whole Parquet at once with the `FileReader::ReadTable` method.
59
+ ///
60
+ /// More advanced users that also want to implement parallelism on top of each
61
+ /// single Parquet files should do this on the RowGroup level. For this, they can
62
+ /// call `FileReader::RowGroup(i)->ReadTable` to receive only the specified
63
+ /// RowGroup as a table.
64
+ ///
65
+ /// In the most advanced situation, where a consumer wants to independently read
66
+ /// RowGroups in parallel and consume each column individually, they can call
67
+ /// `FileReader::RowGroup(i)->Column(j)->Read` and receive an `arrow::Column`
68
+ /// instance.
69
+ ///
70
+ /// Finally, one can also get a stream of record batches using
71
+ /// `FileReader::GetRecordBatchReader()`. This can internally decode columns
72
+ /// in parallel if use_threads was enabled in the ArrowReaderProperties.
73
+ ///
74
+ /// The parquet format supports an optional integer field_id which can be assigned
75
+ /// to a field. Arrow will convert these field IDs to a metadata key named
76
+ /// PARQUET:field_id on the appropriate field.
77
+ // TODO(wesm): nested data does not always make sense with this user
78
+ // interface unless you are only reading a single leaf node from a branch of
79
+ // a table. For example:
80
+ //
81
+ // repeated group data {
82
+ // optional group record {
83
+ // optional int32 val1;
84
+ // optional byte_array val2;
85
+ // optional bool val3;
86
+ // }
87
+ // optional int32 val4;
88
+ // }
89
+ //
90
+ // In the Parquet file, there are 4 leaf nodes:
91
+ //
92
+ // * data.record.val1
93
+ // * data.record.val2
94
+ // * data.record.val3
95
+ // * data.val4
96
+ //
97
+ // When materializing this data in an Arrow array, we would have:
98
+ //
99
+ // data: list<struct<
100
+ // record: struct<
101
+ // val1: int32,
102
+ // val2: string (= list<uint8>),
103
+ // val3: bool,
104
+ // >,
105
+ // val4: int32
106
+ // >>
107
+ //
108
+ // However, in the Parquet format, each leaf node has its own repetition and
109
+ // definition levels describing the structure of the intermediate nodes in
110
+ // this array structure. Thus, we will need to scan the leaf data for a group
111
+ // of leaf nodes part of the same type tree to create a single result Arrow
112
+ // nested array structure.
113
+ //
114
+ // This is additionally complicated "chunky" repeated fields or very large byte
115
+ // arrays
116
+ class PARQUET_EXPORT FileReader {
117
+ public:
118
+ /// Factory function to create a FileReader from a ParquetFileReader and properties
119
+ static ::arrow::Status Make(::arrow::MemoryPool* pool,
120
+ std::unique_ptr<ParquetFileReader> reader,
121
+ const ArrowReaderProperties& properties,
122
+ std::unique_ptr<FileReader>* out);
123
+
124
+ /// Factory function to create a FileReader from a ParquetFileReader
125
+ static ::arrow::Status Make(::arrow::MemoryPool* pool,
126
+ std::unique_ptr<ParquetFileReader> reader,
127
+ std::unique_ptr<FileReader>* out);
128
+
129
+ // Since the distribution of columns amongst a Parquet file's row groups may
130
+ // be uneven (the number of values in each column chunk can be different), we
131
+ // provide a column-oriented read interface. The ColumnReader hides the
132
+ // details of paging through the file's row groups and yielding
133
+ // fully-materialized arrow::Array instances
134
+ //
135
+ // Returns error status if the column of interest is not flat.
136
+ // The indicated column index is relative to the schema
137
+ virtual ::arrow::Status GetColumn(int i, std::unique_ptr<ColumnReader>* out) = 0;
138
+
139
+ /// \brief Return arrow schema for all the columns.
140
+ virtual ::arrow::Status GetSchema(std::shared_ptr<::arrow::Schema>* out) = 0;
141
+
142
+ /// \brief Read column as a whole into a chunked array.
143
+ ///
144
+ /// The index i refers the index of the top level schema field, which may
145
+ /// be nested or flat - e.g.
146
+ ///
147
+ /// 0 foo.bar
148
+ /// foo.bar.baz
149
+ /// foo.qux
150
+ /// 1 foo2
151
+ /// 2 foo3
152
+ ///
153
+ /// i=0 will read the entire foo struct, i=1 the foo2 primitive column etc
154
+ virtual ::arrow::Status ReadColumn(int i,
155
+ std::shared_ptr<::arrow::ChunkedArray>* out) = 0;
156
+
157
+ /// \brief Return a RecordBatchReader of all row groups and columns.
158
+ virtual ::arrow::Status GetRecordBatchReader(
159
+ std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
160
+
161
+ /// \brief Return a RecordBatchReader of row groups selected from row_group_indices.
162
+ ///
163
+ /// Note that the ordering in row_group_indices matters. FileReaders must outlive
164
+ /// their RecordBatchReaders.
165
+ ///
166
+ /// \returns error Status if row_group_indices contains an invalid index
167
+ virtual ::arrow::Status GetRecordBatchReader(
168
+ const std::vector<int>& row_group_indices,
169
+ std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
170
+
171
+ /// \brief Return a RecordBatchReader of row groups selected from
172
+ /// row_group_indices, whose columns are selected by column_indices.
173
+ ///
174
+ /// Note that the ordering in row_group_indices and column_indices
175
+ /// matter. FileReaders must outlive their RecordBatchReaders.
176
+ ///
177
+ /// \returns error Status if either row_group_indices or column_indices
178
+ /// contains an invalid index
179
+ virtual ::arrow::Status GetRecordBatchReader(
180
+ const std::vector<int>& row_group_indices, const std::vector<int>& column_indices,
181
+ std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
182
+
183
+ /// \brief Return a RecordBatchReader of row groups selected from
184
+ /// row_group_indices, whose columns are selected by column_indices.
185
+ ///
186
+ /// Note that the ordering in row_group_indices and column_indices
187
+ /// matter. FileReaders must outlive their RecordBatchReaders.
188
+ ///
189
+ /// \param row_group_indices which row groups to read (order determines read order).
190
+ /// \param column_indices which columns to read (order determines output schema).
191
+ /// \param[out] out record batch stream from parquet data.
192
+ ///
193
+ /// \returns error Status if either row_group_indices or column_indices
194
+ /// contains an invalid index
195
+ ::arrow::Status GetRecordBatchReader(const std::vector<int>& row_group_indices,
196
+ const std::vector<int>& column_indices,
197
+ std::shared_ptr<::arrow::RecordBatchReader>* out);
198
+ ::arrow::Status GetRecordBatchReader(const std::vector<int>& row_group_indices,
199
+ std::shared_ptr<::arrow::RecordBatchReader>* out);
200
+ ::arrow::Status GetRecordBatchReader(std::shared_ptr<::arrow::RecordBatchReader>* out);
201
+
202
+ /// \brief Return a generator of record batches.
203
+ ///
204
+ /// The FileReader must outlive the generator, so this requires that you pass in a
205
+ /// shared_ptr.
206
+ ///
207
+ /// \returns error Result if either row_group_indices or column_indices contains an
208
+ /// invalid index
209
+ virtual ::arrow::Result<
210
+ std::function<::arrow::Future<std::shared_ptr<::arrow::RecordBatch>>()>>
211
+ GetRecordBatchGenerator(std::shared_ptr<FileReader> reader,
212
+ const std::vector<int> row_group_indices,
213
+ const std::vector<int> column_indices,
214
+ ::arrow::internal::Executor* cpu_executor = NULLPTR,
215
+ int64_t rows_to_readahead = 0) = 0;
216
+
217
+ /// Read all columns into a Table
218
+ virtual ::arrow::Status ReadTable(std::shared_ptr<::arrow::Table>* out) = 0;
219
+
220
+ /// \brief Read the given columns into a Table
221
+ ///
222
+ /// The indicated column indices are relative to the internal representation
223
+ /// of the parquet table. For instance :
224
+ /// 0 foo.bar
225
+ /// foo.bar.baz 0
226
+ /// foo.bar.baz2 1
227
+ /// foo.qux 2
228
+ /// 1 foo2 3
229
+ /// 2 foo3 4
230
+ ///
231
+ /// i=0 will read foo.bar.baz, i=1 will read only foo.bar.baz2 and so on.
232
+ /// Only leaf fields have indices; foo itself doesn't have an index.
233
+ /// To get the index for a particular leaf field, one can use
234
+ /// manifest().schema_fields to get the top level fields, and then walk the
235
+ /// tree to identify the relevant leaf fields and access its column_index.
236
+ /// To get the total number of leaf fields, use FileMetadata.num_columns().
237
+ virtual ::arrow::Status ReadTable(const std::vector<int>& column_indices,
238
+ std::shared_ptr<::arrow::Table>* out) = 0;
239
+
240
+ virtual ::arrow::Status ReadRowGroup(int i, const std::vector<int>& column_indices,
241
+ std::shared_ptr<::arrow::Table>* out) = 0;
242
+
243
+ virtual ::arrow::Status ReadRowGroup(int i, std::shared_ptr<::arrow::Table>* out) = 0;
244
+
245
+ virtual ::arrow::Status ReadRowGroups(const std::vector<int>& row_groups,
246
+ const std::vector<int>& column_indices,
247
+ std::shared_ptr<::arrow::Table>* out) = 0;
248
+
249
+ virtual ::arrow::Status ReadRowGroups(const std::vector<int>& row_groups,
250
+ std::shared_ptr<::arrow::Table>* out) = 0;
251
+
252
+ /// \brief Scan file contents with one thread, return number of rows
253
+ virtual ::arrow::Status ScanContents(std::vector<int> columns,
254
+ const int32_t column_batch_size,
255
+ int64_t* num_rows) = 0;
256
+
257
+ /// \brief Return a reader for the RowGroup, this object must not outlive the
258
+ /// FileReader.
259
+ virtual std::shared_ptr<RowGroupReader> RowGroup(int row_group_index) = 0;
260
+
261
+ /// \brief The number of row groups in the file
262
+ virtual int num_row_groups() const = 0;
263
+
264
+ virtual ParquetFileReader* parquet_reader() const = 0;
265
+
266
+ /// Set whether to use multiple threads during reads of multiple columns.
267
+ /// By default only one thread is used.
268
+ virtual void set_use_threads(bool use_threads) = 0;
269
+
270
+ /// Set number of records to read per batch for the RecordBatchReader.
271
+ virtual void set_batch_size(int64_t batch_size) = 0;
272
+
273
+ virtual const ArrowReaderProperties& properties() const = 0;
274
+
275
+ virtual const SchemaManifest& manifest() const = 0;
276
+
277
+ virtual ~FileReader() = default;
278
+ };
279
+
280
+ class RowGroupReader {
281
+ public:
282
+ virtual ~RowGroupReader() = default;
283
+ virtual std::shared_ptr<ColumnChunkReader> Column(int column_index) = 0;
284
+ virtual ::arrow::Status ReadTable(const std::vector<int>& column_indices,
285
+ std::shared_ptr<::arrow::Table>* out) = 0;
286
+ virtual ::arrow::Status ReadTable(std::shared_ptr<::arrow::Table>* out) = 0;
287
+
288
+ private:
289
+ struct Iterator;
290
+ };
291
+
292
+ class ColumnChunkReader {
293
+ public:
294
+ virtual ~ColumnChunkReader() = default;
295
+ virtual ::arrow::Status Read(std::shared_ptr<::arrow::ChunkedArray>* out) = 0;
296
+ };
297
+
298
+ // At this point, the column reader is a stream iterator. It only knows how to
299
+ // read the next batch of values for a particular column from the file until it
300
+ // runs out.
301
+ //
302
+ // We also do not expose any internal Parquet details, such as row groups. This
303
+ // might change in the future.
304
+ class PARQUET_EXPORT ColumnReader {
305
+ public:
306
+ virtual ~ColumnReader() = default;
307
+
308
+ // Scan the next array of the indicated size. The actual size of the
309
+ // returned array may be less than the passed size depending how much data is
310
+ // available in the file.
311
+ //
312
+ // When all the data in the file has been exhausted, the result is set to
313
+ // nullptr.
314
+ //
315
+ // Returns Status::OK on a successful read, including if you have exhausted
316
+ // the data available in the file.
317
+ virtual ::arrow::Status NextBatch(int64_t batch_size,
318
+ std::shared_ptr<::arrow::ChunkedArray>* out) = 0;
319
+ };
320
+
321
+ /// \brief Experimental helper class for bindings (like Python) that struggle
322
+ /// either with std::move or C++ exceptions
323
+ class PARQUET_EXPORT FileReaderBuilder {
324
+ public:
325
+ FileReaderBuilder();
326
+
327
+ /// Create FileReaderBuilder from Arrow file and optional properties / metadata
328
+ ::arrow::Status Open(std::shared_ptr<::arrow::io::RandomAccessFile> file,
329
+ const ReaderProperties& properties = default_reader_properties(),
330
+ std::shared_ptr<FileMetaData> metadata = NULLPTR);
331
+
332
+ /// Create FileReaderBuilder from file path and optional properties / metadata
333
+ ::arrow::Status OpenFile(const std::string& path, bool memory_map = false,
334
+ const ReaderProperties& props = default_reader_properties(),
335
+ std::shared_ptr<FileMetaData> metadata = NULLPTR);
336
+
337
+ ParquetFileReader* raw_reader() { return raw_reader_.get(); }
338
+
339
+ /// Set Arrow MemoryPool for memory allocation
340
+ FileReaderBuilder* memory_pool(::arrow::MemoryPool* pool);
341
+ /// Set Arrow reader properties
342
+ FileReaderBuilder* properties(const ArrowReaderProperties& arg_properties);
343
+ /// Build FileReader instance
344
+ ::arrow::Status Build(std::unique_ptr<FileReader>* out);
345
+ ::arrow::Result<std::unique_ptr<FileReader>> Build();
346
+
347
+ private:
348
+ ::arrow::MemoryPool* pool_;
349
+ ArrowReaderProperties properties_;
350
+ std::unique_ptr<ParquetFileReader> raw_reader_;
351
+ };
352
+
353
+ /// \defgroup parquet-arrow-reader-factories Factory functions for Parquet Arrow readers
354
+ ///
355
+ /// @{
356
+
357
+ /// \brief Build FileReader from Arrow file and MemoryPool
358
+ ///
359
+ /// Advanced settings are supported through the FileReaderBuilder class.
360
+ PARQUET_EXPORT
361
+ ::arrow::Status OpenFile(std::shared_ptr<::arrow::io::RandomAccessFile>,
362
+ ::arrow::MemoryPool* allocator,
363
+ std::unique_ptr<FileReader>* reader);
364
+
365
+ /// @}
366
+
367
+ PARQUET_EXPORT
368
+ ::arrow::Status StatisticsAsScalars(const Statistics& Statistics,
369
+ std::shared_ptr<::arrow::Scalar>* min,
370
+ std::shared_ptr<::arrow::Scalar>* max);
371
+
372
+ namespace internal {
373
+
374
+ PARQUET_EXPORT
375
+ ::arrow::Status FuzzReader(const uint8_t* data, int64_t size);
376
+
377
+ } // namespace internal
378
+ } // namespace arrow
379
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.h ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cassert>
21
+ #include <memory>
22
+ #include <unordered_map>
23
+ #include <unordered_set>
24
+ #include <vector>
25
+
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+ #include "arrow/type_fwd.h"
30
+
31
+ #include "parquet/level_conversion.h"
32
+ #include "parquet/platform.h"
33
+ #include "parquet/schema.h"
34
+
35
+ namespace parquet {
36
+
37
+ class ArrowReaderProperties;
38
+ class ArrowWriterProperties;
39
+ class WriterProperties;
40
+
41
+ namespace arrow {
42
+
43
+ /// \defgroup arrow-to-parquet-schema-conversion Functions to convert an Arrow
44
+ /// schema into a Parquet schema.
45
+ ///
46
+ /// @{
47
+
48
+ PARQUET_EXPORT
49
+ ::arrow::Status FieldToNode(const std::shared_ptr<::arrow::Field>& field,
50
+ const WriterProperties& properties,
51
+ const ArrowWriterProperties& arrow_properties,
52
+ schema::NodePtr* out);
53
+
54
+ PARQUET_EXPORT
55
+ ::arrow::Status ToParquetSchema(const ::arrow::Schema* arrow_schema,
56
+ const WriterProperties& properties,
57
+ const ArrowWriterProperties& arrow_properties,
58
+ std::shared_ptr<SchemaDescriptor>* out);
59
+
60
+ PARQUET_EXPORT
61
+ ::arrow::Status ToParquetSchema(const ::arrow::Schema* arrow_schema,
62
+ const WriterProperties& properties,
63
+ std::shared_ptr<SchemaDescriptor>* out);
64
+
65
+ /// @}
66
+
67
+ /// \defgroup parquet-to-arrow-schema-conversion Functions to convert a Parquet
68
+ /// schema into an Arrow schema.
69
+ ///
70
+ /// @{
71
+
72
+ PARQUET_EXPORT
73
+ ::arrow::Status FromParquetSchema(
74
+ const SchemaDescriptor* parquet_schema, const ArrowReaderProperties& properties,
75
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& key_value_metadata,
76
+ std::shared_ptr<::arrow::Schema>* out);
77
+
78
+ PARQUET_EXPORT
79
+ ::arrow::Status FromParquetSchema(const SchemaDescriptor* parquet_schema,
80
+ const ArrowReaderProperties& properties,
81
+ std::shared_ptr<::arrow::Schema>* out);
82
+
83
+ PARQUET_EXPORT
84
+ ::arrow::Status FromParquetSchema(const SchemaDescriptor* parquet_schema,
85
+ std::shared_ptr<::arrow::Schema>* out);
86
+
87
+ /// @}
88
+
89
+ /// \brief Bridge between an arrow::Field and parquet column indices.
90
+ struct PARQUET_EXPORT SchemaField {
91
+ std::shared_ptr<::arrow::Field> field;
92
+ std::vector<SchemaField> children;
93
+
94
+ // Only set for leaf nodes
95
+ int column_index = -1;
96
+
97
+ parquet::internal::LevelInfo level_info;
98
+
99
+ bool is_leaf() const { return column_index != -1; }
100
+ };
101
+
102
+ /// \brief Bridge between a parquet Schema and an arrow Schema.
103
+ ///
104
+ /// Expose parquet columns as a tree structure. Useful traverse and link
105
+ /// between arrow's Schema and parquet's Schema.
106
+ struct PARQUET_EXPORT SchemaManifest {
107
+ static ::arrow::Status Make(
108
+ const SchemaDescriptor* schema,
109
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata,
110
+ const ArrowReaderProperties& properties, SchemaManifest* manifest);
111
+
112
+ const SchemaDescriptor* descr;
113
+ std::shared_ptr<::arrow::Schema> origin_schema;
114
+ std::shared_ptr<const ::arrow::KeyValueMetadata> schema_metadata;
115
+ std::vector<SchemaField> schema_fields;
116
+
117
+ std::unordered_map<int, const SchemaField*> column_index_to_field;
118
+ std::unordered_map<const SchemaField*, const SchemaField*> child_to_parent;
119
+
120
+ ::arrow::Status GetColumnField(int column_index, const SchemaField** out) const {
121
+ auto it = column_index_to_field.find(column_index);
122
+ if (it == column_index_to_field.end()) {
123
+ return ::arrow::Status::KeyError("Column index ", column_index,
124
+ " not found in schema manifest, may be malformed");
125
+ }
126
+ *out = it->second;
127
+ return ::arrow::Status::OK();
128
+ }
129
+
130
+ const SchemaField* GetParent(const SchemaField* field) const {
131
+ // Returns nullptr also if not found
132
+ auto it = child_to_parent.find(field);
133
+ if (it == child_to_parent.end()) {
134
+ return NULLPTR;
135
+ }
136
+ return it->second;
137
+ }
138
+
139
+ /// Coalesce a list of field indices (relative to the equivalent arrow::Schema) which
140
+ /// correspond to the column root (first node below the parquet schema's root group) of
141
+ /// each leaf referenced in column_indices.
142
+ ///
143
+ /// For example, for leaves `a.b.c`, `a.b.d.e`, and `i.j.k` (column_indices=[0,1,3])
144
+ /// the roots are `a` and `i` (return=[0,2]).
145
+ ///
146
+ /// root
147
+ /// -- a <------
148
+ /// -- -- b | |
149
+ /// -- -- -- c |
150
+ /// -- -- -- d |
151
+ /// -- -- -- -- e
152
+ /// -- f
153
+ /// -- -- g
154
+ /// -- -- -- h
155
+ /// -- i <---
156
+ /// -- -- j |
157
+ /// -- -- -- k
158
+ ::arrow::Result<std::vector<int>> GetFieldIndices(
159
+ const std::vector<int>& column_indices) const {
160
+ const schema::GroupNode* group = descr->group_node();
161
+ std::unordered_set<int> already_added;
162
+
163
+ std::vector<int> out;
164
+ for (int column_idx : column_indices) {
165
+ if (column_idx < 0 || column_idx >= descr->num_columns()) {
166
+ return ::arrow::Status::IndexError("Column index ", column_idx, " is not valid");
167
+ }
168
+
169
+ auto field_node = descr->GetColumnRoot(column_idx);
170
+ auto field_idx = group->FieldIndex(*field_node);
171
+ if (field_idx == -1) {
172
+ return ::arrow::Status::IndexError("Column index ", column_idx, " is not valid");
173
+ }
174
+
175
+ if (already_added.insert(field_idx).second) {
176
+ out.push_back(field_idx);
177
+ }
178
+ }
179
+ return out;
180
+ }
181
+ };
182
+
183
+ } // namespace arrow
184
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.h ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <limits>
21
+ #include <memory>
22
+ #include <random>
23
+ #include <string>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #include "arrow/array.h"
28
+ #include "arrow/array/builder_binary.h"
29
+ #include "arrow/array/builder_decimal.h"
30
+ #include "arrow/array/builder_primitive.h"
31
+ #include "arrow/testing/gtest_util.h"
32
+ #include "arrow/testing/random.h"
33
+ #include "arrow/type_fwd.h"
34
+ #include "arrow/type_traits.h"
35
+ #include "arrow/util/decimal.h"
36
+ #include "arrow/util/float16.h"
37
+ #include "parquet/column_reader.h"
38
+ #include "parquet/test_util.h"
39
+
40
+ namespace parquet {
41
+
42
+ using internal::RecordReader;
43
+
44
+ namespace arrow {
45
+
46
+ using ::arrow::Array;
47
+ using ::arrow::ChunkedArray;
48
+ using ::arrow::Status;
49
+
50
+ template <int32_t PRECISION>
51
+ struct DecimalWithPrecisionAndScale {
52
+ static_assert(PRECISION >= 1 && PRECISION <= 38, "Invalid precision value");
53
+
54
+ using type = ::arrow::Decimal128Type;
55
+ static constexpr ::arrow::Type::type type_id = ::arrow::Decimal128Type::type_id;
56
+ static constexpr int32_t precision = PRECISION;
57
+ static constexpr int32_t scale = PRECISION - 1;
58
+ };
59
+
60
+ template <int32_t PRECISION>
61
+ struct Decimal256WithPrecisionAndScale {
62
+ static_assert(PRECISION >= 1 && PRECISION <= 76, "Invalid precision value");
63
+
64
+ using type = ::arrow::Decimal256Type;
65
+ static constexpr ::arrow::Type::type type_id = ::arrow::Decimal256Type::type_id;
66
+ static constexpr int32_t precision = PRECISION;
67
+ static constexpr int32_t scale = PRECISION - 1;
68
+ };
69
+
70
+ template <class ArrowType>
71
+ ::arrow::enable_if_floating_point<ArrowType, Status> NonNullArray(
72
+ size_t size, std::shared_ptr<Array>* out) {
73
+ using c_type = typename ArrowType::c_type;
74
+ std::vector<c_type> values;
75
+ if constexpr (::arrow::is_half_float_type<ArrowType>::value) {
76
+ values.resize(size);
77
+ test::random_float16_numbers(static_cast<int>(size), 0, ::arrow::util::Float16(0.0f),
78
+ ::arrow::util::Float16(1.0f), values.data());
79
+ } else {
80
+ ::arrow::random_real(size, 0, static_cast<c_type>(0), static_cast<c_type>(1),
81
+ &values);
82
+ }
83
+ ::arrow::NumericBuilder<ArrowType> builder;
84
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
85
+ return builder.Finish(out);
86
+ }
87
+
88
+ template <class ArrowType>
89
+ ::arrow::enable_if_integer<ArrowType, Status> NonNullArray(size_t size,
90
+ std::shared_ptr<Array>* out) {
91
+ std::vector<typename ArrowType::c_type> values;
92
+ ::arrow::randint(size, 0, 64, &values);
93
+
94
+ // Passing data type so this will work with TimestampType too
95
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
96
+ ::arrow::default_memory_pool());
97
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
98
+ return builder.Finish(out);
99
+ }
100
+
101
+ template <class ArrowType>
102
+ ::arrow::enable_if_date<ArrowType, Status> NonNullArray(size_t size,
103
+ std::shared_ptr<Array>* out) {
104
+ std::vector<typename ArrowType::c_type> values;
105
+ ::arrow::randint(size, 0, 24, &values);
106
+ for (size_t i = 0; i < size; i++) {
107
+ values[i] *= 86400000;
108
+ }
109
+
110
+ // Passing data type so this will work with TimestampType too
111
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
112
+ ::arrow::default_memory_pool());
113
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
114
+ return builder.Finish(out);
115
+ }
116
+
117
+ template <class ArrowType>
118
+ ::arrow::enable_if_base_binary<ArrowType, Status> NonNullArray(
119
+ size_t size, std::shared_ptr<Array>* out) {
120
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
121
+ BuilderType builder;
122
+ for (size_t i = 0; i < size; i++) {
123
+ RETURN_NOT_OK(builder.Append("test-string"));
124
+ }
125
+ return builder.Finish(out);
126
+ }
127
+
128
+ template <typename ArrowType>
129
+ ::arrow::enable_if_fixed_size_binary<ArrowType, Status> NonNullArray(
130
+ size_t size, std::shared_ptr<Array>* out) {
131
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
132
+ // set byte_width to the length of "fixed": 5
133
+ // todo: find a way to generate test data with more diversity.
134
+ BuilderType builder(::arrow::fixed_size_binary(5));
135
+ for (size_t i = 0; i < size; i++) {
136
+ RETURN_NOT_OK(builder.Append("fixed"));
137
+ }
138
+ return builder.Finish(out);
139
+ }
140
+
141
+ template <int32_t byte_width>
142
+ static void random_decimals(int64_t n, uint32_t seed, int32_t precision, uint8_t* out) {
143
+ auto gen = ::arrow::random::RandomArrayGenerator(seed);
144
+ std::shared_ptr<Array> decimals;
145
+ if constexpr (byte_width == 16) {
146
+ decimals = gen.Decimal128(::arrow::decimal128(precision, 0), n);
147
+ } else {
148
+ decimals = gen.Decimal256(::arrow::decimal256(precision, 0), n);
149
+ }
150
+ std::memcpy(out, decimals->data()->GetValues<uint8_t>(1, 0), byte_width * n);
151
+ }
152
+
153
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
154
+ ::arrow::enable_if_t<
155
+ std::is_same<ArrowType, DecimalWithPrecisionAndScale<precision>>::value, Status>
156
+ NonNullArray(size_t size, std::shared_ptr<Array>* out) {
157
+ constexpr int32_t kDecimalPrecision = precision;
158
+ constexpr int32_t kDecimalScale = DecimalWithPrecisionAndScale<precision>::scale;
159
+
160
+ const auto type = ::arrow::decimal(kDecimalPrecision, kDecimalScale);
161
+ ::arrow::Decimal128Builder builder(type);
162
+ const int32_t byte_width =
163
+ static_cast<const ::arrow::Decimal128Type&>(*type).byte_width();
164
+
165
+ constexpr int32_t seed = 0;
166
+
167
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
168
+ random_decimals<::arrow::Decimal128Type::kByteWidth>(size, seed, kDecimalPrecision,
169
+ out_buf->mutable_data());
170
+
171
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size));
172
+ return builder.Finish(out);
173
+ }
174
+
175
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
176
+ ::arrow::enable_if_t<
177
+ std::is_same<ArrowType, Decimal256WithPrecisionAndScale<precision>>::value, Status>
178
+ NonNullArray(size_t size, std::shared_ptr<Array>* out) {
179
+ constexpr int32_t kDecimalPrecision = precision;
180
+ constexpr int32_t kDecimalScale = Decimal256WithPrecisionAndScale<precision>::scale;
181
+
182
+ const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale);
183
+ ::arrow::Decimal256Builder builder(type);
184
+ const int32_t byte_width =
185
+ static_cast<const ::arrow::Decimal256Type&>(*type).byte_width();
186
+
187
+ constexpr int32_t seed = 0;
188
+
189
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
190
+ random_decimals<::arrow::Decimal256Type::kByteWidth>(size, seed, kDecimalPrecision,
191
+ out_buf->mutable_data());
192
+
193
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size));
194
+ return builder.Finish(out);
195
+ }
196
+
197
+ template <class ArrowType>
198
+ ::arrow::enable_if_boolean<ArrowType, Status> NonNullArray(size_t size,
199
+ std::shared_ptr<Array>* out) {
200
+ std::vector<uint8_t> values;
201
+ ::arrow::randint(size, 0, 1, &values);
202
+ ::arrow::BooleanBuilder builder;
203
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
204
+ return builder.Finish(out);
205
+ }
206
+
207
+ // This helper function only supports (size/2) nulls.
208
+ template <typename ArrowType>
209
+ ::arrow::enable_if_floating_point<ArrowType, Status> NullableArray(
210
+ size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<Array>* out) {
211
+ using c_type = typename ArrowType::c_type;
212
+ std::vector<c_type> values;
213
+ if constexpr (::arrow::is_half_float_type<ArrowType>::value) {
214
+ values.resize(size);
215
+ test::random_float16_numbers(static_cast<int>(size), 0, ::arrow::util::Float16(-1e4f),
216
+ ::arrow::util::Float16(1e4f), values.data());
217
+ } else {
218
+ ::arrow::random_real(size, seed, static_cast<c_type>(-1e10),
219
+ static_cast<c_type>(1e10), &values);
220
+ }
221
+ std::vector<uint8_t> valid_bytes(size, 1);
222
+
223
+ for (size_t i = 0; i < num_nulls; i++) {
224
+ valid_bytes[i * 2] = 0;
225
+ }
226
+
227
+ ::arrow::NumericBuilder<ArrowType> builder;
228
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
229
+ return builder.Finish(out);
230
+ }
231
+
232
+ // This helper function only supports (size/2) nulls.
233
+ template <typename ArrowType>
234
+ ::arrow::enable_if_integer<ArrowType, Status> NullableArray(size_t size, size_t num_nulls,
235
+ uint32_t seed,
236
+ std::shared_ptr<Array>* out) {
237
+ std::vector<typename ArrowType::c_type> values;
238
+
239
+ // Seed is random in Arrow right now
240
+ (void)seed;
241
+ ::arrow::randint(size, 0, 64, &values);
242
+ std::vector<uint8_t> valid_bytes(size, 1);
243
+
244
+ for (size_t i = 0; i < num_nulls; i++) {
245
+ valid_bytes[i * 2] = 0;
246
+ }
247
+
248
+ // Passing data type so this will work with TimestampType too
249
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
250
+ ::arrow::default_memory_pool());
251
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
252
+ return builder.Finish(out);
253
+ }
254
+
255
+ template <typename ArrowType>
256
+ ::arrow::enable_if_date<ArrowType, Status> NullableArray(size_t size, size_t num_nulls,
257
+ uint32_t seed,
258
+ std::shared_ptr<Array>* out) {
259
+ std::vector<typename ArrowType::c_type> values;
260
+
261
+ // Seed is random in Arrow right now
262
+ (void)seed;
263
+ ::arrow::randint(size, 0, 24, &values);
264
+ for (size_t i = 0; i < size; i++) {
265
+ values[i] *= 86400000;
266
+ }
267
+ std::vector<uint8_t> valid_bytes(size, 1);
268
+
269
+ for (size_t i = 0; i < num_nulls; i++) {
270
+ valid_bytes[i * 2] = 0;
271
+ }
272
+
273
+ // Passing data type so this will work with TimestampType too
274
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
275
+ ::arrow::default_memory_pool());
276
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
277
+ return builder.Finish(out);
278
+ }
279
+
280
+ // This helper function only supports (size/2) nulls yet.
281
+ template <typename ArrowType>
282
+ ::arrow::enable_if_base_binary<ArrowType, Status> NullableArray(
283
+ size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) {
284
+ std::vector<uint8_t> valid_bytes(size, 1);
285
+
286
+ for (size_t i = 0; i < num_nulls; i++) {
287
+ valid_bytes[i * 2] = 0;
288
+ }
289
+
290
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
291
+ BuilderType builder;
292
+
293
+ const int kBufferSize = 10;
294
+ uint8_t buffer[kBufferSize];
295
+ for (size_t i = 0; i < size; i++) {
296
+ if (!valid_bytes[i]) {
297
+ RETURN_NOT_OK(builder.AppendNull());
298
+ } else {
299
+ ::arrow::random_bytes(kBufferSize, seed + static_cast<uint32_t>(i), buffer);
300
+ if (ArrowType::is_utf8) {
301
+ // Trivially force data to be valid UTF8 by making it all ASCII
302
+ for (auto& byte : buffer) {
303
+ byte &= 0x7f;
304
+ }
305
+ }
306
+ RETURN_NOT_OK(builder.Append(buffer, kBufferSize));
307
+ }
308
+ }
309
+ return builder.Finish(out);
310
+ }
311
+
312
+ // This helper function only supports (size/2) nulls yet,
313
+ // same as NullableArray<String|Binary>(..)
314
+ template <typename ArrowType>
315
+ ::arrow::enable_if_fixed_size_binary<ArrowType, Status> NullableArray(
316
+ size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) {
317
+ std::vector<uint8_t> valid_bytes(size, 1);
318
+
319
+ for (size_t i = 0; i < num_nulls; i++) {
320
+ valid_bytes[i * 2] = 0;
321
+ }
322
+
323
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
324
+ const int byte_width = 10;
325
+ BuilderType builder(::arrow::fixed_size_binary(byte_width));
326
+
327
+ const int kBufferSize = byte_width;
328
+ uint8_t buffer[kBufferSize];
329
+ for (size_t i = 0; i < size; i++) {
330
+ if (!valid_bytes[i]) {
331
+ RETURN_NOT_OK(builder.AppendNull());
332
+ } else {
333
+ ::arrow::random_bytes(kBufferSize, seed + static_cast<uint32_t>(i), buffer);
334
+ RETURN_NOT_OK(builder.Append(buffer));
335
+ }
336
+ }
337
+ return builder.Finish(out);
338
+ }
339
+
340
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
341
+ ::arrow::enable_if_t<
342
+ std::is_same<ArrowType, DecimalWithPrecisionAndScale<precision>>::value, Status>
343
+ NullableArray(size_t size, size_t num_nulls, uint32_t seed,
344
+ std::shared_ptr<::arrow::Array>* out) {
345
+ std::vector<uint8_t> valid_bytes(size, '\1');
346
+
347
+ for (size_t i = 0; i < num_nulls; ++i) {
348
+ valid_bytes[i * 2] = '\0';
349
+ }
350
+
351
+ constexpr int32_t kDecimalPrecision = precision;
352
+ constexpr int32_t kDecimalScale = DecimalWithPrecisionAndScale<precision>::scale;
353
+ const auto type = ::arrow::decimal(kDecimalPrecision, kDecimalScale);
354
+ const int32_t byte_width =
355
+ static_cast<const ::arrow::Decimal128Type&>(*type).byte_width();
356
+
357
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
358
+
359
+ random_decimals<::arrow::Decimal128Type::kByteWidth>(size, seed, precision,
360
+ out_buf->mutable_data());
361
+
362
+ ::arrow::Decimal128Builder builder(type);
363
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size, valid_bytes.data()));
364
+ return builder.Finish(out);
365
+ }
366
+
367
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
368
+ ::arrow::enable_if_t<
369
+ std::is_same<ArrowType, Decimal256WithPrecisionAndScale<precision>>::value, Status>
370
+ NullableArray(size_t size, size_t num_nulls, uint32_t seed,
371
+ std::shared_ptr<::arrow::Array>* out) {
372
+ std::vector<uint8_t> valid_bytes(size, '\1');
373
+
374
+ for (size_t i = 0; i < num_nulls; ++i) {
375
+ valid_bytes[i * 2] = '\0';
376
+ }
377
+
378
+ constexpr int32_t kDecimalPrecision = precision;
379
+ constexpr int32_t kDecimalScale = Decimal256WithPrecisionAndScale<precision>::scale;
380
+ const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale);
381
+ const int32_t byte_width =
382
+ static_cast<const ::arrow::Decimal256Type&>(*type).byte_width();
383
+
384
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
385
+
386
+ random_decimals<::arrow::Decimal256Type::kByteWidth>(size, seed, precision,
387
+ out_buf->mutable_data());
388
+
389
+ ::arrow::Decimal256Builder builder(type);
390
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size, valid_bytes.data()));
391
+ return builder.Finish(out);
392
+ }
393
+
394
+ // This helper function only supports (size/2) nulls yet.
395
+ template <class ArrowType>
396
+ ::arrow::enable_if_boolean<ArrowType, Status> NullableArray(size_t size, size_t num_nulls,
397
+ uint32_t seed,
398
+ std::shared_ptr<Array>* out) {
399
+ std::vector<uint8_t> values;
400
+
401
+ // Seed is random in Arrow right now
402
+ (void)seed;
403
+
404
+ ::arrow::randint(size, 0, 1, &values);
405
+ std::vector<uint8_t> valid_bytes(size, 1);
406
+
407
+ for (size_t i = 0; i < num_nulls; i++) {
408
+ valid_bytes[i * 2] = 0;
409
+ }
410
+
411
+ ::arrow::BooleanBuilder builder;
412
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
413
+ return builder.Finish(out);
414
+ }
415
+
416
+ /// Wrap an Array into a ListArray by splitting it up into size lists.
417
+ ///
418
+ /// This helper function only supports (size/2) nulls.
419
+ Status MakeListArray(const std::shared_ptr<Array>& values, int64_t size,
420
+ int64_t null_count, const std::string& item_name,
421
+ bool nullable_values, std::shared_ptr<::arrow::ListArray>* out) {
422
+ // We always include an empty list
423
+ int64_t non_null_entries = size - null_count - 1;
424
+ int64_t length_per_entry = values->length() / non_null_entries;
425
+
426
+ auto offsets = AllocateBuffer();
427
+ RETURN_NOT_OK(offsets->Resize((size + 1) * sizeof(int32_t)));
428
+ int32_t* offsets_ptr = reinterpret_cast<int32_t*>(offsets->mutable_data());
429
+
430
+ auto null_bitmap = AllocateBuffer();
431
+ int64_t bitmap_size = ::arrow::bit_util::BytesForBits(size);
432
+ RETURN_NOT_OK(null_bitmap->Resize(bitmap_size));
433
+ uint8_t* null_bitmap_ptr = null_bitmap->mutable_data();
434
+ memset(null_bitmap_ptr, 0, bitmap_size);
435
+
436
+ int32_t current_offset = 0;
437
+ for (int64_t i = 0; i < size; i++) {
438
+ offsets_ptr[i] = current_offset;
439
+ if (!(((i % 2) == 0) && ((i / 2) < null_count))) {
440
+ // Non-null list (list with index 1 is always empty).
441
+ ::arrow::bit_util::SetBit(null_bitmap_ptr, i);
442
+ if (i != 1) {
443
+ current_offset += static_cast<int32_t>(length_per_entry);
444
+ }
445
+ }
446
+ }
447
+ offsets_ptr[size] = static_cast<int32_t>(values->length());
448
+
449
+ auto value_field = ::arrow::field(item_name, values->type(), nullable_values);
450
+ *out = std::make_shared<::arrow::ListArray>(::arrow::list(value_field), size, offsets,
451
+ values, null_bitmap, null_count);
452
+
453
+ return Status::OK();
454
+ }
455
+
456
+ // Make an array containing only empty lists, with a null values array
457
+ Status MakeEmptyListsArray(int64_t size, std::shared_ptr<Array>* out_array) {
458
+ // Allocate an offsets buffer containing only zeroes
459
+ const int64_t offsets_nbytes = (size + 1) * sizeof(int32_t);
460
+ ARROW_ASSIGN_OR_RAISE(auto offsets_buffer, ::arrow::AllocateBuffer(offsets_nbytes));
461
+ memset(offsets_buffer->mutable_data(), 0, offsets_nbytes);
462
+
463
+ auto value_field =
464
+ ::arrow::field("item", ::arrow::float64(), false /* nullable_values */);
465
+ auto list_type = ::arrow::list(value_field);
466
+
467
+ std::vector<std::shared_ptr<Buffer>> child_buffers = {nullptr /* null bitmap */,
468
+ nullptr /* values */};
469
+ auto child_data =
470
+ ::arrow::ArrayData::Make(value_field->type(), 0, std::move(child_buffers));
471
+
472
+ std::vector<std::shared_ptr<Buffer>> buffers = {nullptr /* bitmap */,
473
+ std::move(offsets_buffer)};
474
+ auto array_data = ::arrow::ArrayData::Make(list_type, size, std::move(buffers));
475
+ array_data->child_data.push_back(child_data);
476
+
477
+ *out_array = ::arrow::MakeArray(array_data);
478
+ return Status::OK();
479
+ }
480
+
481
+ std::shared_ptr<::arrow::Table> MakeSimpleTable(
482
+ const std::shared_ptr<ChunkedArray>& values, bool nullable) {
483
+ auto schema = ::arrow::schema({::arrow::field("col", values->type(), nullable)});
484
+ return ::arrow::Table::Make(schema, {values});
485
+ }
486
+
487
+ std::shared_ptr<::arrow::Table> MakeSimpleTable(const std::shared_ptr<Array>& values,
488
+ bool nullable) {
489
+ auto carr = std::make_shared<::arrow::ChunkedArray>(values);
490
+ return MakeSimpleTable(carr, nullable);
491
+ }
492
+
493
+ template <typename T>
494
+ void ExpectArray(T* expected, Array* result) {
495
+ auto p_array = static_cast<::arrow::PrimitiveArray*>(result);
496
+ for (int i = 0; i < result->length(); i++) {
497
+ EXPECT_EQ(expected[i], reinterpret_cast<const T*>(p_array->values()->data())[i]);
498
+ }
499
+ }
500
+
501
+ template <typename ArrowType>
502
+ void ExpectArrayT(void* expected, Array* result) {
503
+ ::arrow::PrimitiveArray* p_array = static_cast<::arrow::PrimitiveArray*>(result);
504
+ for (int64_t i = 0; i < result->length(); i++) {
505
+ EXPECT_EQ(reinterpret_cast<typename ArrowType::c_type*>(expected)[i],
506
+ reinterpret_cast<const typename ArrowType::c_type*>(
507
+ p_array->values()->data())[i]);
508
+ }
509
+ }
510
+
511
+ template <>
512
+ void ExpectArrayT<::arrow::BooleanType>(void* expected, Array* result) {
513
+ ::arrow::BooleanBuilder builder;
514
+ ARROW_EXPECT_OK(
515
+ builder.AppendValues(reinterpret_cast<uint8_t*>(expected), result->length()));
516
+
517
+ std::shared_ptr<Array> expected_array;
518
+ ARROW_EXPECT_OK(builder.Finish(&expected_array));
519
+ EXPECT_TRUE(result->Equals(*expected_array));
520
+ }
521
+
522
+ } // namespace arrow
523
+
524
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.h ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+
23
+ #include "parquet/platform.h"
24
+ #include "parquet/properties.h"
25
+
26
+ namespace arrow {
27
+
28
+ class Array;
29
+ class ChunkedArray;
30
+ class RecordBatch;
31
+ class Schema;
32
+ class Table;
33
+
34
+ } // namespace arrow
35
+
36
+ namespace parquet {
37
+
38
+ class FileMetaData;
39
+ class ParquetFileWriter;
40
+
41
+ namespace arrow {
42
+
43
+ /// \brief Iterative FileWriter class
44
+ ///
45
+ /// For basic usage, can write a Table at a time, creating one or more row
46
+ /// groups per write call.
47
+ ///
48
+ /// For advanced usage, can write column-by-column: Start a new RowGroup or
49
+ /// Chunk with NewRowGroup, then write column-by-column the whole column chunk.
50
+ ///
51
+ /// If PARQUET:field_id is present as a metadata key on a field, and the corresponding
52
+ /// value is a nonnegative integer, then it will be used as the field_id in the parquet
53
+ /// file.
54
+ class PARQUET_EXPORT FileWriter {
55
+ public:
56
+ static ::arrow::Status Make(MemoryPool* pool, std::unique_ptr<ParquetFileWriter> writer,
57
+ std::shared_ptr<::arrow::Schema> schema,
58
+ std::shared_ptr<ArrowWriterProperties> arrow_properties,
59
+ std::unique_ptr<FileWriter>* out);
60
+
61
+ /// \brief Try to create an Arrow to Parquet file writer.
62
+ ///
63
+ /// \param schema schema of data that will be passed.
64
+ /// \param pool memory pool to use.
65
+ /// \param sink output stream to write Parquet data.
66
+ /// \param properties general Parquet writer properties.
67
+ /// \param arrow_properties Arrow-specific writer properties.
68
+ ///
69
+ /// \since 11.0.0
70
+ static ::arrow::Result<std::unique_ptr<FileWriter>> Open(
71
+ const ::arrow::Schema& schema, MemoryPool* pool,
72
+ std::shared_ptr<::arrow::io::OutputStream> sink,
73
+ std::shared_ptr<WriterProperties> properties = default_writer_properties(),
74
+ std::shared_ptr<ArrowWriterProperties> arrow_properties =
75
+ default_arrow_writer_properties());
76
+
77
+ ARROW_DEPRECATED("Deprecated in 11.0.0. Use Result-returning variants instead.")
78
+ static ::arrow::Status Open(const ::arrow::Schema& schema, MemoryPool* pool,
79
+ std::shared_ptr<::arrow::io::OutputStream> sink,
80
+ std::shared_ptr<WriterProperties> properties,
81
+ std::unique_ptr<FileWriter>* writer);
82
+ ARROW_DEPRECATED("Deprecated in 11.0.0. Use Result-returning variants instead.")
83
+ static ::arrow::Status Open(const ::arrow::Schema& schema, MemoryPool* pool,
84
+ std::shared_ptr<::arrow::io::OutputStream> sink,
85
+ std::shared_ptr<WriterProperties> properties,
86
+ std::shared_ptr<ArrowWriterProperties> arrow_properties,
87
+ std::unique_ptr<FileWriter>* writer);
88
+
89
+ /// Return the Arrow schema to be written to.
90
+ virtual std::shared_ptr<::arrow::Schema> schema() const = 0;
91
+
92
+ /// \brief Write a Table to Parquet.
93
+ ///
94
+ /// \param table Arrow table to write.
95
+ /// \param chunk_size maximum number of rows to write per row group.
96
+ virtual ::arrow::Status WriteTable(
97
+ const ::arrow::Table& table, int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH) = 0;
98
+
99
+ /// \brief Start a new row group.
100
+ ///
101
+ /// Returns an error if not all columns have been written.
102
+ ///
103
+ /// \param chunk_size the number of rows in the next row group.
104
+ virtual ::arrow::Status NewRowGroup(int64_t chunk_size) = 0;
105
+
106
+ /// \brief Write ColumnChunk in row group using an array.
107
+ virtual ::arrow::Status WriteColumnChunk(const ::arrow::Array& data) = 0;
108
+
109
+ /// \brief Write ColumnChunk in row group using slice of a ChunkedArray
110
+ virtual ::arrow::Status WriteColumnChunk(
111
+ const std::shared_ptr<::arrow::ChunkedArray>& data, int64_t offset,
112
+ int64_t size) = 0;
113
+
114
+ /// \brief Write ColumnChunk in a row group using a ChunkedArray
115
+ virtual ::arrow::Status WriteColumnChunk(
116
+ const std::shared_ptr<::arrow::ChunkedArray>& data) = 0;
117
+
118
+ /// \brief Start a new buffered row group.
119
+ ///
120
+ /// Returns an error if not all columns have been written.
121
+ virtual ::arrow::Status NewBufferedRowGroup() = 0;
122
+
123
+ /// \brief Write a RecordBatch into the buffered row group.
124
+ ///
125
+ /// Multiple RecordBatches can be written into the same row group
126
+ /// through this method.
127
+ ///
128
+ /// WriterProperties.max_row_group_length() is respected and a new
129
+ /// row group will be created if the current row group exceeds the
130
+ /// limit.
131
+ ///
132
+ /// Batches get flushed to the output stream once NewBufferedRowGroup()
133
+ /// or Close() is called.
134
+ ///
135
+ /// WARNING: If you are writing multiple files in parallel in the same
136
+ /// executor, deadlock may occur if ArrowWriterProperties::use_threads
137
+ /// is set to true to write columns in parallel. Please disable use_threads
138
+ /// option in this case.
139
+ virtual ::arrow::Status WriteRecordBatch(const ::arrow::RecordBatch& batch) = 0;
140
+
141
+ /// \brief Write the footer and close the file.
142
+ virtual ::arrow::Status Close() = 0;
143
+ virtual ~FileWriter();
144
+
145
+ virtual MemoryPool* memory_pool() const = 0;
146
+ /// \brief Return the file metadata, only available after calling Close().
147
+ virtual const std::shared_ptr<FileMetaData> metadata() const = 0;
148
+ };
149
+
150
+ /// \brief Write Parquet file metadata only to indicated Arrow OutputStream
151
+ PARQUET_EXPORT
152
+ ::arrow::Status WriteFileMetaData(const FileMetaData& file_metadata,
153
+ ::arrow::io::OutputStream* sink);
154
+
155
+ /// \brief Write metadata-only Parquet file to indicated Arrow OutputStream
156
+ PARQUET_EXPORT
157
+ ::arrow::Status WriteMetaDataFile(const FileMetaData& file_metadata,
158
+ ::arrow::io::OutputStream* sink);
159
+
160
+ /// \brief Write a Table to Parquet.
161
+ ///
162
+ /// This writes one table in a single shot. To write a Parquet file with
163
+ /// multiple tables iteratively, see parquet::arrow::FileWriter.
164
+ ///
165
+ /// \param table Table to write.
166
+ /// \param pool memory pool to use.
167
+ /// \param sink output stream to write Parquet data.
168
+ /// \param chunk_size maximum number of rows to write per row group.
169
+ /// \param properties general Parquet writer properties.
170
+ /// \param arrow_properties Arrow-specific writer properties.
171
+ ::arrow::Status PARQUET_EXPORT
172
+ WriteTable(const ::arrow::Table& table, MemoryPool* pool,
173
+ std::shared_ptr<::arrow::io::OutputStream> sink,
174
+ int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH,
175
+ std::shared_ptr<WriterProperties> properties = default_writer_properties(),
176
+ std::shared_ptr<ArrowWriterProperties> arrow_properties =
177
+ default_arrow_writer_properties());
178
+
179
+ } // namespace arrow
180
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter.h ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cmath>
21
+ #include <cstdint>
22
+ #include <memory>
23
+
24
+ #include "arrow/util/bit_util.h"
25
+ #include "arrow/util/logging.h"
26
+ #include "parquet/hasher.h"
27
+ #include "parquet/platform.h"
28
+ #include "parquet/types.h"
29
+
30
+ namespace parquet {
31
+
32
+ // A Bloom filter is a compact structure to indicate whether an item is not in a set or
33
+ // probably in a set. The Bloom filter usually consists of a bit set that represents a
34
+ // set of elements, a hash strategy and a Bloom filter algorithm.
35
+ class PARQUET_EXPORT BloomFilter {
36
+ public:
37
+ // Maximum Bloom filter size, it sets to HDFS default block size 128MB
38
+ // This value will be reconsidered when implementing Bloom filter producer.
39
+ static constexpr uint32_t kMaximumBloomFilterBytes = 128 * 1024 * 1024;
40
+
41
+ /// Determine whether an element exist in set or not.
42
+ ///
43
+ /// @param hash the element to contain.
44
+ /// @return false if value is definitely not in set, and true means PROBABLY
45
+ /// in set.
46
+ virtual bool FindHash(uint64_t hash) const = 0;
47
+
48
+ /// Insert element to set represented by Bloom filter bitset.
49
+ /// @param hash the hash of value to insert into Bloom filter.
50
+ virtual void InsertHash(uint64_t hash) = 0;
51
+
52
+ /// Insert elements to set represented by Bloom filter bitset.
53
+ /// @param hashes the hash values to insert into Bloom filter.
54
+ /// @param num_values the number of hash values to insert.
55
+ virtual void InsertHashes(const uint64_t* hashes, int num_values) = 0;
56
+
57
+ /// Write this Bloom filter to an output stream. A Bloom filter structure should
58
+ /// include bitset length, hash strategy, algorithm, and bitset.
59
+ ///
60
+ /// @param sink the output stream to write
61
+ virtual void WriteTo(ArrowOutputStream* sink) const = 0;
62
+
63
+ /// Get the number of bytes of bitset
64
+ virtual uint32_t GetBitsetSize() const = 0;
65
+
66
+ /// Compute hash for 32 bits value by using its plain encoding result.
67
+ ///
68
+ /// @param value the value to hash.
69
+ /// @return hash result.
70
+ virtual uint64_t Hash(int32_t value) const = 0;
71
+
72
+ /// Compute hash for 64 bits value by using its plain encoding result.
73
+ ///
74
+ /// @param value the value to hash.
75
+ /// @return hash result.
76
+ virtual uint64_t Hash(int64_t value) const = 0;
77
+
78
+ /// Compute hash for float value by using its plain encoding result.
79
+ ///
80
+ /// @param value the value to hash.
81
+ /// @return hash result.
82
+ virtual uint64_t Hash(float value) const = 0;
83
+
84
+ /// Compute hash for double value by using its plain encoding result.
85
+ ///
86
+ /// @param value the value to hash.
87
+ /// @return hash result.
88
+ virtual uint64_t Hash(double value) const = 0;
89
+
90
+ /// Compute hash for Int96 value by using its plain encoding result.
91
+ ///
92
+ /// @param value the value to hash.
93
+ /// @return hash result.
94
+ virtual uint64_t Hash(const Int96* value) const = 0;
95
+
96
+ /// Compute hash for ByteArray value by using its plain encoding result.
97
+ ///
98
+ /// @param value the value to hash.
99
+ /// @return hash result.
100
+ virtual uint64_t Hash(const ByteArray* value) const = 0;
101
+
102
+ /// Compute hash for fixed byte array value by using its plain encoding result.
103
+ ///
104
+ /// @param value the value address.
105
+ /// @param len the value length.
106
+ /// @return hash result.
107
+ virtual uint64_t Hash(const FLBA* value, uint32_t len) const = 0;
108
+
109
+ /// Batch compute hashes for 32 bits values by using its plain encoding result.
110
+ ///
111
+ /// @param values values a pointer to the values to hash.
112
+ /// @param num_values the number of values to hash.
113
+ /// @param hashes a pointer to the output hash values, its length should be equal to
114
+ /// num_values.
115
+ virtual void Hashes(const int32_t* values, int num_values, uint64_t* hashes) const = 0;
116
+
117
+ /// Batch compute hashes for 64 bits values by using its plain encoding result.
118
+ ///
119
+ /// @param values values a pointer to the values to hash.
120
+ /// @param num_values the number of values to hash.
121
+ /// @param hashes a pointer to the output hash values, its length should be equal to
122
+ /// num_values.
123
+ virtual void Hashes(const int64_t* values, int num_values, uint64_t* hashes) const = 0;
124
+
125
+ /// Batch compute hashes for float values by using its plain encoding result.
126
+ ///
127
+ /// @param values values a pointer to the values to hash.
128
+ /// @param num_values the number of values to hash.
129
+ /// @param hashes a pointer to the output hash values, its length should be equal to
130
+ /// num_values.
131
+ virtual void Hashes(const float* values, int num_values, uint64_t* hashes) const = 0;
132
+
133
+ /// Batch compute hashes for double values by using its plain encoding result.
134
+ ///
135
+ /// @param values values a pointer to the values to hash.
136
+ /// @param num_values the number of values to hash.
137
+ /// @param hashes a pointer to the output hash values, its length should be equal to
138
+ /// num_values.
139
+ virtual void Hashes(const double* values, int num_values, uint64_t* hashes) const = 0;
140
+
141
+ /// Batch compute hashes for Int96 values by using its plain encoding result.
142
+ ///
143
+ /// @param values values a pointer to the values to hash.
144
+ /// @param num_values the number of values to hash.
145
+ /// @param hashes a pointer to the output hash values, its length should be equal to
146
+ /// num_values.
147
+ virtual void Hashes(const Int96* values, int num_values, uint64_t* hashes) const = 0;
148
+
149
+ /// Batch compute hashes for ByteArray values by using its plain encoding result.
150
+ ///
151
+ /// @param values values a pointer to the values to hash.
152
+ /// @param num_values the number of values to hash.
153
+ /// @param hashes a pointer to the output hash values, its length should be equal to
154
+ /// num_values.
155
+ virtual void Hashes(const ByteArray* values, int num_values,
156
+ uint64_t* hashes) const = 0;
157
+
158
+ /// Batch compute hashes for fixed byte array values by using its plain encoding result.
159
+ ///
160
+ /// @param values values a pointer to the values to hash.
161
+ /// @param type_len the value length.
162
+ /// @param num_values the number of values to hash.
163
+ /// @param hashes a pointer to the output hash values, its length should be equal to
164
+ /// num_values.
165
+ virtual void Hashes(const FLBA* values, uint32_t type_len, int num_values,
166
+ uint64_t* hashes) const = 0;
167
+
168
+ virtual ~BloomFilter() = default;
169
+
170
+ protected:
171
+ // Hash strategy available for Bloom filter.
172
+ enum class HashStrategy : uint32_t { XXHASH = 0 };
173
+
174
+ // Bloom filter algorithm.
175
+ enum class Algorithm : uint32_t { BLOCK = 0 };
176
+
177
+ enum class CompressionStrategy : uint32_t { UNCOMPRESSED = 0 };
178
+ };
179
+
180
+ /// The BlockSplitBloomFilter is implemented using block-based Bloom filters from
181
+ /// Putze et al.'s "Cache-,Hash- and Space-Efficient Bloom filters". The basic idea is to
182
+ /// hash the item to a tiny Bloom filter which size fit a single cache line or smaller.
183
+ ///
184
+ /// This implementation sets 8 bits in each tiny Bloom filter. Each tiny Bloom
185
+ /// filter is 32 bytes to take advantage of 32-byte SIMD instructions.
186
+ class PARQUET_EXPORT BlockSplitBloomFilter : public BloomFilter {
187
+ public:
188
+ /// The constructor of BlockSplitBloomFilter. It uses XXH64 as hash function.
189
+ ///
190
+ /// \param pool memory pool to use.
191
+ explicit BlockSplitBloomFilter(
192
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
193
+
194
+ /// Initialize the BlockSplitBloomFilter. The range of num_bytes should be within
195
+ /// [kMinimumBloomFilterBytes, kMaximumBloomFilterBytes], it will be
196
+ /// rounded up/down to lower/upper bound if num_bytes is out of range and also
197
+ /// will be rounded up to a power of 2.
198
+ ///
199
+ /// @param num_bytes The number of bytes to store Bloom filter bitset.
200
+ void Init(uint32_t num_bytes);
201
+
202
+ /// Initialize the BlockSplitBloomFilter. It copies the bitset as underlying
203
+ /// bitset because the given bitset may not satisfy the 32-byte alignment requirement
204
+ /// which may lead to segfault when performing SIMD instructions. It is the caller's
205
+ /// responsibility to free the bitset passed in. This is used when reconstructing
206
+ /// a Bloom filter from a parquet file.
207
+ ///
208
+ /// @param bitset The given bitset to initialize the Bloom filter.
209
+ /// @param num_bytes The number of bytes of given bitset.
210
+ void Init(const uint8_t* bitset, uint32_t num_bytes);
211
+
212
+ /// Minimum Bloom filter size, it sets to 32 bytes to fit a tiny Bloom filter.
213
+ static constexpr uint32_t kMinimumBloomFilterBytes = 32;
214
+
215
+ /// Calculate optimal size according to the number of distinct values and false
216
+ /// positive probability.
217
+ ///
218
+ /// @param ndv The number of distinct values.
219
+ /// @param fpp The false positive probability.
220
+ /// @return it always return a value between kMinimumBloomFilterBytes and
221
+ /// kMaximumBloomFilterBytes, and the return value is always a power of 2
222
+ static uint32_t OptimalNumOfBytes(uint32_t ndv, double fpp) {
223
+ uint32_t optimal_num_of_bits = OptimalNumOfBits(ndv, fpp);
224
+ DCHECK(::arrow::bit_util::IsMultipleOf8(optimal_num_of_bits));
225
+ return optimal_num_of_bits >> 3;
226
+ }
227
+
228
+ /// Calculate optimal size according to the number of distinct values and false
229
+ /// positive probability.
230
+ ///
231
+ /// @param ndv The number of distinct values.
232
+ /// @param fpp The false positive probability.
233
+ /// @return it always return a value between kMinimumBloomFilterBytes * 8 and
234
+ /// kMaximumBloomFilterBytes * 8, and the return value is always a power of 16
235
+ static uint32_t OptimalNumOfBits(uint32_t ndv, double fpp) {
236
+ DCHECK(fpp > 0.0 && fpp < 1.0);
237
+ const double m = -8.0 * ndv / log(1 - pow(fpp, 1.0 / 8));
238
+ uint32_t num_bits;
239
+
240
+ // Handle overflow.
241
+ if (m < 0 || m > kMaximumBloomFilterBytes << 3) {
242
+ num_bits = static_cast<uint32_t>(kMaximumBloomFilterBytes << 3);
243
+ } else {
244
+ num_bits = static_cast<uint32_t>(m);
245
+ }
246
+
247
+ // Round up to lower bound
248
+ if (num_bits < kMinimumBloomFilterBytes << 3) {
249
+ num_bits = kMinimumBloomFilterBytes << 3;
250
+ }
251
+
252
+ // Get next power of 2 if bits is not power of 2.
253
+ if ((num_bits & (num_bits - 1)) != 0) {
254
+ num_bits = static_cast<uint32_t>(::arrow::bit_util::NextPower2(num_bits));
255
+ }
256
+
257
+ // Round down to upper bound
258
+ if (num_bits > kMaximumBloomFilterBytes << 3) {
259
+ num_bits = kMaximumBloomFilterBytes << 3;
260
+ }
261
+
262
+ return num_bits;
263
+ }
264
+
265
+ bool FindHash(uint64_t hash) const override;
266
+ void InsertHash(uint64_t hash) override;
267
+ void InsertHashes(const uint64_t* hashes, int num_values) override;
268
+ void WriteTo(ArrowOutputStream* sink) const override;
269
+ uint32_t GetBitsetSize() const override { return num_bytes_; }
270
+
271
+ uint64_t Hash(int32_t value) const override { return hasher_->Hash(value); }
272
+ uint64_t Hash(int64_t value) const override { return hasher_->Hash(value); }
273
+ uint64_t Hash(float value) const override { return hasher_->Hash(value); }
274
+ uint64_t Hash(double value) const override { return hasher_->Hash(value); }
275
+ uint64_t Hash(const Int96* value) const override { return hasher_->Hash(value); }
276
+ uint64_t Hash(const ByteArray* value) const override { return hasher_->Hash(value); }
277
+ uint64_t Hash(const FLBA* value, uint32_t len) const override {
278
+ return hasher_->Hash(value, len);
279
+ }
280
+
281
+ void Hashes(const int32_t* values, int num_values, uint64_t* hashes) const override {
282
+ hasher_->Hashes(values, num_values, hashes);
283
+ }
284
+ void Hashes(const int64_t* values, int num_values, uint64_t* hashes) const override {
285
+ hasher_->Hashes(values, num_values, hashes);
286
+ }
287
+ void Hashes(const float* values, int num_values, uint64_t* hashes) const override {
288
+ hasher_->Hashes(values, num_values, hashes);
289
+ }
290
+ void Hashes(const double* values, int num_values, uint64_t* hashes) const override {
291
+ hasher_->Hashes(values, num_values, hashes);
292
+ }
293
+ void Hashes(const Int96* values, int num_values, uint64_t* hashes) const override {
294
+ hasher_->Hashes(values, num_values, hashes);
295
+ }
296
+ void Hashes(const ByteArray* values, int num_values, uint64_t* hashes) const override {
297
+ hasher_->Hashes(values, num_values, hashes);
298
+ }
299
+ void Hashes(const FLBA* values, uint32_t type_len, int num_values,
300
+ uint64_t* hashes) const override {
301
+ hasher_->Hashes(values, type_len, num_values, hashes);
302
+ }
303
+
304
+ uint64_t Hash(const int32_t* value) const { return hasher_->Hash(*value); }
305
+ uint64_t Hash(const int64_t* value) const { return hasher_->Hash(*value); }
306
+ uint64_t Hash(const float* value) const { return hasher_->Hash(*value); }
307
+ uint64_t Hash(const double* value) const { return hasher_->Hash(*value); }
308
+
309
+ /// Deserialize the Bloom filter from an input stream. It is used when reconstructing
310
+ /// a Bloom filter from a parquet filter.
311
+ ///
312
+ /// @param properties The parquet reader properties.
313
+ /// @param input_stream The input stream from which to construct the bloom filter.
314
+ /// @param bloom_filter_length The length of the serialized bloom filter including
315
+ /// header.
316
+ /// @return The BlockSplitBloomFilter.
317
+ static BlockSplitBloomFilter Deserialize(
318
+ const ReaderProperties& properties, ArrowInputStream* input_stream,
319
+ std::optional<int64_t> bloom_filter_length = std::nullopt);
320
+
321
+ private:
322
+ inline void InsertHashImpl(uint64_t hash);
323
+
324
+ // Bytes in a tiny Bloom filter block.
325
+ static constexpr int kBytesPerFilterBlock = 32;
326
+
327
+ // The number of bits to be set in each tiny Bloom filter
328
+ static constexpr int kBitsSetPerBlock = 8;
329
+
330
+ // A mask structure used to set bits in each tiny Bloom filter.
331
+ struct BlockMask {
332
+ uint32_t item[kBitsSetPerBlock];
333
+ };
334
+
335
+ // The block-based algorithm needs eight odd SALT values to calculate eight indexes
336
+ // of bit to set, one bit in each 32-bit word.
337
+ static constexpr uint32_t SALT[kBitsSetPerBlock] = {
338
+ 0x47b6137bU, 0x44974d91U, 0x8824ad5bU, 0xa2b7289dU,
339
+ 0x705495c7U, 0x2df1424bU, 0x9efc4947U, 0x5c6bfb31U};
340
+
341
+ // Memory pool to allocate aligned buffer for bitset
342
+ ::arrow::MemoryPool* pool_;
343
+
344
+ // The underlying buffer of bitset.
345
+ std::shared_ptr<Buffer> data_;
346
+
347
+ // The number of bytes of Bloom filter bitset.
348
+ uint32_t num_bytes_;
349
+
350
+ // Hash strategy used in this Bloom filter.
351
+ HashStrategy hash_strategy_;
352
+
353
+ // Algorithm used in this Bloom filter.
354
+ Algorithm algorithm_;
355
+
356
+ // Compression used in this Bloom filter.
357
+ CompressionStrategy compression_strategy_;
358
+
359
+ // The hash pointer points to actual hash class used.
360
+ std::unique_ptr<Hasher> hasher_;
361
+ };
362
+
363
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter_reader.h ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "arrow/io/interfaces.h"
21
+ #include "parquet/properties.h"
22
+ #include "parquet/type_fwd.h"
23
+
24
+ namespace parquet {
25
+
26
+ class InternalFileDecryptor;
27
+ class BloomFilter;
28
+
29
+ class PARQUET_EXPORT RowGroupBloomFilterReader {
30
+ public:
31
+ virtual ~RowGroupBloomFilterReader() = default;
32
+
33
+ /// \brief Read bloom filter of a column chunk.
34
+ ///
35
+ /// \param[in] i column ordinal of the column chunk.
36
+ /// \returns bloom filter of the column or nullptr if it does not exist.
37
+ /// \throws ParquetException if the index is out of bound, or read bloom
38
+ /// filter failed.
39
+ virtual std::unique_ptr<BloomFilter> GetColumnBloomFilter(int i) = 0;
40
+ };
41
+
42
+ /// \brief Interface for reading the bloom filter for a Parquet file.
43
+ class PARQUET_EXPORT BloomFilterReader {
44
+ public:
45
+ virtual ~BloomFilterReader() = default;
46
+
47
+ /// \brief Create a BloomFilterReader instance.
48
+ /// \returns a BloomFilterReader instance.
49
+ /// WARNING: The returned BloomFilterReader references to all the input parameters, so
50
+ /// it must not outlive all of the input parameters. Usually these input parameters
51
+ /// come from the same ParquetFileReader object, so it must not outlive the reader
52
+ /// that creates this BloomFilterReader.
53
+ static std::unique_ptr<BloomFilterReader> Make(
54
+ std::shared_ptr<::arrow::io::RandomAccessFile> input,
55
+ std::shared_ptr<FileMetaData> file_metadata, const ReaderProperties& properties,
56
+ std::shared_ptr<InternalFileDecryptor> file_decryptor = NULLPTR);
57
+
58
+ /// \brief Get the bloom filter reader of a specific row group.
59
+ /// \param[in] i row group ordinal to get bloom filter reader.
60
+ /// \returns RowGroupBloomFilterReader of the specified row group. A nullptr may or may
61
+ /// not be returned if the bloom filter for the row group is unavailable. It
62
+ /// is the caller's responsibility to check the return value of follow-up calls
63
+ /// to the RowGroupBloomFilterReader.
64
+ /// \throws ParquetException if the index is out of bound.
65
+ virtual std::shared_ptr<RowGroupBloomFilterReader> RowGroup(int i) = 0;
66
+ };
67
+
68
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/column_page.h ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // This module defines an abstract interface for iterating through pages in a
19
+ // Parquet column chunk within a row group. It could be extended in the future
20
+ // to iterate through all data pages in all chunks in a file.
21
+
22
+ #pragma once
23
+
24
+ #include <cstdint>
25
+ #include <memory>
26
+ #include <optional>
27
+ #include <string>
28
+
29
+ #include "parquet/statistics.h"
30
+ #include "parquet/types.h"
31
+
32
+ namespace parquet {
33
+
34
+ // TODO: Parallel processing is not yet safe because of memory-ownership
35
+ // semantics (the PageReader may or may not own the memory referenced by a
36
+ // page)
37
+ //
38
+ // TODO(wesm): In the future Parquet implementations may store the crc code
39
+ // in format::PageHeader. parquet-mr currently does not, so we also skip it
40
+ // here, both on the read and write path
41
+ class Page {
42
+ public:
43
+ Page(const std::shared_ptr<Buffer>& buffer, PageType::type type)
44
+ : buffer_(buffer), type_(type) {}
45
+
46
+ PageType::type type() const { return type_; }
47
+
48
+ std::shared_ptr<Buffer> buffer() const { return buffer_; }
49
+
50
+ // @returns: a pointer to the page's data
51
+ const uint8_t* data() const { return buffer_->data(); }
52
+
53
+ // @returns: the total size in bytes of the page's data buffer
54
+ int32_t size() const { return static_cast<int32_t>(buffer_->size()); }
55
+
56
+ private:
57
+ std::shared_ptr<Buffer> buffer_;
58
+ PageType::type type_;
59
+ };
60
+
61
+ /// \brief Base type for DataPageV1 and DataPageV2 including common attributes
62
+ class DataPage : public Page {
63
+ public:
64
+ int32_t num_values() const { return num_values_; }
65
+ Encoding::type encoding() const { return encoding_; }
66
+ int64_t uncompressed_size() const { return uncompressed_size_; }
67
+ const EncodedStatistics& statistics() const { return statistics_; }
68
+ /// Return the row ordinal within the row group to the first row in the data page.
69
+ /// Currently it is only present from data pages created by ColumnWriter in order
70
+ /// to collect page index.
71
+ std::optional<int64_t> first_row_index() const { return first_row_index_; }
72
+
73
+ virtual ~DataPage() = default;
74
+
75
+ protected:
76
+ DataPage(PageType::type type, const std::shared_ptr<Buffer>& buffer, int32_t num_values,
77
+ Encoding::type encoding, int64_t uncompressed_size,
78
+ const EncodedStatistics& statistics = EncodedStatistics(),
79
+ std::optional<int64_t> first_row_index = std::nullopt)
80
+ : Page(buffer, type),
81
+ num_values_(num_values),
82
+ encoding_(encoding),
83
+ uncompressed_size_(uncompressed_size),
84
+ statistics_(statistics),
85
+ first_row_index_(std::move(first_row_index)) {}
86
+
87
+ int32_t num_values_;
88
+ Encoding::type encoding_;
89
+ int64_t uncompressed_size_;
90
+ EncodedStatistics statistics_;
91
+ /// Row ordinal within the row group to the first row in the data page.
92
+ std::optional<int64_t> first_row_index_;
93
+ };
94
+
95
+ class DataPageV1 : public DataPage {
96
+ public:
97
+ DataPageV1(const std::shared_ptr<Buffer>& buffer, int32_t num_values,
98
+ Encoding::type encoding, Encoding::type definition_level_encoding,
99
+ Encoding::type repetition_level_encoding, int64_t uncompressed_size,
100
+ const EncodedStatistics& statistics = EncodedStatistics(),
101
+ std::optional<int64_t> first_row_index = std::nullopt)
102
+ : DataPage(PageType::DATA_PAGE, buffer, num_values, encoding, uncompressed_size,
103
+ statistics, std::move(first_row_index)),
104
+ definition_level_encoding_(definition_level_encoding),
105
+ repetition_level_encoding_(repetition_level_encoding) {}
106
+
107
+ Encoding::type repetition_level_encoding() const { return repetition_level_encoding_; }
108
+
109
+ Encoding::type definition_level_encoding() const { return definition_level_encoding_; }
110
+
111
+ private:
112
+ Encoding::type definition_level_encoding_;
113
+ Encoding::type repetition_level_encoding_;
114
+ };
115
+
116
+ class DataPageV2 : public DataPage {
117
+ public:
118
+ DataPageV2(const std::shared_ptr<Buffer>& buffer, int32_t num_values, int32_t num_nulls,
119
+ int32_t num_rows, Encoding::type encoding,
120
+ int32_t definition_levels_byte_length, int32_t repetition_levels_byte_length,
121
+ int64_t uncompressed_size, bool is_compressed = false,
122
+ const EncodedStatistics& statistics = EncodedStatistics(),
123
+ std::optional<int64_t> first_row_index = std::nullopt)
124
+ : DataPage(PageType::DATA_PAGE_V2, buffer, num_values, encoding, uncompressed_size,
125
+ statistics, std::move(first_row_index)),
126
+ num_nulls_(num_nulls),
127
+ num_rows_(num_rows),
128
+ definition_levels_byte_length_(definition_levels_byte_length),
129
+ repetition_levels_byte_length_(repetition_levels_byte_length),
130
+ is_compressed_(is_compressed) {}
131
+
132
+ int32_t num_nulls() const { return num_nulls_; }
133
+
134
+ int32_t num_rows() const { return num_rows_; }
135
+
136
+ int32_t definition_levels_byte_length() const { return definition_levels_byte_length_; }
137
+
138
+ int32_t repetition_levels_byte_length() const { return repetition_levels_byte_length_; }
139
+
140
+ bool is_compressed() const { return is_compressed_; }
141
+
142
+ private:
143
+ int32_t num_nulls_;
144
+ int32_t num_rows_;
145
+ int32_t definition_levels_byte_length_;
146
+ int32_t repetition_levels_byte_length_;
147
+ bool is_compressed_;
148
+ };
149
+
150
+ class DictionaryPage : public Page {
151
+ public:
152
+ DictionaryPage(const std::shared_ptr<Buffer>& buffer, int32_t num_values,
153
+ Encoding::type encoding, bool is_sorted = false)
154
+ : Page(buffer, PageType::DICTIONARY_PAGE),
155
+ num_values_(num_values),
156
+ encoding_(encoding),
157
+ is_sorted_(is_sorted) {}
158
+
159
+ int32_t num_values() const { return num_values_; }
160
+
161
+ Encoding::type encoding() const { return encoding_; }
162
+
163
+ bool is_sorted() const { return is_sorted_; }
164
+
165
+ private:
166
+ int32_t num_values_;
167
+ Encoding::type encoding_;
168
+ bool is_sorted_;
169
+ };
170
+
171
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/column_scanner.h ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <stdio.h>
21
+
22
+ #include <cstdint>
23
+ #include <memory>
24
+ #include <ostream>
25
+ #include <string>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ #include "parquet/column_reader.h"
30
+ #include "parquet/exception.h"
31
+ #include "parquet/platform.h"
32
+ #include "parquet/schema.h"
33
+ #include "parquet/types.h"
34
+
35
+ namespace parquet {
36
+
37
+ static constexpr int64_t DEFAULT_SCANNER_BATCH_SIZE = 128;
38
+
39
+ class PARQUET_EXPORT Scanner {
40
+ public:
41
+ explicit Scanner(std::shared_ptr<ColumnReader> reader,
42
+ int64_t batch_size = DEFAULT_SCANNER_BATCH_SIZE,
43
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool())
44
+ : batch_size_(batch_size),
45
+ level_offset_(0),
46
+ levels_buffered_(0),
47
+ value_buffer_(AllocateBuffer(pool)),
48
+ value_offset_(0),
49
+ values_buffered_(0),
50
+ reader_(std::move(reader)) {
51
+ def_levels_.resize(
52
+ descr()->max_definition_level() > 0 ? static_cast<size_t>(batch_size_) : 0);
53
+ rep_levels_.resize(
54
+ descr()->max_repetition_level() > 0 ? static_cast<size_t>(batch_size_) : 0);
55
+ }
56
+
57
+ virtual ~Scanner() {}
58
+
59
+ static std::shared_ptr<Scanner> Make(
60
+ std::shared_ptr<ColumnReader> col_reader,
61
+ int64_t batch_size = DEFAULT_SCANNER_BATCH_SIZE,
62
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
63
+
64
+ virtual void PrintNext(std::ostream& out, int width, bool with_levels = false) = 0;
65
+
66
+ bool HasNext() { return level_offset_ < levels_buffered_ || reader_->HasNext(); }
67
+
68
+ const ColumnDescriptor* descr() const { return reader_->descr(); }
69
+
70
+ int64_t batch_size() const { return batch_size_; }
71
+
72
+ void SetBatchSize(int64_t batch_size) { batch_size_ = batch_size; }
73
+
74
+ protected:
75
+ int64_t batch_size_;
76
+
77
+ std::vector<int16_t> def_levels_;
78
+ std::vector<int16_t> rep_levels_;
79
+ int level_offset_;
80
+ int levels_buffered_;
81
+
82
+ std::shared_ptr<ResizableBuffer> value_buffer_;
83
+ int value_offset_;
84
+ int64_t values_buffered_;
85
+ std::shared_ptr<ColumnReader> reader_;
86
+ };
87
+
88
+ template <typename DType>
89
+ class PARQUET_TEMPLATE_CLASS_EXPORT TypedScanner : public Scanner {
90
+ public:
91
+ typedef typename DType::c_type T;
92
+
93
+ explicit TypedScanner(std::shared_ptr<ColumnReader> reader,
94
+ int64_t batch_size = DEFAULT_SCANNER_BATCH_SIZE,
95
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool())
96
+ : Scanner(std::move(reader), batch_size, pool) {
97
+ typed_reader_ = static_cast<TypedColumnReader<DType>*>(reader_.get());
98
+ int value_byte_size = type_traits<DType::type_num>::value_byte_size;
99
+ PARQUET_THROW_NOT_OK(value_buffer_->Resize(batch_size_ * value_byte_size));
100
+ values_ = reinterpret_cast<T*>(value_buffer_->mutable_data());
101
+ }
102
+
103
+ virtual ~TypedScanner() {}
104
+
105
+ bool NextLevels(int16_t* def_level, int16_t* rep_level) {
106
+ if (level_offset_ == levels_buffered_) {
107
+ levels_buffered_ = static_cast<int>(
108
+ typed_reader_->ReadBatch(static_cast<int>(batch_size_), def_levels_.data(),
109
+ rep_levels_.data(), values_, &values_buffered_));
110
+
111
+ value_offset_ = 0;
112
+ level_offset_ = 0;
113
+ if (!levels_buffered_) {
114
+ return false;
115
+ }
116
+ }
117
+ *def_level = descr()->max_definition_level() > 0 ? def_levels_[level_offset_] : 0;
118
+ *rep_level = descr()->max_repetition_level() > 0 ? rep_levels_[level_offset_] : 0;
119
+ level_offset_++;
120
+ return true;
121
+ }
122
+
123
+ bool Next(T* val, int16_t* def_level, int16_t* rep_level, bool* is_null) {
124
+ if (level_offset_ == levels_buffered_) {
125
+ if (!HasNext()) {
126
+ // Out of data pages
127
+ return false;
128
+ }
129
+ }
130
+
131
+ NextLevels(def_level, rep_level);
132
+ *is_null = *def_level < descr()->max_definition_level();
133
+
134
+ if (*is_null) {
135
+ return true;
136
+ }
137
+
138
+ if (value_offset_ == values_buffered_) {
139
+ throw ParquetException("Value was non-null, but has not been buffered");
140
+ }
141
+ *val = values_[value_offset_++];
142
+ return true;
143
+ }
144
+
145
+ // Returns true if there is a next value
146
+ bool NextValue(T* val, bool* is_null) {
147
+ if (level_offset_ == levels_buffered_) {
148
+ if (!HasNext()) {
149
+ // Out of data pages
150
+ return false;
151
+ }
152
+ }
153
+
154
+ // Out of values
155
+ int16_t def_level = -1;
156
+ int16_t rep_level = -1;
157
+ NextLevels(&def_level, &rep_level);
158
+ *is_null = def_level < descr()->max_definition_level();
159
+
160
+ if (*is_null) {
161
+ return true;
162
+ }
163
+
164
+ if (value_offset_ == values_buffered_) {
165
+ throw ParquetException("Value was non-null, but has not been buffered");
166
+ }
167
+ *val = values_[value_offset_++];
168
+ return true;
169
+ }
170
+
171
+ virtual void PrintNext(std::ostream& out, int width, bool with_levels = false) {
172
+ T val{};
173
+ int16_t def_level = -1;
174
+ int16_t rep_level = -1;
175
+ bool is_null = false;
176
+ char buffer[80];
177
+
178
+ if (!Next(&val, &def_level, &rep_level, &is_null)) {
179
+ throw ParquetException("No more values buffered");
180
+ }
181
+
182
+ if (with_levels) {
183
+ out << " D:" << def_level << " R:" << rep_level << " ";
184
+ if (!is_null) {
185
+ out << "V:";
186
+ }
187
+ }
188
+
189
+ if (is_null) {
190
+ std::string null_fmt = format_fwf<ByteArrayType>(width);
191
+ snprintf(buffer, sizeof(buffer), null_fmt.c_str(), "NULL");
192
+ } else {
193
+ FormatValue(&val, buffer, sizeof(buffer), width);
194
+ }
195
+ out << buffer;
196
+ }
197
+
198
+ private:
199
+ // The ownership of this object is expressed through the reader_ variable in the base
200
+ TypedColumnReader<DType>* typed_reader_;
201
+
202
+ inline void FormatValue(void* val, char* buffer, int bufsize, int width);
203
+
204
+ T* values_;
205
+ };
206
+
207
+ template <typename DType>
208
+ inline void TypedScanner<DType>::FormatValue(void* val, char* buffer, int bufsize,
209
+ int width) {
210
+ std::string fmt = format_fwf<DType>(width);
211
+ snprintf(buffer, bufsize, fmt.c_str(), *reinterpret_cast<T*>(val));
212
+ }
213
+
214
+ template <>
215
+ inline void TypedScanner<Int96Type>::FormatValue(void* val, char* buffer, int bufsize,
216
+ int width) {
217
+ std::string fmt = format_fwf<Int96Type>(width);
218
+ std::string result = Int96ToString(*reinterpret_cast<Int96*>(val));
219
+ snprintf(buffer, bufsize, fmt.c_str(), result.c_str());
220
+ }
221
+
222
+ template <>
223
+ inline void TypedScanner<ByteArrayType>::FormatValue(void* val, char* buffer, int bufsize,
224
+ int width) {
225
+ std::string fmt = format_fwf<ByteArrayType>(width);
226
+ std::string result = ByteArrayToString(*reinterpret_cast<ByteArray*>(val));
227
+ snprintf(buffer, bufsize, fmt.c_str(), result.c_str());
228
+ }
229
+
230
+ template <>
231
+ inline void TypedScanner<FLBAType>::FormatValue(void* val, char* buffer, int bufsize,
232
+ int width) {
233
+ std::string fmt = format_fwf<FLBAType>(width);
234
+ std::string result = FixedLenByteArrayToString(
235
+ *reinterpret_cast<FixedLenByteArray*>(val), descr()->type_length());
236
+ snprintf(buffer, bufsize, fmt.c_str(), result.c_str());
237
+ }
238
+
239
+ typedef TypedScanner<BooleanType> BoolScanner;
240
+ typedef TypedScanner<Int32Type> Int32Scanner;
241
+ typedef TypedScanner<Int64Type> Int64Scanner;
242
+ typedef TypedScanner<Int96Type> Int96Scanner;
243
+ typedef TypedScanner<FloatType> FloatScanner;
244
+ typedef TypedScanner<DoubleType> DoubleScanner;
245
+ typedef TypedScanner<ByteArrayType> ByteArrayScanner;
246
+ typedef TypedScanner<FLBAType> FixedLenByteArrayScanner;
247
+
248
+ template <typename RType>
249
+ int64_t ScanAll(int32_t batch_size, int16_t* def_levels, int16_t* rep_levels,
250
+ uint8_t* values, int64_t* values_buffered,
251
+ parquet::ColumnReader* reader) {
252
+ typedef typename RType::T Type;
253
+ auto typed_reader = static_cast<RType*>(reader);
254
+ auto vals = reinterpret_cast<Type*>(&values[0]);
255
+ return typed_reader->ReadBatch(batch_size, def_levels, rep_levels, vals,
256
+ values_buffered);
257
+ }
258
+
259
+ int64_t PARQUET_EXPORT ScanAllValues(int32_t batch_size, int16_t* def_levels,
260
+ int16_t* rep_levels, uint8_t* values,
261
+ int64_t* values_buffered,
262
+ parquet::ColumnReader* reader);
263
+
264
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.h ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <cstring>
22
+ #include <memory>
23
+ #include <vector>
24
+
25
+ #include "arrow/util/spaced.h"
26
+
27
+ #include "parquet/exception.h"
28
+ #include "parquet/platform.h"
29
+ #include "parquet/types.h"
30
+
31
+ namespace arrow {
32
+
33
+ class Array;
34
+ class ArrayBuilder;
35
+ class BinaryArray;
36
+ class BinaryBuilder;
37
+ class BooleanBuilder;
38
+ class Int32Type;
39
+ class Int64Type;
40
+ class FloatType;
41
+ class DoubleType;
42
+ class FixedSizeBinaryType;
43
+ template <typename T>
44
+ class NumericBuilder;
45
+ class FixedSizeBinaryBuilder;
46
+ template <typename T>
47
+ class Dictionary32Builder;
48
+
49
+ } // namespace arrow
50
+
51
+ namespace parquet {
52
+
53
+ template <typename DType>
54
+ class TypedEncoder;
55
+
56
+ using BooleanEncoder = TypedEncoder<BooleanType>;
57
+ using Int32Encoder = TypedEncoder<Int32Type>;
58
+ using Int64Encoder = TypedEncoder<Int64Type>;
59
+ using Int96Encoder = TypedEncoder<Int96Type>;
60
+ using FloatEncoder = TypedEncoder<FloatType>;
61
+ using DoubleEncoder = TypedEncoder<DoubleType>;
62
+ using ByteArrayEncoder = TypedEncoder<ByteArrayType>;
63
+ using FLBAEncoder = TypedEncoder<FLBAType>;
64
+
65
+ template <typename DType>
66
+ class TypedDecoder;
67
+
68
+ class BooleanDecoder;
69
+ using Int32Decoder = TypedDecoder<Int32Type>;
70
+ using Int64Decoder = TypedDecoder<Int64Type>;
71
+ using Int96Decoder = TypedDecoder<Int96Type>;
72
+ using FloatDecoder = TypedDecoder<FloatType>;
73
+ using DoubleDecoder = TypedDecoder<DoubleType>;
74
+ using ByteArrayDecoder = TypedDecoder<ByteArrayType>;
75
+ class FLBADecoder;
76
+
77
+ template <typename T>
78
+ struct EncodingTraits;
79
+
80
+ template <>
81
+ struct EncodingTraits<BooleanType> {
82
+ using Encoder = BooleanEncoder;
83
+ using Decoder = BooleanDecoder;
84
+
85
+ using ArrowType = ::arrow::BooleanType;
86
+ using Accumulator = ::arrow::BooleanBuilder;
87
+ struct DictAccumulator {};
88
+ };
89
+
90
+ template <>
91
+ struct EncodingTraits<Int32Type> {
92
+ using Encoder = Int32Encoder;
93
+ using Decoder = Int32Decoder;
94
+
95
+ using ArrowType = ::arrow::Int32Type;
96
+ using Accumulator = ::arrow::NumericBuilder<::arrow::Int32Type>;
97
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::Int32Type>;
98
+ };
99
+
100
+ template <>
101
+ struct EncodingTraits<Int64Type> {
102
+ using Encoder = Int64Encoder;
103
+ using Decoder = Int64Decoder;
104
+
105
+ using ArrowType = ::arrow::Int64Type;
106
+ using Accumulator = ::arrow::NumericBuilder<::arrow::Int64Type>;
107
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::Int64Type>;
108
+ };
109
+
110
+ template <>
111
+ struct EncodingTraits<Int96Type> {
112
+ using Encoder = Int96Encoder;
113
+ using Decoder = Int96Decoder;
114
+
115
+ struct Accumulator {};
116
+ struct DictAccumulator {};
117
+ };
118
+
119
+ template <>
120
+ struct EncodingTraits<FloatType> {
121
+ using Encoder = FloatEncoder;
122
+ using Decoder = FloatDecoder;
123
+
124
+ using ArrowType = ::arrow::FloatType;
125
+ using Accumulator = ::arrow::NumericBuilder<::arrow::FloatType>;
126
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::FloatType>;
127
+ };
128
+
129
+ template <>
130
+ struct EncodingTraits<DoubleType> {
131
+ using Encoder = DoubleEncoder;
132
+ using Decoder = DoubleDecoder;
133
+
134
+ using ArrowType = ::arrow::DoubleType;
135
+ using Accumulator = ::arrow::NumericBuilder<::arrow::DoubleType>;
136
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::DoubleType>;
137
+ };
138
+
139
+ template <>
140
+ struct EncodingTraits<ByteArrayType> {
141
+ using Encoder = ByteArrayEncoder;
142
+ using Decoder = ByteArrayDecoder;
143
+
144
+ using ArrowType = ::arrow::BinaryType;
145
+ /// \brief Internal helper class for decoding BYTE_ARRAY data where we can
146
+ /// overflow the capacity of a single arrow::BinaryArray
147
+ struct Accumulator {
148
+ std::unique_ptr<::arrow::BinaryBuilder> builder;
149
+ std::vector<std::shared_ptr<::arrow::Array>> chunks;
150
+ };
151
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::BinaryType>;
152
+ };
153
+
154
+ template <>
155
+ struct EncodingTraits<FLBAType> {
156
+ using Encoder = FLBAEncoder;
157
+ using Decoder = FLBADecoder;
158
+
159
+ using ArrowType = ::arrow::FixedSizeBinaryType;
160
+ using Accumulator = ::arrow::FixedSizeBinaryBuilder;
161
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::FixedSizeBinaryType>;
162
+ };
163
+
164
+ class ColumnDescriptor;
165
+
166
+ // Untyped base for all encoders
167
+ class Encoder {
168
+ public:
169
+ virtual ~Encoder() = default;
170
+
171
+ virtual int64_t EstimatedDataEncodedSize() = 0;
172
+ virtual std::shared_ptr<Buffer> FlushValues() = 0;
173
+ virtual Encoding::type encoding() const = 0;
174
+
175
+ virtual void Put(const ::arrow::Array& values) = 0;
176
+
177
+ virtual MemoryPool* memory_pool() const = 0;
178
+ };
179
+
180
+ // Base class for value encoders. Since encoders may or not have state (e.g.,
181
+ // dictionary encoding) we use a class instance to maintain any state.
182
+ //
183
+ // Encode interfaces are internal, subject to change without deprecation.
184
+ template <typename DType>
185
+ class TypedEncoder : virtual public Encoder {
186
+ public:
187
+ typedef typename DType::c_type T;
188
+
189
+ using Encoder::Put;
190
+
191
+ virtual void Put(const T* src, int num_values) = 0;
192
+
193
+ virtual void Put(const std::vector<T>& src, int num_values = -1);
194
+
195
+ virtual void PutSpaced(const T* src, int num_values, const uint8_t* valid_bits,
196
+ int64_t valid_bits_offset) = 0;
197
+ };
198
+
199
+ template <typename DType>
200
+ void TypedEncoder<DType>::Put(const std::vector<T>& src, int num_values) {
201
+ if (num_values == -1) {
202
+ num_values = static_cast<int>(src.size());
203
+ }
204
+ Put(src.data(), num_values);
205
+ }
206
+
207
+ template <>
208
+ inline void TypedEncoder<BooleanType>::Put(const std::vector<bool>& src, int num_values) {
209
+ // NOTE(wesm): This stub is here only to satisfy the compiler; it is
210
+ // overridden later with the actual implementation
211
+ }
212
+
213
+ // Base class for dictionary encoders
214
+ template <typename DType>
215
+ class DictEncoder : virtual public TypedEncoder<DType> {
216
+ public:
217
+ /// Writes out any buffered indices to buffer preceded by the bit width of this data.
218
+ /// Returns the number of bytes written.
219
+ /// If the supplied buffer is not big enough, returns -1.
220
+ /// buffer must be preallocated with buffer_len bytes. Use EstimatedDataEncodedSize()
221
+ /// to size buffer.
222
+ virtual int WriteIndices(uint8_t* buffer, int buffer_len) = 0;
223
+
224
+ virtual int dict_encoded_size() const = 0;
225
+
226
+ virtual int bit_width() const = 0;
227
+
228
+ /// Writes out the encoded dictionary to buffer. buffer must be preallocated to
229
+ /// dict_encoded_size() bytes.
230
+ virtual void WriteDict(uint8_t* buffer) const = 0;
231
+
232
+ virtual int num_entries() const = 0;
233
+
234
+ /// \brief EXPERIMENTAL: Append dictionary indices into the encoder. It is
235
+ /// assumed (without any boundschecking) that the indices reference
236
+ /// preexisting dictionary values
237
+ /// \param[in] indices the dictionary index values. Only Int32Array currently
238
+ /// supported
239
+ virtual void PutIndices(const ::arrow::Array& indices) = 0;
240
+
241
+ /// \brief EXPERIMENTAL: Append dictionary into encoder, inserting indices
242
+ /// separately. Currently throws exception if the current dictionary memo is
243
+ /// non-empty
244
+ /// \param[in] values the dictionary values. Only valid for certain
245
+ /// Parquet/Arrow type combinations, like BYTE_ARRAY/BinaryArray
246
+ virtual void PutDictionary(const ::arrow::Array& values) = 0;
247
+ };
248
+
249
+ // ----------------------------------------------------------------------
250
+ // Value decoding
251
+
252
+ class Decoder {
253
+ public:
254
+ virtual ~Decoder() = default;
255
+
256
+ // Sets the data for a new page. This will be called multiple times on the same
257
+ // decoder and should reset all internal state.
258
+ virtual void SetData(int num_values, const uint8_t* data, int len) = 0;
259
+
260
+ // Returns the number of values left (for the last call to SetData()). This is
261
+ // the number of values left in this page.
262
+ virtual int values_left() const = 0;
263
+ virtual Encoding::type encoding() const = 0;
264
+ };
265
+
266
+ template <typename DType>
267
+ class TypedDecoder : virtual public Decoder {
268
+ public:
269
+ using T = typename DType::c_type;
270
+
271
+ /// \brief Decode values into a buffer
272
+ ///
273
+ /// Subclasses may override the more specialized Decode methods below.
274
+ ///
275
+ /// \param[in] buffer destination for decoded values
276
+ /// \param[in] max_values maximum number of values to decode
277
+ /// \return The number of values decoded. Should be identical to max_values except
278
+ /// at the end of the current data page.
279
+ virtual int Decode(T* buffer, int max_values) = 0;
280
+
281
+ /// \brief Decode the values in this data page but leave spaces for null entries.
282
+ ///
283
+ /// \param[in] buffer destination for decoded values
284
+ /// \param[in] num_values size of the def_levels and buffer arrays including the number
285
+ /// of null slots
286
+ /// \param[in] null_count number of null slots
287
+ /// \param[in] valid_bits bitmap data indicating position of valid slots
288
+ /// \param[in] valid_bits_offset offset into valid_bits
289
+ /// \return The number of values decoded, including nulls.
290
+ virtual int DecodeSpaced(T* buffer, int num_values, int null_count,
291
+ const uint8_t* valid_bits, int64_t valid_bits_offset) {
292
+ if (null_count > 0) {
293
+ int values_to_read = num_values - null_count;
294
+ int values_read = Decode(buffer, values_to_read);
295
+ if (values_read != values_to_read) {
296
+ throw ParquetException("Number of values / definition_levels read did not match");
297
+ }
298
+
299
+ return ::arrow::util::internal::SpacedExpand<T>(buffer, num_values, null_count,
300
+ valid_bits, valid_bits_offset);
301
+ } else {
302
+ return Decode(buffer, num_values);
303
+ }
304
+ }
305
+
306
+ /// \brief Decode into an ArrayBuilder or other accumulator
307
+ ///
308
+ /// This function assumes the definition levels were already decoded
309
+ /// as a validity bitmap in the given `valid_bits`. `null_count`
310
+ /// is the number of 0s in `valid_bits`.
311
+ /// As a space optimization, it is allowed for `valid_bits` to be null
312
+ /// if `null_count` is zero.
313
+ ///
314
+ /// \return number of values decoded
315
+ virtual int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
316
+ int64_t valid_bits_offset,
317
+ typename EncodingTraits<DType>::Accumulator* out) = 0;
318
+
319
+ /// \brief Decode into an ArrayBuilder or other accumulator ignoring nulls
320
+ ///
321
+ /// \return number of values decoded
322
+ int DecodeArrowNonNull(int num_values,
323
+ typename EncodingTraits<DType>::Accumulator* out) {
324
+ return DecodeArrow(num_values, 0, /*valid_bits=*/NULLPTR, 0, out);
325
+ }
326
+
327
+ /// \brief Decode into a DictionaryBuilder
328
+ ///
329
+ /// This function assumes the definition levels were already decoded
330
+ /// as a validity bitmap in the given `valid_bits`. `null_count`
331
+ /// is the number of 0s in `valid_bits`.
332
+ /// As a space optimization, it is allowed for `valid_bits` to be null
333
+ /// if `null_count` is zero.
334
+ ///
335
+ /// \return number of values decoded
336
+ virtual int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
337
+ int64_t valid_bits_offset,
338
+ typename EncodingTraits<DType>::DictAccumulator* builder) = 0;
339
+
340
+ /// \brief Decode into a DictionaryBuilder ignoring nulls
341
+ ///
342
+ /// \return number of values decoded
343
+ int DecodeArrowNonNull(int num_values,
344
+ typename EncodingTraits<DType>::DictAccumulator* builder) {
345
+ return DecodeArrow(num_values, 0, /*valid_bits=*/NULLPTR, 0, builder);
346
+ }
347
+ };
348
+
349
+ template <typename DType>
350
+ class DictDecoder : virtual public TypedDecoder<DType> {
351
+ public:
352
+ using T = typename DType::c_type;
353
+
354
+ virtual void SetDict(TypedDecoder<DType>* dictionary) = 0;
355
+
356
+ /// \brief Insert dictionary values into the Arrow dictionary builder's memo,
357
+ /// but do not append any indices
358
+ virtual void InsertDictionary(::arrow::ArrayBuilder* builder) = 0;
359
+
360
+ /// \brief Decode only dictionary indices and append to dictionary
361
+ /// builder. The builder must have had the dictionary from this decoder
362
+ /// inserted already.
363
+ ///
364
+ /// \warning Remember to reset the builder each time the dict decoder is initialized
365
+ /// with a new dictionary page
366
+ virtual int DecodeIndicesSpaced(int num_values, int null_count,
367
+ const uint8_t* valid_bits, int64_t valid_bits_offset,
368
+ ::arrow::ArrayBuilder* builder) = 0;
369
+
370
+ /// \brief Decode only dictionary indices (no nulls)
371
+ ///
372
+ /// \warning Remember to reset the builder each time the dict decoder is initialized
373
+ /// with a new dictionary page
374
+ virtual int DecodeIndices(int num_values, ::arrow::ArrayBuilder* builder) = 0;
375
+
376
+ /// \brief Decode only dictionary indices (no nulls). Same as above
377
+ /// DecodeIndices but target is an array instead of a builder.
378
+ ///
379
+ /// \note API EXPERIMENTAL
380
+ virtual int DecodeIndices(int num_values, int32_t* indices) = 0;
381
+
382
+ /// \brief Get dictionary. The reader will call this API when it encounters a
383
+ /// new dictionary.
384
+ ///
385
+ /// @param[out] dictionary The pointer to dictionary values. Dictionary is owned by
386
+ /// the decoder and is destroyed when the decoder is destroyed.
387
+ /// @param[out] dictionary_length The dictionary length.
388
+ ///
389
+ /// \note API EXPERIMENTAL
390
+ virtual void GetDictionary(const T** dictionary, int32_t* dictionary_length) = 0;
391
+ };
392
+
393
+ // ----------------------------------------------------------------------
394
+ // TypedEncoder specializations, traits, and factory functions
395
+
396
+ class BooleanDecoder : virtual public TypedDecoder<BooleanType> {
397
+ public:
398
+ using TypedDecoder<BooleanType>::Decode;
399
+
400
+ /// \brief Decode and bit-pack values into a buffer
401
+ ///
402
+ /// \param[in] buffer destination for decoded values
403
+ /// This buffer will contain bit-packed values.
404
+ /// \param[in] max_values max values to decode.
405
+ /// \return The number of values decoded. Should be identical to max_values except
406
+ /// at the end of the current data page.
407
+ virtual int Decode(uint8_t* buffer, int max_values) = 0;
408
+ };
409
+
410
+ class FLBADecoder : virtual public TypedDecoder<FLBAType> {
411
+ public:
412
+ using TypedDecoder<FLBAType>::DecodeSpaced;
413
+
414
+ // TODO(wesm): As possible follow-up to PARQUET-1508, we should examine if
415
+ // there is value in adding specialized read methods for
416
+ // FIXED_LEN_BYTE_ARRAY. If only Decimal data can occur with this data type
417
+ // then perhaps not
418
+ };
419
+
420
+ PARQUET_EXPORT
421
+ std::unique_ptr<Encoder> MakeEncoder(
422
+ Type::type type_num, Encoding::type encoding, bool use_dictionary = false,
423
+ const ColumnDescriptor* descr = NULLPTR,
424
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
425
+
426
+ template <typename DType>
427
+ std::unique_ptr<typename EncodingTraits<DType>::Encoder> MakeTypedEncoder(
428
+ Encoding::type encoding, bool use_dictionary = false,
429
+ const ColumnDescriptor* descr = NULLPTR,
430
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) {
431
+ using OutType = typename EncodingTraits<DType>::Encoder;
432
+ std::unique_ptr<Encoder> base =
433
+ MakeEncoder(DType::type_num, encoding, use_dictionary, descr, pool);
434
+ return std::unique_ptr<OutType>(dynamic_cast<OutType*>(base.release()));
435
+ }
436
+
437
+ PARQUET_EXPORT
438
+ std::unique_ptr<Decoder> MakeDecoder(
439
+ Type::type type_num, Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR,
440
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
441
+
442
+ namespace detail {
443
+
444
+ PARQUET_EXPORT
445
+ std::unique_ptr<Decoder> MakeDictDecoder(Type::type type_num,
446
+ const ColumnDescriptor* descr,
447
+ ::arrow::MemoryPool* pool);
448
+
449
+ } // namespace detail
450
+
451
+ template <typename DType>
452
+ std::unique_ptr<DictDecoder<DType>> MakeDictDecoder(
453
+ const ColumnDescriptor* descr = NULLPTR,
454
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) {
455
+ using OutType = DictDecoder<DType>;
456
+ auto decoder = detail::MakeDictDecoder(DType::type_num, descr, pool);
457
+ return std::unique_ptr<OutType>(dynamic_cast<OutType*>(decoder.release()));
458
+ }
459
+
460
+ template <typename DType>
461
+ std::unique_ptr<typename EncodingTraits<DType>::Decoder> MakeTypedDecoder(
462
+ Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR,
463
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) {
464
+ using OutType = typename EncodingTraits<DType>::Decoder;
465
+ std::unique_ptr<Decoder> base = MakeDecoder(DType::type_num, encoding, descr, pool);
466
+ return std::unique_ptr<OutType>(dynamic_cast<OutType*>(base.release()));
467
+ }
468
+
469
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.h ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+
22
+ #include "parquet/encryption/encryption.h"
23
+ #include "parquet/encryption/file_key_wrapper.h"
24
+ #include "parquet/encryption/key_toolkit.h"
25
+ #include "parquet/encryption/kms_client_factory.h"
26
+ #include "parquet/platform.h"
27
+
28
+ namespace parquet::encryption {
29
+
30
+ static constexpr ParquetCipher::type kDefaultEncryptionAlgorithm =
31
+ ParquetCipher::AES_GCM_V1;
32
+ static constexpr bool kDefaultPlaintextFooter = false;
33
+ static constexpr bool kDefaultDoubleWrapping = true;
34
+ static constexpr double kDefaultCacheLifetimeSeconds = 600; // 10 minutes
35
+ static constexpr bool kDefaultInternalKeyMaterial = true;
36
+ static constexpr bool kDefaultUniformEncryption = false;
37
+ static constexpr int32_t kDefaultDataKeyLengthBits = 128;
38
+
39
+ struct PARQUET_EXPORT EncryptionConfiguration {
40
+ explicit EncryptionConfiguration(const std::string& footer_key)
41
+ : footer_key(footer_key) {}
42
+
43
+ /// ID of the master key for footer encryption/signing
44
+ std::string footer_key;
45
+
46
+ /// List of columns to encrypt, with master key IDs (see HIVE-21848).
47
+ /// Format: "masterKeyID:colName,colName;masterKeyID:colName..."
48
+ /// Either
49
+ /// (1) column_keys must be set
50
+ /// or
51
+ /// (2) uniform_encryption must be set to true
52
+ /// If none of (1) and (2) are true, or if both are true, an exception will be
53
+ /// thrown.
54
+ std::string column_keys;
55
+
56
+ /// Encrypt footer and all columns with the same encryption key.
57
+ bool uniform_encryption = kDefaultUniformEncryption;
58
+
59
+ /// Parquet encryption algorithm. Can be "AES_GCM_V1" (default), or "AES_GCM_CTR_V1".
60
+ ParquetCipher::type encryption_algorithm = kDefaultEncryptionAlgorithm;
61
+
62
+ /// Write files with plaintext footer.
63
+ /// The default is false - files are written with encrypted footer.
64
+ bool plaintext_footer = kDefaultPlaintextFooter;
65
+
66
+ /// Use double wrapping - where data encryption keys (DEKs) are encrypted with key
67
+ /// encryption keys (KEKs), which in turn are encrypted with master keys.
68
+ /// The default is true. If set to false, use single wrapping - where DEKs are
69
+ /// encrypted directly with master keys.
70
+ bool double_wrapping = kDefaultDoubleWrapping;
71
+
72
+ /// Lifetime of cached entities (key encryption keys, local wrapping keys, KMS client
73
+ /// objects).
74
+ /// The default is 600 (10 minutes).
75
+ double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds;
76
+
77
+ /// Store key material inside Parquet file footers; this mode doesn’t produce
78
+ /// additional files. By default, true. If set to false, key material is stored in
79
+ /// separate files in the same folder, which enables key rotation for immutable
80
+ /// Parquet files.
81
+ bool internal_key_material = kDefaultInternalKeyMaterial;
82
+
83
+ /// Length of data encryption keys (DEKs), randomly generated by parquet key
84
+ /// management tools. Can be 128, 192 or 256 bits.
85
+ /// The default is 128 bits.
86
+ int32_t data_key_length_bits = kDefaultDataKeyLengthBits;
87
+ };
88
+
89
+ struct PARQUET_EXPORT DecryptionConfiguration {
90
+ /// Lifetime of cached entities (key encryption keys, local wrapping keys, KMS client
91
+ /// objects).
92
+ /// The default is 600 (10 minutes).
93
+ double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds;
94
+ };
95
+
96
+ /// This is a core class, that translates the parameters of high level encryption (like
97
+ /// the names of encrypted columns, names of master keys, etc), into parameters of low
98
+ /// level encryption (like the key metadata, DEK, etc). A factory that produces the low
99
+ /// level FileEncryptionProperties and FileDecryptionProperties objects, from the high
100
+ /// level parameters.
101
+ class PARQUET_EXPORT CryptoFactory {
102
+ public:
103
+ /// a KmsClientFactory object must be registered via this method before calling any of
104
+ /// GetFileEncryptionProperties()/GetFileDecryptionProperties() methods.
105
+ void RegisterKmsClientFactory(std::shared_ptr<KmsClientFactory> kms_client_factory);
106
+
107
+ /// Get the encryption properties for a Parquet file.
108
+ /// If external key material is used then a file system and path to the
109
+ /// parquet file must be provided.
110
+ std::shared_ptr<FileEncryptionProperties> GetFileEncryptionProperties(
111
+ const KmsConnectionConfig& kms_connection_config,
112
+ const EncryptionConfiguration& encryption_config, const std::string& file_path = "",
113
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
114
+
115
+ /// Get decryption properties for a Parquet file.
116
+ /// The returned FileDecryptionProperties object will use the cache inside this
117
+ /// CryptoFactory object, so please keep this
118
+ /// CryptoFactory object alive along with the returned
119
+ /// FileDecryptionProperties object.
120
+ /// If external key material is used then a file system and path to the
121
+ /// parquet file must be provided.
122
+ std::shared_ptr<FileDecryptionProperties> GetFileDecryptionProperties(
123
+ const KmsConnectionConfig& kms_connection_config,
124
+ const DecryptionConfiguration& decryption_config, const std::string& file_path = "",
125
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
126
+
127
+ void RemoveCacheEntriesForToken(const std::string& access_token) {
128
+ key_toolkit_.RemoveCacheEntriesForToken(access_token);
129
+ }
130
+
131
+ void RemoveCacheEntriesForAllTokens() { key_toolkit_.RemoveCacheEntriesForAllTokens(); }
132
+
133
+ /// Rotates master encryption keys for a Parquet file that uses external key material.
134
+ /// In single wrapping mode, data encryption keys are decrypted with the old master keys
135
+ /// and then re-encrypted with new master keys.
136
+ /// In double wrapping mode, key encryption keys are decrypted with the old master keys
137
+ /// and then re-encrypted with new master keys.
138
+ /// This relies on the KMS supporting versioning, such that the old master key is
139
+ /// used when unwrapping a key, and the latest version is used when wrapping a key.
140
+ void RotateMasterKeys(const KmsConnectionConfig& kms_connection_config,
141
+ const std::string& parquet_file_path,
142
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system,
143
+ bool double_wrapping = kDefaultDoubleWrapping,
144
+ double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds);
145
+
146
+ private:
147
+ ColumnPathToEncryptionPropertiesMap GetColumnEncryptionProperties(
148
+ int dek_length, const std::string& column_keys, FileKeyWrapper* key_wrapper);
149
+
150
+ /// Key utilities object for kms client initialization and cache control
151
+ KeyToolkit key_toolkit_;
152
+ };
153
+
154
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.h ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <map>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <utility>
24
+
25
+ #include "parquet/exception.h"
26
+ #include "parquet/schema.h"
27
+ #include "parquet/types.h"
28
+
29
+ namespace parquet {
30
+
31
+ static constexpr ParquetCipher::type kDefaultEncryptionAlgorithm =
32
+ ParquetCipher::AES_GCM_V1;
33
+ static constexpr int32_t kMaximalAadMetadataLength = 256;
34
+ static constexpr bool kDefaultEncryptedFooter = true;
35
+ static constexpr bool kDefaultCheckSignature = true;
36
+ static constexpr bool kDefaultAllowPlaintextFiles = false;
37
+ static constexpr int32_t kAadFileUniqueLength = 8;
38
+
39
+ class ColumnDecryptionProperties;
40
+ using ColumnPathToDecryptionPropertiesMap =
41
+ std::map<std::string, std::shared_ptr<ColumnDecryptionProperties>>;
42
+
43
+ class ColumnEncryptionProperties;
44
+ using ColumnPathToEncryptionPropertiesMap =
45
+ std::map<std::string, std::shared_ptr<ColumnEncryptionProperties>>;
46
+
47
+ class PARQUET_EXPORT DecryptionKeyRetriever {
48
+ public:
49
+ virtual std::string GetKey(const std::string& key_metadata) = 0;
50
+ virtual ~DecryptionKeyRetriever() {}
51
+ };
52
+
53
+ /// Simple integer key retriever
54
+ class PARQUET_EXPORT IntegerKeyIdRetriever : public DecryptionKeyRetriever {
55
+ public:
56
+ void PutKey(uint32_t key_id, const std::string& key);
57
+ std::string GetKey(const std::string& key_metadata) override;
58
+
59
+ private:
60
+ std::map<uint32_t, std::string> key_map_;
61
+ };
62
+
63
+ // Simple string key retriever
64
+ class PARQUET_EXPORT StringKeyIdRetriever : public DecryptionKeyRetriever {
65
+ public:
66
+ void PutKey(const std::string& key_id, const std::string& key);
67
+ std::string GetKey(const std::string& key_metadata) override;
68
+
69
+ private:
70
+ std::map<std::string, std::string> key_map_;
71
+ };
72
+
73
+ class PARQUET_EXPORT HiddenColumnException : public ParquetException {
74
+ public:
75
+ explicit HiddenColumnException(const std::string& columnPath)
76
+ : ParquetException(columnPath.c_str()) {}
77
+ };
78
+
79
+ class PARQUET_EXPORT KeyAccessDeniedException : public ParquetException {
80
+ public:
81
+ explicit KeyAccessDeniedException(const std::string& columnPath)
82
+ : ParquetException(columnPath.c_str()) {}
83
+ };
84
+
85
+ inline const uint8_t* str2bytes(const std::string& str) {
86
+ if (str.empty()) return NULLPTR;
87
+
88
+ char* cbytes = const_cast<char*>(str.c_str());
89
+ return reinterpret_cast<const uint8_t*>(cbytes);
90
+ }
91
+
92
+ class PARQUET_EXPORT ColumnEncryptionProperties {
93
+ public:
94
+ class PARQUET_EXPORT Builder {
95
+ public:
96
+ /// Convenience builder for encrypted columns.
97
+ explicit Builder(const std::string& name) : Builder(name, true) {}
98
+
99
+ /// Convenience builder for encrypted columns.
100
+ explicit Builder(const std::shared_ptr<schema::ColumnPath>& path)
101
+ : Builder(path->ToDotString(), true) {}
102
+
103
+ /// Set a column-specific key.
104
+ /// If key is not set on an encrypted column, the column will
105
+ /// be encrypted with the footer key.
106
+ /// keyBytes Key length must be either 16, 24 or 32 bytes.
107
+ /// The key is cloned, and will be wiped out (array values set to 0) upon completion
108
+ /// of file writing.
109
+ /// Caller is responsible for wiping out the input key array.
110
+ Builder* key(std::string column_key);
111
+
112
+ /// Set a key retrieval metadata.
113
+ /// use either key_metadata() or key_id(), not both
114
+ Builder* key_metadata(const std::string& key_metadata);
115
+
116
+ /// A convenience function to set key metadata using a string id.
117
+ /// Set a key retrieval metadata (converted from String).
118
+ /// use either key_metadata() or key_id(), not both
119
+ /// key_id will be converted to metadata (UTF-8 array).
120
+ Builder* key_id(const std::string& key_id);
121
+
122
+ std::shared_ptr<ColumnEncryptionProperties> build() {
123
+ return std::shared_ptr<ColumnEncryptionProperties>(
124
+ new ColumnEncryptionProperties(encrypted_, column_path_, key_, key_metadata_));
125
+ }
126
+
127
+ private:
128
+ const std::string column_path_;
129
+ bool encrypted_;
130
+ std::string key_;
131
+ std::string key_metadata_;
132
+
133
+ Builder(const std::string path, bool encrypted)
134
+ : column_path_(path), encrypted_(encrypted) {}
135
+ };
136
+
137
+ std::string column_path() const { return column_path_; }
138
+ bool is_encrypted() const { return encrypted_; }
139
+ bool is_encrypted_with_footer_key() const { return encrypted_with_footer_key_; }
140
+ std::string key() const { return key_; }
141
+ std::string key_metadata() const { return key_metadata_; }
142
+
143
+ /// Upon completion of file writing, the encryption key
144
+ /// will be wiped out.
145
+ void WipeOutEncryptionKey() { key_.clear(); }
146
+
147
+ bool is_utilized() {
148
+ if (key_.empty())
149
+ return false; // can re-use column properties without encryption keys
150
+ return utilized_;
151
+ }
152
+
153
+ /// ColumnEncryptionProperties object can be used for writing one file only.
154
+ /// Mark ColumnEncryptionProperties as utilized once it is used in
155
+ /// FileEncryptionProperties as the encryption key will be wiped out upon
156
+ /// completion of file writing.
157
+ void set_utilized() { utilized_ = true; }
158
+
159
+ std::shared_ptr<ColumnEncryptionProperties> DeepClone() {
160
+ std::string key_copy = key_;
161
+ return std::shared_ptr<ColumnEncryptionProperties>(new ColumnEncryptionProperties(
162
+ encrypted_, column_path_, key_copy, key_metadata_));
163
+ }
164
+
165
+ ColumnEncryptionProperties() = default;
166
+ ColumnEncryptionProperties(const ColumnEncryptionProperties& other) = default;
167
+ ColumnEncryptionProperties(ColumnEncryptionProperties&& other) = default;
168
+
169
+ private:
170
+ const std::string column_path_;
171
+ bool encrypted_;
172
+ bool encrypted_with_footer_key_;
173
+ std::string key_;
174
+ std::string key_metadata_;
175
+ bool utilized_;
176
+ explicit ColumnEncryptionProperties(bool encrypted, const std::string& column_path,
177
+ const std::string& key,
178
+ const std::string& key_metadata);
179
+ };
180
+
181
+ class PARQUET_EXPORT ColumnDecryptionProperties {
182
+ public:
183
+ class PARQUET_EXPORT Builder {
184
+ public:
185
+ explicit Builder(const std::string& name) : column_path_(name) {}
186
+
187
+ explicit Builder(const std::shared_ptr<schema::ColumnPath>& path)
188
+ : Builder(path->ToDotString()) {}
189
+
190
+ /// Set an explicit column key. If applied on a file that contains
191
+ /// key metadata for this column the metadata will be ignored,
192
+ /// the column will be decrypted with this key.
193
+ /// key length must be either 16, 24 or 32 bytes.
194
+ Builder* key(const std::string& key);
195
+
196
+ std::shared_ptr<ColumnDecryptionProperties> build();
197
+
198
+ private:
199
+ const std::string column_path_;
200
+ std::string key_;
201
+ };
202
+
203
+ ColumnDecryptionProperties() = default;
204
+ ColumnDecryptionProperties(const ColumnDecryptionProperties& other) = default;
205
+ ColumnDecryptionProperties(ColumnDecryptionProperties&& other) = default;
206
+
207
+ std::string column_path() const { return column_path_; }
208
+ std::string key() const { return key_; }
209
+ bool is_utilized() { return utilized_; }
210
+
211
+ /// ColumnDecryptionProperties object can be used for reading one file only.
212
+ /// Mark ColumnDecryptionProperties as utilized once it is used in
213
+ /// FileDecryptionProperties as the encryption key will be wiped out upon
214
+ /// completion of file reading.
215
+ void set_utilized() { utilized_ = true; }
216
+
217
+ /// Upon completion of file reading, the encryption key
218
+ /// will be wiped out.
219
+ void WipeOutDecryptionKey();
220
+
221
+ std::shared_ptr<ColumnDecryptionProperties> DeepClone();
222
+
223
+ private:
224
+ const std::string column_path_;
225
+ std::string key_;
226
+ bool utilized_;
227
+
228
+ /// This class is only required for setting explicit column decryption keys -
229
+ /// to override key retriever (or to provide keys when key metadata and/or
230
+ /// key retriever are not available)
231
+ explicit ColumnDecryptionProperties(const std::string& column_path,
232
+ const std::string& key);
233
+ };
234
+
235
+ class PARQUET_EXPORT AADPrefixVerifier {
236
+ public:
237
+ /// Verifies identity (AAD Prefix) of individual file,
238
+ /// or of file collection in a data set.
239
+ /// Throws exception if an AAD prefix is wrong.
240
+ /// In a data set, AAD Prefixes should be collected,
241
+ /// and then checked for missing files.
242
+ virtual void Verify(const std::string& aad_prefix) = 0;
243
+ virtual ~AADPrefixVerifier() {}
244
+ };
245
+
246
+ class PARQUET_EXPORT FileDecryptionProperties {
247
+ public:
248
+ class PARQUET_EXPORT Builder {
249
+ public:
250
+ Builder() {
251
+ check_plaintext_footer_integrity_ = kDefaultCheckSignature;
252
+ plaintext_files_allowed_ = kDefaultAllowPlaintextFiles;
253
+ }
254
+
255
+ /// Set an explicit footer key. If applied on a file that contains
256
+ /// footer key metadata the metadata will be ignored, the footer
257
+ /// will be decrypted/verified with this key.
258
+ /// If explicit key is not set, footer key will be fetched from
259
+ /// key retriever.
260
+ /// With explicit keys or AAD prefix, new encryption properties object must be
261
+ /// created for each encrypted file.
262
+ /// Explicit encryption keys (footer and column) are cloned.
263
+ /// Upon completion of file reading, the cloned encryption keys in the properties
264
+ /// will be wiped out (array values set to 0).
265
+ /// Caller is responsible for wiping out the input key array.
266
+ /// param footerKey Key length must be either 16, 24 or 32 bytes.
267
+ Builder* footer_key(const std::string footer_key);
268
+
269
+ /// Set explicit column keys (decryption properties).
270
+ /// Its also possible to set a key retriever on this property object.
271
+ /// Upon file decryption, availability of explicit keys is checked before
272
+ /// invocation of the retriever callback.
273
+ /// If an explicit key is available for a footer or a column,
274
+ /// its key metadata will be ignored.
275
+ Builder* column_keys(
276
+ const ColumnPathToDecryptionPropertiesMap& column_decryption_properties);
277
+
278
+ /// Set a key retriever callback. Its also possible to
279
+ /// set explicit footer or column keys on this file property object.
280
+ /// Upon file decryption, availability of explicit keys is checked before
281
+ /// invocation of the retriever callback.
282
+ /// If an explicit key is available for a footer or a column,
283
+ /// its key metadata will be ignored.
284
+ Builder* key_retriever(const std::shared_ptr<DecryptionKeyRetriever>& key_retriever);
285
+
286
+ /// Skip integrity verification of plaintext footers.
287
+ /// If not called, integrity of plaintext footers will be checked in runtime,
288
+ /// and an exception will be thrown in the following situations:
289
+ /// - footer signing key is not available
290
+ /// (not passed, or not found by key retriever)
291
+ /// - footer content and signature don't match
292
+ Builder* disable_footer_signature_verification() {
293
+ check_plaintext_footer_integrity_ = false;
294
+ return this;
295
+ }
296
+
297
+ /// Explicitly supply the file AAD prefix.
298
+ /// A must when a prefix is used for file encryption, but not stored in file.
299
+ /// If AAD prefix is stored in file, it will be compared to the explicitly
300
+ /// supplied value and an exception will be thrown if they differ.
301
+ Builder* aad_prefix(const std::string& aad_prefix);
302
+
303
+ /// Set callback for verification of AAD Prefixes stored in file.
304
+ Builder* aad_prefix_verifier(std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier);
305
+
306
+ /// By default, reading plaintext (unencrypted) files is not
307
+ /// allowed when using a decryptor
308
+ /// - in order to detect files that were not encrypted by mistake.
309
+ /// However, the default behavior can be overridden by calling this method.
310
+ /// The caller should use then a different method to ensure encryption
311
+ /// of files with sensitive data.
312
+ Builder* plaintext_files_allowed() {
313
+ plaintext_files_allowed_ = true;
314
+ return this;
315
+ }
316
+
317
+ std::shared_ptr<FileDecryptionProperties> build() {
318
+ return std::shared_ptr<FileDecryptionProperties>(new FileDecryptionProperties(
319
+ footer_key_, key_retriever_, check_plaintext_footer_integrity_, aad_prefix_,
320
+ aad_prefix_verifier_, column_decryption_properties_, plaintext_files_allowed_));
321
+ }
322
+
323
+ private:
324
+ std::string footer_key_;
325
+ std::string aad_prefix_;
326
+ std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier_;
327
+ ColumnPathToDecryptionPropertiesMap column_decryption_properties_;
328
+
329
+ std::shared_ptr<DecryptionKeyRetriever> key_retriever_;
330
+ bool check_plaintext_footer_integrity_;
331
+ bool plaintext_files_allowed_;
332
+ };
333
+
334
+ std::string column_key(const std::string& column_path) const;
335
+
336
+ std::string footer_key() const { return footer_key_; }
337
+
338
+ std::string aad_prefix() const { return aad_prefix_; }
339
+
340
+ const std::shared_ptr<DecryptionKeyRetriever>& key_retriever() const {
341
+ return key_retriever_;
342
+ }
343
+
344
+ bool check_plaintext_footer_integrity() const {
345
+ return check_plaintext_footer_integrity_;
346
+ }
347
+
348
+ bool plaintext_files_allowed() const { return plaintext_files_allowed_; }
349
+
350
+ const std::shared_ptr<AADPrefixVerifier>& aad_prefix_verifier() const {
351
+ return aad_prefix_verifier_;
352
+ }
353
+
354
+ /// Upon completion of file reading, the encryption keys in the properties
355
+ /// will be wiped out (array values set to 0).
356
+ void WipeOutDecryptionKeys();
357
+
358
+ bool is_utilized();
359
+
360
+ /// FileDecryptionProperties object can be used for reading one file only.
361
+ /// Mark FileDecryptionProperties as utilized once it is used to read a file as the
362
+ /// encryption keys will be wiped out upon completion of file reading.
363
+ void set_utilized() { utilized_ = true; }
364
+
365
+ /// FileDecryptionProperties object can be used for reading one file only.
366
+ /// (unless this object keeps the keyRetrieval callback only, and no explicit
367
+ /// keys or aadPrefix).
368
+ /// At the end, keys are wiped out in the memory.
369
+ /// This method allows to clone identical properties for another file,
370
+ /// with an option to update the aadPrefix (if newAadPrefix is null,
371
+ /// aadPrefix will be cloned too)
372
+ std::shared_ptr<FileDecryptionProperties> DeepClone(std::string new_aad_prefix = "");
373
+
374
+ private:
375
+ std::string footer_key_;
376
+ std::string aad_prefix_;
377
+ std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier_;
378
+
379
+ const std::string empty_string_ = "";
380
+ ColumnPathToDecryptionPropertiesMap column_decryption_properties_;
381
+
382
+ std::shared_ptr<DecryptionKeyRetriever> key_retriever_;
383
+ bool check_plaintext_footer_integrity_;
384
+ bool plaintext_files_allowed_;
385
+ bool utilized_;
386
+
387
+ FileDecryptionProperties(
388
+ const std::string& footer_key,
389
+ std::shared_ptr<DecryptionKeyRetriever> key_retriever,
390
+ bool check_plaintext_footer_integrity, const std::string& aad_prefix,
391
+ std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier,
392
+ const ColumnPathToDecryptionPropertiesMap& column_decryption_properties,
393
+ bool plaintext_files_allowed);
394
+ };
395
+
396
+ class PARQUET_EXPORT FileEncryptionProperties {
397
+ public:
398
+ class PARQUET_EXPORT Builder {
399
+ public:
400
+ explicit Builder(const std::string& footer_key)
401
+ : parquet_cipher_(kDefaultEncryptionAlgorithm),
402
+ encrypted_footer_(kDefaultEncryptedFooter) {
403
+ footer_key_ = footer_key;
404
+ store_aad_prefix_in_file_ = false;
405
+ }
406
+
407
+ /// Create files with plaintext footer.
408
+ /// If not called, the files will be created with encrypted footer (default).
409
+ Builder* set_plaintext_footer() {
410
+ encrypted_footer_ = false;
411
+ return this;
412
+ }
413
+
414
+ /// Set encryption algorithm.
415
+ /// If not called, files will be encrypted with AES_GCM_V1 (default).
416
+ Builder* algorithm(ParquetCipher::type parquet_cipher) {
417
+ parquet_cipher_ = parquet_cipher;
418
+ return this;
419
+ }
420
+
421
+ /// Set a key retrieval metadata (converted from String).
422
+ /// use either footer_key_metadata or footer_key_id, not both.
423
+ Builder* footer_key_id(const std::string& key_id);
424
+
425
+ /// Set a key retrieval metadata.
426
+ /// use either footer_key_metadata or footer_key_id, not both.
427
+ Builder* footer_key_metadata(const std::string& footer_key_metadata);
428
+
429
+ /// Set the file AAD Prefix.
430
+ Builder* aad_prefix(const std::string& aad_prefix);
431
+
432
+ /// Skip storing AAD Prefix in file.
433
+ /// If not called, and if AAD Prefix is set, it will be stored.
434
+ Builder* disable_aad_prefix_storage();
435
+
436
+ /// Set the list of encrypted columns and their properties (keys etc).
437
+ /// If not called, all columns will be encrypted with the footer key.
438
+ /// If called, the file columns not in the list will be left unencrypted.
439
+ Builder* encrypted_columns(
440
+ const ColumnPathToEncryptionPropertiesMap& encrypted_columns);
441
+
442
+ std::shared_ptr<FileEncryptionProperties> build() {
443
+ return std::shared_ptr<FileEncryptionProperties>(new FileEncryptionProperties(
444
+ parquet_cipher_, footer_key_, footer_key_metadata_, encrypted_footer_,
445
+ aad_prefix_, store_aad_prefix_in_file_, encrypted_columns_));
446
+ }
447
+
448
+ private:
449
+ ParquetCipher::type parquet_cipher_;
450
+ bool encrypted_footer_;
451
+ std::string footer_key_;
452
+ std::string footer_key_metadata_;
453
+
454
+ std::string aad_prefix_;
455
+ bool store_aad_prefix_in_file_;
456
+ ColumnPathToEncryptionPropertiesMap encrypted_columns_;
457
+ };
458
+ bool encrypted_footer() const { return encrypted_footer_; }
459
+
460
+ EncryptionAlgorithm algorithm() const { return algorithm_; }
461
+
462
+ std::string footer_key() const { return footer_key_; }
463
+
464
+ std::string footer_key_metadata() const { return footer_key_metadata_; }
465
+
466
+ std::string file_aad() const { return file_aad_; }
467
+
468
+ std::shared_ptr<ColumnEncryptionProperties> column_encryption_properties(
469
+ const std::string& column_path);
470
+
471
+ bool is_utilized() const { return utilized_; }
472
+
473
+ /// FileEncryptionProperties object can be used for writing one file only.
474
+ /// Mark FileEncryptionProperties as utilized once it is used to write a file as the
475
+ /// encryption keys will be wiped out upon completion of file writing.
476
+ void set_utilized() { utilized_ = true; }
477
+
478
+ /// Upon completion of file writing, the encryption keys
479
+ /// will be wiped out (array values set to 0).
480
+ void WipeOutEncryptionKeys();
481
+
482
+ /// FileEncryptionProperties object can be used for writing one file only.
483
+ /// (at the end, keys are wiped out in the memory).
484
+ /// This method allows to clone identical properties for another file,
485
+ /// with an option to update the aadPrefix (if newAadPrefix is null,
486
+ /// aadPrefix will be cloned too)
487
+ std::shared_ptr<FileEncryptionProperties> DeepClone(std::string new_aad_prefix = "");
488
+
489
+ ColumnPathToEncryptionPropertiesMap encrypted_columns() const {
490
+ return encrypted_columns_;
491
+ }
492
+
493
+ private:
494
+ EncryptionAlgorithm algorithm_;
495
+ std::string footer_key_;
496
+ std::string footer_key_metadata_;
497
+ bool encrypted_footer_;
498
+ std::string file_aad_;
499
+ std::string aad_prefix_;
500
+ bool utilized_;
501
+ bool store_aad_prefix_in_file_;
502
+ ColumnPathToEncryptionPropertiesMap encrypted_columns_;
503
+
504
+ FileEncryptionProperties(ParquetCipher::type cipher, const std::string& footer_key,
505
+ const std::string& footer_key_metadata, bool encrypted_footer,
506
+ const std::string& aad_prefix, bool store_aad_prefix_in_file,
507
+ const ColumnPathToEncryptionPropertiesMap& encrypted_columns);
508
+ };
509
+
510
+ } // namespace parquet
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <set>
21
+ #include <string>
22
+ #include <unordered_map>
23
+
24
+ #include "arrow/filesystem/filesystem.h"
25
+ #include "parquet/platform.h"
26
+
27
+ namespace parquet::encryption {
28
+
29
+ /// Stores encryption key material outside the Parquet file, for example in a separate
30
+ /// small file in the same folder. This is important for “key rotation”, when MEKs have to
31
+ /// be changed (if compromised; or periodically, just in case) - without modifying the
32
+ /// Parquet files (often immutable).
33
+ class PARQUET_EXPORT FileKeyMaterialStore {
34
+ public:
35
+ /// Add key material for one encryption key.
36
+ virtual void AddKeyMaterial(std::string key_id_in_file, std::string key_material) = 0;
37
+
38
+ /// Get key material
39
+ virtual std::string GetKeyMaterial(std::string key_id_in_file) = 0;
40
+
41
+ /// After key material was added for all keys in the given Parquet file,
42
+ /// save material in persistent store.
43
+ virtual void SaveMaterial() = 0;
44
+
45
+ /// Remove key material from persistent store. Used in key rotation.
46
+ virtual void RemoveMaterial() = 0;
47
+
48
+ /// Move key material to another store. Used in key rotation.
49
+ virtual void MoveMaterialTo(std::shared_ptr<FileKeyMaterialStore> target_key_store) = 0;
50
+
51
+ /// Returns the Set of all key IDs in this store (for the given Parquet file)
52
+ virtual std::vector<std::string> GetKeyIDSet() = 0;
53
+
54
+ virtual ~FileKeyMaterialStore() {}
55
+ };
56
+
57
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_wrapper.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+ #include <string>
22
+ #include <unordered_map>
23
+
24
+ #include "arrow/util/concurrent_map.h"
25
+
26
+ #include "parquet/encryption/file_key_material_store.h"
27
+ #include "parquet/encryption/key_encryption_key.h"
28
+ #include "parquet/encryption/key_toolkit.h"
29
+ #include "parquet/encryption/kms_client.h"
30
+ #include "parquet/platform.h"
31
+
32
+ namespace parquet::encryption {
33
+
34
+ // This class will generate "key metadata" from "data encryption key" and "master key",
35
+ // following these steps:
36
+ // 1. Wrap "data encryption key". There are 2 modes:
37
+ // 1.1. single wrapping: encrypt "data encryption key" directly with "master encryption
38
+ // key"
39
+ // 1.2. double wrapping: 2 steps:
40
+ // 1.2.1. "key encryption key" is randomized (see KeyEncryptionKey class)
41
+ // 1.2.2. "data encryption key" is encrypted with the above "key encryption key"
42
+ // 2. Create "key material" (see structure in KeyMaterial class)
43
+ // 3. Create "key metadata" with "key material" inside or a reference to outside "key
44
+ // material" (see structure in KeyMetadata class).
45
+ class PARQUET_EXPORT FileKeyWrapper {
46
+ public:
47
+ static constexpr int kKeyEncryptionKeyLength = 16;
48
+ static constexpr int kKeyEncryptionKeyIdLength = 16;
49
+
50
+ /// key_toolkit and kms_connection_config is to get KmsClient from the cache or create
51
+ /// KmsClient if it's not in the cache yet. cache_entry_lifetime_seconds is life time of
52
+ /// KmsClient in the cache. key_material_store is to store "key material" outside
53
+ /// parquet file, NULL if "key material" is stored inside parquet file.
54
+ FileKeyWrapper(KeyToolkit* key_toolkit,
55
+ const KmsConnectionConfig& kms_connection_config,
56
+ std::shared_ptr<FileKeyMaterialStore> key_material_store,
57
+ double cache_entry_lifetime_seconds, bool double_wrapping);
58
+
59
+ /// Creates key_metadata field for a given data key, via wrapping the key with the
60
+ /// master key.
61
+ /// When external key material is used, an identifier is usually generated automatically
62
+ /// but may be specified explicitly to support key rotation,
63
+ /// which requires keeping the same identifiers.
64
+ std::string GetEncryptionKeyMetadata(const std::string& data_key,
65
+ const std::string& master_key_id,
66
+ bool is_footer_key,
67
+ std::string key_id_in_file = "");
68
+
69
+ private:
70
+ KeyEncryptionKey CreateKeyEncryptionKey(const std::string& master_key_id);
71
+
72
+ /// A map of Master Encryption Key ID -> KeyEncryptionKey, for the current token
73
+ std::shared_ptr<::arrow::util::ConcurrentMap<std::string, KeyEncryptionKey>>
74
+ kek_per_master_key_id_;
75
+
76
+ std::shared_ptr<KmsClient> kms_client_;
77
+ KmsConnectionConfig kms_connection_config_;
78
+ std::shared_ptr<FileKeyMaterialStore> key_material_store_;
79
+ const double cache_entry_lifetime_seconds_;
80
+ const bool double_wrapping_;
81
+ uint16_t key_counter_;
82
+ };
83
+
84
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_system_key_material_store.h ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <set>
21
+ #include <string>
22
+ #include <unordered_map>
23
+
24
+ #include "arrow/filesystem/filesystem.h"
25
+
26
+ #include "parquet/encryption/file_key_material_store.h"
27
+
28
+ namespace parquet::encryption {
29
+
30
+ /// A FileKeyMaterialStore that stores key material in a file system file in the same
31
+ /// folder as the Parquet file.
32
+ class PARQUET_EXPORT FileSystemKeyMaterialStore : public FileKeyMaterialStore {
33
+ public:
34
+ static constexpr const char kKeyMaterialFilePrefix[] = "_KEY_MATERIAL_FOR_";
35
+ static constexpr const char kTempFilePrefix[] = "_TMP";
36
+ static constexpr const char kKeyMaterialFileSuffix[] = ".json";
37
+
38
+ FileSystemKeyMaterialStore() {}
39
+ FileSystemKeyMaterialStore(const std::string& key_material_file_path,
40
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system);
41
+
42
+ /// Creates a new file system key material store for a parquet file.
43
+ /// When use_tmp_prefix is true, files are saved with an extra _TMP prefix so they don't
44
+ /// conflict with existing external material files. This is useful during key rotation
45
+ /// so that temporary key material files can be created while using the existing key
46
+ /// material, before moving the key material to the non-temporary location.
47
+ static std::shared_ptr<FileSystemKeyMaterialStore> Make(
48
+ const std::string& parquet_file_path,
49
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system, bool use_tmp_prefix);
50
+
51
+ /// Add key material for one encryption key.
52
+ void AddKeyMaterial(std::string key_id_in_file, std::string key_material) {
53
+ key_material_map_.insert({key_id_in_file, key_material});
54
+ }
55
+
56
+ /// Get key material
57
+ std::string GetKeyMaterial(std::string key_id_in_file) {
58
+ if (key_material_map_.empty()) {
59
+ LoadKeyMaterialMap();
60
+ }
61
+ auto found = key_material_map_.find(key_id_in_file);
62
+ return found->second;
63
+ }
64
+
65
+ /// After key material was added for all keys in the given Parquet file,
66
+ /// save material in persistent store.
67
+ void SaveMaterial();
68
+
69
+ /// Remove key material from persistent store. Used in key rotation.
70
+ void RemoveMaterial();
71
+
72
+ /// Move key material to another store. Used in key rotation.
73
+ void MoveMaterialTo(std::shared_ptr<FileKeyMaterialStore> target_key_store);
74
+
75
+ /// Returns the Set of all key IDs in this store (for the given Parquet file)
76
+ std::vector<std::string> GetKeyIDSet();
77
+
78
+ private:
79
+ std::string GetStorageFilePath() { return key_material_file_path_; }
80
+
81
+ std::string BuildKeyMaterialMapJson();
82
+ void LoadKeyMaterialMap();
83
+ std::string key_material_file_path_;
84
+ std::shared_ptr<::arrow::fs::FileSystem> file_system_;
85
+ /// Maps ID of a key in Parquet file and key material
86
+ std::unordered_map<std::string, std::string> key_material_map_;
87
+ };
88
+
89
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_encryption_key.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <vector>
22
+
23
+ #include "arrow/util/base64.h"
24
+
25
+ namespace parquet::encryption {
26
+
27
+ // In the double wrapping mode, each "data encryption key" (DEK) is encrypted with a “key
28
+ // encryption key” (KEK), that in turn is encrypted with a "master encryption key" (MEK).
29
+ // In a writer process, a random KEK is generated for each MEK ID, and cached in a <MEK-ID
30
+ // : KEK> map. This allows to perform an interaction with a KMS server only once for each
31
+ // MEK, in order to wrap its KEK. "Data encryption key" (DEK) wrapping is performed
32
+ // locally, and does not involve an interaction with a KMS server.
33
+ class KeyEncryptionKey {
34
+ public:
35
+ KeyEncryptionKey(std::string kek_bytes, std::string kek_id,
36
+ std::string encoded_wrapped_kek)
37
+ : kek_bytes_(std::move(kek_bytes)),
38
+ kek_id_(std::move(kek_id)),
39
+ encoded_kek_id_(::arrow::util::base64_encode(kek_id_)),
40
+ encoded_wrapped_kek_(std::move(encoded_wrapped_kek)) {}
41
+
42
+ const std::string& kek_bytes() const { return kek_bytes_; }
43
+
44
+ const std::string& kek_id() const { return kek_id_; }
45
+
46
+ const std::string& encoded_kek_id() const { return encoded_kek_id_; }
47
+
48
+ const std::string& encoded_wrapped_kek() const { return encoded_wrapped_kek_; }
49
+
50
+ private:
51
+ std::string kek_bytes_;
52
+ std::string kek_id_;
53
+ std::string encoded_kek_id_;
54
+ std::string encoded_wrapped_kek_;
55
+ };
56
+
57
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_metadata.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <string>
21
+ #include <variant>
22
+
23
+ #include "parquet/encryption/key_material.h"
24
+ #include "parquet/exception.h"
25
+ #include "parquet/platform.h"
26
+
27
+ namespace parquet::encryption {
28
+
29
+ // Parquet encryption specification defines "key metadata" as an arbitrary byte array,
30
+ // generated by file writers for each encryption key, and passed to the low level API for
31
+ // storage in the file footer. The "key metadata" field is made available to file readers
32
+ // to enable recovery of the key. This interface can be utilized for implementation
33
+ // of any key management scheme.
34
+ //
35
+ // The keytools package (PARQUET-1373) implements one approach, of many possible, to key
36
+ // management and to generation of the "key metadata" fields. This approach, based on the
37
+ // "envelope encryption" pattern, allows integration with KMS servers. It keeps the actual
38
+ // material, required to recover a key, in a "key material" object (see the KeyMaterial
39
+ // class for details). This class is implemented to support version 1 of the parquet key
40
+ // management tools specification.
41
+ //
42
+ // KeyMetadata writes (and reads) the "key metadata" field as a flat json object,
43
+ // with the following fields:
44
+ // 1. "keyMaterialType" - a String, with the type of key material.
45
+ // 2. "internalStorage" - a boolean. If true, means that "key material" is kept inside the
46
+ // "key metadata" field. If false, "key material" is kept externally (outside Parquet
47
+ // files) - in this case, "key metadata" keeps a reference to the external "key material".
48
+ // 3. "keyReference" - a String, with the reference to the external "key material".
49
+ // Written only if internalStorage is false.
50
+ //
51
+ // If internalStorage is true, "key material" is a part of "key metadata", and the json
52
+ // keeps additional fields, described in the KeyMaterial class.
53
+ class PARQUET_EXPORT KeyMetadata {
54
+ public:
55
+ static constexpr const char kKeyMaterialInternalStorageField[] = "internalStorage";
56
+ static constexpr const char kKeyReferenceField[] = "keyReference";
57
+
58
+ /// key_metadata_bytes is the key metadata field stored in the parquet file,
59
+ /// in the serialized json object format.
60
+ static KeyMetadata Parse(const std::string& key_metadata_bytes);
61
+
62
+ static std::string CreateSerializedForExternalMaterial(
63
+ const std::string& key_reference);
64
+
65
+ bool key_material_stored_internally() const { return is_internal_storage_; }
66
+
67
+ const KeyMaterial& key_material() const {
68
+ if (!is_internal_storage_) {
69
+ throw ParquetException("key material is stored externally.");
70
+ }
71
+ return ::std::get<KeyMaterial>(key_material_or_reference_);
72
+ }
73
+
74
+ const std::string& key_reference() const {
75
+ if (is_internal_storage_) {
76
+ throw ParquetException("key material is stored internally.");
77
+ }
78
+ return ::std::get<std::string>(key_material_or_reference_);
79
+ }
80
+
81
+ private:
82
+ explicit KeyMetadata(const KeyMaterial& key_material);
83
+ explicit KeyMetadata(const std::string& key_reference);
84
+
85
+ bool is_internal_storage_;
86
+ /// If is_internal_storage_ is true, KeyMaterial is set,
87
+ /// else a string referencing to an outside "key material" is set.
88
+ ::std::variant<KeyMaterial, std::string> key_material_or_reference_;
89
+ };
90
+
91
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_toolkit.h ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+ #include <string>
22
+
23
+ #include "parquet/encryption/key_encryption_key.h"
24
+ #include "parquet/encryption/kms_client.h"
25
+ #include "parquet/encryption/kms_client_factory.h"
26
+ #include "parquet/encryption/two_level_cache_with_expiration.h"
27
+ #include "parquet/platform.h"
28
+
29
+ namespace parquet::encryption {
30
+
31
+ static constexpr uint64_t kCacheCleanPeriodForKeyRotation = 60 * 60; // 1 hour
32
+
33
+ // KeyToolkit is a utility that keeps various tools for key management (such as key
34
+ // rotation, kms client instantiation, cache control, etc), plus a number of auxiliary
35
+ // classes for internal use.
36
+ class PARQUET_EXPORT KeyToolkit {
37
+ public:
38
+ KeyToolkit() { last_cache_clean_for_key_rotation_time_ = {}; }
39
+
40
+ /// KMS client two level cache: token -> KMSInstanceId -> KmsClient
41
+ TwoLevelCacheWithExpiration<std::shared_ptr<KmsClient>>& kms_client_cache_per_token() {
42
+ return kms_client_cache_;
43
+ }
44
+ /// Key encryption key two level cache for wrapping: token -> MasterEncryptionKeyId ->
45
+ /// KeyEncryptionKey
46
+ TwoLevelCacheWithExpiration<KeyEncryptionKey>& kek_write_cache_per_token() {
47
+ return key_encryption_key_write_cache_;
48
+ }
49
+
50
+ /// Key encryption key two level cache for unwrapping: token -> KeyEncryptionKeyId ->
51
+ /// KeyEncryptionKeyBytes
52
+ TwoLevelCacheWithExpiration<std::string>& kek_read_cache_per_token() {
53
+ return key_encryption_key_read_cache_;
54
+ }
55
+
56
+ std::shared_ptr<KmsClient> GetKmsClient(
57
+ const KmsConnectionConfig& kms_connection_config, double cache_entry_lifetime_ms);
58
+
59
+ /// Flush any caches that are tied to the (compromised) access_token
60
+ void RemoveCacheEntriesForToken(const std::string& access_token);
61
+
62
+ void RemoveCacheEntriesForAllTokens();
63
+
64
+ void RegisterKmsClientFactory(std::shared_ptr<KmsClientFactory> kms_client_factory) {
65
+ if (kms_client_factory_ != NULL) {
66
+ throw ParquetException("KMS client factory has already been registered.");
67
+ }
68
+ kms_client_factory_ = kms_client_factory;
69
+ }
70
+
71
+ /// Key rotation. In the single wrapping mode, decrypts data keys with old master keys,
72
+ /// then encrypts them with new master keys. In the double wrapping mode, decrypts KEKs
73
+ /// (key encryption keys) with old master keys, generates new KEKs and encrypts them
74
+ /// with new master keys. Works only if key material is not stored internally in file
75
+ /// footers. Not supported in local key wrapping mode. Method can be run by multiple
76
+ /// threads, but each thread must work on different files.
77
+ void RotateMasterKeys(const KmsConnectionConfig& kms_connection_config,
78
+ const std::string& parquet_file_path,
79
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system,
80
+ bool double_wrapping, double cache_lifetime_seconds);
81
+
82
+ private:
83
+ TwoLevelCacheWithExpiration<std::shared_ptr<KmsClient>> kms_client_cache_;
84
+ TwoLevelCacheWithExpiration<KeyEncryptionKey> key_encryption_key_write_cache_;
85
+ TwoLevelCacheWithExpiration<std::string> key_encryption_key_read_cache_;
86
+ std::shared_ptr<KmsClientFactory> kms_client_factory_;
87
+ mutable ::arrow::util::Mutex last_cache_clean_for_key_rotation_time_mutex_;
88
+ internal::TimePoint last_cache_clean_for_key_rotation_time_;
89
+ };
90
+
91
+ // "data encryption key" and "master key identifier" are paired together as output when
92
+ // parsing from "key material"
93
+ class PARQUET_EXPORT KeyWithMasterId {
94
+ public:
95
+ KeyWithMasterId(std::string key_bytes, std::string master_id)
96
+ : key_bytes_(std::move(key_bytes)), master_id_(std::move(master_id)) {}
97
+
98
+ const std::string& data_key() const { return key_bytes_; }
99
+ const std::string& master_id() const { return master_id_; }
100
+
101
+ private:
102
+ const std::string key_bytes_;
103
+ const std::string master_id_;
104
+ };
105
+
106
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client.h ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+ #include <string>
22
+ #include <unordered_map>
23
+
24
+ #include "arrow/util/mutex.h"
25
+
26
+ #include "parquet/exception.h"
27
+ #include "parquet/platform.h"
28
+
29
+ namespace parquet::encryption {
30
+
31
+ /// This class wraps the key access token of a KMS server. If your token changes over
32
+ /// time, you should keep the reference to the KeyAccessToken object and call Refresh()
33
+ /// method every time you have a new token.
34
+ class PARQUET_EXPORT KeyAccessToken {
35
+ public:
36
+ KeyAccessToken() = default;
37
+
38
+ explicit KeyAccessToken(const std::string value) : value_(value) {}
39
+
40
+ void Refresh(const std::string& new_value) {
41
+ auto lock = mutex_.Lock();
42
+ value_ = new_value;
43
+ }
44
+
45
+ const std::string& value() const {
46
+ auto lock = mutex_.Lock();
47
+ return value_;
48
+ }
49
+
50
+ private:
51
+ std::string value_;
52
+ mutable ::arrow::util::Mutex mutex_;
53
+ };
54
+
55
+ struct PARQUET_EXPORT KmsConnectionConfig {
56
+ std::string kms_instance_id;
57
+ std::string kms_instance_url;
58
+ /// If the access token is changed in the future, you should keep a reference to
59
+ /// this object and call Refresh() on it whenever there is a new access token.
60
+ std::shared_ptr<KeyAccessToken> refreshable_key_access_token;
61
+ std::unordered_map<std::string, std::string> custom_kms_conf;
62
+
63
+ KmsConnectionConfig();
64
+
65
+ const std::string& key_access_token() const {
66
+ if (refreshable_key_access_token == NULL ||
67
+ refreshable_key_access_token->value().empty()) {
68
+ throw ParquetException("key access token is not set!");
69
+ }
70
+ return refreshable_key_access_token->value();
71
+ }
72
+
73
+ void SetDefaultIfEmpty();
74
+ };
75
+
76
+ class PARQUET_EXPORT KmsClient {
77
+ public:
78
+ static constexpr const char kKmsInstanceIdDefault[] = "DEFAULT";
79
+ static constexpr const char kKmsInstanceUrlDefault[] = "DEFAULT";
80
+ static constexpr const char kKeyAccessTokenDefault[] = "DEFAULT";
81
+
82
+ /// Wraps a key - encrypts it with the master key, encodes the result
83
+ /// and potentially adds a KMS-specific metadata.
84
+ virtual std::string WrapKey(const std::string& key_bytes,
85
+ const std::string& master_key_identifier) = 0;
86
+
87
+ /// Decrypts (unwraps) a key with the master key.
88
+ virtual std::string UnwrapKey(const std::string& wrapped_key,
89
+ const std::string& master_key_identifier) = 0;
90
+ virtual ~KmsClient() {}
91
+ };
92
+
93
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client_factory.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "parquet/encryption/kms_client.h"
21
+ #include "parquet/platform.h"
22
+
23
+ namespace parquet::encryption {
24
+
25
+ class PARQUET_EXPORT KmsClientFactory {
26
+ public:
27
+ explicit KmsClientFactory(bool wrap_locally = false) : wrap_locally_(wrap_locally) {}
28
+
29
+ virtual ~KmsClientFactory() = default;
30
+
31
+ virtual std::shared_ptr<KmsClient> CreateKmsClient(
32
+ const KmsConnectionConfig& kms_connection_config) = 0;
33
+
34
+ protected:
35
+ bool wrap_locally_;
36
+ };
37
+
38
+ } // namespace parquet::encryption
env-llmeval/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/local_wrap_kms_client.h ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <unordered_map>
21
+ #include <vector>
22
+
23
+ #include "arrow/util/concurrent_map.h"
24
+
25
+ #include "parquet/encryption/kms_client.h"
26
+ #include "parquet/platform.h"
27
+
28
+ namespace parquet::encryption {
29
+
30
+ /// This class supports local wrapping mode, master keys will be fetched from the KMS
31
+ /// server and used to encrypt other keys (data encryption keys or key encryption keys).
32
+ class PARQUET_EXPORT LocalWrapKmsClient : public KmsClient {
33
+ public:
34
+ static constexpr const char kLocalWrapNoKeyVersion[] = "NO_VERSION";
35
+
36
+ explicit LocalWrapKmsClient(const KmsConnectionConfig& kms_connection_config);
37
+
38
+ std::string WrapKey(const std::string& key_bytes,
39
+ const std::string& master_key_identifier) override;
40
+
41
+ std::string UnwrapKey(const std::string& wrapped_key,
42
+ const std::string& master_key_identifier) override;
43
+
44
+ protected:
45
+ /// Get master key from the remote KMS server.
46
+ /// Note: this function might be called by multiple threads
47
+ virtual std::string GetMasterKeyFromServer(
48
+ const std::string& master_key_identifier) = 0;
49
+
50
+ private:
51
+ /// KMS systems wrap keys by encrypting them by master keys, and attaching additional
52
+ /// information (such as the version number of the masker key) to the result of
53
+ /// encryption. The master key version is required in key rotation. Currently, the
54
+ /// local wrapping mode does not support key rotation (because not all KMS systems allow
55
+ /// to fetch a master key by its ID and version number). Still, the local wrapping mode
56
+ /// adds a placeholder for the master key version, that will enable support for key
57
+ /// rotation in this mode in the future, with appropriate KMS systems. This will also
58
+ /// enable backward compatibility, where future readers will be able to extract master
59
+ /// key version in the files written by the current code.
60
+ ///
61
+ /// LocalKeyWrap class writes (and reads) the "key wrap" as a flat json with the
62
+ /// following fields:
63
+ /// 1. "masterKeyVersion" - a String, with the master key version. In the current
64
+ /// version, only one value is allowed - "NO_VERSION".
65
+ /// 2. "encryptedKey" - a String, with the key encrypted by the master key
66
+ /// (base64-encoded).
67
+ class LocalKeyWrap {
68
+ public:
69
+ static constexpr const char kLocalWrapKeyVersionField[] = "masterKeyVersion";
70
+ static constexpr const char kLocalWrapEncryptedKeyField[] = "encryptedKey";
71
+
72
+ LocalKeyWrap(std::string master_key_version, std::string encrypted_encoded_key);
73
+
74
+ static std::string CreateSerialized(const std::string& encrypted_encoded_key);
75
+
76
+ static LocalKeyWrap Parse(const std::string& wrapped_key);
77
+
78
+ const std::string& master_key_version() const { return master_key_version_; }
79
+
80
+ const std::string& encrypted_encoded_key() const { return encrypted_encoded_key_; }
81
+
82
+ private:
83
+ std::string encrypted_encoded_key_;
84
+ std::string master_key_version_;
85
+ };
86
+
87
+ std::string GetKeyFromServer(const std::string& key_identifier);
88
+
89
+ protected:
90
+ KmsConnectionConfig kms_connection_config_;
91
+ ::arrow::util::ConcurrentMap<std::string, std::string> master_key_cache_;
92
+ };
93
+
94
+ } // namespace parquet::encryption