applied-ai-018 commited on
Commit
ab01b71
·
verified ·
1 Parent(s): 6501646

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 +2 -0
  2. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/api.h +34 -0
  3. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/azurefs.h +358 -0
  4. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/filesystem.h +697 -0
  5. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/filesystem_library.h +39 -0
  6. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/gcsfs.h +246 -0
  7. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/hdfs.h +117 -0
  8. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/localfs.h +131 -0
  9. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/mockfs.h +134 -0
  10. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/path_util.h +178 -0
  11. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/s3_test_util.h +101 -0
  12. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/s3fs.h +401 -0
  13. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/test_util.h +256 -0
  14. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/type_fwd.h +53 -0
  15. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/testing/executor_util.h +55 -0
  16. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/testing/gtest_util.h +570 -0
  17. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/aligned_storage.h +145 -0
  18. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator.h +2058 -0
  19. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/basic_decimal.h +492 -0
  20. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/benchmark_util.h +211 -0
  21. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_block_counter.h +570 -0
  22. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_util.h +370 -0
  23. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap.h +466 -0
  24. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_builders.h +43 -0
  25. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_generate.h +112 -0
  26. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_ops.h +244 -0
  27. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_reader.h +273 -0
  28. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking64_default.h +0 -0
  29. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx2.h +28 -0
  30. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx512.h +28 -0
  31. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_default.h +0 -0
  32. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_neon.h +28 -0
  33. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/cancel.h +118 -0
  34. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/compare.h +62 -0
  35. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/compression.h +241 -0
  36. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/concurrent_map.h +68 -0
  37. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/config.h +73 -0
  38. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/converter.h +411 -0
  39. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/counting_semaphore.h +60 -0
  40. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/debug.h +29 -0
  41. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/decimal.h +298 -0
  42. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/formatting.h +656 -0
  43. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/hash_util.h +66 -0
  44. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util_overflow.h +118 -0
  45. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/io_util.h +452 -0
  46. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/iterator.h +568 -0
  47. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/key_value_metadata.h +99 -0
  48. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/launder.h +35 -0
  49. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/math_constants.h +32 -0
  50. llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/memory.h +43 -0
.gitattributes CHANGED
@@ -76,3 +76,5 @@ llmeval-env/lib/python3.10/site-packages/pyarrow/libarrow_python.so filter=lfs d
76
  llmeval-env/lib/python3.10/site-packages/pyarrow/_flight.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
77
  llmeval-env/lib/python3.10/site-packages/pyarrow/libparquet.so.1600 filter=lfs diff=lfs merge=lfs -text
78
  llmeval-env/lib/python3.10/site-packages/pyarrow/libarrow_dataset.so.1600 filter=lfs diff=lfs merge=lfs -text
 
 
 
76
  llmeval-env/lib/python3.10/site-packages/pyarrow/_flight.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
77
  llmeval-env/lib/python3.10/site-packages/pyarrow/libparquet.so.1600 filter=lfs diff=lfs merge=lfs -text
78
  llmeval-env/lib/python3.10/site-packages/pyarrow/libarrow_dataset.so.1600 filter=lfs diff=lfs merge=lfs -text
79
+ llmeval-env/lib/python3.10/site-packages/pyarrow/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
80
+ llmeval-env/lib/python3.10/site-packages/pyarrow/libarrow_substrait.so.1600 filter=lfs diff=lfs merge=lfs -text
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/api.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/util/config.h" // IWYU pragma: export
21
+
22
+ #include "arrow/filesystem/filesystem.h" // IWYU pragma: export
23
+ #ifdef ARROW_AZURE
24
+ #include "arrow/filesystem/azurefs.h" // IWYU pragma: export
25
+ #endif
26
+ #ifdef ARROW_GCS
27
+ #include "arrow/filesystem/gcsfs.h" // IWYU pragma: export
28
+ #endif
29
+ #include "arrow/filesystem/hdfs.h" // IWYU pragma: export
30
+ #include "arrow/filesystem/localfs.h" // IWYU pragma: export
31
+ #include "arrow/filesystem/mockfs.h" // IWYU pragma: export
32
+ #ifdef ARROW_S3
33
+ #include "arrow/filesystem/s3fs.h" // IWYU pragma: export
34
+ #endif
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/azurefs.h ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <vector>
23
+
24
+ #include "arrow/filesystem/filesystem.h"
25
+ #include "arrow/util/macros.h"
26
+ #include "arrow/util/uri.h"
27
+
28
+ namespace Azure::Core::Credentials {
29
+ class TokenCredential;
30
+ }
31
+
32
+ namespace Azure::Storage {
33
+ class StorageSharedKeyCredential;
34
+ }
35
+
36
+ namespace Azure::Storage::Blobs {
37
+ class BlobServiceClient;
38
+ }
39
+
40
+ namespace Azure::Storage::Files::DataLake {
41
+ class DataLakeFileSystemClient;
42
+ class DataLakeServiceClient;
43
+ } // namespace Azure::Storage::Files::DataLake
44
+
45
+ namespace arrow::fs {
46
+
47
+ class TestAzureFileSystem;
48
+ class TestAzureOptions;
49
+
50
+ /// Options for the AzureFileSystem implementation.
51
+ ///
52
+ /// By default, authentication is handled by the Azure SDK's credential chain
53
+ /// which may read from multiple environment variables, such as:
54
+ /// - `AZURE_TENANT_ID`
55
+ /// - `AZURE_CLIENT_ID`
56
+ /// - `AZURE_CLIENT_SECRET`
57
+ /// - `AZURE_AUTHORITY_HOST`
58
+ /// - `AZURE_CLIENT_CERTIFICATE_PATH`
59
+ /// - `AZURE_FEDERATED_TOKEN_FILE`
60
+ ///
61
+ /// Functions are provided for explicit configuration of credentials if that is preferred.
62
+ struct ARROW_EXPORT AzureOptions {
63
+ friend class TestAzureOptions;
64
+
65
+ /// \brief The name of the Azure Storage Account being accessed.
66
+ ///
67
+ /// All service URLs will be constructed using this storage account name.
68
+ /// `ConfigureAccountKeyCredential` assumes the user wants to authenticate
69
+ /// this account.
70
+ std::string account_name;
71
+
72
+ /// \brief hostname[:port] of the Azure Blob Storage Service.
73
+ ///
74
+ /// If the hostname is a relative domain name (one that starts with a '.'), then storage
75
+ /// account URLs will be constructed by prepending the account name to the hostname.
76
+ /// If the hostname is a fully qualified domain name, then the hostname will be used
77
+ /// as-is and the account name will follow the hostname in the URL path.
78
+ ///
79
+ /// Default: ".blob.core.windows.net"
80
+ std::string blob_storage_authority = ".blob.core.windows.net";
81
+
82
+ /// \brief hostname[:port] of the Azure Data Lake Storage Gen 2 Service.
83
+ ///
84
+ /// If the hostname is a relative domain name (one that starts with a '.'), then storage
85
+ /// account URLs will be constructed by prepending the account name to the hostname.
86
+ /// If the hostname is a fully qualified domain name, then the hostname will be used
87
+ /// as-is and the account name will follow the hostname in the URL path.
88
+ ///
89
+ /// Default: ".dfs.core.windows.net"
90
+ std::string dfs_storage_authority = ".dfs.core.windows.net";
91
+
92
+ /// \brief Azure Blob Storage connection transport.
93
+ ///
94
+ /// Default: "https"
95
+ std::string blob_storage_scheme = "https";
96
+
97
+ /// \brief Azure Data Lake Storage Gen 2 connection transport.
98
+ ///
99
+ /// Default: "https"
100
+ std::string dfs_storage_scheme = "https";
101
+
102
+ // TODO(GH-38598): Add support for more auth methods.
103
+ // std::string connection_string;
104
+ // std::string sas_token;
105
+
106
+ /// \brief Default metadata for OpenOutputStream.
107
+ ///
108
+ /// This will be ignored if non-empty metadata is passed to OpenOutputStream.
109
+ std::shared_ptr<const KeyValueMetadata> default_metadata;
110
+
111
+ private:
112
+ enum class CredentialKind {
113
+ kDefault,
114
+ kAnonymous,
115
+ kStorageSharedKey,
116
+ kClientSecret,
117
+ kManagedIdentity,
118
+ kWorkloadIdentity,
119
+ } credential_kind_ = CredentialKind::kDefault;
120
+
121
+ std::shared_ptr<Azure::Storage::StorageSharedKeyCredential>
122
+ storage_shared_key_credential_;
123
+ mutable std::shared_ptr<Azure::Core::Credentials::TokenCredential> token_credential_;
124
+
125
+ public:
126
+ AzureOptions();
127
+ ~AzureOptions();
128
+
129
+ private:
130
+ void ExtractFromUriSchemeAndHierPart(const Uri& uri, std::string* out_path);
131
+ Status ExtractFromUriQuery(const Uri& uri);
132
+
133
+ public:
134
+ /// \brief Construct a new AzureOptions from an URI.
135
+ ///
136
+ /// Supported formats:
137
+ ///
138
+ /// 1. abfs[s]://[:\<password\>@]\<account\>.blob.core.windows.net
139
+ /// [/\<container\>[/\<path\>]]
140
+ /// 2. abfs[s]://\<container\>[:\<password\>]@\<account\>.dfs.core.windows.net
141
+ /// [/path]
142
+ /// 3. abfs[s]://[\<account[:\<password\>]@]\<host[.domain]\>[\<:port\>]
143
+ /// [/\<container\>[/path]]
144
+ /// 4. abfs[s]://[\<account[:\<password\>]@]\<container\>[/path]
145
+ ///
146
+ /// 1. and 2. are compatible with the Azure Data Lake Storage Gen2 URIs:
147
+ /// https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction-abfs-uri
148
+ ///
149
+ /// 3. is for Azure Blob Storage compatible service including Azurite.
150
+ ///
151
+ /// 4. is a shorter version of 1. and 2.
152
+ ///
153
+ /// Note that there is no difference between abfs and abfss. HTTPS is
154
+ /// used with abfs by default. You can force to use HTTP by specifying
155
+ /// "enable_tls=false" query.
156
+ ///
157
+ /// Supported query parameters:
158
+ ///
159
+ /// * blob_storage_authority: Set AzureOptions::blob_storage_authority
160
+ /// * dfs_storage_authority: Set AzureOptions::dfs_storage_authority
161
+ /// * enable_tls: If it's "false" or "0", HTTP not HTTPS is used.
162
+ /// * credential_kind: One of "default", "anonymous",
163
+ /// "workload_identity". If "default" is specified, it's just
164
+ /// ignored. If "anonymous" is specified,
165
+ /// AzureOptions::ConfigureAnonymousCredential() is called. If
166
+ /// "workload_identity" is specified,
167
+ /// AzureOptions::ConfigureWorkloadIdentityCredential() is called.
168
+ /// * tenant_id: You must specify "client_id" and "client_secret"
169
+ /// too. AzureOptions::ConfigureClientSecretCredential() is called.
170
+ /// * client_id: If you don't specify "tenant_id" and
171
+ /// "client_secret",
172
+ /// AzureOptions::ConfigureManagedIdentityCredential() is
173
+ /// called. If you specify "tenant_id" and "client_secret" too,
174
+ /// AzureOptions::ConfigureClientSecretCredential() is called.
175
+ /// * client_secret: You must specify "tenant_id" and "client_id"
176
+ /// too. AzureOptions::ConfigureClientSecretCredential() is called.
177
+ static Result<AzureOptions> FromUri(const Uri& uri, std::string* out_path);
178
+ static Result<AzureOptions> FromUri(const std::string& uri, std::string* out_path);
179
+
180
+ Status ConfigureDefaultCredential();
181
+ Status ConfigureAnonymousCredential();
182
+ Status ConfigureAccountKeyCredential(const std::string& account_key);
183
+ Status ConfigureClientSecretCredential(const std::string& tenant_id,
184
+ const std::string& client_id,
185
+ const std::string& client_secret);
186
+ Status ConfigureManagedIdentityCredential(const std::string& client_id = std::string());
187
+ Status ConfigureWorkloadIdentityCredential();
188
+
189
+ bool Equals(const AzureOptions& other) const;
190
+
191
+ std::string AccountBlobUrl(const std::string& account_name) const;
192
+ std::string AccountDfsUrl(const std::string& account_name) const;
193
+
194
+ Result<std::unique_ptr<Azure::Storage::Blobs::BlobServiceClient>>
195
+ MakeBlobServiceClient() const;
196
+
197
+ Result<std::unique_ptr<Azure::Storage::Files::DataLake::DataLakeServiceClient>>
198
+ MakeDataLakeServiceClient() const;
199
+ };
200
+
201
+ /// \brief FileSystem implementation backed by Azure Blob Storage (ABS) [1] and
202
+ /// Azure Data Lake Storage Gen2 (ADLS Gen2) [2].
203
+ ///
204
+ /// ADLS Gen2 isn't a dedicated service or account type. It's a set of capabilities that
205
+ /// support high throughput analytic workloads, built on Azure Blob Storage. All the data
206
+ /// ingested via the ADLS Gen2 APIs is persisted as blobs in the storage account.
207
+ /// ADLS Gen2 provides filesystem semantics, file-level security, and Hadoop
208
+ /// compatibility. ADLS Gen1 exists as a separate object that will retired on 2024-02-29
209
+ /// and new ADLS accounts use Gen2 instead.
210
+ ///
211
+ /// ADLS Gen2 and Blob APIs can operate on the same data, but there are
212
+ /// some limitations [3]. The ones that are relevant to this
213
+ /// implementation are listed here:
214
+ ///
215
+ /// - You can't use Blob APIs, and ADLS APIs to write to the same instance of a file. If
216
+ /// you write to a file by using ADLS APIs then that file's blocks won't be visible
217
+ /// to calls to the GetBlockList Blob API. The only exception is when you're
218
+ /// overwriting.
219
+ /// - When you use the ListBlobs operation without specifying a delimiter, the results
220
+ /// include both directories and blobs. If you choose to use a delimiter, use only a
221
+ /// forward slash (/) -- the only supported delimiter.
222
+ /// - If you use the DeleteBlob API to delete a directory, that directory is deleted only
223
+ /// if it's empty. This means that you can't use the Blob API delete directories
224
+ /// recursively.
225
+ ///
226
+ /// [1]: https://azure.microsoft.com/en-us/products/storage/blobs
227
+ /// [2]: https://azure.microsoft.com/en-us/products/storage/data-lake-storage
228
+ /// [3]:
229
+ /// https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-known-issues
230
+ class ARROW_EXPORT AzureFileSystem : public FileSystem {
231
+ private:
232
+ class Impl;
233
+ std::unique_ptr<Impl> impl_;
234
+
235
+ explicit AzureFileSystem(std::unique_ptr<Impl>&& impl);
236
+
237
+ friend class TestAzureFileSystem;
238
+ void ForceCachedHierarchicalNamespaceSupport(int hns_support);
239
+
240
+ public:
241
+ ~AzureFileSystem() override = default;
242
+
243
+ static Result<std::shared_ptr<AzureFileSystem>> Make(
244
+ const AzureOptions& options, const io::IOContext& = io::default_io_context());
245
+
246
+ std::string type_name() const override { return "abfs"; }
247
+
248
+ /// Return the original Azure options when constructing the filesystem
249
+ const AzureOptions& options() const;
250
+
251
+ bool Equals(const FileSystem& other) const override;
252
+
253
+ /// \cond FALSE
254
+ using FileSystem::CreateDir;
255
+ using FileSystem::DeleteDirContents;
256
+ using FileSystem::GetFileInfo;
257
+ using FileSystem::OpenAppendStream;
258
+ using FileSystem::OpenOutputStream;
259
+ /// \endcond
260
+
261
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
262
+
263
+ Result<FileInfoVector> GetFileInfo(const FileSelector& select) override;
264
+
265
+ Status CreateDir(const std::string& path, bool recursive) override;
266
+
267
+ /// \brief Delete a directory and its contents recursively.
268
+ ///
269
+ /// Atomicity is guaranteed only on Hierarchical Namespace Storage accounts.
270
+ Status DeleteDir(const std::string& path) override;
271
+
272
+ /// \brief Non-atomically deletes the contents of a directory.
273
+ ///
274
+ /// This function can return a bad Status after only partially deleting the
275
+ /// contents of the directory.
276
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override;
277
+
278
+ /// \brief Deletion of all the containers in the storage account (not
279
+ /// implemented for safety reasons).
280
+ ///
281
+ /// \return Status::NotImplemented
282
+ Status DeleteRootDirContents() override;
283
+
284
+ /// \brief Deletes a file.
285
+ ///
286
+ /// Supported on both flat namespace and Hierarchical Namespace storage
287
+ /// accounts. A check is made to guarantee the parent directory doesn't
288
+ /// disappear after the blob is deleted and while this operation is running,
289
+ /// no other client can delete the parent directory due to the use of leases.
290
+ ///
291
+ /// This means applications can safely retry this operation without coordination to
292
+ /// guarantee only one client/process is trying to delete the same file.
293
+ Status DeleteFile(const std::string& path) override;
294
+
295
+ /// \brief Move/rename a file or directory.
296
+ ///
297
+ /// There are no files immediately at the root directory, so paths like
298
+ /// "/segment" always refer to a container of the storage account and are
299
+ /// treated as directories.
300
+ ///
301
+ /// If `dest` exists but the operation fails for some reason, `Move`
302
+ /// guarantees `dest` is not lost.
303
+ ///
304
+ /// Conditions for a successful move:
305
+ ///
306
+ /// 1. `src` must exist.
307
+ /// 2. `dest` can't contain a strict path prefix of `src`. More generally,
308
+ /// a directory can't be made a subdirectory of itself.
309
+ /// 3. If `dest` already exists and it's a file, `src` must also be a file.
310
+ /// `dest` is then replaced by `src`.
311
+ /// 4. All components of `dest` must exist, except for the last.
312
+ /// 5. If `dest` already exists and it's a directory, `src` must also be a
313
+ /// directory and `dest` must be empty. `dest` is then replaced by `src`
314
+ /// and its contents.
315
+ ///
316
+ /// Leases are used to guarantee the pre-condition checks and the rename
317
+ /// operation are atomic: other clients can't invalidate the pre-condition in
318
+ /// the time between the checks and the actual rename operation.
319
+ ///
320
+ /// This is possible because Move() is only support on storage accounts with
321
+ /// Hierarchical Namespace Support enabled.
322
+ ///
323
+ /// ## Limitations
324
+ ///
325
+ /// - Moves are not supported on storage accounts without
326
+ /// Hierarchical Namespace support enabled
327
+ /// - Moves across different containers are not supported
328
+ /// - Moving a path of the form `/container` is not supported as it would
329
+ /// require moving all the files in a container to another container.
330
+ /// The only exception is a `Move("/container_a", "/container_b")` where
331
+ /// both containers are empty or `container_b` doesn't even exist.
332
+ /// The atomicity of the emptiness checks followed by the renaming operation
333
+ /// is guaranteed by the use of leases.
334
+ Status Move(const std::string& src, const std::string& dest) override;
335
+
336
+ Status CopyFile(const std::string& src, const std::string& dest) override;
337
+
338
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
339
+ const std::string& path) override;
340
+
341
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(const FileInfo& info) override;
342
+
343
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
344
+ const std::string& path) override;
345
+
346
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
347
+ const FileInfo& info) override;
348
+
349
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
350
+ const std::string& path,
351
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
352
+
353
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
354
+ const std::string& path,
355
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
356
+ };
357
+
358
+ } // namespace arrow::fs
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/filesystem.h ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <chrono>
21
+ #include <cstdint>
22
+ #include <functional>
23
+ #include <iosfwd>
24
+ #include <memory>
25
+ #include <string>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ #include "arrow/filesystem/type_fwd.h"
30
+ #include "arrow/io/interfaces.h"
31
+ #include "arrow/type_fwd.h"
32
+ #include "arrow/util/compare.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/type_fwd.h"
35
+ #include "arrow/util/visibility.h"
36
+ #include "arrow/util/windows_fixup.h"
37
+
38
+ namespace arrow {
39
+ namespace fs {
40
+
41
+ using arrow::util::Uri;
42
+
43
+ // A system clock time point expressed as a 64-bit (or more) number of
44
+ // nanoseconds since the epoch.
45
+ using TimePoint =
46
+ std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>;
47
+
48
+ ARROW_EXPORT std::string ToString(FileType);
49
+
50
+ ARROW_EXPORT std::ostream& operator<<(std::ostream& os, FileType);
51
+
52
+ static const int64_t kNoSize = -1;
53
+ static const TimePoint kNoTime = TimePoint(TimePoint::duration(-1));
54
+
55
+ /// \brief FileSystem entry info
56
+ struct ARROW_EXPORT FileInfo : public util::EqualityComparable<FileInfo> {
57
+ FileInfo() = default;
58
+ FileInfo(FileInfo&&) = default;
59
+ FileInfo& operator=(FileInfo&&) = default;
60
+ FileInfo(const FileInfo&) = default;
61
+ FileInfo& operator=(const FileInfo&) = default;
62
+
63
+ explicit FileInfo(std::string path, FileType type = FileType::Unknown)
64
+ : path_(std::move(path)), type_(type) {}
65
+
66
+ /// The file type
67
+ FileType type() const { return type_; }
68
+ void set_type(FileType type) { type_ = type; }
69
+
70
+ /// The full file path in the filesystem
71
+ const std::string& path() const { return path_; }
72
+ void set_path(std::string path) { path_ = std::move(path); }
73
+
74
+ /// The file base name (component after the last directory separator)
75
+ std::string base_name() const;
76
+
77
+ // The directory base name (component before the file base name).
78
+ std::string dir_name() const;
79
+
80
+ /// The size in bytes, if available
81
+ ///
82
+ /// Only regular files are guaranteed to have a size.
83
+ int64_t size() const { return size_; }
84
+ void set_size(int64_t size) { size_ = size; }
85
+
86
+ /// The file extension (excluding the dot)
87
+ std::string extension() const;
88
+
89
+ /// The time of last modification, if available
90
+ TimePoint mtime() const { return mtime_; }
91
+ void set_mtime(TimePoint mtime) { mtime_ = mtime; }
92
+
93
+ bool IsFile() const { return type_ == FileType::File; }
94
+ bool IsDirectory() const { return type_ == FileType::Directory; }
95
+
96
+ bool Equals(const FileInfo& other) const {
97
+ return type() == other.type() && path() == other.path() && size() == other.size() &&
98
+ mtime() == other.mtime();
99
+ }
100
+
101
+ std::string ToString() const;
102
+
103
+ /// Function object implementing less-than comparison and hashing by
104
+ /// path, to support sorting infos, using them as keys, and other
105
+ /// interactions with the STL.
106
+ struct ByPath {
107
+ bool operator()(const FileInfo& l, const FileInfo& r) const {
108
+ return l.path() < r.path();
109
+ }
110
+
111
+ size_t operator()(const FileInfo& i) const {
112
+ return std::hash<std::string>{}(i.path());
113
+ }
114
+ };
115
+
116
+ protected:
117
+ std::string path_;
118
+ FileType type_ = FileType::Unknown;
119
+ int64_t size_ = kNoSize;
120
+ TimePoint mtime_ = kNoTime;
121
+ };
122
+
123
+ ARROW_EXPORT std::ostream& operator<<(std::ostream& os, const FileInfo&);
124
+
125
+ /// \brief File selector for filesystem APIs
126
+ struct ARROW_EXPORT FileSelector {
127
+ /// The directory in which to select files.
128
+ /// If the path exists but doesn't point to a directory, this should be an error.
129
+ std::string base_dir;
130
+ /// The behavior if `base_dir` isn't found in the filesystem. If false,
131
+ /// an error is returned. If true, an empty selection is returned.
132
+ bool allow_not_found;
133
+ /// Whether to recurse into subdirectories.
134
+ bool recursive;
135
+ /// The maximum number of subdirectories to recurse into.
136
+ int32_t max_recursion;
137
+
138
+ FileSelector() : allow_not_found(false), recursive(false), max_recursion(INT32_MAX) {}
139
+ };
140
+
141
+ /// \brief FileSystem, path pair
142
+ struct ARROW_EXPORT FileLocator {
143
+ std::shared_ptr<FileSystem> filesystem;
144
+ std::string path;
145
+ };
146
+
147
+ using FileInfoVector = std::vector<FileInfo>;
148
+ using FileInfoGenerator = std::function<Future<FileInfoVector>()>;
149
+
150
+ } // namespace fs
151
+
152
+ template <>
153
+ struct IterationTraits<fs::FileInfoVector> {
154
+ static fs::FileInfoVector End() { return {}; }
155
+ static bool IsEnd(const fs::FileInfoVector& val) { return val.empty(); }
156
+ };
157
+
158
+ namespace fs {
159
+
160
+ /// \brief Abstract file system API
161
+ class ARROW_EXPORT FileSystem
162
+ /// \cond false
163
+ : public std::enable_shared_from_this<FileSystem>
164
+ /// \endcond
165
+ { // NOLINT
166
+ public:
167
+ virtual ~FileSystem();
168
+
169
+ virtual std::string type_name() const = 0;
170
+
171
+ /// EXPERIMENTAL: The IOContext associated with this filesystem.
172
+ const io::IOContext& io_context() const { return io_context_; }
173
+
174
+ /// Normalize path for the given filesystem
175
+ ///
176
+ /// The default implementation of this method is a no-op, but subclasses
177
+ /// may allow normalizing irregular path forms (such as Windows local paths).
178
+ virtual Result<std::string> NormalizePath(std::string path);
179
+
180
+ /// \brief Ensure a URI (or path) is compatible with the given filesystem and return the
181
+ /// path
182
+ ///
183
+ /// \param uri_string A URI representing a resource in the given filesystem.
184
+ ///
185
+ /// This method will check to ensure the given filesystem is compatible with the
186
+ /// URI. This can be useful when the user provides both a URI and a filesystem or
187
+ /// when a user provides multiple URIs that should be compatible with the same
188
+ /// filesystem.
189
+ ///
190
+ /// uri_string can be an absolute path instead of a URI. In that case it will ensure
191
+ /// the filesystem (if supplied) is the local filesystem (or some custom filesystem that
192
+ /// is capable of reading local paths) and will normalize the path's file separators.
193
+ ///
194
+ /// Note, this method only checks to ensure the URI scheme is valid. It will not detect
195
+ /// inconsistencies like a mismatching region or endpoint override.
196
+ ///
197
+ /// \return The path inside the filesystem that is indicated by the URI.
198
+ virtual Result<std::string> PathFromUri(const std::string& uri_string) const;
199
+
200
+ virtual bool Equals(const FileSystem& other) const = 0;
201
+
202
+ virtual bool Equals(const std::shared_ptr<FileSystem>& other) const {
203
+ return Equals(*other);
204
+ }
205
+
206
+ /// Get info for the given target.
207
+ ///
208
+ /// Any symlink is automatically dereferenced, recursively.
209
+ /// A nonexistent or unreachable file returns an Ok status and
210
+ /// has a FileType of value NotFound. An error status indicates
211
+ /// a truly exceptional condition (low-level I/O error, etc.).
212
+ virtual Result<FileInfo> GetFileInfo(const std::string& path) = 0;
213
+ /// Same, for many targets at once.
214
+ virtual Result<FileInfoVector> GetFileInfo(const std::vector<std::string>& paths);
215
+ /// Same, according to a selector.
216
+ ///
217
+ /// The selector's base directory will not be part of the results, even if
218
+ /// it exists.
219
+ /// If it doesn't exist, see `FileSelector::allow_not_found`.
220
+ virtual Result<FileInfoVector> GetFileInfo(const FileSelector& select) = 0;
221
+
222
+ /// Async version of GetFileInfo
223
+ virtual Future<FileInfoVector> GetFileInfoAsync(const std::vector<std::string>& paths);
224
+
225
+ /// Streaming async version of GetFileInfo
226
+ ///
227
+ /// The returned generator is not async-reentrant, i.e. you need to wait for
228
+ /// the returned future to complete before calling the generator again.
229
+ virtual FileInfoGenerator GetFileInfoGenerator(const FileSelector& select);
230
+
231
+ /// Create a directory and subdirectories.
232
+ ///
233
+ /// This function succeeds if the directory already exists.
234
+ virtual Status CreateDir(const std::string& path, bool recursive) = 0;
235
+ Status CreateDir(const std::string& path) { return CreateDir(path, true); }
236
+
237
+ /// Delete a directory and its contents, recursively.
238
+ virtual Status DeleteDir(const std::string& path) = 0;
239
+
240
+ /// Delete a directory's contents, recursively.
241
+ ///
242
+ /// Like DeleteDir, but doesn't delete the directory itself.
243
+ /// Passing an empty path ("" or "/") is disallowed, see DeleteRootDirContents.
244
+ virtual Status DeleteDirContents(const std::string& path, bool missing_dir_ok) = 0;
245
+ Status DeleteDirContents(const std::string& path) {
246
+ return DeleteDirContents(path, false);
247
+ }
248
+
249
+ /// Async version of DeleteDirContents.
250
+ virtual Future<> DeleteDirContentsAsync(const std::string& path, bool missing_dir_ok);
251
+
252
+ /// Async version of DeleteDirContents.
253
+ ///
254
+ /// This overload allows missing directories.
255
+ Future<> DeleteDirContentsAsync(const std::string& path);
256
+
257
+ /// EXPERIMENTAL: Delete the root directory's contents, recursively.
258
+ ///
259
+ /// Implementations may decide to raise an error if this operation is
260
+ /// too dangerous.
261
+ // NOTE: may decide to remove this if it's deemed not useful
262
+ virtual Status DeleteRootDirContents() = 0;
263
+
264
+ /// Delete a file.
265
+ virtual Status DeleteFile(const std::string& path) = 0;
266
+ /// Delete many files.
267
+ ///
268
+ /// The default implementation issues individual delete operations in sequence.
269
+ virtual Status DeleteFiles(const std::vector<std::string>& paths);
270
+
271
+ /// Move / rename a file or directory.
272
+ ///
273
+ /// If the destination exists:
274
+ /// - if it is a non-empty directory, an error is returned
275
+ /// - otherwise, if it has the same type as the source, it is replaced
276
+ /// - otherwise, behavior is unspecified (implementation-dependent).
277
+ virtual Status Move(const std::string& src, const std::string& dest) = 0;
278
+
279
+ /// Copy a file.
280
+ ///
281
+ /// If the destination exists and is a directory, an error is returned.
282
+ /// Otherwise, it is replaced.
283
+ virtual Status CopyFile(const std::string& src, const std::string& dest) = 0;
284
+
285
+ /// Open an input stream for sequential reading.
286
+ virtual Result<std::shared_ptr<io::InputStream>> OpenInputStream(
287
+ const std::string& path) = 0;
288
+
289
+ /// Open an input stream for sequential reading.
290
+ ///
291
+ /// This override assumes the given FileInfo validly represents the file's
292
+ /// characteristics, and may optimize access depending on them (for example
293
+ /// avoid querying the file size or its existence).
294
+ virtual Result<std::shared_ptr<io::InputStream>> OpenInputStream(const FileInfo& info);
295
+
296
+ /// Open an input file for random access reading.
297
+ virtual Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
298
+ const std::string& path) = 0;
299
+
300
+ /// Open an input file for random access reading.
301
+ ///
302
+ /// This override assumes the given FileInfo validly represents the file's
303
+ /// characteristics, and may optimize access depending on them (for example
304
+ /// avoid querying the file size or its existence).
305
+ virtual Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
306
+ const FileInfo& info);
307
+
308
+ /// Async version of OpenInputStream
309
+ virtual Future<std::shared_ptr<io::InputStream>> OpenInputStreamAsync(
310
+ const std::string& path);
311
+
312
+ /// Async version of OpenInputStream
313
+ virtual Future<std::shared_ptr<io::InputStream>> OpenInputStreamAsync(
314
+ const FileInfo& info);
315
+
316
+ /// Async version of OpenInputFile
317
+ virtual Future<std::shared_ptr<io::RandomAccessFile>> OpenInputFileAsync(
318
+ const std::string& path);
319
+
320
+ /// Async version of OpenInputFile
321
+ virtual Future<std::shared_ptr<io::RandomAccessFile>> OpenInputFileAsync(
322
+ const FileInfo& info);
323
+
324
+ /// Open an output stream for sequential writing.
325
+ ///
326
+ /// If the target already exists, existing data is truncated.
327
+ virtual Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
328
+ const std::string& path,
329
+ const std::shared_ptr<const KeyValueMetadata>& metadata) = 0;
330
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(const std::string& path);
331
+
332
+ /// Open an output stream for appending.
333
+ ///
334
+ /// If the target doesn't exist, a new empty file is created.
335
+ ///
336
+ /// Note: some filesystem implementations do not support efficient appending
337
+ /// to an existing file, in which case this method will return NotImplemented.
338
+ /// Consider writing to multiple files (using e.g. the dataset layer) instead.
339
+ virtual Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
340
+ const std::string& path,
341
+ const std::shared_ptr<const KeyValueMetadata>& metadata) = 0;
342
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(const std::string& path);
343
+
344
+ protected:
345
+ explicit FileSystem(io::IOContext io_context = io::default_io_context())
346
+ : io_context_(std::move(io_context)) {}
347
+
348
+ io::IOContext io_context_;
349
+ // Whether metadata operations (such as GetFileInfo or OpenInputStream)
350
+ // are cheap enough that the default async variants don't bother with
351
+ // a thread pool.
352
+ bool default_async_is_sync_ = true;
353
+ };
354
+
355
+ using FileSystemFactory = std::function<Result<std::shared_ptr<FileSystem>>(
356
+ const Uri& uri, const io::IOContext& io_context, std::string* out_path)>;
357
+
358
+ /// \brief A FileSystem implementation that delegates to another
359
+ /// implementation after prepending a fixed base path.
360
+ ///
361
+ /// This is useful to expose a logical view of a subtree of a filesystem,
362
+ /// for example a directory in a LocalFileSystem.
363
+ /// This works on abstract paths, i.e. paths using forward slashes and
364
+ /// and a single root "/". Windows paths are not guaranteed to work.
365
+ /// This makes no security guarantee. For example, symlinks may allow to
366
+ /// "escape" the subtree and access other parts of the underlying filesystem.
367
+ class ARROW_EXPORT SubTreeFileSystem : public FileSystem {
368
+ public:
369
+ // This constructor may abort if base_path is invalid.
370
+ explicit SubTreeFileSystem(const std::string& base_path,
371
+ std::shared_ptr<FileSystem> base_fs);
372
+ ~SubTreeFileSystem() override;
373
+
374
+ std::string type_name() const override { return "subtree"; }
375
+ std::string base_path() const { return base_path_; }
376
+ std::shared_ptr<FileSystem> base_fs() const { return base_fs_; }
377
+
378
+ Result<std::string> NormalizePath(std::string path) override;
379
+ Result<std::string> PathFromUri(const std::string& uri_string) const override;
380
+
381
+ bool Equals(const FileSystem& other) const override;
382
+
383
+ /// \cond FALSE
384
+ using FileSystem::CreateDir;
385
+ using FileSystem::DeleteDirContents;
386
+ using FileSystem::GetFileInfo;
387
+ using FileSystem::OpenAppendStream;
388
+ using FileSystem::OpenOutputStream;
389
+ /// \endcond
390
+
391
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
392
+ Result<FileInfoVector> GetFileInfo(const FileSelector& select) override;
393
+
394
+ FileInfoGenerator GetFileInfoGenerator(const FileSelector& select) override;
395
+
396
+ Status CreateDir(const std::string& path, bool recursive) override;
397
+
398
+ Status DeleteDir(const std::string& path) override;
399
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override;
400
+ Status DeleteRootDirContents() override;
401
+
402
+ Status DeleteFile(const std::string& path) override;
403
+
404
+ Status Move(const std::string& src, const std::string& dest) override;
405
+
406
+ Status CopyFile(const std::string& src, const std::string& dest) override;
407
+
408
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
409
+ const std::string& path) override;
410
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(const FileInfo& info) override;
411
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
412
+ const std::string& path) override;
413
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
414
+ const FileInfo& info) override;
415
+
416
+ Future<std::shared_ptr<io::InputStream>> OpenInputStreamAsync(
417
+ const std::string& path) override;
418
+ Future<std::shared_ptr<io::InputStream>> OpenInputStreamAsync(
419
+ const FileInfo& info) override;
420
+ Future<std::shared_ptr<io::RandomAccessFile>> OpenInputFileAsync(
421
+ const std::string& path) override;
422
+ Future<std::shared_ptr<io::RandomAccessFile>> OpenInputFileAsync(
423
+ const FileInfo& info) override;
424
+
425
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
426
+ const std::string& path,
427
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
428
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
429
+ const std::string& path,
430
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
431
+
432
+ protected:
433
+ SubTreeFileSystem() = default;
434
+
435
+ const std::string base_path_;
436
+ std::shared_ptr<FileSystem> base_fs_;
437
+
438
+ Result<std::string> PrependBase(const std::string& s) const;
439
+ Result<std::string> PrependBaseNonEmpty(const std::string& s) const;
440
+ Result<std::string> StripBase(const std::string& s) const;
441
+ Status FixInfo(FileInfo* info) const;
442
+
443
+ static Result<std::string> NormalizeBasePath(
444
+ std::string base_path, const std::shared_ptr<FileSystem>& base_fs);
445
+ };
446
+
447
+ /// \brief A FileSystem implementation that delegates to another
448
+ /// implementation but inserts latencies at various points.
449
+ class ARROW_EXPORT SlowFileSystem : public FileSystem {
450
+ public:
451
+ SlowFileSystem(std::shared_ptr<FileSystem> base_fs,
452
+ std::shared_ptr<io::LatencyGenerator> latencies);
453
+ SlowFileSystem(std::shared_ptr<FileSystem> base_fs, double average_latency);
454
+ SlowFileSystem(std::shared_ptr<FileSystem> base_fs, double average_latency,
455
+ int32_t seed);
456
+
457
+ std::string type_name() const override { return "slow"; }
458
+ bool Equals(const FileSystem& other) const override;
459
+ Result<std::string> PathFromUri(const std::string& uri_string) const override;
460
+
461
+ /// \cond FALSE
462
+ using FileSystem::CreateDir;
463
+ using FileSystem::DeleteDirContents;
464
+ using FileSystem::GetFileInfo;
465
+ using FileSystem::OpenAppendStream;
466
+ using FileSystem::OpenOutputStream;
467
+ /// \endcond
468
+
469
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
470
+ Result<FileInfoVector> GetFileInfo(const FileSelector& select) override;
471
+
472
+ Status CreateDir(const std::string& path, bool recursive) override;
473
+
474
+ Status DeleteDir(const std::string& path) override;
475
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override;
476
+ Status DeleteRootDirContents() override;
477
+
478
+ Status DeleteFile(const std::string& path) override;
479
+
480
+ Status Move(const std::string& src, const std::string& dest) override;
481
+
482
+ Status CopyFile(const std::string& src, const std::string& dest) override;
483
+
484
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
485
+ const std::string& path) override;
486
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(const FileInfo& info) override;
487
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
488
+ const std::string& path) override;
489
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
490
+ const FileInfo& info) override;
491
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
492
+ const std::string& path,
493
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
494
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
495
+ const std::string& path,
496
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
497
+
498
+ protected:
499
+ std::shared_ptr<FileSystem> base_fs_;
500
+ std::shared_ptr<io::LatencyGenerator> latencies_;
501
+ };
502
+
503
+ /// \brief Ensure all registered filesystem implementations are finalized.
504
+ ///
505
+ /// Individual finalizers may wait for concurrent calls to finish so as to avoid
506
+ /// race conditions. After this function has been called, all filesystem APIs
507
+ /// will fail with an error.
508
+ ///
509
+ /// The user is responsible for synchronization of calls to this function.
510
+ void EnsureFinalized();
511
+
512
+ /// \defgroup filesystem-factories Functions for creating FileSystem instances
513
+ ///
514
+ /// @{
515
+
516
+ /// \brief Create a new FileSystem by URI
517
+ ///
518
+ /// Recognized schemes are "file", "mock", "hdfs", "viewfs", "s3",
519
+ /// "gs" and "gcs".
520
+ ///
521
+ /// Support for other schemes can be added using RegisterFileSystemFactory.
522
+ ///
523
+ /// \param[in] uri a URI-based path, ex: file:///some/local/path
524
+ /// \param[out] out_path (optional) Path inside the filesystem.
525
+ /// \return out_fs FileSystem instance.
526
+ ARROW_EXPORT
527
+ Result<std::shared_ptr<FileSystem>> FileSystemFromUri(const std::string& uri,
528
+ std::string* out_path = NULLPTR);
529
+
530
+ /// \brief Create a new FileSystem by URI with a custom IO context
531
+ ///
532
+ /// Recognized schemes are "file", "mock", "hdfs", "viewfs", "s3",
533
+ /// "gs" and "gcs".
534
+ ///
535
+ /// Support for other schemes can be added using RegisterFileSystemFactory.
536
+ ///
537
+ /// \param[in] uri a URI-based path, ex: file:///some/local/path
538
+ /// \param[in] io_context an IOContext which will be associated with the filesystem
539
+ /// \param[out] out_path (optional) Path inside the filesystem.
540
+ /// \return out_fs FileSystem instance.
541
+ ARROW_EXPORT
542
+ Result<std::shared_ptr<FileSystem>> FileSystemFromUri(const std::string& uri,
543
+ const io::IOContext& io_context,
544
+ std::string* out_path = NULLPTR);
545
+
546
+ /// \brief Create a new FileSystem by URI
547
+ ///
548
+ /// Support for other schemes can be added using RegisterFileSystemFactory.
549
+ ///
550
+ /// Same as FileSystemFromUri, but in addition also recognize non-URIs
551
+ /// and treat them as local filesystem paths. Only absolute local filesystem
552
+ /// paths are allowed.
553
+ ARROW_EXPORT
554
+ Result<std::shared_ptr<FileSystem>> FileSystemFromUriOrPath(
555
+ const std::string& uri, std::string* out_path = NULLPTR);
556
+
557
+ /// \brief Create a new FileSystem by URI with a custom IO context
558
+ ///
559
+ /// Support for other schemes can be added using RegisterFileSystemFactory.
560
+ ///
561
+ /// Same as FileSystemFromUri, but in addition also recognize non-URIs
562
+ /// and treat them as local filesystem paths. Only absolute local filesystem
563
+ /// paths are allowed.
564
+ ARROW_EXPORT
565
+ Result<std::shared_ptr<FileSystem>> FileSystemFromUriOrPath(
566
+ const std::string& uri, const io::IOContext& io_context,
567
+ std::string* out_path = NULLPTR);
568
+
569
+ /// @}
570
+
571
+ /// \defgroup filesystem-factory-registration Helpers for FileSystem registration
572
+ ///
573
+ /// @{
574
+
575
+ /// \brief Register a FileSystem factory
576
+ ///
577
+ /// Support for custom URI schemes can be added by registering a factory
578
+ /// for the corresponding FileSystem.
579
+ ///
580
+ /// \param[in] scheme a Uri scheme which the factory will handle.
581
+ /// If a factory has already been registered for a scheme,
582
+ /// the new factory will be ignored.
583
+ /// \param[in] factory a function which can produce a FileSystem for Uris which match
584
+ /// scheme.
585
+ /// \param[in] finalizer a function which must be called to finalize the factory before
586
+ /// the process exits, or nullptr if no finalization is necessary.
587
+ /// \return raises KeyError if a name collision occurs.
588
+ ARROW_EXPORT Status RegisterFileSystemFactory(std::string scheme,
589
+ FileSystemFactory factory,
590
+ std::function<void()> finalizer = {});
591
+
592
+ /// \brief Register FileSystem factories from a shared library
593
+ ///
594
+ /// FileSystem implementations may be housed in separate shared libraries and only
595
+ /// registered when the shared library is explicitly loaded. FileSystemRegistrar is
596
+ /// provided to simplify definition of such libraries: each instance at namespace scope
597
+ /// in the library will register a factory for a scheme. Any library which uses
598
+ /// FileSystemRegistrars and which must be dynamically loaded should be loaded using
599
+ /// LoadFileSystemFactories(), which will additionally merge registries are if necessary
600
+ /// (static linkage to arrow can produce isolated registries).
601
+ ARROW_EXPORT Status LoadFileSystemFactories(const char* libpath);
602
+
603
+ struct ARROW_EXPORT FileSystemRegistrar {
604
+ /// \brief Register a FileSystem factory at load time
605
+ ///
606
+ /// Support for custom URI schemes can be added by registering a factory for the
607
+ /// corresponding FileSystem. An instance of this helper can be defined at namespace
608
+ /// scope to cause the factory to be registered at load time.
609
+ ///
610
+ /// Global constructors will finish execution before main() starts if the registrar is
611
+ /// linked into the same binary as main(), or before dlopen()/LoadLibrary() returns if
612
+ /// the library in which the registrar is defined is dynamically loaded.
613
+ ///
614
+ /// \code
615
+ /// FileSystemRegistrar kSlowFileSystemModule{
616
+ /// "slowfile",
617
+ /// [](const Uri& uri, const io::IOContext& io_context, std::string* out_path)
618
+ /// ->Result<std::shared_ptr<FileSystem>> {
619
+ /// auto local_uri = "file" + uri.ToString().substr(uri.scheme().size());
620
+ /// ARROW_ASSIGN_OR_RAISE(auto base_fs,
621
+ /// FileSystemFromUri(local_uri, io_context, out_path));
622
+ /// double average_latency = 1;
623
+ /// int32_t seed = 0xDEADBEEF;
624
+ /// ARROW_ASSIGN_OR_RAISE(auto params, uri.query_item());
625
+ /// for (const auto& [key, value] : params) {
626
+ /// if (key == "average_latency") {
627
+ /// average_latency = std::stod(value);
628
+ /// }
629
+ /// if (key == "seed") {
630
+ /// seed = std::stoi(value, nullptr, /*base=*/16);
631
+ /// }
632
+ /// }
633
+ /// return std::make_shared<SlowFileSystem>(base_fs, average_latency, seed);
634
+ /// }));
635
+ /// \endcode
636
+ ///
637
+ /// \param[in] scheme a Uri scheme which the factory will handle.
638
+ /// If a factory has already been registered for a scheme, the
639
+ /// new factory will be ignored.
640
+ /// \param[in] factory a function which can produce a FileSystem for Uris which match
641
+ /// scheme.
642
+ /// \param[in] finalizer a function which must be called to finalize the factory before
643
+ /// the process exits, or nullptr if no finalization is necessary.
644
+ FileSystemRegistrar(std::string scheme, FileSystemFactory factory,
645
+ std::function<void()> finalizer = {});
646
+ };
647
+
648
+ /// @}
649
+
650
+ namespace internal {
651
+ ARROW_EXPORT void* GetFileSystemRegistry();
652
+ } // namespace internal
653
+
654
+ /// \brief Copy files, including from one FileSystem to another
655
+ ///
656
+ /// If a source and destination are resident in the same FileSystem FileSystem::CopyFile
657
+ /// will be used, otherwise the file will be opened as a stream in both FileSystems and
658
+ /// chunks copied from the source to the destination. No directories will be created.
659
+ ARROW_EXPORT
660
+ Status CopyFiles(const std::vector<FileLocator>& sources,
661
+ const std::vector<FileLocator>& destinations,
662
+ const io::IOContext& io_context = io::default_io_context(),
663
+ int64_t chunk_size = 1024 * 1024, bool use_threads = true);
664
+
665
+ /// \brief Copy selected files, including from one FileSystem to another
666
+ ///
667
+ /// Directories will be created under the destination base directory as needed.
668
+ ARROW_EXPORT
669
+ Status CopyFiles(const std::shared_ptr<FileSystem>& source_fs,
670
+ const FileSelector& source_sel,
671
+ const std::shared_ptr<FileSystem>& destination_fs,
672
+ const std::string& destination_base_dir,
673
+ const io::IOContext& io_context = io::default_io_context(),
674
+ int64_t chunk_size = 1024 * 1024, bool use_threads = true);
675
+
676
+ struct FileSystemGlobalOptions {
677
+ /// Path to a single PEM file holding all TLS CA certificates
678
+ ///
679
+ /// If empty, the underlying TLS library's defaults will be used.
680
+ std::string tls_ca_file_path;
681
+
682
+ /// Path to a directory holding TLS CA certificates in individual PEM files
683
+ /// named along the OpenSSL "hashed" format.
684
+ ///
685
+ /// If empty, the underlying TLS library's defaults will be used.
686
+ std::string tls_ca_dir_path;
687
+ };
688
+
689
+ /// EXPERIMENTAL: optional global initialization routine
690
+ ///
691
+ /// This is for environments (such as manylinux) where the path
692
+ /// to TLS CA certificates needs to be configured at runtime.
693
+ ARROW_EXPORT
694
+ Status Initialize(const FileSystemGlobalOptions& options);
695
+
696
+ } // namespace fs
697
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/filesystem_library.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/filesystem/filesystem.h"
21
+
22
+ namespace arrow::fs {
23
+ extern "C" {
24
+
25
+ // ARROW_FORCE_EXPORT ensures this function's visibility is
26
+ // _declspec(dllexport)/[[gnu::visibility("default")]] even when
27
+ // this header is #included by a non-arrow source, as in a third
28
+ // party filesystem implementation.
29
+ ARROW_FORCE_EXPORT void* arrow_filesystem_get_registry() {
30
+ // In the case where libarrow is linked statically both to the executable and to a
31
+ // dynamically loaded filesystem implementation library, the library contains a
32
+ // duplicate definition of the registry into which the library's instances of
33
+ // FileSystemRegistrar insert their factories. This function is made accessible to
34
+ // dlsym/GetProcAddress to enable detection of such duplicate registries and merging
35
+ // into the registry accessible to the executable.
36
+ return internal::GetFileSystemRegistry();
37
+ }
38
+ }
39
+ } // namespace arrow::fs
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/gcsfs.h ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <optional>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "arrow/filesystem/filesystem.h"
26
+ #include "arrow/util/uri.h"
27
+
28
+ namespace arrow {
29
+ namespace fs {
30
+ namespace internal {
31
+
32
+ // Opaque wrapper for GCS's library credentials to avoid exposing in Arrow headers.
33
+ struct GcsCredentialsHolder;
34
+
35
+ } // namespace internal
36
+
37
+ class GcsFileSystem;
38
+
39
+ /// \brief Container for GCS Credentials and information necessary to recreate them.
40
+ class ARROW_EXPORT GcsCredentials {
41
+ public:
42
+ bool Equals(const GcsCredentials& other) const;
43
+ bool anonymous() const { return anonymous_; }
44
+ const std::string& access_token() const { return access_token_; }
45
+ TimePoint expiration() const { return expiration_; }
46
+ const std::string& target_service_account() const { return target_service_account_; }
47
+ const std::string& json_credentials() const { return json_credentials_; }
48
+ const std::shared_ptr<internal::GcsCredentialsHolder>& holder() const {
49
+ return holder_;
50
+ }
51
+
52
+ private:
53
+ GcsCredentials() = default;
54
+ bool anonymous_ = false;
55
+ std::string access_token_;
56
+ TimePoint expiration_;
57
+ std::string target_service_account_;
58
+ std::string json_credentials_;
59
+ std::shared_ptr<internal::GcsCredentialsHolder> holder_;
60
+ friend class GcsFileSystem;
61
+ friend struct GcsOptions;
62
+ };
63
+
64
+ /// Options for the GcsFileSystem implementation.
65
+ struct ARROW_EXPORT GcsOptions {
66
+ /// \brief Equivalent to GcsOptions::Defaults().
67
+ GcsOptions();
68
+ GcsCredentials credentials;
69
+
70
+ std::string endpoint_override;
71
+ std::string scheme;
72
+ /// \brief Location to use for creating buckets.
73
+ std::string default_bucket_location;
74
+
75
+ /// \brief If set used to control total time allowed for retrying underlying
76
+ /// errors.
77
+ ///
78
+ /// The default policy is to retry for up to 15 minutes.
79
+ std::optional<double> retry_limit_seconds;
80
+
81
+ /// \brief Default metadata for OpenOutputStream.
82
+ ///
83
+ /// This will be ignored if non-empty metadata is passed to OpenOutputStream.
84
+ std::shared_ptr<const KeyValueMetadata> default_metadata;
85
+
86
+ /// \brief The project to use for creating buckets.
87
+ ///
88
+ /// If not set, the library uses the GOOGLE_CLOUD_PROJECT environment
89
+ /// variable. Most I/O operations do not need a project id, only applications
90
+ /// that create new buckets need a project id.
91
+ std::optional<std::string> project_id;
92
+
93
+ bool Equals(const GcsOptions& other) const;
94
+
95
+ /// \brief Initialize with Google Default Credentials
96
+ ///
97
+ /// Create options configured to use [Application Default Credentials][aip/4110]. The
98
+ /// details of this mechanism are too involved to describe here, but suffice is to say
99
+ /// that applications can override any defaults using an environment variable
100
+ /// (`GOOGLE_APPLICATION_CREDENTIALS`), and that the defaults work with most Google
101
+ /// Cloud Platform deployment environments (GCE, GKE, Cloud Run, etc.), and that have
102
+ /// the same behavior as the `gcloud` CLI tool on your workstation.
103
+ ///
104
+ /// \see https://cloud.google.com/docs/authentication
105
+ ///
106
+ /// [aip/4110]: https://google.aip.dev/auth/4110
107
+ static GcsOptions Defaults();
108
+
109
+ /// \brief Initialize with anonymous credentials
110
+ static GcsOptions Anonymous();
111
+
112
+ /// \brief Initialize with access token
113
+ ///
114
+ /// These credentials are useful when using an out-of-band mechanism to fetch access
115
+ /// tokens. Note that access tokens are time limited, you will need to manually refresh
116
+ /// the tokens created by the out-of-band mechanism.
117
+ static GcsOptions FromAccessToken(const std::string& access_token,
118
+ TimePoint expiration);
119
+
120
+ /// \brief Initialize with service account impersonation
121
+ ///
122
+ /// Service account impersonation allows one principal (a user or service account) to
123
+ /// impersonate a service account. It requires that the calling principal has the
124
+ /// necessary permissions *on* the service account.
125
+ static GcsOptions FromImpersonatedServiceAccount(
126
+ const GcsCredentials& base_credentials, const std::string& target_service_account);
127
+
128
+ /// Creates service account credentials from a JSON object in string form.
129
+ ///
130
+ /// The @p json_object is expected to be in the format described by [aip/4112]. Such an
131
+ /// object contains the identity of a service account, as well as a private key that can
132
+ /// be used to sign tokens, showing the caller was holding the private key.
133
+ ///
134
+ /// In GCP one can create several "keys" for each service account, and these keys are
135
+ /// downloaded as a JSON "key file". The contents of such a file are in the format
136
+ /// required by this function. Remember that key files and their contents should be
137
+ /// treated as any other secret with security implications, think of them as passwords
138
+ /// (because they are!), don't store them or output them where unauthorized persons may
139
+ /// read them.
140
+ ///
141
+ /// Most applications should probably use default credentials, maybe pointing them to a
142
+ /// file with these contents. Using this function may be useful when the json object is
143
+ /// obtained from a Cloud Secret Manager or a similar service.
144
+ ///
145
+ /// [aip/4112]: https://google.aip.dev/auth/4112
146
+ static GcsOptions FromServiceAccountCredentials(const std::string& json_object);
147
+
148
+ /// Initialize from URIs such as "gs://bucket/object".
149
+ static Result<GcsOptions> FromUri(const arrow::util::Uri& uri, std::string* out_path);
150
+ static Result<GcsOptions> FromUri(const std::string& uri, std::string* out_path);
151
+ };
152
+
153
+ /// \brief GCS-backed FileSystem implementation.
154
+ ///
155
+ /// GCS (Google Cloud Storage - https://cloud.google.com/storage) is a scalable object
156
+ /// storage system for any amount of data. The main abstractions in GCS are buckets and
157
+ /// objects. A bucket is a namespace for objects, buckets can store any number of objects,
158
+ /// tens of millions and even billions is not uncommon. Each object contains a single
159
+ /// blob of data, up to 5TiB in size. Buckets are typically configured to keep a single
160
+ /// version of each object, but versioning can be enabled. Versioning is important because
161
+ /// objects are immutable, once created one cannot append data to the object or modify the
162
+ /// object data in any way.
163
+ ///
164
+ /// GCS buckets are in a global namespace, if a Google Cloud customer creates a bucket
165
+ /// named `foo` no other customer can create a bucket with the same name. Note that a
166
+ /// principal (a user or service account) may only list the buckets they are entitled to,
167
+ /// and then only within a project. It is not possible to list "all" the buckets.
168
+ ///
169
+ /// Within each bucket objects are in flat namespace. GCS does not have folders or
170
+ /// directories. However, following some conventions it is possible to emulate
171
+ /// directories. To this end, this class:
172
+ ///
173
+ /// - All buckets are treated as directories at the "root"
174
+ /// - Creating a root directory results in a new bucket being created, this may be slower
175
+ /// than most GCS operations.
176
+ /// - The class creates marker objects for a directory, using a metadata attribute to
177
+ /// annotate the file.
178
+ /// - GCS can list all the objects with a given prefix, this is used to emulate listing
179
+ /// of directories.
180
+ /// - In object lists GCS can summarize all the objects with a common prefix as a single
181
+ /// entry, this is used to emulate non-recursive lists. Note that GCS list time is
182
+ /// proportional to the number of objects in the prefix. Listing recursively takes
183
+ /// almost the same time as non-recursive lists.
184
+ ///
185
+ class ARROW_EXPORT GcsFileSystem : public FileSystem {
186
+ public:
187
+ ~GcsFileSystem() override = default;
188
+
189
+ std::string type_name() const override;
190
+ const GcsOptions& options() const;
191
+
192
+ bool Equals(const FileSystem& other) const override;
193
+ Result<std::string> PathFromUri(const std::string& uri_string) const override;
194
+
195
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
196
+ Result<FileInfoVector> GetFileInfo(const FileSelector& select) override;
197
+
198
+ Status CreateDir(const std::string& path, bool recursive) override;
199
+
200
+ Status DeleteDir(const std::string& path) override;
201
+
202
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok = false) override;
203
+
204
+ /// This is not implemented in GcsFileSystem, as it would be too dangerous.
205
+ Status DeleteRootDirContents() override;
206
+
207
+ Status DeleteFile(const std::string& path) override;
208
+
209
+ Status Move(const std::string& src, const std::string& dest) override;
210
+
211
+ Status CopyFile(const std::string& src, const std::string& dest) override;
212
+
213
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
214
+ const std::string& path) override;
215
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(const FileInfo& info) override;
216
+
217
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
218
+ const std::string& path) override;
219
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
220
+ const FileInfo& info) override;
221
+
222
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
223
+ const std::string& path,
224
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
225
+
226
+ ARROW_DEPRECATED(
227
+ "Deprecated. "
228
+ "OpenAppendStream is unsupported on the GCS FileSystem.")
229
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
230
+ const std::string& path,
231
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
232
+
233
+ /// Create a GcsFileSystem instance from the given options.
234
+ // TODO(ARROW-16884): make this return Result for consistency
235
+ static std::shared_ptr<GcsFileSystem> Make(
236
+ const GcsOptions& options, const io::IOContext& = io::default_io_context());
237
+
238
+ private:
239
+ explicit GcsFileSystem(const GcsOptions& options, const io::IOContext& io_context);
240
+
241
+ class Impl;
242
+ std::shared_ptr<Impl> impl_;
243
+ };
244
+
245
+ } // namespace fs
246
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/hdfs.h ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <vector>
23
+
24
+ #include "arrow/filesystem/filesystem.h"
25
+ #include "arrow/io/hdfs.h"
26
+ #include "arrow/util/uri.h"
27
+
28
+ namespace arrow::fs {
29
+
30
+ /// Options for the HDFS implementation.
31
+ struct ARROW_EXPORT HdfsOptions {
32
+ HdfsOptions() = default;
33
+ ~HdfsOptions() = default;
34
+
35
+ /// Hdfs configuration options, contains host, port, driver
36
+ io::HdfsConnectionConfig connection_config;
37
+
38
+ /// Used by Hdfs OpenWritable Interface.
39
+ int32_t buffer_size = 0;
40
+ int16_t replication = 3;
41
+ int64_t default_block_size = 0;
42
+
43
+ void ConfigureEndPoint(std::string host, int port);
44
+ void ConfigureReplication(int16_t replication);
45
+ void ConfigureUser(std::string user_name);
46
+ void ConfigureBufferSize(int32_t buffer_size);
47
+ void ConfigureBlockSize(int64_t default_block_size);
48
+ void ConfigureKerberosTicketCachePath(std::string path);
49
+ void ConfigureExtraConf(std::string key, std::string val);
50
+
51
+ bool Equals(const HdfsOptions& other) const;
52
+
53
+ static Result<HdfsOptions> FromUri(const ::arrow::util::Uri& uri);
54
+ static Result<HdfsOptions> FromUri(const std::string& uri);
55
+ };
56
+
57
+ /// HDFS-backed FileSystem implementation.
58
+ ///
59
+ /// implementation notes:
60
+ /// - This is a wrapper of arrow/io/hdfs, so we can use FileSystem API to handle hdfs.
61
+ class ARROW_EXPORT HadoopFileSystem : public FileSystem {
62
+ public:
63
+ ~HadoopFileSystem() override;
64
+
65
+ std::string type_name() const override { return "hdfs"; }
66
+ HdfsOptions options() const;
67
+ bool Equals(const FileSystem& other) const override;
68
+ Result<std::string> PathFromUri(const std::string& uri_string) const override;
69
+
70
+ /// \cond FALSE
71
+ using FileSystem::CreateDir;
72
+ using FileSystem::DeleteDirContents;
73
+ using FileSystem::GetFileInfo;
74
+ using FileSystem::OpenAppendStream;
75
+ using FileSystem::OpenOutputStream;
76
+ /// \endcond
77
+
78
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
79
+ Result<std::vector<FileInfo>> GetFileInfo(const FileSelector& select) override;
80
+
81
+ Status CreateDir(const std::string& path, bool recursive) override;
82
+
83
+ Status DeleteDir(const std::string& path) override;
84
+
85
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override;
86
+
87
+ Status DeleteRootDirContents() override;
88
+
89
+ Status DeleteFile(const std::string& path) override;
90
+
91
+ Status Move(const std::string& src, const std::string& dest) override;
92
+
93
+ Status CopyFile(const std::string& src, const std::string& dest) override;
94
+
95
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
96
+ const std::string& path) override;
97
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
98
+ const std::string& path) override;
99
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
100
+ const std::string& path,
101
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
102
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
103
+ const std::string& path,
104
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
105
+
106
+ /// Create a HdfsFileSystem instance from the given options.
107
+ static Result<std::shared_ptr<HadoopFileSystem>> Make(
108
+ const HdfsOptions& options, const io::IOContext& = io::default_io_context());
109
+
110
+ protected:
111
+ HadoopFileSystem(const HdfsOptions& options, const io::IOContext&);
112
+
113
+ class Impl;
114
+ std::unique_ptr<Impl> impl_;
115
+ };
116
+
117
+ } // namespace arrow::fs
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/localfs.h ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <vector>
23
+
24
+ #include "arrow/filesystem/filesystem.h"
25
+
26
+ namespace arrow {
27
+ namespace internal {
28
+
29
+ class Uri;
30
+
31
+ }
32
+
33
+ namespace fs {
34
+
35
+ /// Options for the LocalFileSystem implementation.
36
+ struct ARROW_EXPORT LocalFileSystemOptions {
37
+ static constexpr int32_t kDefaultDirectoryReadahead = 16;
38
+ static constexpr int32_t kDefaultFileInfoBatchSize = 1000;
39
+
40
+ /// Whether OpenInputStream and OpenInputFile return a mmap'ed file,
41
+ /// or a regular one.
42
+ bool use_mmap = false;
43
+
44
+ /// Options related to `GetFileInfoGenerator` interface.
45
+
46
+ /// EXPERIMENTAL: The maximum number of directories processed in parallel
47
+ /// by `GetFileInfoGenerator`.
48
+ int32_t directory_readahead = kDefaultDirectoryReadahead;
49
+
50
+ /// EXPERIMENTAL: The maximum number of entries aggregated into each
51
+ /// FileInfoVector chunk by `GetFileInfoGenerator`.
52
+ ///
53
+ /// Since each FileInfo entry needs a separate `stat` system call, a
54
+ /// directory with a very large number of files may take a lot of time to
55
+ /// process entirely. By generating a FileInfoVector after this chunk
56
+ /// size is reached, we ensure FileInfo entries can start being consumed
57
+ /// from the FileInfoGenerator with less initial latency.
58
+ int32_t file_info_batch_size = kDefaultFileInfoBatchSize;
59
+
60
+ /// \brief Initialize with defaults
61
+ static LocalFileSystemOptions Defaults();
62
+
63
+ bool Equals(const LocalFileSystemOptions& other) const;
64
+
65
+ static Result<LocalFileSystemOptions> FromUri(const ::arrow::util::Uri& uri,
66
+ std::string* out_path);
67
+ };
68
+
69
+ /// \brief A FileSystem implementation accessing files on the local machine.
70
+ ///
71
+ /// This class handles only `/`-separated paths. If desired, conversion
72
+ /// from Windows backslash-separated paths should be done by the caller.
73
+ /// Details such as symlinks are abstracted away (symlinks are always
74
+ /// followed, except when deleting an entry).
75
+ class ARROW_EXPORT LocalFileSystem : public FileSystem {
76
+ public:
77
+ explicit LocalFileSystem(const io::IOContext& = io::default_io_context());
78
+ explicit LocalFileSystem(const LocalFileSystemOptions&,
79
+ const io::IOContext& = io::default_io_context());
80
+ ~LocalFileSystem() override;
81
+
82
+ std::string type_name() const override { return "local"; }
83
+
84
+ Result<std::string> NormalizePath(std::string path) override;
85
+ Result<std::string> PathFromUri(const std::string& uri_string) const override;
86
+
87
+ bool Equals(const FileSystem& other) const override;
88
+
89
+ LocalFileSystemOptions options() const { return options_; }
90
+
91
+ /// \cond FALSE
92
+ using FileSystem::CreateDir;
93
+ using FileSystem::DeleteDirContents;
94
+ using FileSystem::GetFileInfo;
95
+ using FileSystem::OpenAppendStream;
96
+ using FileSystem::OpenOutputStream;
97
+ /// \endcond
98
+
99
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
100
+ Result<std::vector<FileInfo>> GetFileInfo(const FileSelector& select) override;
101
+ FileInfoGenerator GetFileInfoGenerator(const FileSelector& select) override;
102
+
103
+ Status CreateDir(const std::string& path, bool recursive) override;
104
+
105
+ Status DeleteDir(const std::string& path) override;
106
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override;
107
+ Status DeleteRootDirContents() override;
108
+
109
+ Status DeleteFile(const std::string& path) override;
110
+
111
+ Status Move(const std::string& src, const std::string& dest) override;
112
+
113
+ Status CopyFile(const std::string& src, const std::string& dest) override;
114
+
115
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
116
+ const std::string& path) override;
117
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
118
+ const std::string& path) override;
119
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
120
+ const std::string& path,
121
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
122
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
123
+ const std::string& path,
124
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
125
+
126
+ protected:
127
+ LocalFileSystemOptions options_;
128
+ };
129
+
130
+ } // namespace fs
131
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/mockfs.h ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <iosfwd>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <string_view>
24
+ #include <vector>
25
+
26
+ #include "arrow/filesystem/filesystem.h"
27
+ #include "arrow/util/windows_fixup.h"
28
+
29
+ namespace arrow::fs::internal {
30
+
31
+ struct MockDirInfo {
32
+ std::string full_path;
33
+ TimePoint mtime;
34
+
35
+ bool operator==(const MockDirInfo& other) const {
36
+ return mtime == other.mtime && full_path == other.full_path;
37
+ }
38
+
39
+ ARROW_FRIEND_EXPORT friend std::ostream& operator<<(std::ostream&, const MockDirInfo&);
40
+ };
41
+
42
+ struct MockFileInfo {
43
+ std::string full_path;
44
+ TimePoint mtime;
45
+ std::string_view data;
46
+
47
+ bool operator==(const MockFileInfo& other) const {
48
+ return mtime == other.mtime && full_path == other.full_path && data == other.data;
49
+ }
50
+
51
+ ARROW_FRIEND_EXPORT friend std::ostream& operator<<(std::ostream&, const MockFileInfo&);
52
+ };
53
+
54
+ /// A mock FileSystem implementation that holds its contents in memory.
55
+ ///
56
+ /// Useful for validating the FileSystem API, writing conformance suite,
57
+ /// and bootstrapping FileSystem-based APIs.
58
+ class ARROW_EXPORT MockFileSystem : public FileSystem {
59
+ public:
60
+ explicit MockFileSystem(TimePoint current_time,
61
+ const io::IOContext& = io::default_io_context());
62
+ ~MockFileSystem() override;
63
+
64
+ std::string type_name() const override { return "mock"; }
65
+
66
+ bool Equals(const FileSystem& other) const override;
67
+ Result<std::string> PathFromUri(const std::string& uri_string) const override;
68
+
69
+ /// \cond FALSE
70
+ using FileSystem::CreateDir;
71
+ using FileSystem::DeleteDirContents;
72
+ using FileSystem::GetFileInfo;
73
+ using FileSystem::OpenAppendStream;
74
+ using FileSystem::OpenOutputStream;
75
+ /// \endcond
76
+
77
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
78
+ Result<std::vector<FileInfo>> GetFileInfo(const FileSelector& select) override;
79
+
80
+ Status CreateDir(const std::string& path, bool recursive) override;
81
+
82
+ Status DeleteDir(const std::string& path) override;
83
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override;
84
+ Status DeleteRootDirContents() override;
85
+
86
+ Status DeleteFile(const std::string& path) override;
87
+
88
+ Status Move(const std::string& src, const std::string& dest) override;
89
+
90
+ Status CopyFile(const std::string& src, const std::string& dest) override;
91
+
92
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
93
+ const std::string& path) override;
94
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
95
+ const std::string& path) override;
96
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
97
+ const std::string& path,
98
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
99
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
100
+ const std::string& path,
101
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
102
+
103
+ // Contents-dumping helpers to ease testing.
104
+ // Output is lexicographically-ordered by full path.
105
+ std::vector<MockDirInfo> AllDirs();
106
+ std::vector<MockFileInfo> AllFiles();
107
+
108
+ // Create a File with a content from a string.
109
+ Status CreateFile(const std::string& path, std::string_view content,
110
+ bool recursive = true);
111
+
112
+ // Create a MockFileSystem out of (empty) FileInfo. The content of every
113
+ // file is empty and of size 0. All directories will be created recursively.
114
+ static Result<std::shared_ptr<FileSystem>> Make(TimePoint current_time,
115
+ const std::vector<FileInfo>& infos);
116
+
117
+ class Impl;
118
+
119
+ protected:
120
+ std::unique_ptr<Impl> impl_;
121
+ };
122
+
123
+ class ARROW_EXPORT MockAsyncFileSystem : public MockFileSystem {
124
+ public:
125
+ explicit MockAsyncFileSystem(TimePoint current_time,
126
+ const io::IOContext& io_context = io::default_io_context())
127
+ : MockFileSystem(current_time, io_context) {
128
+ default_async_is_sync_ = false;
129
+ }
130
+
131
+ FileInfoGenerator GetFileInfoGenerator(const FileSelector& select) override;
132
+ };
133
+
134
+ } // namespace arrow::fs::internal
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/path_util.h ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <optional>
21
+ #include <string>
22
+ #include <string_view>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "arrow/type_fwd.h"
27
+
28
+ namespace arrow {
29
+ namespace fs {
30
+ namespace internal {
31
+
32
+ constexpr char kSep = '/';
33
+
34
+ // Computations on abstract paths (not local paths with system-dependent behaviour).
35
+ // Abstract paths are typically used in URIs.
36
+
37
+ // Split an abstract path into its individual components.
38
+ ARROW_EXPORT
39
+ std::vector<std::string> SplitAbstractPath(const std::string& path, char sep = kSep);
40
+
41
+ // Slice the individual components of an abstract path and combine them
42
+ //
43
+ // If offset or length are negative then an empty string is returned
44
+ // If offset is >= the number of components then an empty string is returned
45
+ // If offset + length is >= the number of components then length is truncated
46
+ ARROW_EXPORT
47
+ std::string SliceAbstractPath(const std::string& path, int offset, int length,
48
+ char sep = kSep);
49
+
50
+ // Return the extension of the file
51
+ ARROW_EXPORT std::string GetAbstractPathExtension(const std::string& s);
52
+
53
+ // Return the depth (number of components) of an abstract path
54
+ //
55
+ // Trailing slashes do not count towards depth
56
+ // Leading slashes do not count towards depth
57
+ //
58
+ // The root path ("/") has depth 0
59
+ ARROW_EXPORT int GetAbstractPathDepth(std::string_view path);
60
+
61
+ // Return the parent directory and basename of an abstract path. Both values may be
62
+ // empty.
63
+ ARROW_EXPORT
64
+ std::pair<std::string, std::string> GetAbstractPathParent(const std::string& s);
65
+
66
+ // Validate an abstract path.
67
+ ARROW_EXPORT
68
+ Status ValidateAbstractPath(std::string_view path);
69
+
70
+ // Validate the components of an abstract path.
71
+ ARROW_EXPORT
72
+ Status ValidateAbstractPathParts(const std::vector<std::string>& parts);
73
+
74
+ // Append a non-empty stem to an abstract path.
75
+ ARROW_EXPORT
76
+ std::string ConcatAbstractPath(std::string_view base, std::string_view stem);
77
+
78
+ // Make path relative to base, if it starts with base. Otherwise error out.
79
+ ARROW_EXPORT
80
+ Result<std::string> MakeAbstractPathRelative(const std::string& base,
81
+ const std::string& path);
82
+
83
+ ARROW_EXPORT
84
+ std::string EnsureLeadingSlash(std::string_view s);
85
+
86
+ ARROW_EXPORT
87
+ std::string_view RemoveLeadingSlash(std::string_view s);
88
+
89
+ ARROW_EXPORT
90
+ std::string EnsureTrailingSlash(std::string_view s);
91
+
92
+ /// \brief remove the forward slash (if any) from the given path
93
+ /// \param s the input path
94
+ /// \param preserve_root if true, allow a path of just "/" to remain unchanged
95
+ ARROW_EXPORT
96
+ std::string_view RemoveTrailingSlash(std::string_view s, bool preserve_root = false);
97
+
98
+ ARROW_EXPORT
99
+ Status AssertNoTrailingSlash(std::string_view s);
100
+
101
+ inline bool HasTrailingSlash(std::string_view s) {
102
+ return !s.empty() && s.back() == kSep;
103
+ }
104
+
105
+ inline bool HasLeadingSlash(std::string_view s) {
106
+ return !s.empty() && s.front() == kSep;
107
+ }
108
+
109
+ ARROW_EXPORT
110
+ bool IsAncestorOf(std::string_view ancestor, std::string_view descendant);
111
+
112
+ ARROW_EXPORT
113
+ std::optional<std::string_view> RemoveAncestor(std::string_view ancestor,
114
+ std::string_view descendant);
115
+
116
+ /// Return a vector of ancestors between a base path and a descendant.
117
+ /// For example,
118
+ ///
119
+ /// AncestorsFromBasePath("a/b", "a/b/c/d/e") -> ["a/b/c", "a/b/c/d"]
120
+ ARROW_EXPORT
121
+ std::vector<std::string> AncestorsFromBasePath(std::string_view base_path,
122
+ std::string_view descendant);
123
+
124
+ /// Given a vector of paths of directories which must be created, produce a the minimal
125
+ /// subset for passing to CreateDir(recursive=true) by removing redundant parent
126
+ /// directories
127
+ ARROW_EXPORT
128
+ std::vector<std::string> MinimalCreateDirSet(std::vector<std::string> dirs);
129
+
130
+ // Join the components of an abstract path.
131
+ template <class StringIt>
132
+ std::string JoinAbstractPath(StringIt it, StringIt end, char sep = kSep) {
133
+ std::string path;
134
+ for (; it != end; ++it) {
135
+ if (it->empty()) continue;
136
+
137
+ if (!path.empty()) {
138
+ path += sep;
139
+ }
140
+ path += *it;
141
+ }
142
+ return path;
143
+ }
144
+
145
+ template <class StringRange>
146
+ std::string JoinAbstractPath(const StringRange& range, char sep = kSep) {
147
+ return JoinAbstractPath(range.begin(), range.end(), sep);
148
+ }
149
+
150
+ /// Convert slashes to backslashes, on all platforms. Mostly useful for testing.
151
+ ARROW_EXPORT
152
+ std::string ToBackslashes(std::string_view s);
153
+
154
+ /// Ensure a local path is abstract, by converting backslashes to regular slashes
155
+ /// on Windows. Return the path unchanged on other systems.
156
+ ARROW_EXPORT
157
+ std::string ToSlashes(std::string_view s);
158
+
159
+ ARROW_EXPORT
160
+ bool IsEmptyPath(std::string_view s);
161
+
162
+ ARROW_EXPORT
163
+ bool IsLikelyUri(std::string_view s);
164
+
165
+ class ARROW_EXPORT Globber {
166
+ public:
167
+ ~Globber();
168
+ explicit Globber(std::string pattern);
169
+ bool Matches(const std::string& path);
170
+
171
+ protected:
172
+ struct Impl;
173
+ std::unique_ptr<Impl> impl_;
174
+ };
175
+
176
+ } // namespace internal
177
+ } // namespace fs
178
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/s3_test_util.h ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <utility>
23
+
24
+ #include <gtest/gtest.h>
25
+
26
+ #include "arrow/filesystem/s3fs.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/testing/gtest_util.h"
29
+ #include "arrow/testing/util.h"
30
+ #include "arrow/util/checked_cast.h"
31
+ #include "arrow/util/macros.h"
32
+
33
+ namespace arrow {
34
+ namespace fs {
35
+
36
+ // A minio test server, managed as a child process
37
+
38
+ class MinioTestServer {
39
+ public:
40
+ MinioTestServer();
41
+ ~MinioTestServer();
42
+
43
+ Status Start();
44
+
45
+ Status Stop();
46
+
47
+ std::string connect_string() const;
48
+
49
+ std::string access_key() const;
50
+
51
+ std::string secret_key() const;
52
+
53
+ private:
54
+ struct Impl;
55
+ std::unique_ptr<Impl> impl_;
56
+ };
57
+
58
+ // A Minio "environment" that spawns Minio processes in advances, such as
59
+ // to hide process launch latencies during testing.
60
+
61
+ class MinioTestEnvironment : public ::testing::Environment {
62
+ public:
63
+ MinioTestEnvironment();
64
+ ~MinioTestEnvironment();
65
+
66
+ void SetUp() override;
67
+
68
+ Result<std::shared_ptr<MinioTestServer>> GetOneServer();
69
+
70
+ protected:
71
+ struct Impl;
72
+ std::unique_ptr<Impl> impl_;
73
+ };
74
+
75
+ // A global test "environment", to ensure that the S3 API is initialized before
76
+ // running unit tests.
77
+
78
+ class S3Environment : public ::testing::Environment {
79
+ public:
80
+ // We set this environment variable to speed up tests by ensuring
81
+ // DefaultAWSCredentialsProviderChain does not query (inaccessible)
82
+ // EC2 metadata endpoint.
83
+ // This must be done before spawning any Minio child process to avoid any race
84
+ // condition accessing environment variables.
85
+ S3Environment() : ec2_metadata_disabled_guard_("AWS_EC2_METADATA_DISABLED", "true") {}
86
+
87
+ void SetUp() override {
88
+ // Change this to increase logging during tests
89
+ S3GlobalOptions options;
90
+ options.log_level = S3LogLevel::Fatal;
91
+ ASSERT_OK(InitializeS3(options));
92
+ }
93
+
94
+ void TearDown() override { ASSERT_OK(FinalizeS3()); }
95
+
96
+ private:
97
+ EnvVarGuard ec2_metadata_disabled_guard_;
98
+ };
99
+
100
+ } // namespace fs
101
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/s3fs.h ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <vector>
23
+
24
+ #include "arrow/filesystem/filesystem.h"
25
+ #include "arrow/util/macros.h"
26
+ #include "arrow/util/uri.h"
27
+
28
+ namespace Aws {
29
+ namespace Auth {
30
+
31
+ class AWSCredentialsProvider;
32
+ class STSAssumeRoleCredentialsProvider;
33
+
34
+ } // namespace Auth
35
+ namespace STS {
36
+ class STSClient;
37
+ }
38
+ } // namespace Aws
39
+
40
+ namespace arrow {
41
+ namespace fs {
42
+
43
+ /// Options for using a proxy for S3
44
+ struct ARROW_EXPORT S3ProxyOptions {
45
+ std::string scheme;
46
+ std::string host;
47
+ int port = -1;
48
+ std::string username;
49
+ std::string password;
50
+
51
+ /// Initialize from URI such as http://username:password@host:port
52
+ /// or http://host:port
53
+ static Result<S3ProxyOptions> FromUri(const std::string& uri);
54
+ static Result<S3ProxyOptions> FromUri(const ::arrow::util::Uri& uri);
55
+
56
+ bool Equals(const S3ProxyOptions& other) const;
57
+ };
58
+
59
+ enum class S3CredentialsKind : int8_t {
60
+ /// Anonymous access (no credentials used)
61
+ Anonymous,
62
+ /// Use default AWS credentials, configured through environment variables
63
+ Default,
64
+ /// Use explicitly-provided access key pair
65
+ Explicit,
66
+ /// Assume role through a role ARN
67
+ Role,
68
+ /// Use web identity token to assume role, configured through environment variables
69
+ WebIdentity
70
+ };
71
+
72
+ /// Pure virtual class for describing custom S3 retry strategies
73
+ class ARROW_EXPORT S3RetryStrategy {
74
+ public:
75
+ virtual ~S3RetryStrategy() = default;
76
+
77
+ /// Simple struct where each field corresponds to a field in Aws::Client::AWSError
78
+ struct AWSErrorDetail {
79
+ /// Corresponds to AWSError::GetErrorType()
80
+ int error_type;
81
+ /// Corresponds to AWSError::GetMessage()
82
+ std::string message;
83
+ /// Corresponds to AWSError::GetExceptionName()
84
+ std::string exception_name;
85
+ /// Corresponds to AWSError::ShouldRetry()
86
+ bool should_retry;
87
+ };
88
+ /// Returns true if the S3 request resulting in the provided error should be retried.
89
+ virtual bool ShouldRetry(const AWSErrorDetail& error, int64_t attempted_retries) = 0;
90
+ /// Returns the time in milliseconds the S3 client should sleep for until retrying.
91
+ virtual int64_t CalculateDelayBeforeNextRetry(const AWSErrorDetail& error,
92
+ int64_t attempted_retries) = 0;
93
+ /// Returns a stock AWS Default retry strategy.
94
+ static std::shared_ptr<S3RetryStrategy> GetAwsDefaultRetryStrategy(
95
+ int64_t max_attempts);
96
+ /// Returns a stock AWS Standard retry strategy.
97
+ static std::shared_ptr<S3RetryStrategy> GetAwsStandardRetryStrategy(
98
+ int64_t max_attempts);
99
+ };
100
+
101
+ /// Options for the S3FileSystem implementation.
102
+ struct ARROW_EXPORT S3Options {
103
+ /// \brief AWS region to connect to.
104
+ ///
105
+ /// If unset, the AWS SDK will choose a default value. The exact algorithm
106
+ /// depends on the SDK version. Before 1.8, the default is hardcoded
107
+ /// to "us-east-1". Since 1.8, several heuristics are used to determine
108
+ /// the region (environment variables, configuration profile, EC2 metadata
109
+ /// server).
110
+ std::string region;
111
+
112
+ /// \brief Socket connection timeout, in seconds
113
+ ///
114
+ /// If negative, the AWS SDK default value is used (typically 1 second).
115
+ double connect_timeout = -1;
116
+
117
+ /// \brief Socket read timeout on Windows and macOS, in seconds
118
+ ///
119
+ /// If negative, the AWS SDK default value is used (typically 3 seconds).
120
+ /// This option is ignored on non-Windows, non-macOS systems.
121
+ double request_timeout = -1;
122
+
123
+ /// If non-empty, override region with a connect string such as "localhost:9000"
124
+ // XXX perhaps instead take a URL like "http://localhost:9000"?
125
+ std::string endpoint_override;
126
+ /// S3 connection transport, default "https"
127
+ std::string scheme = "https";
128
+
129
+ /// ARN of role to assume
130
+ std::string role_arn;
131
+ /// Optional identifier for an assumed role session.
132
+ std::string session_name;
133
+ /// Optional external identifier to pass to STS when assuming a role
134
+ std::string external_id;
135
+ /// Frequency (in seconds) to refresh temporary credentials from assumed role
136
+ int load_frequency = 900;
137
+
138
+ /// If connection is through a proxy, set options here
139
+ S3ProxyOptions proxy_options;
140
+
141
+ /// AWS credentials provider
142
+ std::shared_ptr<Aws::Auth::AWSCredentialsProvider> credentials_provider;
143
+
144
+ /// Type of credentials being used. Set along with credentials_provider.
145
+ S3CredentialsKind credentials_kind = S3CredentialsKind::Default;
146
+
147
+ /// Whether to use virtual addressing of buckets
148
+ ///
149
+ /// If true, then virtual addressing is always enabled.
150
+ /// If false, then virtual addressing is only enabled if `endpoint_override` is empty.
151
+ ///
152
+ /// This can be used for non-AWS backends that only support virtual hosted-style access.
153
+ bool force_virtual_addressing = false;
154
+
155
+ /// Whether OutputStream writes will be issued in the background, without blocking.
156
+ bool background_writes = true;
157
+
158
+ /// Whether to allow creation of buckets
159
+ ///
160
+ /// When S3FileSystem creates new buckets, it does not pass any non-default settings.
161
+ /// In AWS S3, the bucket and all objects will be not publicly visible, and there
162
+ /// will be no bucket policies and no resource tags. To have more control over how
163
+ /// buckets are created, use a different API to create them.
164
+ bool allow_bucket_creation = false;
165
+
166
+ /// Whether to allow deletion of buckets
167
+ bool allow_bucket_deletion = false;
168
+
169
+ /// \brief Default metadata for OpenOutputStream.
170
+ ///
171
+ /// This will be ignored if non-empty metadata is passed to OpenOutputStream.
172
+ std::shared_ptr<const KeyValueMetadata> default_metadata;
173
+
174
+ /// Optional retry strategy to determine which error types should be retried, and the
175
+ /// delay between retries.
176
+ std::shared_ptr<S3RetryStrategy> retry_strategy;
177
+
178
+ S3Options();
179
+
180
+ /// Configure with the default AWS credentials provider chain.
181
+ void ConfigureDefaultCredentials();
182
+
183
+ /// Configure with anonymous credentials. This will only let you access public buckets.
184
+ void ConfigureAnonymousCredentials();
185
+
186
+ /// Configure with explicit access and secret key.
187
+ void ConfigureAccessKey(const std::string& access_key, const std::string& secret_key,
188
+ const std::string& session_token = "");
189
+
190
+ /// Configure with credentials from an assumed role.
191
+ void ConfigureAssumeRoleCredentials(
192
+ const std::string& role_arn, const std::string& session_name = "",
193
+ const std::string& external_id = "", int load_frequency = 900,
194
+ const std::shared_ptr<Aws::STS::STSClient>& stsClient = NULLPTR);
195
+
196
+ /// Configure with credentials from role assumed using a web identity token
197
+ void ConfigureAssumeRoleWithWebIdentityCredentials();
198
+
199
+ std::string GetAccessKey() const;
200
+ std::string GetSecretKey() const;
201
+ std::string GetSessionToken() const;
202
+
203
+ bool Equals(const S3Options& other) const;
204
+
205
+ /// \brief Initialize with default credentials provider chain
206
+ ///
207
+ /// This is recommended if you use the standard AWS environment variables
208
+ /// and/or configuration file.
209
+ static S3Options Defaults();
210
+
211
+ /// \brief Initialize with anonymous credentials.
212
+ ///
213
+ /// This will only let you access public buckets.
214
+ static S3Options Anonymous();
215
+
216
+ /// \brief Initialize with explicit access and secret key.
217
+ ///
218
+ /// Optionally, a session token may also be provided for temporary credentials
219
+ /// (from STS).
220
+ static S3Options FromAccessKey(const std::string& access_key,
221
+ const std::string& secret_key,
222
+ const std::string& session_token = "");
223
+
224
+ /// \brief Initialize from an assumed role.
225
+ static S3Options FromAssumeRole(
226
+ const std::string& role_arn, const std::string& session_name = "",
227
+ const std::string& external_id = "", int load_frequency = 900,
228
+ const std::shared_ptr<Aws::STS::STSClient>& stsClient = NULLPTR);
229
+
230
+ /// \brief Initialize from an assumed role with web-identity.
231
+ /// Uses the AWS SDK which uses environment variables to
232
+ /// generate temporary credentials.
233
+ static S3Options FromAssumeRoleWithWebIdentity();
234
+
235
+ static Result<S3Options> FromUri(const ::arrow::util::Uri& uri,
236
+ std::string* out_path = NULLPTR);
237
+ static Result<S3Options> FromUri(const std::string& uri,
238
+ std::string* out_path = NULLPTR);
239
+ };
240
+
241
+ /// S3-backed FileSystem implementation.
242
+ ///
243
+ /// Some implementation notes:
244
+ /// - buckets are special and the operations available on them may be limited
245
+ /// or more expensive than desired.
246
+ class ARROW_EXPORT S3FileSystem : public FileSystem {
247
+ public:
248
+ ~S3FileSystem() override;
249
+
250
+ std::string type_name() const override { return "s3"; }
251
+
252
+ /// Return the original S3 options when constructing the filesystem
253
+ S3Options options() const;
254
+ /// Return the actual region this filesystem connects to
255
+ std::string region() const;
256
+
257
+ bool Equals(const FileSystem& other) const override;
258
+ Result<std::string> PathFromUri(const std::string& uri_string) const override;
259
+
260
+ /// \cond FALSE
261
+ using FileSystem::CreateDir;
262
+ using FileSystem::DeleteDirContents;
263
+ using FileSystem::DeleteDirContentsAsync;
264
+ using FileSystem::GetFileInfo;
265
+ using FileSystem::OpenAppendStream;
266
+ using FileSystem::OpenOutputStream;
267
+ /// \endcond
268
+
269
+ Result<FileInfo> GetFileInfo(const std::string& path) override;
270
+ Result<std::vector<FileInfo>> GetFileInfo(const FileSelector& select) override;
271
+
272
+ FileInfoGenerator GetFileInfoGenerator(const FileSelector& select) override;
273
+
274
+ Status CreateDir(const std::string& path, bool recursive) override;
275
+
276
+ Status DeleteDir(const std::string& path) override;
277
+ Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override;
278
+ Future<> DeleteDirContentsAsync(const std::string& path, bool missing_dir_ok) override;
279
+ Status DeleteRootDirContents() override;
280
+
281
+ Status DeleteFile(const std::string& path) override;
282
+
283
+ Status Move(const std::string& src, const std::string& dest) override;
284
+
285
+ Status CopyFile(const std::string& src, const std::string& dest) override;
286
+
287
+ /// Create a sequential input stream for reading from a S3 object.
288
+ ///
289
+ /// NOTE: Reads from the stream will be synchronous and unbuffered.
290
+ /// You way want to wrap the stream in a BufferedInputStream or use
291
+ /// a custom readahead strategy to avoid idle waits.
292
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(
293
+ const std::string& path) override;
294
+ /// Create a sequential input stream for reading from a S3 object.
295
+ ///
296
+ /// This override avoids a HEAD request by assuming the FileInfo
297
+ /// contains correct information.
298
+ Result<std::shared_ptr<io::InputStream>> OpenInputStream(const FileInfo& info) override;
299
+
300
+ /// Create a random access file for reading from a S3 object.
301
+ ///
302
+ /// See OpenInputStream for performance notes.
303
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
304
+ const std::string& path) override;
305
+ /// Create a random access file for reading from a S3 object.
306
+ ///
307
+ /// This override avoids a HEAD request by assuming the FileInfo
308
+ /// contains correct information.
309
+ Result<std::shared_ptr<io::RandomAccessFile>> OpenInputFile(
310
+ const FileInfo& info) override;
311
+
312
+ /// Create a sequential output stream for writing to a S3 object.
313
+ ///
314
+ /// NOTE: Writes to the stream will be buffered. Depending on
315
+ /// S3Options.background_writes, they can be synchronous or not.
316
+ /// It is recommended to enable background_writes unless you prefer
317
+ /// implementing your own background execution strategy.
318
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
319
+ const std::string& path,
320
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
321
+
322
+ Result<std::shared_ptr<io::OutputStream>> OpenAppendStream(
323
+ const std::string& path,
324
+ const std::shared_ptr<const KeyValueMetadata>& metadata) override;
325
+
326
+ /// Create a S3FileSystem instance from the given options.
327
+ static Result<std::shared_ptr<S3FileSystem>> Make(
328
+ const S3Options& options, const io::IOContext& = io::default_io_context());
329
+
330
+ protected:
331
+ explicit S3FileSystem(const S3Options& options, const io::IOContext&);
332
+
333
+ class Impl;
334
+ std::shared_ptr<Impl> impl_;
335
+ };
336
+
337
+ enum class S3LogLevel : int8_t { Off, Fatal, Error, Warn, Info, Debug, Trace };
338
+
339
+ struct ARROW_EXPORT S3GlobalOptions {
340
+ S3LogLevel log_level;
341
+ /// The number of threads to configure when creating AWS' I/O event loop
342
+ ///
343
+ /// Defaults to 1 as recommended by AWS' doc when the # of connections is
344
+ /// expected to be, at most, in the hundreds
345
+ ///
346
+ /// For more details see Aws::Crt::Io::EventLoopGroup
347
+ int num_event_loop_threads = 1;
348
+
349
+ /// \brief Initialize with default options
350
+ ///
351
+ /// For log_level, this method first tries to extract a suitable value from the
352
+ /// environment variable ARROW_S3_LOG_LEVEL.
353
+ static S3GlobalOptions Defaults();
354
+ };
355
+
356
+ /// \brief Initialize the S3 APIs with the specified set of options.
357
+ ///
358
+ /// It is required to call this function at least once before using S3FileSystem.
359
+ ///
360
+ /// Once this function is called you MUST call FinalizeS3 before the end of the
361
+ /// application in order to avoid a segmentation fault at shutdown.
362
+ ARROW_EXPORT
363
+ Status InitializeS3(const S3GlobalOptions& options);
364
+
365
+ /// \brief Ensure the S3 APIs are initialized, but only if not already done.
366
+ ///
367
+ /// If necessary, this will call InitializeS3() with some default options.
368
+ ARROW_EXPORT
369
+ Status EnsureS3Initialized();
370
+
371
+ /// Whether S3 was initialized, and not finalized.
372
+ ARROW_EXPORT
373
+ bool IsS3Initialized();
374
+
375
+ /// Whether S3 was finalized.
376
+ ARROW_EXPORT
377
+ bool IsS3Finalized();
378
+
379
+ /// \brief Shutdown the S3 APIs.
380
+ ///
381
+ /// This can wait for some S3 concurrent calls to finish so as to avoid
382
+ /// race conditions.
383
+ /// After this function has been called, all S3 calls will fail with an error.
384
+ ///
385
+ /// Calls to InitializeS3() and FinalizeS3() should be serialized by the
386
+ /// application (this also applies to EnsureS3Initialized() and
387
+ /// EnsureS3Finalized()).
388
+ ARROW_EXPORT
389
+ Status FinalizeS3();
390
+
391
+ /// \brief Ensure the S3 APIs are shutdown, but only if not already done.
392
+ ///
393
+ /// If necessary, this will call FinalizeS3().
394
+ ARROW_EXPORT
395
+ Status EnsureS3Finalized();
396
+
397
+ ARROW_EXPORT
398
+ Result<std::string> ResolveS3BucketRegion(const std::string& bucket);
399
+
400
+ } // namespace fs
401
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/test_util.h ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <chrono>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "arrow/filesystem/filesystem.h"
26
+ #include "arrow/filesystem/mockfs.h"
27
+ #include "arrow/testing/visibility.h"
28
+ #include "arrow/util/counting_semaphore.h"
29
+
30
+ namespace arrow {
31
+ namespace fs {
32
+
33
+ static constexpr double kTimeSlack = 2.0; // In seconds
34
+
35
+ static inline FileInfo File(std::string path) {
36
+ return FileInfo(std::move(path), FileType::File);
37
+ }
38
+
39
+ static inline FileInfo Dir(std::string path) {
40
+ return FileInfo(std::move(path), FileType::Directory);
41
+ }
42
+
43
+ // A subclass of MockFileSystem that blocks operations until an unlock method is
44
+ // called.
45
+ //
46
+ // This is intended for testing fine-grained ordering of filesystem operations.
47
+ //
48
+ // N.B. Only OpenOutputStream supports gating at the moment but this is simply because
49
+ // it is all that has been needed so far. Feel free to add support for more methods
50
+ // as required.
51
+ class ARROW_TESTING_EXPORT GatedMockFilesystem : public internal::MockFileSystem {
52
+ public:
53
+ GatedMockFilesystem(TimePoint current_time,
54
+ const io::IOContext& = io::default_io_context());
55
+ ~GatedMockFilesystem() override;
56
+
57
+ Result<std::shared_ptr<io::OutputStream>> OpenOutputStream(
58
+ const std::string& path,
59
+ const std::shared_ptr<const KeyValueMetadata>& metadata = {}) override;
60
+
61
+ // Wait until at least num_waiters are waiting on OpenOutputStream
62
+ Status WaitForOpenOutputStream(uint32_t num_waiters);
63
+ // Unlock `num_waiters` individual calls to OpenOutputStream
64
+ Status UnlockOpenOutputStream(uint32_t num_waiters);
65
+
66
+ private:
67
+ util::CountingSemaphore open_output_sem_;
68
+ };
69
+
70
+ ARROW_TESTING_EXPORT
71
+ void CreateFile(FileSystem* fs, const std::string& path, const std::string& data);
72
+
73
+ // Sort a vector of FileInfo by lexicographic path order
74
+ ARROW_TESTING_EXPORT
75
+ void SortInfos(FileInfoVector* infos);
76
+
77
+ // Create a copy of a FileInfo vector sorted by lexicographic path order
78
+ ARROW_TESTING_EXPORT
79
+ FileInfoVector SortedInfos(const FileInfoVector& infos);
80
+
81
+ ARROW_TESTING_EXPORT
82
+ void CollectFileInfoGenerator(FileInfoGenerator gen, FileInfoVector* out_infos);
83
+
84
+ ARROW_TESTING_EXPORT
85
+ void AssertFileInfo(const FileInfo& info, const std::string& path, FileType type);
86
+
87
+ ARROW_TESTING_EXPORT
88
+ void AssertFileInfo(const FileInfo& info, const std::string& path, FileType type,
89
+ TimePoint mtime);
90
+
91
+ ARROW_TESTING_EXPORT
92
+ void AssertFileInfo(const FileInfo& info, const std::string& path, FileType type,
93
+ TimePoint mtime, int64_t size);
94
+
95
+ ARROW_TESTING_EXPORT
96
+ void AssertFileInfo(const FileInfo& info, const std::string& path, FileType type,
97
+ int64_t size);
98
+
99
+ ARROW_TESTING_EXPORT
100
+ void AssertFileInfo(FileSystem* fs, const std::string& path, FileType type);
101
+
102
+ ARROW_TESTING_EXPORT
103
+ void AssertFileInfo(FileSystem* fs, const std::string& path, FileType type,
104
+ TimePoint mtime);
105
+
106
+ ARROW_TESTING_EXPORT
107
+ void AssertFileInfo(FileSystem* fs, const std::string& path, FileType type,
108
+ TimePoint mtime, int64_t size);
109
+
110
+ ARROW_TESTING_EXPORT
111
+ void AssertFileInfo(FileSystem* fs, const std::string& path, FileType type, int64_t size);
112
+
113
+ ARROW_TESTING_EXPORT
114
+ void AssertFileContents(FileSystem* fs, const std::string& path,
115
+ const std::string& expected_data);
116
+
117
+ template <typename Duration>
118
+ void AssertDurationBetween(Duration d, double min_secs, double max_secs) {
119
+ auto seconds = std::chrono::duration_cast<std::chrono::duration<double>>(d);
120
+ ASSERT_GE(seconds.count(), min_secs);
121
+ ASSERT_LE(seconds.count(), max_secs);
122
+ }
123
+
124
+ // Generic tests for FileSystem implementations.
125
+ // To use this class, subclass both from it and ::testing::Test,
126
+ // implement GetEmptyFileSystem(), and use GENERIC_FS_TEST_FUNCTIONS()
127
+ // to define the various tests.
128
+ class ARROW_TESTING_EXPORT GenericFileSystemTest {
129
+ public:
130
+ virtual ~GenericFileSystemTest();
131
+
132
+ void TestEmpty();
133
+ void TestNormalizePath();
134
+ void TestCreateDir();
135
+ void TestDeleteDir();
136
+ void TestDeleteDirContents();
137
+ void TestDeleteRootDirContents();
138
+ void TestDeleteFile();
139
+ void TestDeleteFiles();
140
+ void TestMoveFile();
141
+ void TestMoveDir();
142
+ void TestCopyFile();
143
+ void TestGetFileInfo();
144
+ void TestGetFileInfoVector();
145
+ void TestGetFileInfoSelector();
146
+ void TestGetFileInfoSelectorWithRecursion();
147
+ void TestGetFileInfoAsync();
148
+ void TestGetFileInfoGenerator();
149
+ void TestOpenOutputStream();
150
+ void TestOpenAppendStream();
151
+ void TestOpenInputStream();
152
+ void TestOpenInputStreamWithFileInfo();
153
+ void TestOpenInputStreamAsync();
154
+ void TestOpenInputFile();
155
+ void TestOpenInputFileWithFileInfo();
156
+ void TestOpenInputFileAsync();
157
+ void TestSpecialChars();
158
+
159
+ protected:
160
+ // This function should return the filesystem under test.
161
+ virtual std::shared_ptr<FileSystem> GetEmptyFileSystem() = 0;
162
+
163
+ // Override the following functions to specify deviations from expected
164
+ // filesystem semantics.
165
+ // - Whether the filesystem may "implicitly" create intermediate directories
166
+ virtual bool have_implicit_directories() const { return false; }
167
+ // - Whether the filesystem may allow writing a file "over" a directory
168
+ virtual bool allow_write_file_over_dir() const { return false; }
169
+ // - Whether the filesystem allows reading a directory
170
+ virtual bool allow_read_dir_as_file() const { return false; }
171
+ // - Whether the filesystem allows moving a file
172
+ virtual bool allow_move_file() const { return true; }
173
+ // - Whether the filesystem allows moving a directory
174
+ virtual bool allow_move_dir() const { return true; }
175
+ // - Whether the filesystem allows moving a directory "over" a non-empty destination
176
+ virtual bool allow_move_dir_over_non_empty_dir() const { return false; }
177
+ // - Whether the filesystem allows appending to a file
178
+ virtual bool allow_append_to_file() const { return true; }
179
+ // - Whether the filesystem allows appending to a nonexistent file
180
+ virtual bool allow_append_to_new_file() const { return true; }
181
+ // - Whether the filesystem supports directory modification times
182
+ virtual bool have_directory_mtimes() const { return true; }
183
+ // - Whether some directory tree deletion tests may fail randomly
184
+ virtual bool have_flaky_directory_tree_deletion() const { return false; }
185
+ // - Whether the filesystem stores some metadata alongside files
186
+ virtual bool have_file_metadata() const { return false; }
187
+ // - Whether the filesystem has a false positive memory leak with generator
188
+ virtual bool have_false_positive_memory_leak_with_generator() const { return false; }
189
+
190
+ void TestEmpty(FileSystem* fs);
191
+ void TestNormalizePath(FileSystem* fs);
192
+ void TestCreateDir(FileSystem* fs);
193
+ void TestDeleteDir(FileSystem* fs);
194
+ void TestDeleteDirContents(FileSystem* fs);
195
+ void TestDeleteRootDirContents(FileSystem* fs);
196
+ void TestDeleteFile(FileSystem* fs);
197
+ void TestDeleteFiles(FileSystem* fs);
198
+ void TestMoveFile(FileSystem* fs);
199
+ void TestMoveDir(FileSystem* fs);
200
+ void TestCopyFile(FileSystem* fs);
201
+ void TestGetFileInfo(FileSystem* fs);
202
+ void TestGetFileInfoVector(FileSystem* fs);
203
+ void TestGetFileInfoSelector(FileSystem* fs);
204
+ void TestGetFileInfoSelectorWithRecursion(FileSystem* fs);
205
+ void TestGetFileInfoAsync(FileSystem* fs);
206
+ void TestGetFileInfoGenerator(FileSystem* fs);
207
+ void TestOpenOutputStream(FileSystem* fs);
208
+ void TestOpenAppendStream(FileSystem* fs);
209
+ void TestOpenInputStream(FileSystem* fs);
210
+ void TestOpenInputStreamWithFileInfo(FileSystem* fs);
211
+ void TestOpenInputStreamAsync(FileSystem* fs);
212
+ void TestOpenInputFile(FileSystem* fs);
213
+ void TestOpenInputFileWithFileInfo(FileSystem* fs);
214
+ void TestOpenInputFileAsync(FileSystem* fs);
215
+ void TestSpecialChars(FileSystem* fs);
216
+ };
217
+
218
+ #define GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, NAME) \
219
+ TEST_MACRO(TEST_CLASS, NAME) { this->Test##NAME(); }
220
+
221
+ #define GENERIC_FS_TEST_FUNCTIONS_MACROS(TEST_MACRO, TEST_CLASS) \
222
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, Empty) \
223
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, NormalizePath) \
224
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, CreateDir) \
225
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, DeleteDir) \
226
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, DeleteDirContents) \
227
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, DeleteRootDirContents) \
228
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, DeleteFile) \
229
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, DeleteFiles) \
230
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, MoveFile) \
231
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, MoveDir) \
232
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, CopyFile) \
233
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, GetFileInfo) \
234
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, GetFileInfoVector) \
235
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, GetFileInfoSelector) \
236
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, GetFileInfoSelectorWithRecursion) \
237
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, GetFileInfoAsync) \
238
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, GetFileInfoGenerator) \
239
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenOutputStream) \
240
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenAppendStream) \
241
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenInputStream) \
242
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenInputStreamWithFileInfo) \
243
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenInputStreamAsync) \
244
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenInputFile) \
245
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenInputFileWithFileInfo) \
246
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, OpenInputFileAsync) \
247
+ GENERIC_FS_TEST_FUNCTION(TEST_MACRO, TEST_CLASS, SpecialChars)
248
+
249
+ #define GENERIC_FS_TEST_FUNCTIONS(TEST_CLASS) \
250
+ GENERIC_FS_TEST_FUNCTIONS_MACROS(TEST_F, TEST_CLASS)
251
+
252
+ #define GENERIC_FS_TYPED_TEST_FUNCTIONS(TEST_CLASS) \
253
+ GENERIC_FS_TEST_FUNCTIONS_MACROS(TYPED_TEST, TEST_CLASS)
254
+
255
+ } // namespace fs
256
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/filesystem/type_fwd.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
22
+ namespace arrow {
23
+ namespace fs {
24
+
25
+ /// \brief FileSystem entry type
26
+ enum class FileType : int8_t {
27
+ /// Entry is not found
28
+ NotFound,
29
+ /// Entry exists but its type is unknown
30
+ ///
31
+ /// This can designate a special file such as a Unix socket or character
32
+ /// device, or Windows NUL / CON / ...
33
+ Unknown,
34
+ /// Entry is a regular file
35
+ File,
36
+ /// Entry is a directory
37
+ Directory
38
+ };
39
+
40
+ struct FileInfo;
41
+
42
+ struct FileSelector;
43
+
44
+ class FileSystem;
45
+ class AzureFileSystem;
46
+ class GcsFileSystem;
47
+ class LocalFileSystem;
48
+ class S3FileSystem;
49
+ class SlowFileSystem;
50
+ class SubTreeFileSystem;
51
+
52
+ } // namespace fs
53
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/testing/executor_util.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/util/thread_pool.h"
21
+
22
+ namespace arrow {
23
+
24
+ /// An executor which synchronously runs the task as part of the SpawnReal call.
25
+ class MockExecutor : public internal::Executor {
26
+ public:
27
+ int GetCapacity() override { return 0; }
28
+
29
+ Status SpawnReal(internal::TaskHints hints, internal::FnOnce<void()> task, StopToken,
30
+ StopCallback&&) override {
31
+ spawn_count++;
32
+ std::move(task)();
33
+ return Status::OK();
34
+ }
35
+
36
+ int spawn_count = 0;
37
+ };
38
+
39
+ /// An executor which does not actually run the task. Can be used to simulate situations
40
+ /// where the executor schedules a task in a long queue and doesn't get around to running
41
+ /// it for a while
42
+ class DelayedExecutor : public internal::Executor {
43
+ public:
44
+ int GetCapacity() override { return 0; }
45
+
46
+ Status SpawnReal(internal::TaskHints hints, internal::FnOnce<void()> task, StopToken,
47
+ StopCallback&&) override {
48
+ captured_tasks.push_back(std::move(task));
49
+ return Status::OK();
50
+ }
51
+
52
+ std::vector<internal::FnOnce<void()>> captured_tasks;
53
+ };
54
+
55
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/testing/gtest_util.h ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <cstdlib>
23
+ #include <cstring>
24
+ #include <functional>
25
+ #include <memory>
26
+ #include <optional>
27
+ #include <string>
28
+ #include <string_view>
29
+ #include <type_traits>
30
+ #include <utility>
31
+ #include <vector>
32
+
33
+ #include <gtest/gtest.h>
34
+
35
+ #include "arrow/compare.h"
36
+ #include "arrow/result.h"
37
+ #include "arrow/status.h"
38
+ #include "arrow/testing/gtest_compat.h"
39
+ #include "arrow/testing/visibility.h"
40
+ #include "arrow/type_fwd.h"
41
+ #include "arrow/type_traits.h"
42
+ #include "arrow/util/macros.h"
43
+ #include "arrow/util/string_builder.h"
44
+ #include "arrow/util/type_fwd.h"
45
+
46
+ // NOTE: failing must be inline in the macros below, to get correct file / line number
47
+ // reporting on test failures.
48
+
49
+ // NOTE: using a for loop for this macro allows extra failure messages to be
50
+ // appended with operator<<
51
+ #define ASSERT_RAISES(ENUM, expr) \
52
+ for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); \
53
+ !_st.Is##ENUM();) \
54
+ FAIL() << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " ARROW_STRINGIFY( \
55
+ ENUM) ", but got " \
56
+ << _st.ToString()
57
+
58
+ #define ASSERT_RAISES_WITH_MESSAGE(ENUM, message, expr) \
59
+ do { \
60
+ auto _res = (expr); \
61
+ ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \
62
+ if (!_st.Is##ENUM()) { \
63
+ FAIL() << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " ARROW_STRINGIFY( \
64
+ ENUM) ", but got " \
65
+ << _st.ToString(); \
66
+ } \
67
+ ASSERT_EQ((message), _st.ToStringWithoutContextLines()); \
68
+ } while (false)
69
+
70
+ #define EXPECT_RAISES_WITH_MESSAGE_THAT(ENUM, matcher, expr) \
71
+ do { \
72
+ auto _res = (expr); \
73
+ ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \
74
+ EXPECT_TRUE(_st.Is##ENUM()) << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " \
75
+ << ARROW_STRINGIFY(ENUM) ", but got " << _st.ToString(); \
76
+ EXPECT_THAT(_st.ToStringWithoutContextLines(), (matcher)); \
77
+ } while (false)
78
+
79
+ #define EXPECT_RAISES_WITH_CODE_AND_MESSAGE_THAT(code, matcher, expr) \
80
+ do { \
81
+ auto _res = (expr); \
82
+ ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \
83
+ EXPECT_EQ(_st.CodeAsString(), Status::CodeAsString(code)); \
84
+ EXPECT_THAT(_st.ToStringWithoutContextLines(), (matcher)); \
85
+ } while (false)
86
+
87
+ #define ASSERT_OK(expr) \
88
+ for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); !_st.ok();) \
89
+ FAIL() << "'" ARROW_STRINGIFY(expr) "' failed with " << _st.ToString()
90
+
91
+ #define ASSERT_OK_NO_THROW(expr) ASSERT_NO_THROW(ASSERT_OK(expr))
92
+
93
+ #define ARROW_EXPECT_OK(expr) \
94
+ do { \
95
+ auto _res = (expr); \
96
+ ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \
97
+ EXPECT_TRUE(_st.ok()) << "'" ARROW_STRINGIFY(expr) "' failed with " \
98
+ << _st.ToString(); \
99
+ } while (false)
100
+
101
+ #define ASSERT_NOT_OK(expr) \
102
+ for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); _st.ok();) \
103
+ FAIL() << "'" ARROW_STRINGIFY(expr) "' did not failed" << _st.ToString()
104
+
105
+ #define ABORT_NOT_OK(expr) \
106
+ do { \
107
+ auto _res = (expr); \
108
+ ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \
109
+ if (ARROW_PREDICT_FALSE(!_st.ok())) { \
110
+ _st.Abort(); \
111
+ } \
112
+ } while (false);
113
+
114
+ #define ASSIGN_OR_HANDLE_ERROR_IMPL(handle_error, status_name, lhs, rexpr) \
115
+ auto&& status_name = (rexpr); \
116
+ handle_error(status_name.status()); \
117
+ lhs = std::move(status_name).ValueOrDie();
118
+
119
+ #define ASSERT_OK_AND_ASSIGN(lhs, rexpr) \
120
+ ASSIGN_OR_HANDLE_ERROR_IMPL( \
121
+ ASSERT_OK, ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), lhs, rexpr);
122
+
123
+ #define ASSIGN_OR_ABORT(lhs, rexpr) \
124
+ ASSIGN_OR_HANDLE_ERROR_IMPL(ABORT_NOT_OK, \
125
+ ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \
126
+ lhs, rexpr);
127
+
128
+ #define EXPECT_OK_AND_ASSIGN(lhs, rexpr) \
129
+ ASSIGN_OR_HANDLE_ERROR_IMPL(ARROW_EXPECT_OK, \
130
+ ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \
131
+ lhs, rexpr);
132
+
133
+ #define ASSERT_OK_AND_EQ(expected, expr) \
134
+ do { \
135
+ ASSERT_OK_AND_ASSIGN(auto _actual, (expr)); \
136
+ ASSERT_EQ(expected, _actual); \
137
+ } while (0)
138
+
139
+ // A generalized version of GTest's SCOPED_TRACE that takes arbitrary arguments.
140
+ // ARROW_SCOPED_TRACE("some variable = ", some_variable, ...)
141
+
142
+ #define ARROW_SCOPED_TRACE(...) SCOPED_TRACE(::arrow::util::StringBuilder(__VA_ARGS__))
143
+
144
+ namespace arrow {
145
+
146
+ // ----------------------------------------------------------------------
147
+ // Useful testing::Types declarations
148
+
149
+ inline void PrintTo(StatusCode code, std::ostream* os) {
150
+ *os << Status::CodeAsString(code);
151
+ }
152
+
153
+ using NumericArrowTypes =
154
+ ::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int8Type, Int16Type,
155
+ Int32Type, Int64Type, FloatType, DoubleType>;
156
+
157
+ using RealArrowTypes = ::testing::Types<FloatType, DoubleType>;
158
+
159
+ using IntegralArrowTypes = ::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type,
160
+ Int8Type, Int16Type, Int32Type, Int64Type>;
161
+
162
+ using PhysicalIntegralArrowTypes =
163
+ ::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int8Type, Int16Type,
164
+ Int32Type, Int64Type, Date32Type, Date64Type, Time32Type, Time64Type,
165
+ TimestampType, MonthIntervalType>;
166
+
167
+ using PrimitiveArrowTypes =
168
+ ::testing::Types<BooleanType, Int8Type, UInt8Type, Int16Type, UInt16Type, Int32Type,
169
+ UInt32Type, Int64Type, UInt64Type, FloatType, DoubleType>;
170
+
171
+ using TemporalArrowTypes =
172
+ ::testing::Types<Date32Type, Date64Type, TimestampType, Time32Type, Time64Type>;
173
+
174
+ using DecimalArrowTypes = ::testing::Types<Decimal128Type, Decimal256Type>;
175
+
176
+ using BaseBinaryArrowTypes =
177
+ ::testing::Types<BinaryType, LargeBinaryType, StringType, LargeStringType>;
178
+
179
+ using BaseBinaryOrBinaryViewLikeArrowTypes =
180
+ ::testing::Types<BinaryType, LargeBinaryType, BinaryViewType, StringType,
181
+ LargeStringType, StringViewType>;
182
+
183
+ using BinaryArrowTypes = ::testing::Types<BinaryType, LargeBinaryType>;
184
+
185
+ using StringArrowTypes = ::testing::Types<StringType, LargeStringType>;
186
+
187
+ using StringOrStringViewArrowTypes =
188
+ ::testing::Types<StringType, LargeStringType, StringViewType>;
189
+
190
+ using ListArrowTypes = ::testing::Types<ListType, LargeListType>;
191
+
192
+ using UnionArrowTypes = ::testing::Types<SparseUnionType, DenseUnionType>;
193
+
194
+ class Array;
195
+ class ChunkedArray;
196
+ class RecordBatch;
197
+ class Table;
198
+ struct Datum;
199
+
200
+ #define ASSERT_ARRAYS_EQUAL(lhs, rhs) AssertArraysEqual((lhs), (rhs))
201
+ #define ASSERT_BATCHES_EQUAL(lhs, rhs) AssertBatchesEqual((lhs), (rhs))
202
+ #define ASSERT_BATCHES_APPROX_EQUAL(lhs, rhs) AssertBatchesApproxEqual((lhs), (rhs))
203
+ #define ASSERT_TABLES_EQUAL(lhs, rhs) AssertTablesEqual((lhs), (rhs))
204
+
205
+ // Default EqualOptions for testing
206
+ static inline EqualOptions TestingEqualOptions() {
207
+ return EqualOptions{}.nans_equal(true).signed_zeros_equal(false);
208
+ }
209
+
210
+ // If verbose is true, then the arrays will be pretty printed
211
+ ARROW_TESTING_EXPORT void AssertArraysEqual(
212
+ const Array& expected, const Array& actual, bool verbose = false,
213
+ const EqualOptions& options = TestingEqualOptions());
214
+ ARROW_TESTING_EXPORT void AssertArraysApproxEqual(
215
+ const Array& expected, const Array& actual, bool verbose = false,
216
+ const EqualOptions& options = TestingEqualOptions());
217
+ // Returns true when values are both null
218
+ ARROW_TESTING_EXPORT void AssertScalarsEqual(
219
+ const Scalar& expected, const Scalar& actual, bool verbose = false,
220
+ const EqualOptions& options = TestingEqualOptions());
221
+ ARROW_TESTING_EXPORT void AssertScalarsApproxEqual(
222
+ const Scalar& expected, const Scalar& actual, bool verbose = false,
223
+ const EqualOptions& options = TestingEqualOptions());
224
+ ARROW_TESTING_EXPORT void AssertBatchesEqual(
225
+ const RecordBatch& expected, const RecordBatch& actual, bool check_metadata = false,
226
+ const EqualOptions& options = TestingEqualOptions());
227
+ ARROW_TESTING_EXPORT void AssertBatchesApproxEqual(
228
+ const RecordBatch& expected, const RecordBatch& actual,
229
+ const EqualOptions& options = TestingEqualOptions());
230
+ ARROW_TESTING_EXPORT void AssertChunkedEqual(
231
+ const ChunkedArray& expected, const ChunkedArray& actual,
232
+ const EqualOptions& options = TestingEqualOptions());
233
+ ARROW_TESTING_EXPORT void AssertChunkedEqual(
234
+ const ChunkedArray& actual, const ArrayVector& expected,
235
+ const EqualOptions& options = TestingEqualOptions());
236
+ // Like ChunkedEqual, but permits different chunk layout
237
+ ARROW_TESTING_EXPORT void AssertChunkedEquivalent(
238
+ const ChunkedArray& expected, const ChunkedArray& actual,
239
+ const EqualOptions& options = TestingEqualOptions());
240
+ ARROW_TESTING_EXPORT void AssertChunkedApproxEquivalent(
241
+ const ChunkedArray& expected, const ChunkedArray& actual,
242
+ const EqualOptions& options = TestingEqualOptions());
243
+ ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer,
244
+ const std::vector<uint8_t>& expected);
245
+ ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer,
246
+ std::string_view expected);
247
+ ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer, const Buffer& expected);
248
+
249
+ ARROW_TESTING_EXPORT void AssertTypeEqual(const DataType& lhs, const DataType& rhs,
250
+ bool check_metadata = false);
251
+ ARROW_TESTING_EXPORT void AssertTypeEqual(const std::shared_ptr<DataType>& lhs,
252
+ const std::shared_ptr<DataType>& rhs,
253
+ bool check_metadata = false);
254
+ ARROW_TESTING_EXPORT void AssertFieldEqual(const Field& lhs, const Field& rhs,
255
+ bool check_metadata = false);
256
+ ARROW_TESTING_EXPORT void AssertFieldEqual(const std::shared_ptr<Field>& lhs,
257
+ const std::shared_ptr<Field>& rhs,
258
+ bool check_metadata = false);
259
+ ARROW_TESTING_EXPORT void AssertSchemaEqual(const Schema& lhs, const Schema& rhs,
260
+ bool check_metadata = false);
261
+ ARROW_TESTING_EXPORT void AssertSchemaEqual(const std::shared_ptr<Schema>& lhs,
262
+ const std::shared_ptr<Schema>& rhs,
263
+ bool check_metadata = false);
264
+
265
+ ARROW_TESTING_EXPORT void AssertTypeNotEqual(const DataType& lhs, const DataType& rhs,
266
+ bool check_metadata = false);
267
+ ARROW_TESTING_EXPORT void AssertTypeNotEqual(const std::shared_ptr<DataType>& lhs,
268
+ const std::shared_ptr<DataType>& rhs,
269
+ bool check_metadata = false);
270
+ ARROW_TESTING_EXPORT void AssertFieldNotEqual(const Field& lhs, const Field& rhs,
271
+ bool check_metadata = false);
272
+ ARROW_TESTING_EXPORT void AssertFieldNotEqual(const std::shared_ptr<Field>& lhs,
273
+ const std::shared_ptr<Field>& rhs,
274
+ bool check_metadata = false);
275
+ ARROW_TESTING_EXPORT void AssertSchemaNotEqual(const Schema& lhs, const Schema& rhs,
276
+ bool check_metadata = false);
277
+ ARROW_TESTING_EXPORT void AssertSchemaNotEqual(const std::shared_ptr<Schema>& lhs,
278
+ const std::shared_ptr<Schema>& rhs,
279
+ bool check_metadata = false);
280
+
281
+ ARROW_TESTING_EXPORT Result<std::optional<std::string>> PrintArrayDiff(
282
+ const ChunkedArray& expected, const ChunkedArray& actual);
283
+
284
+ ARROW_TESTING_EXPORT void AssertTablesEqual(
285
+ const Table& expected, const Table& actual, bool same_chunk_layout = true,
286
+ bool flatten = false, const EqualOptions& options = TestingEqualOptions());
287
+
288
+ ARROW_TESTING_EXPORT void AssertDatumsEqual(
289
+ const Datum& expected, const Datum& actual, bool verbose = false,
290
+ const EqualOptions& options = TestingEqualOptions());
291
+ ARROW_TESTING_EXPORT void AssertDatumsApproxEqual(
292
+ const Datum& expected, const Datum& actual, bool verbose = false,
293
+ const EqualOptions& options = TestingEqualOptions());
294
+
295
+ template <typename C_TYPE>
296
+ void AssertNumericDataEqual(const C_TYPE* raw_data,
297
+ const std::vector<C_TYPE>& expected_values) {
298
+ for (auto expected : expected_values) {
299
+ ASSERT_EQ(expected, *raw_data);
300
+ ++raw_data;
301
+ }
302
+ }
303
+
304
+ ARROW_TESTING_EXPORT void CompareBatch(
305
+ const RecordBatch& left, const RecordBatch& right, bool compare_metadata = true,
306
+ const EqualOptions& options = TestingEqualOptions());
307
+
308
+ ARROW_TESTING_EXPORT void ApproxCompareBatch(
309
+ const RecordBatch& left, const RecordBatch& right, bool compare_metadata = true,
310
+ const EqualOptions& options = TestingEqualOptions());
311
+
312
+ // Check if the padding of the buffers of the array is zero.
313
+ // Also cause valgrind warnings if the padding bytes are uninitialized.
314
+ ARROW_TESTING_EXPORT void AssertZeroPadded(const Array& array);
315
+
316
+ // Check if the valid buffer bytes are initialized
317
+ // and cause valgrind warnings otherwise.
318
+ ARROW_TESTING_EXPORT void TestInitialized(const ArrayData& array);
319
+ ARROW_TESTING_EXPORT void TestInitialized(const Array& array);
320
+
321
+ #define DECL_T() typedef typename TestFixture::T T;
322
+
323
+ #define DECL_TYPE() typedef typename TestFixture::Type Type;
324
+
325
+ // ArrayFromJSON: construct an Array from a simple JSON representation
326
+
327
+ ARROW_TESTING_EXPORT
328
+ std::shared_ptr<Array> ArrayFromJSON(const std::shared_ptr<DataType>&,
329
+ std::string_view json);
330
+
331
+ ARROW_TESTING_EXPORT
332
+ std::shared_ptr<Array> DictArrayFromJSON(const std::shared_ptr<DataType>& type,
333
+ std::string_view indices_json,
334
+ std::string_view dictionary_json);
335
+
336
+ ARROW_TESTING_EXPORT
337
+ std::shared_ptr<RecordBatch> RecordBatchFromJSON(const std::shared_ptr<Schema>&,
338
+ std::string_view);
339
+
340
+ ARROW_TESTING_EXPORT
341
+ std::shared_ptr<ChunkedArray> ChunkedArrayFromJSON(const std::shared_ptr<DataType>&,
342
+ const std::vector<std::string>& json);
343
+
344
+ ARROW_TESTING_EXPORT
345
+ std::shared_ptr<Scalar> ScalarFromJSON(const std::shared_ptr<DataType>&,
346
+ std::string_view json);
347
+
348
+ ARROW_TESTING_EXPORT
349
+ std::shared_ptr<Scalar> DictScalarFromJSON(const std::shared_ptr<DataType>&,
350
+ std::string_view index_json,
351
+ std::string_view dictionary_json);
352
+
353
+ ARROW_TESTING_EXPORT
354
+ std::shared_ptr<Table> TableFromJSON(const std::shared_ptr<Schema>&,
355
+ const std::vector<std::string>& json);
356
+
357
+ ARROW_TESTING_EXPORT
358
+ std::shared_ptr<Tensor> TensorFromJSON(const std::shared_ptr<DataType>& type,
359
+ std::string_view data, std::string_view shape,
360
+ std::string_view strides = "[]",
361
+ std::string_view dim_names = "[]");
362
+
363
+ ARROW_TESTING_EXPORT
364
+ std::shared_ptr<Tensor> TensorFromJSON(const std::shared_ptr<DataType>& type,
365
+ std::string_view data,
366
+ const std::vector<int64_t>& shape,
367
+ const std::vector<int64_t>& strides = {},
368
+ const std::vector<std::string>& dim_names = {});
369
+
370
+ ARROW_TESTING_EXPORT
371
+ Result<std::shared_ptr<Table>> RunEndEncodeTableColumns(
372
+ const Table& table, const std::vector<int>& column_indices);
373
+
374
+ // Given an array, return a new identical array except for one validity bit
375
+ // set to a new value.
376
+ // This is useful to force the underlying "value" of null entries to otherwise
377
+ // invalid data and check that errors don't get reported.
378
+ ARROW_TESTING_EXPORT
379
+ std::shared_ptr<Array> TweakValidityBit(const std::shared_ptr<Array>& array,
380
+ int64_t index, bool validity);
381
+
382
+ ARROW_TESTING_EXPORT
383
+ void SleepFor(double seconds);
384
+
385
+ // Sleeps for a very small amount of time. The thread will be yielded
386
+ // at least once ensuring that context switches could happen. It is intended
387
+ // to be used for stress testing parallel code and shouldn't be assumed to do any
388
+ // reliable timing.
389
+ ARROW_TESTING_EXPORT
390
+ void SleepABit();
391
+
392
+ // Wait until predicate is true or timeout in seconds expires.
393
+ ARROW_TESTING_EXPORT
394
+ void BusyWait(double seconds, std::function<bool()> predicate);
395
+
396
+ // \see SleepABit
397
+ ARROW_TESTING_EXPORT
398
+ Future<> SleepABitAsync();
399
+
400
+ ARROW_TESTING_EXPORT bool FileIsClosed(int fd);
401
+
402
+ template <typename T>
403
+ std::vector<T> IteratorToVector(Iterator<T> iterator) {
404
+ EXPECT_OK_AND_ASSIGN(auto out, iterator.ToVector());
405
+ return out;
406
+ }
407
+
408
+ ARROW_TESTING_EXPORT
409
+ bool LocaleExists(const char* locale);
410
+
411
+ #ifndef _WIN32
412
+ ARROW_TESTING_EXPORT
413
+ void AssertChildExit(int child_pid, int expected_exit_status = 0);
414
+ #endif
415
+
416
+ // A RAII-style object that switches to a new locale, and switches back
417
+ // to the old locale when going out of scope. Doesn't do anything if the
418
+ // new locale doesn't exist on the local machine.
419
+ // ATTENTION: may crash with an assertion failure on Windows debug builds.
420
+ // See ARROW-6108, also https://gerrit.libreoffice.org/#/c/54110/
421
+ class ARROW_TESTING_EXPORT LocaleGuard {
422
+ public:
423
+ explicit LocaleGuard(const char* new_locale);
424
+ ~LocaleGuard();
425
+
426
+ protected:
427
+ class Impl;
428
+ std::unique_ptr<Impl> impl_;
429
+ };
430
+
431
+ class ARROW_TESTING_EXPORT EnvVarGuard {
432
+ public:
433
+ EnvVarGuard(const std::string& name, const std::string& value);
434
+ ~EnvVarGuard();
435
+
436
+ protected:
437
+ const std::string name_;
438
+ std::string old_value_;
439
+ bool was_set_;
440
+ };
441
+
442
+ namespace internal {
443
+ class SignalHandler;
444
+ }
445
+
446
+ class ARROW_TESTING_EXPORT SignalHandlerGuard {
447
+ public:
448
+ typedef void (*Callback)(int);
449
+
450
+ SignalHandlerGuard(int signum, Callback cb);
451
+ SignalHandlerGuard(int signum, const internal::SignalHandler& handler);
452
+ ~SignalHandlerGuard();
453
+
454
+ protected:
455
+ struct Impl;
456
+ std::unique_ptr<Impl> impl_;
457
+ };
458
+
459
+ #ifndef ARROW_LARGE_MEMORY_TESTS
460
+ #define LARGE_MEMORY_TEST(name) DISABLED_##name
461
+ #else
462
+ #define LARGE_MEMORY_TEST(name) name
463
+ #endif
464
+
465
+ inline void PrintTo(const Status& st, std::ostream* os) { *os << st.ToString(); }
466
+
467
+ template <typename T>
468
+ void PrintTo(const Result<T>& result, std::ostream* os) {
469
+ if (result.ok()) {
470
+ ::testing::internal::UniversalPrint(result.ValueOrDie(), os);
471
+ } else {
472
+ *os << result.status();
473
+ }
474
+ }
475
+
476
+ // A data type with only move constructors (no copy, no default).
477
+ struct MoveOnlyDataType {
478
+ explicit MoveOnlyDataType(int x) : data(new int(x)) {}
479
+
480
+ MoveOnlyDataType(const MoveOnlyDataType& other) = delete;
481
+ MoveOnlyDataType& operator=(const MoveOnlyDataType& other) = delete;
482
+
483
+ MoveOnlyDataType(MoveOnlyDataType&& other) { MoveFrom(&other); }
484
+ MoveOnlyDataType& operator=(MoveOnlyDataType&& other) {
485
+ MoveFrom(&other);
486
+ return *this;
487
+ }
488
+
489
+ MoveOnlyDataType& operator=(int x) {
490
+ if (data != nullptr) {
491
+ delete data;
492
+ }
493
+ data = new int(x);
494
+ return *this;
495
+ }
496
+
497
+ ~MoveOnlyDataType() { Destroy(); }
498
+
499
+ void Destroy() {
500
+ if (data != nullptr) {
501
+ delete data;
502
+ data = nullptr;
503
+ moves = -1;
504
+ }
505
+ }
506
+
507
+ void MoveFrom(MoveOnlyDataType* other) {
508
+ Destroy();
509
+ data = other->data;
510
+ other->data = nullptr;
511
+ moves = other->moves + 1;
512
+ }
513
+
514
+ int ToInt() const { return data == nullptr ? -42 : *data; }
515
+
516
+ bool operator==(const MoveOnlyDataType& other) const {
517
+ return data != nullptr && other.data != nullptr && *data == *other.data;
518
+ }
519
+ bool operator<(const MoveOnlyDataType& other) const {
520
+ return data == nullptr || (other.data != nullptr && *data < *other.data);
521
+ }
522
+
523
+ bool operator==(int other) const { return data != nullptr && *data == other; }
524
+ friend bool operator==(int left, const MoveOnlyDataType& right) {
525
+ return right == left;
526
+ }
527
+
528
+ int* data = nullptr;
529
+ int moves = 0;
530
+ };
531
+
532
+ // A task that blocks until unlocked. Useful for timing tests.
533
+ class ARROW_TESTING_EXPORT GatingTask {
534
+ public:
535
+ explicit GatingTask(double timeout_seconds = 10);
536
+ /// \brief During destruction we wait for all pending tasks to finish
537
+ ~GatingTask();
538
+
539
+ /// \brief Creates a new waiting task (presumably to spawn on a thread). It will return
540
+ /// invalid if the timeout arrived before the unlock. The task will not complete until
541
+ /// unlocked or timed out
542
+ ///
543
+ /// Note: The GatingTask must outlive any Task instances
544
+ std::function<void()> Task();
545
+ /// \brief Creates a new waiting task as a future. The future will not complete
546
+ /// until unlocked.
547
+ Future<> AsyncTask();
548
+ /// \brief Waits until at least count tasks are running.
549
+ Status WaitForRunning(int count);
550
+ /// \brief Unlocks all waiting tasks. Returns an invalid status if any waiting task has
551
+ /// timed out
552
+ Status Unlock();
553
+
554
+ static std::shared_ptr<GatingTask> Make(double timeout_seconds = 10);
555
+
556
+ private:
557
+ class Impl;
558
+ std::shared_ptr<Impl> impl_;
559
+ };
560
+
561
+ /// \brief create an exact copy of the data where each buffer has a max alignment of 1
562
+ ///
563
+ /// This method does not recurse into the dictionary or children
564
+ ARROW_TESTING_EXPORT std::shared_ptr<ArrayData> UnalignBuffers(const ArrayData& array);
565
+ /// \brief create an exact copy of the array where each buffer has a max alignment of 1
566
+ ///
567
+ /// This method does not recurse into the dictionary or children
568
+ ARROW_TESTING_EXPORT std::shared_ptr<Array> UnalignBuffers(const Array& array);
569
+
570
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/aligned_storage.h ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <cstring>
21
+ #include <type_traits>
22
+ #include <utility>
23
+
24
+ #include "arrow/util/launder.h"
25
+ #include "arrow/util/macros.h"
26
+
27
+ namespace arrow {
28
+ namespace internal {
29
+
30
+ template <typename T>
31
+ class AlignedStorage {
32
+ public:
33
+ static constexpr bool can_memcpy = std::is_trivial<T>::value;
34
+
35
+ constexpr T* get() noexcept {
36
+ return arrow::internal::launder(reinterpret_cast<T*>(&data_));
37
+ }
38
+
39
+ constexpr const T* get() const noexcept {
40
+ // Use fully qualified name to avoid ambiguities with MSVC (ARROW-14800)
41
+ return arrow::internal::launder(reinterpret_cast<const T*>(&data_));
42
+ }
43
+
44
+ void destroy() noexcept {
45
+ if (!std::is_trivially_destructible<T>::value) {
46
+ get()->~T();
47
+ }
48
+ }
49
+
50
+ template <typename... A>
51
+ void construct(A&&... args) noexcept {
52
+ new (&data_) T(std::forward<A>(args)...);
53
+ }
54
+
55
+ template <typename V>
56
+ void assign(V&& v) noexcept {
57
+ *get() = std::forward<V>(v);
58
+ }
59
+
60
+ void move_construct(AlignedStorage* other) noexcept {
61
+ new (&data_) T(std::move(*other->get()));
62
+ }
63
+
64
+ void move_assign(AlignedStorage* other) noexcept { *get() = std::move(*other->get()); }
65
+
66
+ template <bool CanMemcpy = can_memcpy>
67
+ static typename std::enable_if<CanMemcpy>::type move_construct_several(
68
+ AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, size_t n,
69
+ size_t memcpy_length) noexcept {
70
+ memcpy(dest->get(), src->get(), memcpy_length * sizeof(T));
71
+ }
72
+
73
+ template <bool CanMemcpy = can_memcpy>
74
+ static typename std::enable_if<CanMemcpy>::type
75
+ move_construct_several_and_destroy_source(AlignedStorage* ARROW_RESTRICT src,
76
+ AlignedStorage* ARROW_RESTRICT dest, size_t n,
77
+ size_t memcpy_length) noexcept {
78
+ memcpy(dest->get(), src->get(), memcpy_length * sizeof(T));
79
+ }
80
+
81
+ template <bool CanMemcpy = can_memcpy>
82
+ static typename std::enable_if<!CanMemcpy>::type move_construct_several(
83
+ AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, size_t n,
84
+ size_t memcpy_length) noexcept {
85
+ for (size_t i = 0; i < n; ++i) {
86
+ new (dest[i].get()) T(std::move(*src[i].get()));
87
+ }
88
+ }
89
+
90
+ template <bool CanMemcpy = can_memcpy>
91
+ static typename std::enable_if<!CanMemcpy>::type
92
+ move_construct_several_and_destroy_source(AlignedStorage* ARROW_RESTRICT src,
93
+ AlignedStorage* ARROW_RESTRICT dest, size_t n,
94
+ size_t memcpy_length) noexcept {
95
+ for (size_t i = 0; i < n; ++i) {
96
+ new (dest[i].get()) T(std::move(*src[i].get()));
97
+ src[i].destroy();
98
+ }
99
+ }
100
+
101
+ static void move_construct_several(AlignedStorage* ARROW_RESTRICT src,
102
+ AlignedStorage* ARROW_RESTRICT dest,
103
+ size_t n) noexcept {
104
+ move_construct_several(src, dest, n, n);
105
+ }
106
+
107
+ static void move_construct_several_and_destroy_source(
108
+ AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest,
109
+ size_t n) noexcept {
110
+ move_construct_several_and_destroy_source(src, dest, n, n);
111
+ }
112
+
113
+ static void destroy_several(AlignedStorage* p, size_t n) noexcept {
114
+ if (!std::is_trivially_destructible<T>::value) {
115
+ for (size_t i = 0; i < n; ++i) {
116
+ p[i].destroy();
117
+ }
118
+ }
119
+ }
120
+
121
+ private:
122
+ #if !defined(__clang__) && defined(__GNUC__) && defined(__i386__)
123
+ // Workaround for GCC bug on i386:
124
+ // alignof(int64 | float64) can give different results depending on the
125
+ // compilation context, leading to internal ABI mismatch manifesting
126
+ // in incorrect propagation of Result<int64 | float64> between
127
+ // compilation units.
128
+ // (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88115)
129
+ static constexpr size_t alignment() {
130
+ if (std::is_integral_v<T> && sizeof(T) == 8) {
131
+ return 4;
132
+ } else if (std::is_floating_point_v<T> && sizeof(T) == 8) {
133
+ return 4;
134
+ }
135
+ return alignof(T);
136
+ }
137
+
138
+ typename std::aligned_storage<sizeof(T), alignment()>::type data_;
139
+ #else
140
+ typename std::aligned_storage<sizeof(T), alignof(T)>::type data_;
141
+ #endif
142
+ };
143
+
144
+ } // namespace internal
145
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator.h ADDED
@@ -0,0 +1,2058 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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>
21
+ #include <cassert>
22
+ #include <cstring>
23
+ #include <deque>
24
+ #include <limits>
25
+ #include <optional>
26
+ #include <queue>
27
+
28
+ #include "arrow/util/async_generator_fwd.h"
29
+ #include "arrow/util/async_util.h"
30
+ #include "arrow/util/functional.h"
31
+ #include "arrow/util/future.h"
32
+ #include "arrow/util/io_util.h"
33
+ #include "arrow/util/iterator.h"
34
+ #include "arrow/util/mutex.h"
35
+ #include "arrow/util/queue.h"
36
+ #include "arrow/util/thread_pool.h"
37
+
38
+ namespace arrow {
39
+
40
+ // The methods in this file create, modify, and utilize AsyncGenerator which is an
41
+ // iterator of futures. This allows an asynchronous source (like file input) to be run
42
+ // through a pipeline in the same way that iterators can be used to create pipelined
43
+ // workflows.
44
+ //
45
+ // In order to support pipeline parallelism we introduce the concept of asynchronous
46
+ // reentrancy. This is different than synchronous reentrancy. With synchronous code a
47
+ // function is reentrant if the function can be called again while a previous call to that
48
+ // function is still running. Unless otherwise specified none of these generators are
49
+ // synchronously reentrant. Care should be taken to avoid calling them in such a way (and
50
+ // the utilities Visit/Collect/Await take care to do this).
51
+ //
52
+ // Asynchronous reentrancy on the other hand means the function is called again before the
53
+ // future returned by the function is marked finished (but after the call to get the
54
+ // future returns). Some of these generators are async-reentrant while others (e.g.
55
+ // those that depend on ordered processing like decompression) are not. Read the MakeXYZ
56
+ // function comments to determine which generators support async reentrancy.
57
+ //
58
+ // Note: Generators that are not asynchronously reentrant can still support readahead
59
+ // (\see MakeSerialReadaheadGenerator).
60
+ //
61
+ // Readahead operators, and some other operators, may introduce queueing. Any operators
62
+ // that introduce buffering should detail the amount of buffering they introduce in their
63
+ // MakeXYZ function comments.
64
+ //
65
+ // A generator should always be fully consumed before it is destroyed.
66
+ // A generator should not mark a future complete with an error status or a terminal value
67
+ // until all outstanding futures have completed. Generators that spawn multiple
68
+ // concurrent futures may need to hold onto an error while other concurrent futures wrap
69
+ // up.
70
+ template <typename T>
71
+ struct IterationTraits<AsyncGenerator<T>> {
72
+ /// \brief by default when iterating through a sequence of AsyncGenerator<T>,
73
+ /// an empty function indicates the end of iteration.
74
+ static AsyncGenerator<T> End() { return AsyncGenerator<T>(); }
75
+
76
+ static bool IsEnd(const AsyncGenerator<T>& val) { return !val; }
77
+ };
78
+
79
+ template <typename T>
80
+ Future<T> AsyncGeneratorEnd() {
81
+ return Future<T>::MakeFinished(IterationTraits<T>::End());
82
+ }
83
+
84
+ /// returning a future that completes when all have been visited
85
+ template <typename T, typename Visitor>
86
+ Future<> VisitAsyncGenerator(AsyncGenerator<T> generator, Visitor visitor) {
87
+ struct LoopBody {
88
+ struct Callback {
89
+ Result<ControlFlow<>> operator()(const T& next) {
90
+ if (IsIterationEnd(next)) {
91
+ return Break();
92
+ } else {
93
+ auto visited = visitor(next);
94
+ if (visited.ok()) {
95
+ return Continue();
96
+ } else {
97
+ return visited;
98
+ }
99
+ }
100
+ }
101
+
102
+ Visitor visitor;
103
+ };
104
+
105
+ Future<ControlFlow<>> operator()() {
106
+ Callback callback{visitor};
107
+ auto next = generator();
108
+ return next.Then(std::move(callback));
109
+ }
110
+
111
+ AsyncGenerator<T> generator;
112
+ Visitor visitor;
113
+ };
114
+
115
+ return Loop(LoopBody{std::move(generator), std::move(visitor)});
116
+ }
117
+
118
+ /// \brief Wait for an async generator to complete, discarding results.
119
+ template <typename T>
120
+ Future<> DiscardAllFromAsyncGenerator(AsyncGenerator<T> generator) {
121
+ std::function<Status(T)> visitor = [](const T&) { return Status::OK(); };
122
+ return VisitAsyncGenerator(generator, visitor);
123
+ }
124
+
125
+ /// \brief Collect the results of an async generator into a vector
126
+ template <typename T>
127
+ Future<std::vector<T>> CollectAsyncGenerator(AsyncGenerator<T> generator) {
128
+ auto vec = std::make_shared<std::vector<T>>();
129
+ auto loop_body = [generator = std::move(generator),
130
+ vec = std::move(vec)]() -> Future<ControlFlow<std::vector<T>>> {
131
+ auto next = generator();
132
+ return next.Then([vec](const T& result) -> Result<ControlFlow<std::vector<T>>> {
133
+ if (IsIterationEnd(result)) {
134
+ return Break(*vec);
135
+ } else {
136
+ vec->push_back(result);
137
+ return Continue();
138
+ }
139
+ });
140
+ };
141
+ return Loop(std::move(loop_body));
142
+ }
143
+
144
+ /// \see MakeMappedGenerator
145
+ template <typename T, typename V>
146
+ class MappingGenerator {
147
+ public:
148
+ MappingGenerator(AsyncGenerator<T> source, std::function<Future<V>(const T&)> map)
149
+ : state_(std::make_shared<State>(std::move(source), std::move(map))) {}
150
+
151
+ Future<V> operator()() {
152
+ auto future = Future<V>::Make();
153
+ bool should_trigger;
154
+ {
155
+ auto guard = state_->mutex.Lock();
156
+ if (state_->finished) {
157
+ return AsyncGeneratorEnd<V>();
158
+ }
159
+ should_trigger = state_->waiting_jobs.empty();
160
+ state_->waiting_jobs.push_back(future);
161
+ }
162
+ if (should_trigger) {
163
+ state_->source().AddCallback(Callback{state_});
164
+ }
165
+ return future;
166
+ }
167
+
168
+ private:
169
+ struct State {
170
+ State(AsyncGenerator<T> source, std::function<Future<V>(const T&)> map)
171
+ : source(std::move(source)),
172
+ map(std::move(map)),
173
+ waiting_jobs(),
174
+ mutex(),
175
+ finished(false) {}
176
+
177
+ void Purge() {
178
+ // This might be called by an original callback (if the source iterator fails or
179
+ // ends) or by a mapped callback (if the map function fails or ends prematurely).
180
+ // Either way it should only be called once and after finished is set so there is no
181
+ // need to guard access to `waiting_jobs`.
182
+ while (!waiting_jobs.empty()) {
183
+ waiting_jobs.front().MarkFinished(IterationTraits<V>::End());
184
+ waiting_jobs.pop_front();
185
+ }
186
+ }
187
+
188
+ AsyncGenerator<T> source;
189
+ std::function<Future<V>(const T&)> map;
190
+ std::deque<Future<V>> waiting_jobs;
191
+ util::Mutex mutex;
192
+ bool finished;
193
+ };
194
+
195
+ struct Callback;
196
+
197
+ struct MappedCallback {
198
+ void operator()(const Result<V>& maybe_next) {
199
+ bool end = !maybe_next.ok() || IsIterationEnd(*maybe_next);
200
+ bool should_purge = false;
201
+ if (end) {
202
+ {
203
+ auto guard = state->mutex.Lock();
204
+ should_purge = !state->finished;
205
+ state->finished = true;
206
+ }
207
+ }
208
+ sink.MarkFinished(maybe_next);
209
+ if (should_purge) {
210
+ state->Purge();
211
+ }
212
+ }
213
+ std::shared_ptr<State> state;
214
+ Future<V> sink;
215
+ };
216
+
217
+ struct Callback {
218
+ void operator()(const Result<T>& maybe_next) {
219
+ Future<V> sink;
220
+ bool end = !maybe_next.ok() || IsIterationEnd(*maybe_next);
221
+ bool should_purge = false;
222
+ bool should_trigger;
223
+ {
224
+ auto guard = state->mutex.Lock();
225
+ // A MappedCallback may have purged or be purging the queue;
226
+ // we shouldn't do anything here.
227
+ if (state->finished) return;
228
+ if (end) {
229
+ should_purge = !state->finished;
230
+ state->finished = true;
231
+ }
232
+ sink = state->waiting_jobs.front();
233
+ state->waiting_jobs.pop_front();
234
+ should_trigger = !end && !state->waiting_jobs.empty();
235
+ }
236
+ if (should_purge) {
237
+ state->Purge();
238
+ }
239
+ if (should_trigger) {
240
+ state->source().AddCallback(Callback{state});
241
+ }
242
+ if (maybe_next.ok()) {
243
+ const T& val = maybe_next.ValueUnsafe();
244
+ if (IsIterationEnd(val)) {
245
+ sink.MarkFinished(IterationTraits<V>::End());
246
+ } else {
247
+ Future<V> mapped_fut = state->map(val);
248
+ mapped_fut.AddCallback(MappedCallback{std::move(state), std::move(sink)});
249
+ }
250
+ } else {
251
+ sink.MarkFinished(maybe_next.status());
252
+ }
253
+ }
254
+
255
+ std::shared_ptr<State> state;
256
+ };
257
+
258
+ std::shared_ptr<State> state_;
259
+ };
260
+
261
+ /// \brief Create a generator that will apply the map function to each element of
262
+ /// source. The map function is not called on the end token.
263
+ ///
264
+ /// Note: This function makes a copy of `map` for each item
265
+ /// Note: Errors returned from the `map` function will be propagated
266
+ ///
267
+ /// If the source generator is async-reentrant then this generator will be also
268
+ template <typename T, typename MapFn,
269
+ typename Mapped = detail::result_of_t<MapFn(const T&)>,
270
+ typename V = typename EnsureFuture<Mapped>::type::ValueType>
271
+ AsyncGenerator<V> MakeMappedGenerator(AsyncGenerator<T> source_generator, MapFn map) {
272
+ auto map_callback = [map = std::move(map)](const T& val) mutable -> Future<V> {
273
+ return ToFuture(map(val));
274
+ };
275
+ return MappingGenerator<T, V>(std::move(source_generator), std::move(map_callback));
276
+ }
277
+
278
+ /// \brief Create a generator that will apply the map function to
279
+ /// each element of source. The map function is not called on the end
280
+ /// token. The result of the map function should be another
281
+ /// generator; all these generators will then be flattened to produce
282
+ /// a single stream of items.
283
+ ///
284
+ /// Note: This function makes a copy of `map` for each item
285
+ /// Note: Errors returned from the `map` function will be propagated
286
+ ///
287
+ /// If the source generator is async-reentrant then this generator will be also
288
+ template <typename T, typename MapFn,
289
+ typename Mapped = detail::result_of_t<MapFn(const T&)>,
290
+ typename V = typename EnsureFuture<Mapped>::type::ValueType>
291
+ AsyncGenerator<T> MakeFlatMappedGenerator(AsyncGenerator<T> source_generator, MapFn map) {
292
+ return MakeConcatenatedGenerator(
293
+ MakeMappedGenerator(std::move(source_generator), std::move(map)));
294
+ }
295
+
296
+ /// \see MakeSequencingGenerator
297
+ template <typename T, typename ComesAfter, typename IsNext>
298
+ class SequencingGenerator {
299
+ public:
300
+ SequencingGenerator(AsyncGenerator<T> source, ComesAfter compare, IsNext is_next,
301
+ T initial_value)
302
+ : state_(std::make_shared<State>(std::move(source), std::move(compare),
303
+ std::move(is_next), std::move(initial_value))) {}
304
+
305
+ Future<T> operator()() {
306
+ {
307
+ auto guard = state_->mutex.Lock();
308
+ // We can send a result immediately if the top of the queue is either an
309
+ // error or the next item
310
+ if (!state_->queue.empty() &&
311
+ (!state_->queue.top().ok() ||
312
+ state_->is_next(state_->previous_value, *state_->queue.top()))) {
313
+ auto result = std::move(state_->queue.top());
314
+ if (result.ok()) {
315
+ state_->previous_value = *result;
316
+ }
317
+ state_->queue.pop();
318
+ return Future<T>::MakeFinished(result);
319
+ }
320
+ if (state_->finished) {
321
+ return AsyncGeneratorEnd<T>();
322
+ }
323
+ // The next item is not in the queue so we will need to wait
324
+ auto new_waiting_fut = Future<T>::Make();
325
+ state_->waiting_future = new_waiting_fut;
326
+ guard.Unlock();
327
+ state_->source().AddCallback(Callback{state_});
328
+ return new_waiting_fut;
329
+ }
330
+ }
331
+
332
+ private:
333
+ struct WrappedComesAfter {
334
+ bool operator()(const Result<T>& left, const Result<T>& right) {
335
+ if (!left.ok() || !right.ok()) {
336
+ // Should never happen
337
+ return false;
338
+ }
339
+ return compare(*left, *right);
340
+ }
341
+ ComesAfter compare;
342
+ };
343
+
344
+ struct State {
345
+ State(AsyncGenerator<T> source, ComesAfter compare, IsNext is_next, T initial_value)
346
+ : source(std::move(source)),
347
+ is_next(std::move(is_next)),
348
+ previous_value(std::move(initial_value)),
349
+ waiting_future(),
350
+ queue(WrappedComesAfter{compare}),
351
+ finished(false),
352
+ mutex() {}
353
+
354
+ AsyncGenerator<T> source;
355
+ IsNext is_next;
356
+ T previous_value;
357
+ Future<T> waiting_future;
358
+ std::priority_queue<Result<T>, std::vector<Result<T>>, WrappedComesAfter> queue;
359
+ bool finished;
360
+ util::Mutex mutex;
361
+ };
362
+
363
+ class Callback {
364
+ public:
365
+ explicit Callback(std::shared_ptr<State> state) : state_(std::move(state)) {}
366
+
367
+ void operator()(const Result<T> result) {
368
+ Future<T> to_deliver;
369
+ bool finished;
370
+ {
371
+ auto guard = state_->mutex.Lock();
372
+ bool ready_to_deliver = false;
373
+ if (!result.ok()) {
374
+ // Clear any cached results
375
+ while (!state_->queue.empty()) {
376
+ state_->queue.pop();
377
+ }
378
+ ready_to_deliver = true;
379
+ state_->finished = true;
380
+ } else if (IsIterationEnd<T>(result.ValueUnsafe())) {
381
+ ready_to_deliver = state_->queue.empty();
382
+ state_->finished = true;
383
+ } else {
384
+ ready_to_deliver = state_->is_next(state_->previous_value, *result);
385
+ }
386
+
387
+ if (ready_to_deliver && state_->waiting_future.is_valid()) {
388
+ to_deliver = state_->waiting_future;
389
+ if (result.ok()) {
390
+ state_->previous_value = *result;
391
+ }
392
+ } else {
393
+ state_->queue.push(result);
394
+ }
395
+ // Capture state_->finished so we can access it outside the mutex
396
+ finished = state_->finished;
397
+ }
398
+ // Must deliver result outside of the mutex
399
+ if (to_deliver.is_valid()) {
400
+ to_deliver.MarkFinished(result);
401
+ } else {
402
+ // Otherwise, if we didn't get the next item (or a terminal item), we
403
+ // need to keep looking
404
+ if (!finished) {
405
+ state_->source().AddCallback(Callback{state_});
406
+ }
407
+ }
408
+ }
409
+
410
+ private:
411
+ const std::shared_ptr<State> state_;
412
+ };
413
+
414
+ const std::shared_ptr<State> state_;
415
+ };
416
+
417
+ /// \brief Buffer an AsyncGenerator to return values in sequence order ComesAfter
418
+ /// and IsNext determine the sequence order.
419
+ ///
420
+ /// ComesAfter should be a BinaryPredicate that only returns true if a comes after b
421
+ ///
422
+ /// IsNext should be a BinaryPredicate that returns true, given `a` and `b`, only if
423
+ /// `b` follows immediately after `a`. It should return true given `initial_value` and
424
+ /// `b` if `b` is the first item in the sequence.
425
+ ///
426
+ /// This operator will queue unboundedly while waiting for the next item. It is intended
427
+ /// for jittery sources that might scatter an ordered sequence. It is NOT intended to
428
+ /// sort. Using it to try and sort could result in excessive RAM usage. This generator
429
+ /// will queue up to N blocks where N is the max "out of order"ness of the source.
430
+ ///
431
+ /// For example, if the source is 1,6,2,5,4,3 it will queue 3 blocks because 3 is 3
432
+ /// blocks beyond where it belongs.
433
+ ///
434
+ /// This generator is not async-reentrant but it consists only of a simple log(n)
435
+ /// insertion into a priority queue.
436
+ template <typename T, typename ComesAfter, typename IsNext>
437
+ AsyncGenerator<T> MakeSequencingGenerator(AsyncGenerator<T> source_generator,
438
+ ComesAfter compare, IsNext is_next,
439
+ T initial_value) {
440
+ return SequencingGenerator<T, ComesAfter, IsNext>(
441
+ std::move(source_generator), std::move(compare), std::move(is_next),
442
+ std::move(initial_value));
443
+ }
444
+
445
+ /// \see MakeTransformedGenerator
446
+ template <typename T, typename V>
447
+ class TransformingGenerator {
448
+ // The transforming generator state will be referenced as an async generator but will
449
+ // also be referenced via callback to various futures. If the async generator owner
450
+ // moves it around we need the state to be consistent for future callbacks.
451
+ struct TransformingGeneratorState
452
+ : std::enable_shared_from_this<TransformingGeneratorState> {
453
+ TransformingGeneratorState(AsyncGenerator<T> generator, Transformer<T, V> transformer)
454
+ : generator_(std::move(generator)),
455
+ transformer_(std::move(transformer)),
456
+ last_value_(),
457
+ finished_() {}
458
+
459
+ Future<V> operator()() {
460
+ while (true) {
461
+ auto maybe_next_result = Pump();
462
+ if (!maybe_next_result.ok()) {
463
+ return Future<V>::MakeFinished(maybe_next_result.status());
464
+ }
465
+ auto maybe_next = std::move(maybe_next_result).ValueUnsafe();
466
+ if (maybe_next.has_value()) {
467
+ return Future<V>::MakeFinished(*std::move(maybe_next));
468
+ }
469
+
470
+ auto next_fut = generator_();
471
+ // If finished already, process results immediately inside the loop to avoid
472
+ // stack overflow
473
+ if (next_fut.is_finished()) {
474
+ auto next_result = next_fut.result();
475
+ if (next_result.ok()) {
476
+ last_value_ = *next_result;
477
+ } else {
478
+ return Future<V>::MakeFinished(next_result.status());
479
+ }
480
+ // Otherwise, if not finished immediately, add callback to process results
481
+ } else {
482
+ auto self = this->shared_from_this();
483
+ return next_fut.Then([self](const T& next_result) {
484
+ self->last_value_ = next_result;
485
+ return (*self)();
486
+ });
487
+ }
488
+ }
489
+ }
490
+
491
+ // See comment on TransformingIterator::Pump
492
+ Result<std::optional<V>> Pump() {
493
+ if (!finished_ && last_value_.has_value()) {
494
+ ARROW_ASSIGN_OR_RAISE(TransformFlow<V> next, transformer_(*last_value_));
495
+ if (next.ReadyForNext()) {
496
+ if (IsIterationEnd(*last_value_)) {
497
+ finished_ = true;
498
+ }
499
+ last_value_.reset();
500
+ }
501
+ if (next.Finished()) {
502
+ finished_ = true;
503
+ }
504
+ if (next.HasValue()) {
505
+ return next.Value();
506
+ }
507
+ }
508
+ if (finished_) {
509
+ return IterationTraits<V>::End();
510
+ }
511
+ return std::nullopt;
512
+ }
513
+
514
+ AsyncGenerator<T> generator_;
515
+ Transformer<T, V> transformer_;
516
+ std::optional<T> last_value_;
517
+ bool finished_;
518
+ };
519
+
520
+ public:
521
+ explicit TransformingGenerator(AsyncGenerator<T> generator,
522
+ Transformer<T, V> transformer)
523
+ : state_(std::make_shared<TransformingGeneratorState>(std::move(generator),
524
+ std::move(transformer))) {}
525
+
526
+ Future<V> operator()() { return (*state_)(); }
527
+
528
+ protected:
529
+ std::shared_ptr<TransformingGeneratorState> state_;
530
+ };
531
+
532
+ /// \brief Transform an async generator using a transformer function returning a new
533
+ /// AsyncGenerator
534
+ ///
535
+ /// The transform function here behaves exactly the same as the transform function in
536
+ /// MakeTransformedIterator and you can safely use the same transform function to
537
+ /// transform both synchronous and asynchronous streams.
538
+ ///
539
+ /// This generator is not async-reentrant
540
+ ///
541
+ /// This generator may queue up to 1 instance of T but will not delay
542
+ template <typename T, typename V>
543
+ AsyncGenerator<V> MakeTransformedGenerator(AsyncGenerator<T> generator,
544
+ Transformer<T, V> transformer) {
545
+ return TransformingGenerator<T, V>(generator, transformer);
546
+ }
547
+
548
+ /// \see MakeSerialReadaheadGenerator
549
+ template <typename T>
550
+ class SerialReadaheadGenerator {
551
+ public:
552
+ SerialReadaheadGenerator(AsyncGenerator<T> source_generator, int max_readahead)
553
+ : state_(std::make_shared<State>(std::move(source_generator), max_readahead)) {}
554
+
555
+ Future<T> operator()() {
556
+ if (state_->first_) {
557
+ // Lazy generator, need to wait for the first ask to prime the pump
558
+ state_->first_ = false;
559
+ auto next = state_->source_();
560
+ return next.Then(Callback{state_}, ErrCallback{state_});
561
+ }
562
+
563
+ // This generator is not async-reentrant. We won't be called until the last
564
+ // future finished so we know there is something in the queue
565
+ auto finished = state_->finished_.load();
566
+ if (finished && state_->readahead_queue_.IsEmpty()) {
567
+ return AsyncGeneratorEnd<T>();
568
+ }
569
+
570
+ std::shared_ptr<Future<T>> next;
571
+ if (!state_->readahead_queue_.Read(next)) {
572
+ return Status::UnknownError("Could not read from readahead_queue");
573
+ }
574
+
575
+ auto last_available = state_->spaces_available_.fetch_add(1);
576
+ if (last_available == 0 && !finished) {
577
+ // Reader idled out, we need to restart it
578
+ ARROW_RETURN_NOT_OK(state_->Pump(state_));
579
+ }
580
+ return *next;
581
+ }
582
+
583
+ private:
584
+ struct State {
585
+ State(AsyncGenerator<T> source, int max_readahead)
586
+ : first_(true),
587
+ source_(std::move(source)),
588
+ finished_(false),
589
+ // There is one extra "space" for the in-flight request
590
+ spaces_available_(max_readahead + 1),
591
+ // The SPSC queue has size-1 "usable" slots so we need to overallocate 1
592
+ readahead_queue_(max_readahead + 1) {}
593
+
594
+ Status Pump(const std::shared_ptr<State>& self) {
595
+ // Can't do readahead_queue.write(source().Then(...)) because then the
596
+ // callback might run immediately and add itself to the queue before this gets added
597
+ // to the queue messing up the order.
598
+ auto next_slot = std::make_shared<Future<T>>();
599
+ auto written = readahead_queue_.Write(next_slot);
600
+ if (!written) {
601
+ return Status::UnknownError("Could not write to readahead_queue");
602
+ }
603
+ // If this Pump is being called from a callback it is possible for the source to
604
+ // poll and read from the queue between the Write and this spot where we fill the
605
+ // value in. However, it is not possible for the future to read this value we are
606
+ // writing. That is because this callback (the callback for future X) must be
607
+ // finished before future X is marked complete and this source is not pulled
608
+ // reentrantly so it will not poll for future X+1 until this callback has completed.
609
+ *next_slot = source_().Then(Callback{self}, ErrCallback{self});
610
+ return Status::OK();
611
+ }
612
+
613
+ // Only accessed by the consumer end
614
+ bool first_;
615
+ // Accessed by both threads
616
+ AsyncGenerator<T> source_;
617
+ std::atomic<bool> finished_;
618
+ // The queue has a size but it is not atomic. We keep track of how many spaces are
619
+ // left in the queue here so we know if we've just written the last value and we need
620
+ // to stop reading ahead or if we've just read from a full queue and we need to
621
+ // restart reading ahead
622
+ std::atomic<uint32_t> spaces_available_;
623
+ // Needs to be a queue of shared_ptr and not Future because we set the value of the
624
+ // future after we add it to the queue
625
+ util::SpscQueue<std::shared_ptr<Future<T>>> readahead_queue_;
626
+ };
627
+
628
+ struct Callback {
629
+ Result<T> operator()(const T& next) {
630
+ if (IsIterationEnd(next)) {
631
+ state_->finished_.store(true);
632
+ return next;
633
+ }
634
+ auto last_available = state_->spaces_available_.fetch_sub(1);
635
+ if (last_available > 1) {
636
+ ARROW_RETURN_NOT_OK(state_->Pump(state_));
637
+ }
638
+ return next;
639
+ }
640
+
641
+ std::shared_ptr<State> state_;
642
+ };
643
+
644
+ struct ErrCallback {
645
+ Result<T> operator()(const Status& st) {
646
+ state_->finished_.store(true);
647
+ return st;
648
+ }
649
+
650
+ std::shared_ptr<State> state_;
651
+ };
652
+
653
+ std::shared_ptr<State> state_;
654
+ };
655
+
656
+ /// \see MakeFromFuture
657
+ template <typename T>
658
+ class FutureFirstGenerator {
659
+ public:
660
+ explicit FutureFirstGenerator(Future<AsyncGenerator<T>> future)
661
+ : state_(std::make_shared<State>(std::move(future))) {}
662
+
663
+ Future<T> operator()() {
664
+ if (state_->source_) {
665
+ return state_->source_();
666
+ } else {
667
+ auto state = state_;
668
+ return state_->future_.Then([state](const AsyncGenerator<T>& source) {
669
+ state->source_ = source;
670
+ return state->source_();
671
+ });
672
+ }
673
+ }
674
+
675
+ private:
676
+ struct State {
677
+ explicit State(Future<AsyncGenerator<T>> future) : future_(future), source_() {}
678
+
679
+ Future<AsyncGenerator<T>> future_;
680
+ AsyncGenerator<T> source_;
681
+ };
682
+
683
+ std::shared_ptr<State> state_;
684
+ };
685
+
686
+ /// \brief Transform a Future<AsyncGenerator<T>> into an AsyncGenerator<T>
687
+ /// that waits for the future to complete as part of the first item.
688
+ ///
689
+ /// This generator is not async-reentrant (even if the generator yielded by future is)
690
+ ///
691
+ /// This generator does not queue
692
+ template <typename T>
693
+ AsyncGenerator<T> MakeFromFuture(Future<AsyncGenerator<T>> future) {
694
+ return FutureFirstGenerator<T>(std::move(future));
695
+ }
696
+
697
+ /// \brief Create a generator that will pull from the source into a queue. Unlike
698
+ /// MakeReadaheadGenerator this will not pull reentrantly from the source.
699
+ ///
700
+ /// The source generator does not need to be async-reentrant
701
+ ///
702
+ /// This generator is not async-reentrant (even if the source is)
703
+ ///
704
+ /// This generator may queue up to max_readahead additional instances of T
705
+ template <typename T>
706
+ AsyncGenerator<T> MakeSerialReadaheadGenerator(AsyncGenerator<T> source_generator,
707
+ int max_readahead) {
708
+ return SerialReadaheadGenerator<T>(std::move(source_generator), max_readahead);
709
+ }
710
+
711
+ /// \brief Create a generator that immediately pulls from the source
712
+ ///
713
+ /// Typical generators do not pull from their source until they themselves
714
+ /// are pulled. This generator does not follow that convention and will call
715
+ /// generator() once before it returns. The returned generator will otherwise
716
+ /// mirror the source.
717
+ ///
718
+ /// This generator forwards async-reentrant pressure to the source
719
+ /// This generator buffers one item (the first result) until it is delivered.
720
+ template <typename T>
721
+ AsyncGenerator<T> MakeAutoStartingGenerator(AsyncGenerator<T> generator) {
722
+ struct AutostartGenerator {
723
+ Future<T> operator()() {
724
+ if (first_future->is_valid()) {
725
+ Future<T> result = *first_future;
726
+ *first_future = Future<T>();
727
+ return result;
728
+ }
729
+ return source();
730
+ }
731
+
732
+ std::shared_ptr<Future<T>> first_future;
733
+ AsyncGenerator<T> source;
734
+ };
735
+
736
+ std::shared_ptr<Future<T>> first_future = std::make_shared<Future<T>>(generator());
737
+ return AutostartGenerator{std::move(first_future), std::move(generator)};
738
+ }
739
+
740
+ /// \see MakeReadaheadGenerator
741
+ template <typename T>
742
+ class ReadaheadGenerator {
743
+ public:
744
+ ReadaheadGenerator(AsyncGenerator<T> source_generator, int max_readahead)
745
+ : state_(std::make_shared<State>(std::move(source_generator), max_readahead)) {}
746
+
747
+ Future<T> AddMarkFinishedContinuation(Future<T> fut) {
748
+ auto state = state_;
749
+ return fut.Then(
750
+ [state](const T& result) -> Future<T> {
751
+ state->MarkFinishedIfDone(result);
752
+ if (state->finished.load()) {
753
+ if (state->num_running.fetch_sub(1) == 1) {
754
+ state->final_future.MarkFinished();
755
+ }
756
+ } else {
757
+ state->num_running.fetch_sub(1);
758
+ }
759
+ return result;
760
+ },
761
+ [state](const Status& err) -> Future<T> {
762
+ // If there is an error we need to make sure all running
763
+ // tasks finish before we return the error.
764
+ state->finished.store(true);
765
+ if (state->num_running.fetch_sub(1) == 1) {
766
+ state->final_future.MarkFinished();
767
+ }
768
+ return state->final_future.Then([err]() -> Result<T> { return err; });
769
+ });
770
+ }
771
+
772
+ Future<T> operator()() {
773
+ if (state_->readahead_queue.empty()) {
774
+ // This is the first request, let's pump the underlying queue
775
+ state_->num_running.store(state_->max_readahead);
776
+ for (int i = 0; i < state_->max_readahead; i++) {
777
+ auto next = state_->source_generator();
778
+ auto next_after_check = AddMarkFinishedContinuation(std::move(next));
779
+ state_->readahead_queue.push(std::move(next_after_check));
780
+ }
781
+ }
782
+ // Pop one and add one
783
+ auto result = state_->readahead_queue.front();
784
+ state_->readahead_queue.pop();
785
+ if (state_->finished.load()) {
786
+ state_->readahead_queue.push(AsyncGeneratorEnd<T>());
787
+ } else {
788
+ state_->num_running.fetch_add(1);
789
+ auto back_of_queue = state_->source_generator();
790
+ auto back_of_queue_after_check =
791
+ AddMarkFinishedContinuation(std::move(back_of_queue));
792
+ state_->readahead_queue.push(std::move(back_of_queue_after_check));
793
+ }
794
+ return result;
795
+ }
796
+
797
+ private:
798
+ struct State {
799
+ State(AsyncGenerator<T> source_generator, int max_readahead)
800
+ : source_generator(std::move(source_generator)), max_readahead(max_readahead) {}
801
+
802
+ void MarkFinishedIfDone(const T& next_result) {
803
+ if (IsIterationEnd(next_result)) {
804
+ finished.store(true);
805
+ }
806
+ }
807
+
808
+ AsyncGenerator<T> source_generator;
809
+ int max_readahead;
810
+ Future<> final_future = Future<>::Make();
811
+ std::atomic<int> num_running{0};
812
+ std::atomic<bool> finished{false};
813
+ std::queue<Future<T>> readahead_queue;
814
+ };
815
+
816
+ std::shared_ptr<State> state_;
817
+ };
818
+
819
+ /// \brief A generator where the producer pushes items on a queue.
820
+ ///
821
+ /// No back-pressure is applied, so this generator is mostly useful when
822
+ /// producing the values is neither CPU- nor memory-expensive (e.g. fetching
823
+ /// filesystem metadata).
824
+ ///
825
+ /// This generator is not async-reentrant.
826
+ template <typename T>
827
+ class PushGenerator {
828
+ struct State {
829
+ State() {}
830
+
831
+ util::Mutex mutex;
832
+ std::deque<Result<T>> result_q;
833
+ std::optional<Future<T>> consumer_fut;
834
+ bool finished = false;
835
+ };
836
+
837
+ public:
838
+ /// Producer API for PushGenerator
839
+ class Producer {
840
+ public:
841
+ explicit Producer(const std::shared_ptr<State>& state) : weak_state_(state) {}
842
+
843
+ /// \brief Push a value on the queue
844
+ ///
845
+ /// True is returned if the value was pushed, false if the generator is
846
+ /// already closed or destroyed. If the latter, it is recommended to stop
847
+ /// producing any further values.
848
+ bool Push(Result<T> result) {
849
+ auto state = weak_state_.lock();
850
+ if (!state) {
851
+ // Generator was destroyed
852
+ return false;
853
+ }
854
+ auto lock = state->mutex.Lock();
855
+ if (state->finished) {
856
+ // Closed early
857
+ return false;
858
+ }
859
+ if (state->consumer_fut.has_value()) {
860
+ auto fut = std::move(state->consumer_fut.value());
861
+ state->consumer_fut.reset();
862
+ lock.Unlock(); // unlock before potentially invoking a callback
863
+ fut.MarkFinished(std::move(result));
864
+ } else {
865
+ state->result_q.push_back(std::move(result));
866
+ }
867
+ return true;
868
+ }
869
+
870
+ /// \brief Tell the consumer we have finished producing
871
+ ///
872
+ /// It is allowed to call this and later call Push() again ("early close").
873
+ /// In this case, calls to Push() after the queue is closed are silently
874
+ /// ignored. This can help implementing non-trivial cancellation cases.
875
+ ///
876
+ /// True is returned on success, false if the generator is already closed
877
+ /// or destroyed.
878
+ bool Close() {
879
+ auto state = weak_state_.lock();
880
+ if (!state) {
881
+ // Generator was destroyed
882
+ return false;
883
+ }
884
+ auto lock = state->mutex.Lock();
885
+ if (state->finished) {
886
+ // Already closed
887
+ return false;
888
+ }
889
+ state->finished = true;
890
+ if (state->consumer_fut.has_value()) {
891
+ auto fut = std::move(state->consumer_fut.value());
892
+ state->consumer_fut.reset();
893
+ lock.Unlock(); // unlock before potentially invoking a callback
894
+ fut.MarkFinished(IterationTraits<T>::End());
895
+ }
896
+ return true;
897
+ }
898
+
899
+ /// Return whether the generator was closed or destroyed.
900
+ bool is_closed() const {
901
+ auto state = weak_state_.lock();
902
+ if (!state) {
903
+ // Generator was destroyed
904
+ return true;
905
+ }
906
+ auto lock = state->mutex.Lock();
907
+ return state->finished;
908
+ }
909
+
910
+ private:
911
+ const std::weak_ptr<State> weak_state_;
912
+ };
913
+
914
+ PushGenerator() : state_(std::make_shared<State>()) {}
915
+
916
+ /// Read an item from the queue
917
+ Future<T> operator()() const {
918
+ auto lock = state_->mutex.Lock();
919
+ assert(!state_->consumer_fut.has_value()); // Non-reentrant
920
+ if (!state_->result_q.empty()) {
921
+ auto fut = Future<T>::MakeFinished(std::move(state_->result_q.front()));
922
+ state_->result_q.pop_front();
923
+ return fut;
924
+ }
925
+ if (state_->finished) {
926
+ return AsyncGeneratorEnd<T>();
927
+ }
928
+ auto fut = Future<T>::Make();
929
+ state_->consumer_fut = fut;
930
+ return fut;
931
+ }
932
+
933
+ /// \brief Return producer-side interface
934
+ ///
935
+ /// The returned object must be used by the producer to push values on the queue.
936
+ /// Only a single Producer object should be instantiated.
937
+ Producer producer() { return Producer{state_}; }
938
+
939
+ private:
940
+ const std::shared_ptr<State> state_;
941
+ };
942
+
943
+ /// \brief Create a generator that pulls reentrantly from a source
944
+ /// This generator will pull reentrantly from a source, ensuring that max_readahead
945
+ /// requests are active at any given time.
946
+ ///
947
+ /// The source generator must be async-reentrant
948
+ ///
949
+ /// This generator itself is async-reentrant.
950
+ ///
951
+ /// This generator may queue up to max_readahead instances of T
952
+ template <typename T>
953
+ AsyncGenerator<T> MakeReadaheadGenerator(AsyncGenerator<T> source_generator,
954
+ int max_readahead) {
955
+ return ReadaheadGenerator<T>(std::move(source_generator), max_readahead);
956
+ }
957
+
958
+ /// \brief Creates a generator that will yield finished futures from a vector
959
+ ///
960
+ /// This generator is async-reentrant
961
+ template <typename T>
962
+ AsyncGenerator<T> MakeVectorGenerator(std::vector<T> vec) {
963
+ struct State {
964
+ explicit State(std::vector<T> vec_) : vec(std::move(vec_)), vec_idx(0) {}
965
+
966
+ std::vector<T> vec;
967
+ std::atomic<std::size_t> vec_idx;
968
+ };
969
+
970
+ auto state = std::make_shared<State>(std::move(vec));
971
+ return [state]() {
972
+ auto idx = state->vec_idx.fetch_add(1);
973
+ if (idx >= state->vec.size()) {
974
+ // Eagerly return memory
975
+ state->vec.clear();
976
+ return AsyncGeneratorEnd<T>();
977
+ }
978
+ return Future<T>::MakeFinished(state->vec[idx]);
979
+ };
980
+ }
981
+
982
+ /// \see MakeMergedGenerator
983
+ template <typename T>
984
+ class MergedGenerator {
985
+ // Note, the implementation of this class is quite complex at the moment (PRs to
986
+ // simplify are always welcome)
987
+ //
988
+ // Terminology is borrowed from rxjs. This is a pull based implementation of the
989
+ // mergeAll operator. The "outer subscription" refers to the async
990
+ // generator that the caller provided when creating this. The outer subscription
991
+ // yields generators.
992
+ //
993
+ // Each of these generators is then subscribed to (up to max_subscriptions) and these
994
+ // are referred to as "inner subscriptions".
995
+ //
996
+ // As soon as we start we try and establish `max_subscriptions` inner subscriptions. For
997
+ // each inner subscription we will cache up to 1 value. This means we may have more
998
+ // values than we have been asked for. In our example, if a caller asks for one record
999
+ // batch we will start scanning `max_subscriptions` different files. For each file we
1000
+ // will only queue up to 1 batch (so a separate readahead is needed on the file if batch
1001
+ // readahead is desired).
1002
+ //
1003
+ // If the caller is slow we may accumulate ready-to-deliver items. These are stored
1004
+ // in `delivered_jobs`.
1005
+ //
1006
+ // If the caller is very quick we may accumulate requests. These are stored in
1007
+ // `waiting_jobs`.
1008
+ //
1009
+ // It may be helpful to consider an example, in the scanner the outer subscription
1010
+ // is some kind of asynchronous directory listing. The inner subscription is
1011
+ // then a scan on a file yielded by the directory listing.
1012
+ //
1013
+ // An "outstanding" request is when we have polled either the inner or outer
1014
+ // subscription but that future hasn't completed yet.
1015
+ //
1016
+ // There are three possible "events" that can happen.
1017
+ // * A caller could request the next future
1018
+ // * An outer callback occurs when the next subscription is ready (e.g. the directory
1019
+ // listing has produced a new file)
1020
+ // * An inner callback occurs when one of the inner subscriptions emits a value (e.g.
1021
+ // a file scan emits a record batch)
1022
+ //
1023
+ // Any time an event happens the logic is broken into two phases. First, we grab the
1024
+ // lock and modify the shared state. While doing this we figure out what callbacks we
1025
+ // will need to execute. Then, we give up the lock and execute these callbacks. It is
1026
+ // important to execute these callbacks without the lock to avoid deadlock.
1027
+ public:
1028
+ explicit MergedGenerator(AsyncGenerator<AsyncGenerator<T>> source,
1029
+ int max_subscriptions)
1030
+ : state_(std::make_shared<State>(std::move(source), max_subscriptions)) {}
1031
+
1032
+ Future<T> operator()() {
1033
+ // A caller has requested a future
1034
+ Future<T> waiting_future;
1035
+ std::shared_ptr<DeliveredJob> delivered_job;
1036
+ bool mark_generator_complete = false;
1037
+ {
1038
+ auto guard = state_->mutex.Lock();
1039
+ if (!state_->delivered_jobs.empty()) {
1040
+ // If we have a job sitting around we can deliver it
1041
+ delivered_job = std::move(state_->delivered_jobs.front());
1042
+ state_->delivered_jobs.pop_front();
1043
+ if (state_->IsCompleteUnlocked(guard)) {
1044
+ // It's possible this waiting job was the only thing left to handle and
1045
+ // we have now completed the generator.
1046
+ mark_generator_complete = true;
1047
+ } else {
1048
+ // Since we had a job sitting around we also had an inner subscription
1049
+ // that had paused. We are going to restart this inner subscription and
1050
+ // so there will be a new outstanding request.
1051
+ state_->outstanding_requests++;
1052
+ }
1053
+ } else if (state_->broken ||
1054
+ (!state_->first && state_->num_running_subscriptions == 0)) {
1055
+ // If we are broken or exhausted then prepare a terminal item but
1056
+ // we won't complete it until we've finished.
1057
+ Result<T> end_res = IterationEnd<T>();
1058
+ if (!state_->final_error.ok()) {
1059
+ end_res = state_->final_error;
1060
+ state_->final_error = Status::OK();
1061
+ }
1062
+ return state_->all_finished.Then([end_res]() -> Result<T> { return end_res; });
1063
+ } else {
1064
+ // Otherwise we just queue the request and it will be completed when one of the
1065
+ // ongoing inner subscriptions delivers a result
1066
+ waiting_future = Future<T>::Make();
1067
+ state_->waiting_jobs.push_back(std::make_shared<Future<T>>(waiting_future));
1068
+ }
1069
+ if (state_->first) {
1070
+ // On the first request we are going to try and immediately fill our queue
1071
+ // of subscriptions. We assume we are going to be able to start them all.
1072
+ state_->outstanding_requests +=
1073
+ static_cast<int>(state_->active_subscriptions.size());
1074
+ state_->num_running_subscriptions +=
1075
+ static_cast<int>(state_->active_subscriptions.size());
1076
+ }
1077
+ }
1078
+ // If we grabbed a finished item from the delivered_jobs queue then we may need
1079
+ // to mark the generator finished or issue a request for a new item to fill in
1080
+ // the spot we just vacated. Notice that we issue that request to the same
1081
+ // subscription that delivered it (deliverer).
1082
+ if (delivered_job) {
1083
+ if (mark_generator_complete) {
1084
+ state_->all_finished.MarkFinished();
1085
+ } else {
1086
+ delivered_job->deliverer().AddCallback(
1087
+ InnerCallback(state_, delivered_job->index));
1088
+ }
1089
+ return std::move(delivered_job->value);
1090
+ }
1091
+ // On the first call we try and fill up our subscriptions. It's possible the outer
1092
+ // generator only has a few items and we can't fill up to what we were hoping. In
1093
+ // that case we have to bail early.
1094
+ if (state_->first) {
1095
+ state_->first = false;
1096
+ mark_generator_complete = false;
1097
+ for (int i = 0; i < static_cast<int>(state_->active_subscriptions.size()); i++) {
1098
+ state_->PullSource().AddCallback(
1099
+ OuterCallback{state_, static_cast<std::size_t>(i)});
1100
+ // If we have to bail early then we need to update the shared state again so
1101
+ // we need to reacquire the lock.
1102
+ auto guard = state_->mutex.Lock();
1103
+ if (state_->source_exhausted) {
1104
+ int excess_requests =
1105
+ static_cast<int>(state_->active_subscriptions.size()) - i - 1;
1106
+ state_->outstanding_requests -= excess_requests;
1107
+ state_->num_running_subscriptions -= excess_requests;
1108
+ if (excess_requests > 0) {
1109
+ // It's possible that we are completing the generator by reducing the number
1110
+ // of outstanding requests (e.g. this happens when the outer subscription and
1111
+ // all inner subscriptions are synchronous)
1112
+ mark_generator_complete = state_->IsCompleteUnlocked(guard);
1113
+ }
1114
+ break;
1115
+ }
1116
+ }
1117
+ if (mark_generator_complete) {
1118
+ state_->MarkFinishedAndPurge();
1119
+ }
1120
+ }
1121
+ return waiting_future;
1122
+ }
1123
+
1124
+ private:
1125
+ struct DeliveredJob {
1126
+ explicit DeliveredJob(AsyncGenerator<T> deliverer_, Result<T> value_,
1127
+ std::size_t index_)
1128
+ : deliverer(deliverer_), value(std::move(value_)), index(index_) {}
1129
+
1130
+ // The generator that delivered this result, we will request another item
1131
+ // from this generator once the result is delivered
1132
+ AsyncGenerator<T> deliverer;
1133
+ // The result we received from the generator
1134
+ Result<T> value;
1135
+ // The index of the generator (in active_subscriptions) that delivered this
1136
+ // result. This is used if we need to replace a finished generator.
1137
+ std::size_t index;
1138
+ };
1139
+
1140
+ struct State {
1141
+ State(AsyncGenerator<AsyncGenerator<T>> source, int max_subscriptions)
1142
+ : source(std::move(source)),
1143
+ active_subscriptions(max_subscriptions),
1144
+ delivered_jobs(),
1145
+ waiting_jobs(),
1146
+ mutex(),
1147
+ first(true),
1148
+ broken(false),
1149
+ source_exhausted(false),
1150
+ outstanding_requests(0),
1151
+ num_running_subscriptions(0),
1152
+ final_error(Status::OK()) {}
1153
+
1154
+ Future<AsyncGenerator<T>> PullSource() {
1155
+ // Need to guard access to source() so we don't pull sync-reentrantly which
1156
+ // is never valid.
1157
+ auto lock = mutex.Lock();
1158
+ return source();
1159
+ }
1160
+
1161
+ void SignalErrorUnlocked(const util::Mutex::Guard& guard) {
1162
+ broken = true;
1163
+ // Empty any results that have arrived but not asked for.
1164
+ while (!delivered_jobs.empty()) {
1165
+ delivered_jobs.pop_front();
1166
+ }
1167
+ }
1168
+
1169
+ // This function is called outside the mutex but it will only ever be
1170
+ // called once
1171
+ void MarkFinishedAndPurge() {
1172
+ all_finished.MarkFinished();
1173
+ while (!waiting_jobs.empty()) {
1174
+ waiting_jobs.front()->MarkFinished(IterationEnd<T>());
1175
+ waiting_jobs.pop_front();
1176
+ }
1177
+ }
1178
+
1179
+ // This is called outside the mutex but it is only ever called
1180
+ // once and Future<>::AddCallback is thread-safe
1181
+ void MarkFinalError(const Status& err, Future<T> maybe_sink) {
1182
+ if (maybe_sink.is_valid()) {
1183
+ // Someone is waiting for this error so lets mark it complete when
1184
+ // all the work is done
1185
+ all_finished.AddCallback([maybe_sink, err](const Status& status) mutable {
1186
+ maybe_sink.MarkFinished(err);
1187
+ });
1188
+ } else {
1189
+ // No one is waiting for this error right now so it will be delivered
1190
+ // next.
1191
+ final_error = err;
1192
+ }
1193
+ }
1194
+
1195
+ bool IsCompleteUnlocked(const util::Mutex::Guard& guard) {
1196
+ return outstanding_requests == 0 &&
1197
+ (broken || (source_exhausted && num_running_subscriptions == 0 &&
1198
+ delivered_jobs.empty()));
1199
+ }
1200
+
1201
+ bool MarkTaskFinishedUnlocked(const util::Mutex::Guard& guard) {
1202
+ --outstanding_requests;
1203
+ return IsCompleteUnlocked(guard);
1204
+ }
1205
+
1206
+ // The outer generator. Each item we pull from this will be its own generator
1207
+ // and become an inner subscription
1208
+ AsyncGenerator<AsyncGenerator<T>> source;
1209
+ // active_subscriptions and delivered_jobs will be bounded by max_subscriptions
1210
+ std::vector<AsyncGenerator<T>> active_subscriptions;
1211
+ // Results delivered by the inner subscriptions that weren't yet asked for by the
1212
+ // caller
1213
+ std::deque<std::shared_ptr<DeliveredJob>> delivered_jobs;
1214
+ // waiting_jobs is unbounded, reentrant pulls (e.g. AddReadahead) will provide the
1215
+ // backpressure
1216
+ std::deque<std::shared_ptr<Future<T>>> waiting_jobs;
1217
+ // A future that will be marked complete when the terminal item has arrived and all
1218
+ // outstanding futures have completed. It is used to hold off emission of an error
1219
+ // until all outstanding work is done.
1220
+ Future<> all_finished = Future<>::Make();
1221
+ util::Mutex mutex;
1222
+ // A flag cleared when the caller firsts asks for a future. Used to start polling.
1223
+ bool first;
1224
+ // A flag set when an error arrives, prevents us from issuing new requests.
1225
+ bool broken;
1226
+ // A flag set when the outer subscription has been exhausted. Prevents us from
1227
+ // pulling it further (even though it would be generally harmless) and lets us know we
1228
+ // are finishing up.
1229
+ bool source_exhausted;
1230
+ // The number of futures that we have requested from either the outer or inner
1231
+ // subscriptions that have not yet completed. We cannot mark all_finished until this
1232
+ // reaches 0. This will never be greater than max_subscriptions
1233
+ int outstanding_requests;
1234
+ // The number of running subscriptions. We ramp this up to `max_subscriptions` as
1235
+ // soon as the first item is requested and then it stays at that level (each exhausted
1236
+ // inner subscription is replaced by a new inner subscription) until the outer
1237
+ // subscription is exhausted at which point this descends to 0 (and source_exhausted)
1238
+ // is then set to true.
1239
+ int num_running_subscriptions;
1240
+ // If an error arrives, and the caller hasn't asked for that item, we store the error
1241
+ // here. It is analagous to delivered_jobs but for errors instead of finished
1242
+ // results.
1243
+ Status final_error;
1244
+ };
1245
+
1246
+ struct InnerCallback {
1247
+ InnerCallback(std::shared_ptr<State> state, std::size_t index, bool recursive = false)
1248
+ : state(std::move(state)), index(index), recursive(recursive) {}
1249
+
1250
+ void operator()(const Result<T>& maybe_next_ref) {
1251
+ // An item has been delivered by one of the inner subscriptions
1252
+ Future<T> next_fut;
1253
+ const Result<T>* maybe_next = &maybe_next_ref;
1254
+
1255
+ // When an item is delivered (and the caller has asked for it) we grab the
1256
+ // next item from the inner subscription. To avoid this behavior leading to an
1257
+ // infinite loop (this can happen if the caller's callback asks for the next item)
1258
+ // we use a while loop.
1259
+ while (true) {
1260
+ Future<T> sink;
1261
+ bool sub_finished = maybe_next->ok() && IsIterationEnd(**maybe_next);
1262
+ bool pull_next_sub = false;
1263
+ bool was_broken = false;
1264
+ bool should_mark_gen_complete = false;
1265
+ bool should_mark_final_error = false;
1266
+ {
1267
+ auto guard = state->mutex.Lock();
1268
+ if (state->broken) {
1269
+ // We've errored out previously so ignore the result. If anyone was waiting
1270
+ // for this they will get IterationEnd when we purge
1271
+ was_broken = true;
1272
+ } else {
1273
+ if (!sub_finished) {
1274
+ // There is a result to deliver. Either we can deliver it now or we will
1275
+ // queue it up
1276
+ if (state->waiting_jobs.empty()) {
1277
+ state->delivered_jobs.push_back(std::make_shared<DeliveredJob>(
1278
+ state->active_subscriptions[index], *maybe_next, index));
1279
+ } else {
1280
+ sink = std::move(*state->waiting_jobs.front());
1281
+ state->waiting_jobs.pop_front();
1282
+ }
1283
+ }
1284
+
1285
+ // If this is the first error then we transition the state to a broken state
1286
+ if (!maybe_next->ok()) {
1287
+ should_mark_final_error = true;
1288
+ state->SignalErrorUnlocked(guard);
1289
+ }
1290
+ }
1291
+
1292
+ // If we finished this inner subscription then we need to grab a new inner
1293
+ // subscription to take its spot. If we can't (because we're broken or
1294
+ // exhausted) then we aren't going to be starting any new futures and so
1295
+ // the number of running subscriptions drops.
1296
+ pull_next_sub = sub_finished && !state->source_exhausted && !was_broken;
1297
+ if (sub_finished && !pull_next_sub) {
1298
+ state->num_running_subscriptions--;
1299
+ }
1300
+ // There are three situations we won't pull again. If an error occurred or we
1301
+ // are already finished or if no one was waiting for our result and so we queued
1302
+ // it up. We will decrement outstanding_requests and possibly mark the
1303
+ // generator completed.
1304
+ if (state->broken || (!sink.is_valid() && !sub_finished) ||
1305
+ (sub_finished && state->source_exhausted)) {
1306
+ if (state->MarkTaskFinishedUnlocked(guard)) {
1307
+ should_mark_gen_complete = true;
1308
+ }
1309
+ }
1310
+ }
1311
+
1312
+ // Now we have given up the lock and we can take all the actions we decided we
1313
+ // need to take.
1314
+ if (should_mark_final_error) {
1315
+ state->MarkFinalError(maybe_next->status(), std::move(sink));
1316
+ }
1317
+
1318
+ if (should_mark_gen_complete) {
1319
+ state->MarkFinishedAndPurge();
1320
+ }
1321
+
1322
+ // An error occurred elsewhere so there is no need to mark any future
1323
+ // finished (will happen during the purge) or pull from anything
1324
+ if (was_broken) {
1325
+ return;
1326
+ }
1327
+
1328
+ if (pull_next_sub) {
1329
+ if (recursive) {
1330
+ was_empty = true;
1331
+ return;
1332
+ }
1333
+ // We pulled an end token so we need to start a new subscription
1334
+ // in our spot
1335
+ state->PullSource().AddCallback(OuterCallback{state, index});
1336
+ } else if (sink.is_valid()) {
1337
+ // We pulled a valid result and there was someone waiting for it
1338
+ // so lets fetch the next result from our subscription
1339
+ sink.MarkFinished(*maybe_next);
1340
+ next_fut = state->active_subscriptions[index]();
1341
+ if (next_fut.TryAddCallback([this]() { return InnerCallback(state, index); })) {
1342
+ return;
1343
+ }
1344
+ // Already completed. Avoid very deep recursion by looping
1345
+ // here instead of relying on the callback.
1346
+ maybe_next = &next_fut.result();
1347
+ continue;
1348
+ }
1349
+ // else: We pulled a valid result but no one was waiting for it so
1350
+ // we can just stop.
1351
+ return;
1352
+ }
1353
+ }
1354
+ std::shared_ptr<State> state;
1355
+ std::size_t index;
1356
+ bool recursive;
1357
+ bool was_empty = false;
1358
+ };
1359
+
1360
+ struct OuterCallback {
1361
+ void operator()(const Result<AsyncGenerator<T>>& initial_maybe_next) {
1362
+ Result<AsyncGenerator<T>> maybe_next = initial_maybe_next;
1363
+ while (true) {
1364
+ // We have been given a new inner subscription
1365
+ bool should_continue = false;
1366
+ bool should_mark_gen_complete = false;
1367
+ bool should_deliver_error = false;
1368
+ bool source_exhausted = maybe_next.ok() && IsIterationEnd(*maybe_next);
1369
+ Future<T> error_sink;
1370
+ {
1371
+ auto guard = state->mutex.Lock();
1372
+ if (!maybe_next.ok() || source_exhausted || state->broken) {
1373
+ // If here then we will not pull any more from the outer source
1374
+ if (!state->broken && !maybe_next.ok()) {
1375
+ state->SignalErrorUnlocked(guard);
1376
+ // If here then we are the first error so we need to deliver it
1377
+ should_deliver_error = true;
1378
+ if (!state->waiting_jobs.empty()) {
1379
+ error_sink = std::move(*state->waiting_jobs.front());
1380
+ state->waiting_jobs.pop_front();
1381
+ }
1382
+ }
1383
+ if (source_exhausted) {
1384
+ state->source_exhausted = true;
1385
+ state->num_running_subscriptions--;
1386
+ }
1387
+ if (state->MarkTaskFinishedUnlocked(guard)) {
1388
+ should_mark_gen_complete = true;
1389
+ }
1390
+ } else {
1391
+ state->active_subscriptions[index] = *maybe_next;
1392
+ should_continue = true;
1393
+ }
1394
+ }
1395
+ if (should_deliver_error) {
1396
+ state->MarkFinalError(maybe_next.status(), std::move(error_sink));
1397
+ }
1398
+ if (should_mark_gen_complete) {
1399
+ state->MarkFinishedAndPurge();
1400
+ }
1401
+ if (should_continue) {
1402
+ // There is a possibility that a large sequence of immediately available inner
1403
+ // callbacks could lead to a stack overflow. To avoid this we need to
1404
+ // synchronously loop through inner/outer callbacks until we either find an
1405
+ // unfinished future or we find an actual item to deliver.
1406
+ Future<T> next_item = (*maybe_next)();
1407
+ if (!next_item.TryAddCallback([this] { return InnerCallback(state, index); })) {
1408
+ // By setting recursive to true we signal to the inner callback that, if it is
1409
+ // empty, instead of adding a new outer callback, it should just immediately
1410
+ // return, flagging was_empty so that we know we need to check the next
1411
+ // subscription.
1412
+ InnerCallback immediate_inner(state, index, /*recursive=*/true);
1413
+ immediate_inner(next_item.result());
1414
+ if (immediate_inner.was_empty) {
1415
+ Future<AsyncGenerator<T>> next_source = state->PullSource();
1416
+ if (next_source.TryAddCallback([this] {
1417
+ return OuterCallback{state, index};
1418
+ })) {
1419
+ // We hit an unfinished future so we can stop looping
1420
+ return;
1421
+ }
1422
+ // The current subscription was immediately and synchronously empty
1423
+ // and we were able to synchronously pull the next subscription so we
1424
+ // can keep looping.
1425
+ maybe_next = next_source.result();
1426
+ continue;
1427
+ }
1428
+ }
1429
+ }
1430
+ return;
1431
+ }
1432
+ }
1433
+ std::shared_ptr<State> state;
1434
+ std::size_t index;
1435
+ };
1436
+
1437
+ std::shared_ptr<State> state_;
1438
+ };
1439
+
1440
+ /// \brief Create a generator that takes in a stream of generators and pulls from up to
1441
+ /// max_subscriptions at a time
1442
+ ///
1443
+ /// Note: This may deliver items out of sequence. For example, items from the third
1444
+ /// AsyncGenerator generated by the source may be emitted before some items from the first
1445
+ /// AsyncGenerator generated by the source.
1446
+ ///
1447
+ /// This generator will pull from source async-reentrantly unless max_subscriptions is 1
1448
+ /// This generator will not pull from the individual subscriptions reentrantly. Add
1449
+ /// readahead to the individual subscriptions if that is desired.
1450
+ /// This generator is async-reentrant
1451
+ ///
1452
+ /// This generator may queue up to max_subscriptions instances of T
1453
+ template <typename T>
1454
+ AsyncGenerator<T> MakeMergedGenerator(AsyncGenerator<AsyncGenerator<T>> source,
1455
+ int max_subscriptions) {
1456
+ return MergedGenerator<T>(std::move(source), max_subscriptions);
1457
+ }
1458
+
1459
+ template <typename T>
1460
+ Result<AsyncGenerator<T>> MakeSequencedMergedGenerator(
1461
+ AsyncGenerator<AsyncGenerator<T>> source, int max_subscriptions) {
1462
+ if (max_subscriptions < 0) {
1463
+ return Status::Invalid("max_subscriptions must be a positive integer");
1464
+ }
1465
+ if (max_subscriptions == 1) {
1466
+ return Status::Invalid("Use MakeConcatenatedGenerator if max_subscriptions is 1");
1467
+ }
1468
+ AsyncGenerator<AsyncGenerator<T>> autostarting_source = MakeMappedGenerator(
1469
+ std::move(source),
1470
+ [](const AsyncGenerator<T>& sub) { return MakeAutoStartingGenerator(sub); });
1471
+ AsyncGenerator<AsyncGenerator<T>> sub_readahead =
1472
+ MakeSerialReadaheadGenerator(std::move(autostarting_source), max_subscriptions - 1);
1473
+ return MakeConcatenatedGenerator(std::move(sub_readahead));
1474
+ }
1475
+
1476
+ /// \brief Create a generator that takes in a stream of generators and pulls from each
1477
+ /// one in sequence.
1478
+ ///
1479
+ /// This generator is async-reentrant but will never pull from source reentrantly and
1480
+ /// will never pull from any subscription reentrantly.
1481
+ ///
1482
+ /// This generator may queue 1 instance of T
1483
+ ///
1484
+ /// TODO: Could potentially make a bespoke implementation instead of MergedGenerator that
1485
+ /// forwards async-reentrant requests instead of buffering them (which is what
1486
+ /// MergedGenerator does)
1487
+ template <typename T>
1488
+ AsyncGenerator<T> MakeConcatenatedGenerator(AsyncGenerator<AsyncGenerator<T>> source) {
1489
+ return MergedGenerator<T>(std::move(source), 1);
1490
+ }
1491
+
1492
+ template <typename T>
1493
+ struct Enumerated {
1494
+ T value;
1495
+ int index;
1496
+ bool last;
1497
+ };
1498
+
1499
+ template <typename T>
1500
+ struct IterationTraits<Enumerated<T>> {
1501
+ static Enumerated<T> End() { return Enumerated<T>{IterationEnd<T>(), -1, false}; }
1502
+ static bool IsEnd(const Enumerated<T>& val) { return val.index < 0; }
1503
+ };
1504
+
1505
+ /// \see MakeEnumeratedGenerator
1506
+ template <typename T>
1507
+ class EnumeratingGenerator {
1508
+ public:
1509
+ EnumeratingGenerator(AsyncGenerator<T> source, T initial_value)
1510
+ : state_(std::make_shared<State>(std::move(source), std::move(initial_value))) {}
1511
+
1512
+ Future<Enumerated<T>> operator()() {
1513
+ if (state_->finished) {
1514
+ return AsyncGeneratorEnd<Enumerated<T>>();
1515
+ } else {
1516
+ auto state = state_;
1517
+ return state->source().Then([state](const T& next) {
1518
+ auto finished = IsIterationEnd<T>(next);
1519
+ auto prev = Enumerated<T>{state->prev_value, state->prev_index, finished};
1520
+ state->prev_value = next;
1521
+ state->prev_index++;
1522
+ state->finished = finished;
1523
+ return prev;
1524
+ });
1525
+ }
1526
+ }
1527
+
1528
+ private:
1529
+ struct State {
1530
+ State(AsyncGenerator<T> source, T initial_value)
1531
+ : source(std::move(source)), prev_value(std::move(initial_value)), prev_index(0) {
1532
+ finished = IsIterationEnd<T>(prev_value);
1533
+ }
1534
+
1535
+ AsyncGenerator<T> source;
1536
+ T prev_value;
1537
+ int prev_index;
1538
+ bool finished;
1539
+ };
1540
+
1541
+ std::shared_ptr<State> state_;
1542
+ };
1543
+
1544
+ /// Wrap items from a source generator with positional information
1545
+ ///
1546
+ /// When used with MakeMergedGenerator and MakeSequencingGenerator this allows items to be
1547
+ /// processed in a "first-available" fashion and later resequenced which can reduce the
1548
+ /// impact of sources with erratic performance (e.g. a filesystem where some items may
1549
+ /// take longer to read than others).
1550
+ ///
1551
+ /// TODO(ARROW-12371) Would require this generator be async-reentrant
1552
+ ///
1553
+ /// \see MakeSequencingGenerator for an example of putting items back in order
1554
+ ///
1555
+ /// This generator is not async-reentrant
1556
+ ///
1557
+ /// This generator buffers one item (so it knows which item is the last item)
1558
+ template <typename T>
1559
+ AsyncGenerator<Enumerated<T>> MakeEnumeratedGenerator(AsyncGenerator<T> source) {
1560
+ return FutureFirstGenerator<Enumerated<T>>(
1561
+ source().Then([source](const T& initial_value) -> AsyncGenerator<Enumerated<T>> {
1562
+ return EnumeratingGenerator<T>(std::move(source), initial_value);
1563
+ }));
1564
+ }
1565
+
1566
+ /// \see MakeTransferredGenerator
1567
+ template <typename T>
1568
+ class TransferringGenerator {
1569
+ public:
1570
+ explicit TransferringGenerator(AsyncGenerator<T> source, internal::Executor* executor)
1571
+ : source_(std::move(source)), executor_(executor) {}
1572
+
1573
+ Future<T> operator()() { return executor_->Transfer(source_()); }
1574
+
1575
+ private:
1576
+ AsyncGenerator<T> source_;
1577
+ internal::Executor* executor_;
1578
+ };
1579
+
1580
+ /// \brief Transfer a future to an underlying executor.
1581
+ ///
1582
+ /// Continuations run on the returned future will be run on the given executor
1583
+ /// if they cannot be run synchronously.
1584
+ ///
1585
+ /// This is often needed to move computation off I/O threads or other external
1586
+ /// completion sources and back on to the CPU executor so the I/O thread can
1587
+ /// stay busy and focused on I/O
1588
+ ///
1589
+ /// Keep in mind that continuations called on an already completed future will
1590
+ /// always be run synchronously and so no transfer will happen in that case.
1591
+ ///
1592
+ /// This generator is async reentrant if the source is
1593
+ ///
1594
+ /// This generator will not queue
1595
+ template <typename T>
1596
+ AsyncGenerator<T> MakeTransferredGenerator(AsyncGenerator<T> source,
1597
+ internal::Executor* executor) {
1598
+ return TransferringGenerator<T>(std::move(source), executor);
1599
+ }
1600
+
1601
+ /// \see MakeBackgroundGenerator
1602
+ template <typename T>
1603
+ class BackgroundGenerator {
1604
+ public:
1605
+ explicit BackgroundGenerator(Iterator<T> it, internal::Executor* io_executor, int max_q,
1606
+ int q_restart)
1607
+ : state_(std::make_shared<State>(io_executor, std::move(it), max_q, q_restart)),
1608
+ cleanup_(std::make_shared<Cleanup>(state_.get())) {}
1609
+
1610
+ Future<T> operator()() {
1611
+ auto guard = state_->mutex.Lock();
1612
+ Future<T> waiting_future;
1613
+ if (state_->queue.empty()) {
1614
+ if (state_->finished) {
1615
+ return AsyncGeneratorEnd<T>();
1616
+ } else {
1617
+ waiting_future = Future<T>::Make();
1618
+ state_->waiting_future = waiting_future;
1619
+ }
1620
+ } else {
1621
+ auto next = Future<T>::MakeFinished(std::move(state_->queue.front()));
1622
+ state_->queue.pop();
1623
+ if (state_->NeedsRestart()) {
1624
+ return state_->RestartTask(state_, std::move(guard), std::move(next));
1625
+ }
1626
+ return next;
1627
+ }
1628
+ // This should only trigger the very first time this method is called
1629
+ if (state_->NeedsRestart()) {
1630
+ return state_->RestartTask(state_, std::move(guard), std::move(waiting_future));
1631
+ }
1632
+ return waiting_future;
1633
+ }
1634
+
1635
+ protected:
1636
+ static constexpr uint64_t kUnlikelyThreadId{std::numeric_limits<uint64_t>::max()};
1637
+
1638
+ struct State {
1639
+ State(internal::Executor* io_executor, Iterator<T> it, int max_q, int q_restart)
1640
+ : io_executor(io_executor),
1641
+ max_q(max_q),
1642
+ q_restart(q_restart),
1643
+ it(std::move(it)),
1644
+ reading(false),
1645
+ finished(false),
1646
+ should_shutdown(false) {}
1647
+
1648
+ void ClearQueue() {
1649
+ while (!queue.empty()) {
1650
+ queue.pop();
1651
+ }
1652
+ }
1653
+
1654
+ bool TaskIsRunning() const { return task_finished.is_valid(); }
1655
+
1656
+ bool NeedsRestart() const {
1657
+ return !finished && !reading && static_cast<int>(queue.size()) <= q_restart;
1658
+ }
1659
+
1660
+ void DoRestartTask(std::shared_ptr<State> state, util::Mutex::Guard guard) {
1661
+ // If we get here we are actually going to start a new task so let's create a
1662
+ // task_finished future for it
1663
+ state->task_finished = Future<>::Make();
1664
+ state->reading = true;
1665
+ auto spawn_status = io_executor->Spawn(
1666
+ [state]() { BackgroundGenerator::WorkerTask(std::move(state)); });
1667
+ if (!spawn_status.ok()) {
1668
+ // If we can't spawn a new task then send an error to the consumer (either via a
1669
+ // waiting future or the queue) and mark ourselves finished
1670
+ state->finished = true;
1671
+ state->task_finished = Future<>();
1672
+ if (waiting_future.has_value()) {
1673
+ auto to_deliver = std::move(waiting_future.value());
1674
+ waiting_future.reset();
1675
+ guard.Unlock();
1676
+ to_deliver.MarkFinished(spawn_status);
1677
+ } else {
1678
+ ClearQueue();
1679
+ queue.push(spawn_status);
1680
+ }
1681
+ }
1682
+ }
1683
+
1684
+ Future<T> RestartTask(std::shared_ptr<State> state, util::Mutex::Guard guard,
1685
+ Future<T> next) {
1686
+ if (TaskIsRunning()) {
1687
+ // If the task is still cleaning up we need to wait for it to finish before
1688
+ // restarting. We also want to block the consumer until we've restarted the
1689
+ // reader to avoid multiple restarts
1690
+ return task_finished.Then([state, next]() {
1691
+ // This may appear dangerous (recursive mutex) but we should be guaranteed the
1692
+ // outer guard has been released by this point. We know...
1693
+ // * task_finished is not already finished (it would be invalid in that case)
1694
+ // * task_finished will not be marked complete until we've given up the mutex
1695
+ auto guard_ = state->mutex.Lock();
1696
+ state->DoRestartTask(state, std::move(guard_));
1697
+ return next;
1698
+ });
1699
+ }
1700
+ // Otherwise we can restart immediately
1701
+ DoRestartTask(std::move(state), std::move(guard));
1702
+ return next;
1703
+ }
1704
+
1705
+ internal::Executor* io_executor;
1706
+ const int max_q;
1707
+ const int q_restart;
1708
+ Iterator<T> it;
1709
+ std::atomic<uint64_t> worker_thread_id{kUnlikelyThreadId};
1710
+
1711
+ // If true, the task is actively pumping items from the queue and does not need a
1712
+ // restart
1713
+ bool reading;
1714
+ // Set to true when a terminal item arrives
1715
+ bool finished;
1716
+ // Signal to the background task to end early because consumers have given up on it
1717
+ bool should_shutdown;
1718
+ // If the queue is empty, the consumer will create a waiting future and wait for it
1719
+ std::queue<Result<T>> queue;
1720
+ std::optional<Future<T>> waiting_future;
1721
+ // Every background task is given a future to complete when it is entirely finished
1722
+ // processing and ready for the next task to start or for State to be destroyed
1723
+ Future<> task_finished;
1724
+ util::Mutex mutex;
1725
+ };
1726
+
1727
+ // Cleanup task that will be run when all consumer references to the generator are lost
1728
+ struct Cleanup {
1729
+ explicit Cleanup(State* state) : state(state) {}
1730
+ ~Cleanup() {
1731
+ /// TODO: Once ARROW-13109 is available then we can be force consumers to spawn and
1732
+ /// there is no need to perform this check.
1733
+ ///
1734
+ /// It's a deadlock if we enter cleanup from
1735
+ /// the worker thread but it can happen if the consumer doesn't transfer away
1736
+ assert(state->worker_thread_id.load() != ::arrow::internal::GetThreadId());
1737
+ Future<> finish_fut;
1738
+ {
1739
+ auto lock = state->mutex.Lock();
1740
+ if (!state->TaskIsRunning()) {
1741
+ return;
1742
+ }
1743
+ // Signal the current task to stop and wait for it to finish
1744
+ state->should_shutdown = true;
1745
+ finish_fut = state->task_finished;
1746
+ }
1747
+ // Using future as a condition variable here
1748
+ Status st = finish_fut.status();
1749
+ ARROW_UNUSED(st);
1750
+ }
1751
+ State* state;
1752
+ };
1753
+
1754
+ static void WorkerTask(std::shared_ptr<State> state) {
1755
+ state->worker_thread_id.store(::arrow::internal::GetThreadId());
1756
+ // We need to capture the state to read while outside the mutex
1757
+ bool reading = true;
1758
+ while (reading) {
1759
+ auto next = state->it.Next();
1760
+ // Need to capture state->waiting_future inside the mutex to mark finished outside
1761
+ Future<T> waiting_future;
1762
+ {
1763
+ auto guard = state->mutex.Lock();
1764
+
1765
+ if (state->should_shutdown) {
1766
+ state->finished = true;
1767
+ break;
1768
+ }
1769
+
1770
+ if (!next.ok() || IsIterationEnd<T>(*next)) {
1771
+ // Terminal item. Mark finished to true, send this last item, and quit
1772
+ state->finished = true;
1773
+ if (!next.ok()) {
1774
+ state->ClearQueue();
1775
+ }
1776
+ }
1777
+ // At this point we are going to send an item. Either we will add it to the
1778
+ // queue or deliver it to a waiting future.
1779
+ if (state->waiting_future.has_value()) {
1780
+ waiting_future = std::move(state->waiting_future.value());
1781
+ state->waiting_future.reset();
1782
+ } else {
1783
+ state->queue.push(std::move(next));
1784
+ // We just filled up the queue so it is time to quit. We may need to notify
1785
+ // a cleanup task so we transition to Quitting
1786
+ if (static_cast<int>(state->queue.size()) >= state->max_q) {
1787
+ state->reading = false;
1788
+ }
1789
+ }
1790
+ reading = state->reading && !state->finished;
1791
+ }
1792
+ // This should happen outside the mutex. Presumably there is a
1793
+ // transferring generator on the other end that will quickly transfer any
1794
+ // callbacks off of this thread so we can continue looping. Still, best not to
1795
+ // rely on that
1796
+ if (waiting_future.is_valid()) {
1797
+ waiting_future.MarkFinished(next);
1798
+ }
1799
+ }
1800
+ // Once we've sent our last item we can notify any waiters that we are done and so
1801
+ // either state can be cleaned up or a new background task can be started
1802
+ Future<> task_finished;
1803
+ {
1804
+ auto guard = state->mutex.Lock();
1805
+ // After we give up the mutex state can be safely deleted. We will no longer
1806
+ // reference it. We can safely transition to idle now.
1807
+ task_finished = state->task_finished;
1808
+ state->task_finished = Future<>();
1809
+ state->worker_thread_id.store(kUnlikelyThreadId);
1810
+ }
1811
+ task_finished.MarkFinished();
1812
+ }
1813
+
1814
+ std::shared_ptr<State> state_;
1815
+ // state_ is held by both the generator and the background thread so it won't be cleaned
1816
+ // up when all consumer references are relinquished. cleanup_ is only held by the
1817
+ // generator so it will be destructed when the last consumer reference is gone. We use
1818
+ // this to cleanup / stop the background generator in case the consuming end stops
1819
+ // listening (e.g. due to a downstream error)
1820
+ std::shared_ptr<Cleanup> cleanup_;
1821
+ };
1822
+
1823
+ constexpr int kDefaultBackgroundMaxQ = 32;
1824
+ constexpr int kDefaultBackgroundQRestart = 16;
1825
+
1826
+ /// \brief Create an AsyncGenerator<T> by iterating over an Iterator<T> on a background
1827
+ /// thread
1828
+ ///
1829
+ /// The parameter max_q and q_restart control queue size and background thread task
1830
+ /// management. If the background task is fast you typically don't want it creating a
1831
+ /// thread task for every item. Instead the background thread will run until it fills
1832
+ /// up a readahead queue.
1833
+ ///
1834
+ /// Once the queue has filled up the background thread task will terminate (allowing other
1835
+ /// I/O tasks to use the thread). Once the queue has been drained enough (specified by
1836
+ /// q_restart) then the background thread task will be restarted. If q_restart is too low
1837
+ /// then you may exhaust the queue waiting for the background thread task to start running
1838
+ /// again. If it is too high then it will be constantly stopping and restarting the
1839
+ /// background queue task
1840
+ ///
1841
+ /// The "background thread" is a logical thread and will run as tasks on the io_executor.
1842
+ /// This thread may stop and start when the queue fills up but there will only be one
1843
+ /// active background thread task at any given time. You MUST transfer away from this
1844
+ /// background generator. Otherwise there could be a race condition if a callback on the
1845
+ /// background thread deletes the last consumer reference to the background generator. You
1846
+ /// can transfer onto the same executor as the background thread, it is only necessary to
1847
+ /// create a new thread task, not to switch executors.
1848
+ ///
1849
+ /// This generator is not async-reentrant
1850
+ ///
1851
+ /// This generator will queue up to max_q blocks
1852
+ template <typename T>
1853
+ static Result<AsyncGenerator<T>> MakeBackgroundGenerator(
1854
+ Iterator<T> iterator, internal::Executor* io_executor,
1855
+ int max_q = kDefaultBackgroundMaxQ, int q_restart = kDefaultBackgroundQRestart) {
1856
+ if (max_q < q_restart) {
1857
+ return Status::Invalid("max_q must be >= q_restart");
1858
+ }
1859
+ return BackgroundGenerator<T>(std::move(iterator), io_executor, max_q, q_restart);
1860
+ }
1861
+
1862
+ /// \brief Create an AsyncGenerator<T> by iterating over an Iterator<T> synchronously
1863
+ ///
1864
+ /// This should only be used if you know the source iterator does not involve any
1865
+ /// I/O (or other blocking calls). Otherwise a CPU thread will be blocked and, depending
1866
+ /// on the complexity of the iterator, it may lead to deadlock.
1867
+ ///
1868
+ /// If you are not certain if there will be I/O then it is better to use
1869
+ /// MakeBackgroundGenerator. If helpful you can think of this as the AsyncGenerator
1870
+ /// equivalent of Future::MakeFinished
1871
+ ///
1872
+ /// It is impossible to call this in an async-reentrant manner since the returned
1873
+ /// future will be completed by the time it is polled.
1874
+ ///
1875
+ /// This generator does not queue
1876
+ template <typename T>
1877
+ static Result<AsyncGenerator<T>> MakeBlockingGenerator(
1878
+ std::shared_ptr<Iterator<T>> iterator) {
1879
+ return [it = std::move(iterator)]() mutable -> Future<T> {
1880
+ return Future<T>::MakeFinished(it->Next());
1881
+ };
1882
+ }
1883
+
1884
+ template <typename T>
1885
+ static Result<AsyncGenerator<T>> MakeBlockingGenerator(Iterator<T> iterator) {
1886
+ return MakeBlockingGenerator(std::make_shared<Iterator<T>>(std::move(iterator)));
1887
+ }
1888
+
1889
+ /// \see MakeGeneratorIterator
1890
+ template <typename T>
1891
+ class GeneratorIterator {
1892
+ public:
1893
+ explicit GeneratorIterator(AsyncGenerator<T> source) : source_(std::move(source)) {}
1894
+
1895
+ Result<T> Next() { return source_().result(); }
1896
+
1897
+ private:
1898
+ AsyncGenerator<T> source_;
1899
+ };
1900
+
1901
+ /// \brief Convert an AsyncGenerator<T> to an Iterator<T> which blocks until each future
1902
+ /// is finished
1903
+ template <typename T>
1904
+ Iterator<T> MakeGeneratorIterator(AsyncGenerator<T> source) {
1905
+ return Iterator<T>(GeneratorIterator<T>(std::move(source)));
1906
+ }
1907
+
1908
+ /// \brief Add readahead to an iterator using a background thread.
1909
+ ///
1910
+ /// Under the hood this is converting the iterator to a generator using
1911
+ /// MakeBackgroundGenerator, adding readahead to the converted generator with
1912
+ /// MakeReadaheadGenerator, and then converting back to an iterator using
1913
+ /// MakeGeneratorIterator.
1914
+ template <typename T>
1915
+ Result<Iterator<T>> MakeReadaheadIterator(Iterator<T> it, int readahead_queue_size) {
1916
+ ARROW_ASSIGN_OR_RAISE(auto io_executor, internal::ThreadPool::Make(1));
1917
+ auto max_q = readahead_queue_size;
1918
+ auto q_restart = std::max(1, max_q / 2);
1919
+ ARROW_ASSIGN_OR_RAISE(
1920
+ auto background_generator,
1921
+ MakeBackgroundGenerator(std::move(it), io_executor.get(), max_q, q_restart));
1922
+ // Capture io_executor to keep it alive as long as owned_bg_generator is still
1923
+ // referenced
1924
+ AsyncGenerator<T> owned_bg_generator = [io_executor, background_generator]() {
1925
+ return background_generator();
1926
+ };
1927
+ return MakeGeneratorIterator(std::move(owned_bg_generator));
1928
+ }
1929
+
1930
+ /// \brief Make a generator that returns a single pre-generated future
1931
+ ///
1932
+ /// This generator is async-reentrant.
1933
+ template <typename T>
1934
+ std::function<Future<T>()> MakeSingleFutureGenerator(Future<T> future) {
1935
+ assert(future.is_valid());
1936
+ auto state = std::make_shared<Future<T>>(std::move(future));
1937
+ return [state]() -> Future<T> {
1938
+ auto fut = std::move(*state);
1939
+ if (fut.is_valid()) {
1940
+ return fut;
1941
+ } else {
1942
+ return AsyncGeneratorEnd<T>();
1943
+ }
1944
+ };
1945
+ }
1946
+
1947
+ /// \brief Make a generator that immediately ends.
1948
+ ///
1949
+ /// This generator is async-reentrant.
1950
+ template <typename T>
1951
+ std::function<Future<T>()> MakeEmptyGenerator() {
1952
+ return []() -> Future<T> { return AsyncGeneratorEnd<T>(); };
1953
+ }
1954
+
1955
+ /// \brief Make a generator that always fails with a given error
1956
+ ///
1957
+ /// This generator is async-reentrant.
1958
+ template <typename T>
1959
+ AsyncGenerator<T> MakeFailingGenerator(Status st) {
1960
+ assert(!st.ok());
1961
+ auto state = std::make_shared<Status>(std::move(st));
1962
+ return [state]() -> Future<T> {
1963
+ auto st = std::move(*state);
1964
+ if (!st.ok()) {
1965
+ return std::move(st);
1966
+ } else {
1967
+ return AsyncGeneratorEnd<T>();
1968
+ }
1969
+ };
1970
+ }
1971
+
1972
+ /// \brief Make a generator that always fails with a given error
1973
+ ///
1974
+ /// This overload allows inferring the return type from the argument.
1975
+ template <typename T>
1976
+ AsyncGenerator<T> MakeFailingGenerator(const Result<T>& result) {
1977
+ return MakeFailingGenerator<T>(result.status());
1978
+ }
1979
+
1980
+ /// \brief Prepend initial_values onto a generator
1981
+ ///
1982
+ /// This generator is async-reentrant but will buffer requests and will not
1983
+ /// pull from following_values async-reentrantly.
1984
+ template <typename T>
1985
+ AsyncGenerator<T> MakeGeneratorStartsWith(std::vector<T> initial_values,
1986
+ AsyncGenerator<T> following_values) {
1987
+ auto initial_values_vec_gen = MakeVectorGenerator(std::move(initial_values));
1988
+ auto gen_gen = MakeVectorGenerator<AsyncGenerator<T>>(
1989
+ {std::move(initial_values_vec_gen), std::move(following_values)});
1990
+ return MakeConcatenatedGenerator(std::move(gen_gen));
1991
+ }
1992
+
1993
+ template <typename T>
1994
+ struct CancellableGenerator {
1995
+ Future<T> operator()() {
1996
+ if (stop_token.IsStopRequested()) {
1997
+ return stop_token.Poll();
1998
+ }
1999
+ return source();
2000
+ }
2001
+
2002
+ AsyncGenerator<T> source;
2003
+ StopToken stop_token;
2004
+ };
2005
+
2006
+ /// \brief Allow an async generator to be cancelled
2007
+ ///
2008
+ /// This generator is async-reentrant
2009
+ template <typename T>
2010
+ AsyncGenerator<T> MakeCancellable(AsyncGenerator<T> source, StopToken stop_token) {
2011
+ return CancellableGenerator<T>{std::move(source), std::move(stop_token)};
2012
+ }
2013
+
2014
+ template <typename T>
2015
+ class DefaultIfEmptyGenerator {
2016
+ public:
2017
+ DefaultIfEmptyGenerator(AsyncGenerator<T> source, T or_value)
2018
+ : state_(std::make_shared<State>(std::move(source), std::move(or_value))) {}
2019
+
2020
+ Future<T> operator()() {
2021
+ if (state_->first) {
2022
+ state_->first = false;
2023
+ struct {
2024
+ T or_value;
2025
+
2026
+ Result<T> operator()(const T& value) {
2027
+ if (IterationTraits<T>::IsEnd(value)) {
2028
+ return std::move(or_value);
2029
+ }
2030
+ return value;
2031
+ }
2032
+ } Continuation;
2033
+ Continuation.or_value = std::move(state_->or_value);
2034
+ return state_->source().Then(std::move(Continuation));
2035
+ }
2036
+ return state_->source();
2037
+ }
2038
+
2039
+ private:
2040
+ struct State {
2041
+ AsyncGenerator<T> source;
2042
+ T or_value;
2043
+ bool first;
2044
+ State(AsyncGenerator<T> source_, T or_value_)
2045
+ : source(std::move(source_)), or_value(std::move(or_value_)), first(true) {}
2046
+ };
2047
+ std::shared_ptr<State> state_;
2048
+ };
2049
+
2050
+ /// \brief If the generator is empty, return the given value, else
2051
+ /// forward the values from the generator.
2052
+ ///
2053
+ /// This generator is async-reentrant.
2054
+ template <typename T>
2055
+ AsyncGenerator<T> MakeDefaultIfEmptyGenerator(AsyncGenerator<T> source, T or_value) {
2056
+ return DefaultIfEmptyGenerator<T>(std::move(source), std::move(or_value));
2057
+ }
2058
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/basic_decimal.h ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <cstdint>
22
+ #include <cstring>
23
+ #include <limits>
24
+ #include <string>
25
+ #include <type_traits>
26
+
27
+ #include "arrow/util/endian.h"
28
+ #include "arrow/util/macros.h"
29
+ #include "arrow/util/type_traits.h"
30
+ #include "arrow/util/visibility.h"
31
+
32
+ namespace arrow {
33
+
34
+ enum class DecimalStatus {
35
+ kSuccess,
36
+ kDivideByZero,
37
+ kOverflow,
38
+ kRescaleDataLoss,
39
+ };
40
+
41
+ template <typename Derived, int BIT_WIDTH, int NWORDS = BIT_WIDTH / 64>
42
+ class ARROW_EXPORT GenericBasicDecimal {
43
+ protected:
44
+ struct LittleEndianArrayTag {};
45
+
46
+ #if ARROW_LITTLE_ENDIAN
47
+ static constexpr int kHighWordIndex = NWORDS - 1;
48
+ static constexpr int kLowWordIndex = 0;
49
+ #else
50
+ static constexpr int kHighWordIndex = 0;
51
+ static constexpr int kLowWordIndex = NWORDS - 1;
52
+ #endif
53
+
54
+ public:
55
+ static constexpr int kBitWidth = BIT_WIDTH;
56
+ static constexpr int kByteWidth = kBitWidth / 8;
57
+ static constexpr int kNumWords = NWORDS;
58
+
59
+ // A constructor tag to introduce a little-endian encoded array
60
+ static constexpr LittleEndianArrayTag LittleEndianArray{};
61
+
62
+ using WordArray = std::array<uint64_t, NWORDS>;
63
+
64
+ /// \brief Empty constructor creates a decimal with a value of 0.
65
+ constexpr GenericBasicDecimal() noexcept : array_({0}) {}
66
+
67
+ /// \brief Create a decimal from the two's complement representation.
68
+ ///
69
+ /// Input array is assumed to be in native endianness.
70
+ explicit constexpr GenericBasicDecimal(const WordArray& array) noexcept
71
+ : array_(array) {}
72
+
73
+ /// \brief Create a decimal from the two's complement representation.
74
+ ///
75
+ /// Input array is assumed to be in little endianness, with native endian elements.
76
+ GenericBasicDecimal(LittleEndianArrayTag, const WordArray& array) noexcept
77
+ : GenericBasicDecimal(bit_util::little_endian::ToNative(array)) {}
78
+
79
+ /// \brief Create a decimal from any integer not wider than 64 bits.
80
+ template <typename T,
81
+ typename = typename std::enable_if<
82
+ std::is_integral<T>::value && (sizeof(T) <= sizeof(uint64_t)), T>::type>
83
+ constexpr GenericBasicDecimal(T value) noexcept // NOLINT(runtime/explicit)
84
+ : array_(WordsFromLowBits(value)) {}
85
+
86
+ /// \brief Create a decimal from an array of bytes.
87
+ ///
88
+ /// Bytes are assumed to be in native-endian byte order.
89
+ explicit GenericBasicDecimal(const uint8_t* bytes) {
90
+ memcpy(array_.data(), bytes, sizeof(array_));
91
+ }
92
+
93
+ /// \brief Get the bits of the two's complement representation of the number.
94
+ ///
95
+ /// The elements are in native endian order. The bits within each uint64_t element
96
+ /// are in native endian order. For example, on a little endian machine,
97
+ /// BasicDecimal128(123).native_endian_array() = {123, 0};
98
+ /// but on a big endian machine,
99
+ /// BasicDecimal128(123).native_endian_array() = {0, 123};
100
+ constexpr const WordArray& native_endian_array() const { return array_; }
101
+
102
+ /// \brief Get the bits of the two's complement representation of the number.
103
+ ///
104
+ /// The elements are in little endian order. However, the bits within each
105
+ /// uint64_t element are in native endian order.
106
+ /// For example, BasicDecimal128(123).little_endian_array() = {123, 0};
107
+ WordArray little_endian_array() const {
108
+ return bit_util::little_endian::FromNative(array_);
109
+ }
110
+
111
+ const uint8_t* native_endian_bytes() const {
112
+ return reinterpret_cast<const uint8_t*>(array_.data());
113
+ }
114
+
115
+ uint8_t* mutable_native_endian_bytes() {
116
+ return reinterpret_cast<uint8_t*>(array_.data());
117
+ }
118
+
119
+ /// \brief Return the raw bytes of the value in native-endian byte order.
120
+ std::array<uint8_t, kByteWidth> ToBytes() const {
121
+ std::array<uint8_t, kByteWidth> out{{0}};
122
+ memcpy(out.data(), array_.data(), kByteWidth);
123
+ return out;
124
+ }
125
+
126
+ /// \brief Copy the raw bytes of the value in native-endian byte order.
127
+ void ToBytes(uint8_t* out) const { memcpy(out, array_.data(), kByteWidth); }
128
+
129
+ /// Return 1 if positive or zero, -1 if strictly negative.
130
+ int64_t Sign() const {
131
+ return 1 | (static_cast<int64_t>(array_[kHighWordIndex]) >> 63);
132
+ }
133
+
134
+ bool IsNegative() const { return static_cast<int64_t>(array_[kHighWordIndex]) < 0; }
135
+
136
+ explicit operator bool() const { return array_ != WordArray{}; }
137
+
138
+ friend bool operator==(const GenericBasicDecimal& left,
139
+ const GenericBasicDecimal& right) {
140
+ return left.array_ == right.array_;
141
+ }
142
+
143
+ friend bool operator!=(const GenericBasicDecimal& left,
144
+ const GenericBasicDecimal& right) {
145
+ return left.array_ != right.array_;
146
+ }
147
+
148
+ protected:
149
+ WordArray array_;
150
+
151
+ template <typename T>
152
+ static constexpr uint64_t SignExtend(T low_bits) noexcept {
153
+ return low_bits >= T{} ? uint64_t{0} : ~uint64_t{0};
154
+ }
155
+
156
+ template <typename T>
157
+ static constexpr WordArray WordsFromLowBits(T low_bits) {
158
+ WordArray words{};
159
+ if (low_bits < T{}) {
160
+ for (auto& word : words) {
161
+ word = ~uint64_t{0};
162
+ }
163
+ }
164
+ words[kLowWordIndex] = static_cast<uint64_t>(low_bits);
165
+ return words;
166
+ }
167
+ };
168
+
169
+ /// Represents a signed 128-bit integer in two's complement.
170
+ ///
171
+ /// This class is also compiled into LLVM IR - so, it should not have cpp references like
172
+ /// streams and boost.
173
+ class ARROW_EXPORT BasicDecimal128 : public GenericBasicDecimal<BasicDecimal128, 128> {
174
+ public:
175
+ static constexpr int kMaxPrecision = 38;
176
+ static constexpr int kMaxScale = 38;
177
+
178
+ using GenericBasicDecimal::GenericBasicDecimal;
179
+
180
+ constexpr BasicDecimal128() noexcept : GenericBasicDecimal() {}
181
+
182
+ /// \brief Create a BasicDecimal128 from the two's complement representation.
183
+ #if ARROW_LITTLE_ENDIAN
184
+ constexpr BasicDecimal128(int64_t high, uint64_t low) noexcept
185
+ : BasicDecimal128(WordArray{low, static_cast<uint64_t>(high)}) {}
186
+ #else
187
+ constexpr BasicDecimal128(int64_t high, uint64_t low) noexcept
188
+ : BasicDecimal128(WordArray{static_cast<uint64_t>(high), low}) {}
189
+ #endif
190
+
191
+ /// \brief Negate the current value (in-place)
192
+ BasicDecimal128& Negate();
193
+
194
+ /// \brief Absolute value (in-place)
195
+ BasicDecimal128& Abs();
196
+
197
+ /// \brief Absolute value
198
+ static BasicDecimal128 Abs(const BasicDecimal128& left);
199
+
200
+ /// \brief Add a number to this one. The result is truncated to 128 bits.
201
+ BasicDecimal128& operator+=(const BasicDecimal128& right);
202
+
203
+ /// \brief Subtract a number from this one. The result is truncated to 128 bits.
204
+ BasicDecimal128& operator-=(const BasicDecimal128& right);
205
+
206
+ /// \brief Multiply this number by another number. The result is truncated to 128 bits.
207
+ BasicDecimal128& operator*=(const BasicDecimal128& right);
208
+
209
+ /// Divide this number by right and return the result.
210
+ ///
211
+ /// This operation is not destructive.
212
+ /// The answer rounds to zero. Signs work like:
213
+ /// 21 / 5 -> 4, 1
214
+ /// -21 / 5 -> -4, -1
215
+ /// 21 / -5 -> -4, 1
216
+ /// -21 / -5 -> 4, -1
217
+ /// \param[in] divisor the number to divide by
218
+ /// \param[out] result the quotient
219
+ /// \param[out] remainder the remainder after the division
220
+ DecimalStatus Divide(const BasicDecimal128& divisor, BasicDecimal128* result,
221
+ BasicDecimal128* remainder) const;
222
+
223
+ /// \brief In-place division.
224
+ BasicDecimal128& operator/=(const BasicDecimal128& right);
225
+
226
+ /// \brief Bitwise "or" between two BasicDecimal128.
227
+ BasicDecimal128& operator|=(const BasicDecimal128& right);
228
+
229
+ /// \brief Bitwise "and" between two BasicDecimal128.
230
+ BasicDecimal128& operator&=(const BasicDecimal128& right);
231
+
232
+ /// \brief Shift left by the given number of bits.
233
+ BasicDecimal128& operator<<=(uint32_t bits);
234
+
235
+ BasicDecimal128 operator<<(uint32_t bits) const {
236
+ auto res = *this;
237
+ res <<= bits;
238
+ return res;
239
+ }
240
+
241
+ /// \brief Shift right by the given number of bits.
242
+ ///
243
+ /// Negative values will sign-extend.
244
+ BasicDecimal128& operator>>=(uint32_t bits);
245
+
246
+ BasicDecimal128 operator>>(uint32_t bits) const {
247
+ auto res = *this;
248
+ res >>= bits;
249
+ return res;
250
+ }
251
+
252
+ /// \brief Get the high bits of the two's complement representation of the number.
253
+ constexpr int64_t high_bits() const {
254
+ #if ARROW_LITTLE_ENDIAN
255
+ return static_cast<int64_t>(array_[1]);
256
+ #else
257
+ return static_cast<int64_t>(array_[0]);
258
+ #endif
259
+ }
260
+
261
+ /// \brief Get the low bits of the two's complement representation of the number.
262
+ constexpr uint64_t low_bits() const {
263
+ #if ARROW_LITTLE_ENDIAN
264
+ return array_[0];
265
+ #else
266
+ return array_[1];
267
+ #endif
268
+ }
269
+
270
+ /// \brief separate the integer and fractional parts for the given scale.
271
+ void GetWholeAndFraction(int32_t scale, BasicDecimal128* whole,
272
+ BasicDecimal128* fraction) const;
273
+
274
+ /// \brief Scale multiplier for given scale value.
275
+ static const BasicDecimal128& GetScaleMultiplier(int32_t scale);
276
+ /// \brief Half-scale multiplier for given scale value.
277
+ static const BasicDecimal128& GetHalfScaleMultiplier(int32_t scale);
278
+
279
+ /// \brief Convert BasicDecimal128 from one scale to another
280
+ DecimalStatus Rescale(int32_t original_scale, int32_t new_scale,
281
+ BasicDecimal128* out) const;
282
+
283
+ /// \brief Scale up.
284
+ BasicDecimal128 IncreaseScaleBy(int32_t increase_by) const;
285
+
286
+ /// \brief Scale down.
287
+ /// - If 'round' is true, the right-most digits are dropped and the result value is
288
+ /// rounded up (+1 for +ve, -1 for -ve) based on the value of the dropped digits
289
+ /// (>= 10^reduce_by / 2).
290
+ /// - If 'round' is false, the right-most digits are simply dropped.
291
+ BasicDecimal128 ReduceScaleBy(int32_t reduce_by, bool round = true) const;
292
+
293
+ /// \brief Whether this number fits in the given precision
294
+ ///
295
+ /// Return true if the number of significant digits is less or equal to `precision`.
296
+ bool FitsInPrecision(int32_t precision) const;
297
+
298
+ /// \brief count the number of leading binary zeroes.
299
+ int32_t CountLeadingBinaryZeros() const;
300
+
301
+ /// \brief Get the maximum valid unscaled decimal value.
302
+ static const BasicDecimal128& GetMaxValue();
303
+
304
+ /// \brief Get the maximum valid unscaled decimal value for the given precision.
305
+ static BasicDecimal128 GetMaxValue(int32_t precision);
306
+
307
+ /// \brief Get the maximum decimal value (is not a valid value).
308
+ static constexpr BasicDecimal128 GetMaxSentinel() {
309
+ return BasicDecimal128(/*high=*/std::numeric_limits<int64_t>::max(),
310
+ /*low=*/std::numeric_limits<uint64_t>::max());
311
+ }
312
+ /// \brief Get the minimum decimal value (is not a valid value).
313
+ static constexpr BasicDecimal128 GetMinSentinel() {
314
+ return BasicDecimal128(/*high=*/std::numeric_limits<int64_t>::min(),
315
+ /*low=*/std::numeric_limits<uint64_t>::min());
316
+ }
317
+ };
318
+
319
+ ARROW_EXPORT bool operator<(const BasicDecimal128& left, const BasicDecimal128& right);
320
+ ARROW_EXPORT bool operator<=(const BasicDecimal128& left, const BasicDecimal128& right);
321
+ ARROW_EXPORT bool operator>(const BasicDecimal128& left, const BasicDecimal128& right);
322
+ ARROW_EXPORT bool operator>=(const BasicDecimal128& left, const BasicDecimal128& right);
323
+
324
+ ARROW_EXPORT BasicDecimal128 operator-(const BasicDecimal128& operand);
325
+ ARROW_EXPORT BasicDecimal128 operator~(const BasicDecimal128& operand);
326
+ ARROW_EXPORT BasicDecimal128 operator+(const BasicDecimal128& left,
327
+ const BasicDecimal128& right);
328
+ ARROW_EXPORT BasicDecimal128 operator-(const BasicDecimal128& left,
329
+ const BasicDecimal128& right);
330
+ ARROW_EXPORT BasicDecimal128 operator*(const BasicDecimal128& left,
331
+ const BasicDecimal128& right);
332
+ ARROW_EXPORT BasicDecimal128 operator/(const BasicDecimal128& left,
333
+ const BasicDecimal128& right);
334
+ ARROW_EXPORT BasicDecimal128 operator%(const BasicDecimal128& left,
335
+ const BasicDecimal128& right);
336
+
337
+ class ARROW_EXPORT BasicDecimal256 : public GenericBasicDecimal<BasicDecimal256, 256> {
338
+ public:
339
+ using GenericBasicDecimal::GenericBasicDecimal;
340
+
341
+ static constexpr int kMaxPrecision = 76;
342
+ static constexpr int kMaxScale = 76;
343
+
344
+ constexpr BasicDecimal256() noexcept : GenericBasicDecimal() {}
345
+
346
+ explicit BasicDecimal256(const BasicDecimal128& value) noexcept
347
+ : BasicDecimal256(bit_util::little_endian::ToNative<uint64_t, 4>(
348
+ {value.low_bits(), static_cast<uint64_t>(value.high_bits()),
349
+ SignExtend(value.high_bits()), SignExtend(value.high_bits())})) {}
350
+
351
+ /// \brief Negate the current value (in-place)
352
+ BasicDecimal256& Negate();
353
+
354
+ /// \brief Absolute value (in-place)
355
+ BasicDecimal256& Abs();
356
+
357
+ /// \brief Absolute value
358
+ static BasicDecimal256 Abs(const BasicDecimal256& left);
359
+
360
+ /// \brief Add a number to this one. The result is truncated to 256 bits.
361
+ BasicDecimal256& operator+=(const BasicDecimal256& right);
362
+
363
+ /// \brief Subtract a number from this one. The result is truncated to 256 bits.
364
+ BasicDecimal256& operator-=(const BasicDecimal256& right);
365
+
366
+ /// \brief Get the lowest bits of the two's complement representation of the number.
367
+ uint64_t low_bits() const { return bit_util::little_endian::Make(array_)[0]; }
368
+
369
+ /// \brief separate the integer and fractional parts for the given scale.
370
+ void GetWholeAndFraction(int32_t scale, BasicDecimal256* whole,
371
+ BasicDecimal256* fraction) const;
372
+
373
+ /// \brief Scale multiplier for given scale value.
374
+ static const BasicDecimal256& GetScaleMultiplier(int32_t scale);
375
+ /// \brief Half-scale multiplier for given scale value.
376
+ static const BasicDecimal256& GetHalfScaleMultiplier(int32_t scale);
377
+
378
+ /// \brief Convert BasicDecimal256 from one scale to another
379
+ DecimalStatus Rescale(int32_t original_scale, int32_t new_scale,
380
+ BasicDecimal256* out) const;
381
+
382
+ /// \brief Scale up.
383
+ BasicDecimal256 IncreaseScaleBy(int32_t increase_by) const;
384
+
385
+ /// \brief Scale down.
386
+ /// - If 'round' is true, the right-most digits are dropped and the result value is
387
+ /// rounded up (+1 for positive, -1 for negative) based on the value of the
388
+ /// dropped digits (>= 10^reduce_by / 2).
389
+ /// - If 'round' is false, the right-most digits are simply dropped.
390
+ BasicDecimal256 ReduceScaleBy(int32_t reduce_by, bool round = true) const;
391
+
392
+ /// \brief Whether this number fits in the given precision
393
+ ///
394
+ /// Return true if the number of significant digits is less or equal to `precision`.
395
+ bool FitsInPrecision(int32_t precision) const;
396
+
397
+ /// \brief Multiply this number by another number. The result is truncated to 256 bits.
398
+ BasicDecimal256& operator*=(const BasicDecimal256& right);
399
+
400
+ /// Divide this number by right and return the result.
401
+ ///
402
+ /// This operation is not destructive.
403
+ /// The answer rounds to zero. Signs work like:
404
+ /// 21 / 5 -> 4, 1
405
+ /// -21 / 5 -> -4, -1
406
+ /// 21 / -5 -> -4, 1
407
+ /// -21 / -5 -> 4, -1
408
+ /// \param[in] divisor the number to divide by
409
+ /// \param[out] result the quotient
410
+ /// \param[out] remainder the remainder after the division
411
+ DecimalStatus Divide(const BasicDecimal256& divisor, BasicDecimal256* result,
412
+ BasicDecimal256* remainder) const;
413
+
414
+ /// \brief Shift left by the given number of bits.
415
+ BasicDecimal256& operator<<=(uint32_t bits);
416
+
417
+ BasicDecimal256 operator<<(uint32_t bits) const {
418
+ auto res = *this;
419
+ res <<= bits;
420
+ return res;
421
+ }
422
+
423
+ /// \brief Shift right by the given number of bits.
424
+ ///
425
+ /// Negative values will sign-extend.
426
+ BasicDecimal256& operator>>=(uint32_t bits);
427
+
428
+ BasicDecimal256 operator>>(uint32_t bits) const {
429
+ auto res = *this;
430
+ res >>= bits;
431
+ return res;
432
+ }
433
+
434
+ /// \brief In-place division.
435
+ BasicDecimal256& operator/=(const BasicDecimal256& right);
436
+
437
+ /// \brief Get the maximum valid unscaled decimal value for the given precision.
438
+ static BasicDecimal256 GetMaxValue(int32_t precision);
439
+
440
+ /// \brief Get the maximum decimal value (is not a valid value).
441
+ static constexpr BasicDecimal256 GetMaxSentinel() {
442
+ #if ARROW_LITTLE_ENDIAN
443
+ return BasicDecimal256({std::numeric_limits<uint64_t>::max(),
444
+ std::numeric_limits<uint64_t>::max(),
445
+ std::numeric_limits<uint64_t>::max(),
446
+ static_cast<uint64_t>(std::numeric_limits<int64_t>::max())});
447
+ #else
448
+ return BasicDecimal256({static_cast<uint64_t>(std::numeric_limits<int64_t>::max()),
449
+ std::numeric_limits<uint64_t>::max(),
450
+ std::numeric_limits<uint64_t>::max(),
451
+ std::numeric_limits<uint64_t>::max()});
452
+ #endif
453
+ }
454
+ /// \brief Get the minimum decimal value (is not a valid value).
455
+ static constexpr BasicDecimal256 GetMinSentinel() {
456
+ #if ARROW_LITTLE_ENDIAN
457
+ return BasicDecimal256(
458
+ {0, 0, 0, static_cast<uint64_t>(std::numeric_limits<int64_t>::min())});
459
+ #else
460
+ return BasicDecimal256(
461
+ {static_cast<uint64_t>(std::numeric_limits<int64_t>::min()), 0, 0, 0});
462
+ #endif
463
+ }
464
+ };
465
+
466
+ ARROW_EXPORT bool operator<(const BasicDecimal256& left, const BasicDecimal256& right);
467
+
468
+ ARROW_EXPORT inline bool operator<=(const BasicDecimal256& left,
469
+ const BasicDecimal256& right) {
470
+ return !operator<(right, left);
471
+ }
472
+
473
+ ARROW_EXPORT inline bool operator>(const BasicDecimal256& left,
474
+ const BasicDecimal256& right) {
475
+ return operator<(right, left);
476
+ }
477
+
478
+ ARROW_EXPORT inline bool operator>=(const BasicDecimal256& left,
479
+ const BasicDecimal256& right) {
480
+ return !operator<(left, right);
481
+ }
482
+
483
+ ARROW_EXPORT BasicDecimal256 operator-(const BasicDecimal256& operand);
484
+ ARROW_EXPORT BasicDecimal256 operator~(const BasicDecimal256& operand);
485
+ ARROW_EXPORT BasicDecimal256 operator+(const BasicDecimal256& left,
486
+ const BasicDecimal256& right);
487
+ ARROW_EXPORT BasicDecimal256 operator*(const BasicDecimal256& left,
488
+ const BasicDecimal256& right);
489
+ ARROW_EXPORT BasicDecimal256 operator/(const BasicDecimal256& left,
490
+ const BasicDecimal256& right);
491
+
492
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/benchmark_util.h ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <algorithm>
19
+ #include <cstdint>
20
+ #include <string>
21
+
22
+ #include "benchmark/benchmark.h"
23
+
24
+ #include "arrow/memory_pool.h"
25
+ #include "arrow/type_fwd.h"
26
+ #include "arrow/util/cpu_info.h"
27
+ #include "arrow/util/logging.h" // IWYU pragma: keep
28
+
29
+ namespace arrow {
30
+
31
+ // Benchmark changed its parameter type between releases from
32
+ // int to int64_t. As it doesn't have version macros, we need
33
+ // to apply C++ template magic.
34
+
35
+ template <typename Func>
36
+ struct BenchmarkArgsType;
37
+
38
+ // Pattern matching that extracts the vector element type of Benchmark::Args()
39
+ template <typename Values>
40
+ struct BenchmarkArgsType<benchmark::internal::Benchmark* (
41
+ benchmark::internal::Benchmark::*)(const std::vector<Values>&)> {
42
+ using type = Values;
43
+ };
44
+
45
+ using ArgsType =
46
+ typename BenchmarkArgsType<decltype(&benchmark::internal::Benchmark::Args)>::type;
47
+
48
+ using internal::CpuInfo;
49
+
50
+ static const CpuInfo* cpu_info = CpuInfo::GetInstance();
51
+
52
+ static const int64_t kL1Size = cpu_info->CacheSize(CpuInfo::CacheLevel::L1);
53
+ static const int64_t kL2Size = cpu_info->CacheSize(CpuInfo::CacheLevel::L2);
54
+ static const int64_t kL3Size = cpu_info->CacheSize(CpuInfo::CacheLevel::L3);
55
+ static const int64_t kCantFitInL3Size = kL3Size * 4;
56
+ static const std::vector<int64_t> kMemorySizes = {kL1Size, kL2Size, kL3Size,
57
+ kCantFitInL3Size};
58
+ // 0 is treated as "no nulls"
59
+ static const std::vector<ArgsType> kInverseNullProportions = {10000, 100, 10, 2, 1, 0};
60
+
61
+ struct GenericItemsArgs {
62
+ // number of items processed per iteration
63
+ const int64_t size;
64
+
65
+ // proportion of nulls in generated arrays
66
+ double null_proportion;
67
+
68
+ explicit GenericItemsArgs(benchmark::State& state)
69
+ : size(state.range(0)), state_(state) {
70
+ if (state.range(1) == 0) {
71
+ this->null_proportion = 0.0;
72
+ } else {
73
+ this->null_proportion = std::min(1., 1. / static_cast<double>(state.range(1)));
74
+ }
75
+ }
76
+
77
+ ~GenericItemsArgs() {
78
+ state_.counters["size"] = static_cast<double>(size);
79
+ state_.counters["null_percent"] = null_proportion * 100;
80
+ state_.SetItemsProcessed(state_.iterations() * size);
81
+ }
82
+
83
+ private:
84
+ benchmark::State& state_;
85
+ };
86
+
87
+ void BenchmarkSetArgsWithSizes(benchmark::internal::Benchmark* bench,
88
+ const std::vector<int64_t>& sizes = kMemorySizes) {
89
+ bench->Unit(benchmark::kMicrosecond);
90
+
91
+ for (const auto size : sizes) {
92
+ for (const auto inverse_null_proportion : kInverseNullProportions) {
93
+ bench->Args({static_cast<ArgsType>(size), inverse_null_proportion});
94
+ }
95
+ }
96
+ }
97
+
98
+ void BenchmarkSetArgs(benchmark::internal::Benchmark* bench) {
99
+ BenchmarkSetArgsWithSizes(bench, kMemorySizes);
100
+ }
101
+
102
+ void RegressionSetArgs(benchmark::internal::Benchmark* bench) {
103
+ // Regression do not need to account for cache hierarchy, thus optimize for
104
+ // the best case.
105
+ BenchmarkSetArgsWithSizes(bench, {kL1Size});
106
+ }
107
+
108
+ // RAII struct to handle some of the boilerplate in regression benchmarks
109
+ struct RegressionArgs {
110
+ // size of memory tested (per iteration) in bytes
111
+ int64_t size;
112
+
113
+ // proportion of nulls in generated arrays
114
+ double null_proportion;
115
+
116
+ // If size_is_bytes is true, then it's a number of bytes, otherwise it's the
117
+ // number of items processed (for reporting)
118
+ explicit RegressionArgs(benchmark::State& state, bool size_is_bytes = true)
119
+ : size(state.range(0)), state_(state), size_is_bytes_(size_is_bytes) {
120
+ if (state.range(1) == 0) {
121
+ this->null_proportion = 0.0;
122
+ } else {
123
+ this->null_proportion = std::min(1., 1. / static_cast<double>(state.range(1)));
124
+ }
125
+ }
126
+
127
+ ~RegressionArgs() {
128
+ state_.counters["size"] = static_cast<double>(size);
129
+ state_.counters["null_percent"] = null_proportion * 100;
130
+ if (size_is_bytes_) {
131
+ state_.SetBytesProcessed(state_.iterations() * size);
132
+ } else {
133
+ state_.SetItemsProcessed(state_.iterations() * size);
134
+ }
135
+ }
136
+
137
+ private:
138
+ benchmark::State& state_;
139
+ bool size_is_bytes_;
140
+ };
141
+
142
+ class MemoryPoolMemoryManager : public benchmark::MemoryManager {
143
+ void Start() override {
144
+ memory_pool = std::make_shared<ProxyMemoryPool>(default_memory_pool());
145
+
146
+ MemoryPool* default_pool = default_memory_pool();
147
+ global_allocations_start = default_pool->num_allocations();
148
+ }
149
+
150
+ // BENCHMARK_DONT_OPTIMIZE is used here to detect Google Benchmark
151
+ // 1.8.0. We can remove this Stop(Result*) when we require Google
152
+ // Benchmark 1.8.0 or later.
153
+ #ifndef BENCHMARK_DONT_OPTIMIZE
154
+ void Stop(Result* result) override { Stop(*result); }
155
+ #endif
156
+
157
+ void Stop(benchmark::MemoryManager::Result& result) override {
158
+ // If num_allocations is still zero, we assume that the memory pool wasn't passed down
159
+ // so we should record them.
160
+ MemoryPool* default_pool = default_memory_pool();
161
+ int64_t new_default_allocations =
162
+ default_pool->num_allocations() - global_allocations_start;
163
+
164
+ // Only record metrics if (1) there were allocations and (2) we
165
+ // recorded at least one.
166
+ if (new_default_allocations > 0 && memory_pool->num_allocations() > 0) {
167
+ if (new_default_allocations > memory_pool->num_allocations()) {
168
+ // If we missed some, let's report that.
169
+ int64_t missed_allocations =
170
+ new_default_allocations - memory_pool->num_allocations();
171
+ ARROW_LOG(WARNING) << "BenchmarkMemoryTracker recorded some allocations "
172
+ << "for a benchmark, but missed " << missed_allocations
173
+ << " allocations.\n";
174
+ }
175
+
176
+ result.max_bytes_used = memory_pool->max_memory();
177
+ result.total_allocated_bytes = memory_pool->total_bytes_allocated();
178
+ result.num_allocs = memory_pool->num_allocations();
179
+ }
180
+ }
181
+
182
+ public:
183
+ std::shared_ptr<::arrow::ProxyMemoryPool> memory_pool;
184
+
185
+ protected:
186
+ int64_t global_allocations_start;
187
+ };
188
+
189
+ /// \brief Track memory pool allocations in benchmarks.
190
+ ///
191
+ /// Instantiate as a global variable to register the hooks into Google Benchmark
192
+ /// to collect memory metrics. Before each benchmark, a new ProxyMemoryPool is
193
+ /// created. It can then be accessed with memory_pool(). Once the benchmark is
194
+ /// complete, the hook will record the maximum memory used, the total bytes
195
+ /// allocated, and the total number of allocations. If no allocations were seen,
196
+ /// (for example, if you forgot to pass down the memory pool), then these metrics
197
+ /// will not be saved.
198
+ ///
199
+ /// Since this is used as one global variable, this will not work if multiple
200
+ /// benchmarks are run concurrently or for multi-threaded benchmarks (ones
201
+ /// that use `->ThreadRange(...)`).
202
+ class BenchmarkMemoryTracker {
203
+ public:
204
+ BenchmarkMemoryTracker() : manager_() { ::benchmark::RegisterMemoryManager(&manager_); }
205
+ ::arrow::MemoryPool* memory_pool() const { return manager_.memory_pool.get(); }
206
+
207
+ protected:
208
+ ::arrow::MemoryPoolMemoryManager manager_;
209
+ };
210
+
211
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_block_counter.h ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <limits>
23
+ #include <memory>
24
+
25
+ #include "arrow/buffer.h"
26
+ #include "arrow/status.h"
27
+ #include "arrow/util/bit_util.h"
28
+ #include "arrow/util/endian.h"
29
+ #include "arrow/util/macros.h"
30
+ #include "arrow/util/ubsan.h"
31
+ #include "arrow/util/visibility.h"
32
+
33
+ namespace arrow {
34
+ namespace internal {
35
+ namespace detail {
36
+
37
+ inline uint64_t LoadWord(const uint8_t* bytes) {
38
+ return bit_util::ToLittleEndian(util::SafeLoadAs<uint64_t>(bytes));
39
+ }
40
+
41
+ inline uint64_t ShiftWord(uint64_t current, uint64_t next, int64_t shift) {
42
+ if (shift == 0) {
43
+ return current;
44
+ }
45
+ return (current >> shift) | (next << (64 - shift));
46
+ }
47
+
48
+ // These templates are here to help with unit tests
49
+
50
+ template <typename T>
51
+ constexpr T BitNot(T x) {
52
+ return ~x;
53
+ }
54
+
55
+ template <>
56
+ constexpr bool BitNot(bool x) {
57
+ return !x;
58
+ }
59
+
60
+ struct BitBlockAnd {
61
+ template <typename T>
62
+ static constexpr T Call(T left, T right) {
63
+ return left & right;
64
+ }
65
+ };
66
+
67
+ struct BitBlockAndNot {
68
+ template <typename T>
69
+ static constexpr T Call(T left, T right) {
70
+ return left & BitNot(right);
71
+ }
72
+ };
73
+
74
+ struct BitBlockOr {
75
+ template <typename T>
76
+ static constexpr T Call(T left, T right) {
77
+ return left | right;
78
+ }
79
+ };
80
+
81
+ struct BitBlockOrNot {
82
+ template <typename T>
83
+ static constexpr T Call(T left, T right) {
84
+ return left | BitNot(right);
85
+ }
86
+ };
87
+
88
+ } // namespace detail
89
+
90
+ /// \brief Return value from bit block counters: the total number of bits and
91
+ /// the number of set bits.
92
+ struct BitBlockCount {
93
+ int16_t length;
94
+ int16_t popcount;
95
+
96
+ bool NoneSet() const { return this->popcount == 0; }
97
+ bool AllSet() const { return this->length == this->popcount; }
98
+ };
99
+
100
+ /// \brief A class that scans through a true/false bitmap to compute popcounts
101
+ /// 64 or 256 bits at a time. This is used to accelerate processing of
102
+ /// mostly-not-null array data.
103
+ class ARROW_EXPORT BitBlockCounter {
104
+ public:
105
+ BitBlockCounter(const uint8_t* bitmap, int64_t start_offset, int64_t length)
106
+ : bitmap_(util::MakeNonNull(bitmap) + start_offset / 8),
107
+ bits_remaining_(length),
108
+ offset_(start_offset % 8) {}
109
+
110
+ /// \brief The bit size of each word run
111
+ static constexpr int64_t kWordBits = 64;
112
+
113
+ /// \brief The bit size of four words run
114
+ static constexpr int64_t kFourWordsBits = kWordBits * 4;
115
+
116
+ /// \brief Return the next run of available bits, usually 256. The returned
117
+ /// pair contains the size of run and the number of true values. The last
118
+ /// block will have a length less than 256 if the bitmap length is not a
119
+ /// multiple of 256, and will return 0-length blocks in subsequent
120
+ /// invocations.
121
+ BitBlockCount NextFourWords() {
122
+ using detail::LoadWord;
123
+ using detail::ShiftWord;
124
+
125
+ if (!bits_remaining_) {
126
+ return {0, 0};
127
+ }
128
+ int64_t total_popcount = 0;
129
+ if (offset_ == 0) {
130
+ if (bits_remaining_ < kFourWordsBits) {
131
+ return GetBlockSlow(kFourWordsBits);
132
+ }
133
+ total_popcount += bit_util::PopCount(LoadWord(bitmap_));
134
+ total_popcount += bit_util::PopCount(LoadWord(bitmap_ + 8));
135
+ total_popcount += bit_util::PopCount(LoadWord(bitmap_ + 16));
136
+ total_popcount += bit_util::PopCount(LoadWord(bitmap_ + 24));
137
+ } else {
138
+ // When the offset is > 0, we need there to be a word beyond the last
139
+ // aligned word in the bitmap for the bit shifting logic.
140
+ if (bits_remaining_ < 5 * kFourWordsBits - offset_) {
141
+ return GetBlockSlow(kFourWordsBits);
142
+ }
143
+ auto current = LoadWord(bitmap_);
144
+ auto next = LoadWord(bitmap_ + 8);
145
+ total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_));
146
+ current = next;
147
+ next = LoadWord(bitmap_ + 16);
148
+ total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_));
149
+ current = next;
150
+ next = LoadWord(bitmap_ + 24);
151
+ total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_));
152
+ current = next;
153
+ next = LoadWord(bitmap_ + 32);
154
+ total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_));
155
+ }
156
+ bitmap_ += bit_util::BytesForBits(kFourWordsBits);
157
+ bits_remaining_ -= kFourWordsBits;
158
+ return {256, static_cast<int16_t>(total_popcount)};
159
+ }
160
+
161
+ /// \brief Return the next run of available bits, usually 64. The returned
162
+ /// pair contains the size of run and the number of true values. The last
163
+ /// block will have a length less than 64 if the bitmap length is not a
164
+ /// multiple of 64, and will return 0-length blocks in subsequent
165
+ /// invocations.
166
+ BitBlockCount NextWord() {
167
+ using detail::LoadWord;
168
+ using detail::ShiftWord;
169
+
170
+ if (!bits_remaining_) {
171
+ return {0, 0};
172
+ }
173
+ int64_t popcount = 0;
174
+ if (offset_ == 0) {
175
+ if (bits_remaining_ < kWordBits) {
176
+ return GetBlockSlow(kWordBits);
177
+ }
178
+ popcount = bit_util::PopCount(LoadWord(bitmap_));
179
+ } else {
180
+ // When the offset is > 0, we need there to be a word beyond the last
181
+ // aligned word in the bitmap for the bit shifting logic.
182
+ if (bits_remaining_ < 2 * kWordBits - offset_) {
183
+ return GetBlockSlow(kWordBits);
184
+ }
185
+ popcount = bit_util::PopCount(
186
+ ShiftWord(LoadWord(bitmap_), LoadWord(bitmap_ + 8), offset_));
187
+ }
188
+ bitmap_ += kWordBits / 8;
189
+ bits_remaining_ -= kWordBits;
190
+ return {64, static_cast<int16_t>(popcount)};
191
+ }
192
+
193
+ private:
194
+ /// \brief Return block with the requested size when doing word-wise
195
+ /// computation is not possible due to inadequate bits remaining.
196
+ BitBlockCount GetBlockSlow(int64_t block_size) noexcept;
197
+
198
+ const uint8_t* bitmap_;
199
+ int64_t bits_remaining_;
200
+ int64_t offset_;
201
+ };
202
+
203
+ /// \brief A tool to iterate through a possibly nonexistent validity bitmap,
204
+ /// to allow us to write one code path for both the with-nulls and no-nulls
205
+ /// cases without giving up a lot of performance.
206
+ class ARROW_EXPORT OptionalBitBlockCounter {
207
+ public:
208
+ // validity_bitmap may be NULLPTR
209
+ OptionalBitBlockCounter(const uint8_t* validity_bitmap, int64_t offset, int64_t length);
210
+
211
+ // validity_bitmap may be null
212
+ OptionalBitBlockCounter(const std::shared_ptr<Buffer>& validity_bitmap, int64_t offset,
213
+ int64_t length);
214
+
215
+ /// Return block count for next word when the bitmap is available otherwise
216
+ /// return a block with length up to INT16_MAX when there is no validity
217
+ /// bitmap (so all the referenced values are not null).
218
+ BitBlockCount NextBlock() {
219
+ static constexpr int64_t kMaxBlockSize = std::numeric_limits<int16_t>::max();
220
+ if (has_bitmap_) {
221
+ BitBlockCount block = counter_.NextWord();
222
+ position_ += block.length;
223
+ return block;
224
+ } else {
225
+ int16_t block_size =
226
+ static_cast<int16_t>(std::min(kMaxBlockSize, length_ - position_));
227
+ position_ += block_size;
228
+ // All values are non-null
229
+ return {block_size, block_size};
230
+ }
231
+ }
232
+
233
+ // Like NextBlock, but returns a word-sized block even when there is no
234
+ // validity bitmap
235
+ BitBlockCount NextWord() {
236
+ static constexpr int64_t kWordSize = 64;
237
+ if (has_bitmap_) {
238
+ BitBlockCount block = counter_.NextWord();
239
+ position_ += block.length;
240
+ return block;
241
+ } else {
242
+ int16_t block_size = static_cast<int16_t>(std::min(kWordSize, length_ - position_));
243
+ position_ += block_size;
244
+ // All values are non-null
245
+ return {block_size, block_size};
246
+ }
247
+ }
248
+
249
+ private:
250
+ const bool has_bitmap_;
251
+ int64_t position_;
252
+ int64_t length_;
253
+ BitBlockCounter counter_;
254
+ };
255
+
256
+ /// \brief A class that computes popcounts on the result of bitwise operations
257
+ /// between two bitmaps, 64 bits at a time. A 64-bit word is loaded from each
258
+ /// bitmap, then the popcount is computed on e.g. the bitwise-and of the two
259
+ /// words.
260
+ class ARROW_EXPORT BinaryBitBlockCounter {
261
+ public:
262
+ BinaryBitBlockCounter(const uint8_t* left_bitmap, int64_t left_offset,
263
+ const uint8_t* right_bitmap, int64_t right_offset, int64_t length)
264
+ : left_bitmap_(util::MakeNonNull(left_bitmap) + left_offset / 8),
265
+ left_offset_(left_offset % 8),
266
+ right_bitmap_(util::MakeNonNull(right_bitmap) + right_offset / 8),
267
+ right_offset_(right_offset % 8),
268
+ bits_remaining_(length) {}
269
+
270
+ /// \brief Return the popcount of the bitwise-and of the next run of
271
+ /// available bits, up to 64. The returned pair contains the size of run and
272
+ /// the number of true values. The last block will have a length less than 64
273
+ /// if the bitmap length is not a multiple of 64, and will return 0-length
274
+ /// blocks in subsequent invocations.
275
+ BitBlockCount NextAndWord() { return NextWord<detail::BitBlockAnd>(); }
276
+
277
+ /// \brief Computes "x & ~y" block for each available run of bits.
278
+ BitBlockCount NextAndNotWord() { return NextWord<detail::BitBlockAndNot>(); }
279
+
280
+ /// \brief Computes "x | y" block for each available run of bits.
281
+ BitBlockCount NextOrWord() { return NextWord<detail::BitBlockOr>(); }
282
+
283
+ /// \brief Computes "x | ~y" block for each available run of bits.
284
+ BitBlockCount NextOrNotWord() { return NextWord<detail::BitBlockOrNot>(); }
285
+
286
+ private:
287
+ template <class Op>
288
+ BitBlockCount NextWord() {
289
+ using detail::LoadWord;
290
+ using detail::ShiftWord;
291
+
292
+ if (!bits_remaining_) {
293
+ return {0, 0};
294
+ }
295
+ // When the offset is > 0, we need there to be a word beyond the last aligned
296
+ // word in the bitmap for the bit shifting logic.
297
+ constexpr int64_t kWordBits = BitBlockCounter::kWordBits;
298
+ const int64_t bits_required_to_use_words =
299
+ std::max(left_offset_ == 0 ? 64 : 64 + (64 - left_offset_),
300
+ right_offset_ == 0 ? 64 : 64 + (64 - right_offset_));
301
+ if (bits_remaining_ < bits_required_to_use_words) {
302
+ const int16_t run_length =
303
+ static_cast<int16_t>(std::min(bits_remaining_, kWordBits));
304
+ int16_t popcount = 0;
305
+ for (int64_t i = 0; i < run_length; ++i) {
306
+ if (Op::Call(bit_util::GetBit(left_bitmap_, left_offset_ + i),
307
+ bit_util::GetBit(right_bitmap_, right_offset_ + i))) {
308
+ ++popcount;
309
+ }
310
+ }
311
+ // This code path should trigger _at most_ 2 times. In the "two times"
312
+ // case, the first time the run length will be a multiple of 8.
313
+ left_bitmap_ += run_length / 8;
314
+ right_bitmap_ += run_length / 8;
315
+ bits_remaining_ -= run_length;
316
+ return {run_length, popcount};
317
+ }
318
+
319
+ int64_t popcount = 0;
320
+ if (left_offset_ == 0 && right_offset_ == 0) {
321
+ popcount =
322
+ bit_util::PopCount(Op::Call(LoadWord(left_bitmap_), LoadWord(right_bitmap_)));
323
+ } else {
324
+ auto left_word =
325
+ ShiftWord(LoadWord(left_bitmap_), LoadWord(left_bitmap_ + 8), left_offset_);
326
+ auto right_word =
327
+ ShiftWord(LoadWord(right_bitmap_), LoadWord(right_bitmap_ + 8), right_offset_);
328
+ popcount = bit_util::PopCount(Op::Call(left_word, right_word));
329
+ }
330
+ left_bitmap_ += kWordBits / 8;
331
+ right_bitmap_ += kWordBits / 8;
332
+ bits_remaining_ -= kWordBits;
333
+ return {64, static_cast<int16_t>(popcount)};
334
+ }
335
+
336
+ const uint8_t* left_bitmap_;
337
+ int64_t left_offset_;
338
+ const uint8_t* right_bitmap_;
339
+ int64_t right_offset_;
340
+ int64_t bits_remaining_;
341
+ };
342
+
343
+ class ARROW_EXPORT OptionalBinaryBitBlockCounter {
344
+ public:
345
+ // Any bitmap may be NULLPTR
346
+ OptionalBinaryBitBlockCounter(const uint8_t* left_bitmap, int64_t left_offset,
347
+ const uint8_t* right_bitmap, int64_t right_offset,
348
+ int64_t length);
349
+
350
+ // Any bitmap may be null
351
+ OptionalBinaryBitBlockCounter(const std::shared_ptr<Buffer>& left_bitmap,
352
+ int64_t left_offset,
353
+ const std::shared_ptr<Buffer>& right_bitmap,
354
+ int64_t right_offset, int64_t length);
355
+
356
+ BitBlockCount NextAndBlock() {
357
+ static constexpr int64_t kMaxBlockSize = std::numeric_limits<int16_t>::max();
358
+ switch (has_bitmap_) {
359
+ case HasBitmap::BOTH: {
360
+ BitBlockCount block = binary_counter_.NextAndWord();
361
+ position_ += block.length;
362
+ return block;
363
+ }
364
+ case HasBitmap::ONE: {
365
+ BitBlockCount block = unary_counter_.NextWord();
366
+ position_ += block.length;
367
+ return block;
368
+ }
369
+ case HasBitmap::NONE:
370
+ default: {
371
+ const int16_t block_size =
372
+ static_cast<int16_t>(std::min(kMaxBlockSize, length_ - position_));
373
+ position_ += block_size;
374
+ // All values are non-null
375
+ return {block_size, block_size};
376
+ }
377
+ }
378
+ }
379
+
380
+ BitBlockCount NextOrNotBlock() {
381
+ static constexpr int64_t kMaxBlockSize = std::numeric_limits<int16_t>::max();
382
+ switch (has_bitmap_) {
383
+ case HasBitmap::BOTH: {
384
+ BitBlockCount block = binary_counter_.NextOrNotWord();
385
+ position_ += block.length;
386
+ return block;
387
+ }
388
+ case HasBitmap::ONE: {
389
+ BitBlockCount block = unary_counter_.NextWord();
390
+ position_ += block.length;
391
+ return block;
392
+ }
393
+ case HasBitmap::NONE:
394
+ default: {
395
+ const int16_t block_size =
396
+ static_cast<int16_t>(std::min(kMaxBlockSize, length_ - position_));
397
+ position_ += block_size;
398
+ // All values are non-null
399
+ return {block_size, block_size};
400
+ }
401
+ }
402
+ }
403
+
404
+ private:
405
+ enum class HasBitmap : int { BOTH, ONE, NONE };
406
+
407
+ const HasBitmap has_bitmap_;
408
+ int64_t position_;
409
+ int64_t length_;
410
+ BitBlockCounter unary_counter_;
411
+ BinaryBitBlockCounter binary_counter_;
412
+
413
+ static HasBitmap HasBitmapFromBitmaps(bool has_left, bool has_right) {
414
+ switch (static_cast<int>(has_left) + static_cast<int>(has_right)) {
415
+ case 0:
416
+ return HasBitmap::NONE;
417
+ case 1:
418
+ return HasBitmap::ONE;
419
+ default: // 2
420
+ return HasBitmap::BOTH;
421
+ }
422
+ }
423
+ };
424
+
425
+ // Functional-style bit block visitors.
426
+
427
+ template <typename VisitNotNull, typename VisitNull>
428
+ static Status VisitBitBlocks(const uint8_t* bitmap, int64_t offset, int64_t length,
429
+ VisitNotNull&& visit_not_null, VisitNull&& visit_null) {
430
+ internal::OptionalBitBlockCounter bit_counter(bitmap, offset, length);
431
+ int64_t position = 0;
432
+ while (position < length) {
433
+ internal::BitBlockCount block = bit_counter.NextBlock();
434
+ if (block.AllSet()) {
435
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
436
+ ARROW_RETURN_NOT_OK(visit_not_null(position));
437
+ }
438
+ } else if (block.NoneSet()) {
439
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
440
+ ARROW_RETURN_NOT_OK(visit_null());
441
+ }
442
+ } else {
443
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
444
+ if (bit_util::GetBit(bitmap, offset + position)) {
445
+ ARROW_RETURN_NOT_OK(visit_not_null(position));
446
+ } else {
447
+ ARROW_RETURN_NOT_OK(visit_null());
448
+ }
449
+ }
450
+ }
451
+ }
452
+ return Status::OK();
453
+ }
454
+
455
+ template <typename VisitNotNull, typename VisitNull>
456
+ static void VisitBitBlocksVoid(const uint8_t* bitmap, int64_t offset, int64_t length,
457
+ VisitNotNull&& visit_not_null, VisitNull&& visit_null) {
458
+ internal::OptionalBitBlockCounter bit_counter(bitmap, offset, length);
459
+ int64_t position = 0;
460
+ while (position < length) {
461
+ internal::BitBlockCount block = bit_counter.NextBlock();
462
+ if (block.AllSet()) {
463
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
464
+ visit_not_null(position);
465
+ }
466
+ } else if (block.NoneSet()) {
467
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
468
+ visit_null();
469
+ }
470
+ } else {
471
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
472
+ if (bit_util::GetBit(bitmap, offset + position)) {
473
+ visit_not_null(position);
474
+ } else {
475
+ visit_null();
476
+ }
477
+ }
478
+ }
479
+ }
480
+ }
481
+
482
+ template <typename VisitNotNull, typename VisitNull>
483
+ static Status VisitTwoBitBlocks(const uint8_t* left_bitmap, int64_t left_offset,
484
+ const uint8_t* right_bitmap, int64_t right_offset,
485
+ int64_t length, VisitNotNull&& visit_not_null,
486
+ VisitNull&& visit_null) {
487
+ if (left_bitmap == NULLPTR || right_bitmap == NULLPTR) {
488
+ // At most one bitmap is present
489
+ if (left_bitmap == NULLPTR) {
490
+ return VisitBitBlocks(right_bitmap, right_offset, length,
491
+ std::forward<VisitNotNull>(visit_not_null),
492
+ std::forward<VisitNull>(visit_null));
493
+ } else {
494
+ return VisitBitBlocks(left_bitmap, left_offset, length,
495
+ std::forward<VisitNotNull>(visit_not_null),
496
+ std::forward<VisitNull>(visit_null));
497
+ }
498
+ }
499
+ BinaryBitBlockCounter bit_counter(left_bitmap, left_offset, right_bitmap, right_offset,
500
+ length);
501
+ int64_t position = 0;
502
+ while (position < length) {
503
+ BitBlockCount block = bit_counter.NextAndWord();
504
+ if (block.AllSet()) {
505
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
506
+ ARROW_RETURN_NOT_OK(visit_not_null(position));
507
+ }
508
+ } else if (block.NoneSet()) {
509
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
510
+ ARROW_RETURN_NOT_OK(visit_null());
511
+ }
512
+ } else {
513
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
514
+ if (bit_util::GetBit(left_bitmap, left_offset + position) &&
515
+ bit_util::GetBit(right_bitmap, right_offset + position)) {
516
+ ARROW_RETURN_NOT_OK(visit_not_null(position));
517
+ } else {
518
+ ARROW_RETURN_NOT_OK(visit_null());
519
+ }
520
+ }
521
+ }
522
+ }
523
+ return Status::OK();
524
+ }
525
+
526
+ template <typename VisitNotNull, typename VisitNull>
527
+ static void VisitTwoBitBlocksVoid(const uint8_t* left_bitmap, int64_t left_offset,
528
+ const uint8_t* right_bitmap, int64_t right_offset,
529
+ int64_t length, VisitNotNull&& visit_not_null,
530
+ VisitNull&& visit_null) {
531
+ if (left_bitmap == NULLPTR || right_bitmap == NULLPTR) {
532
+ // At most one bitmap is present
533
+ if (left_bitmap == NULLPTR) {
534
+ return VisitBitBlocksVoid(right_bitmap, right_offset, length,
535
+ std::forward<VisitNotNull>(visit_not_null),
536
+ std::forward<VisitNull>(visit_null));
537
+ } else {
538
+ return VisitBitBlocksVoid(left_bitmap, left_offset, length,
539
+ std::forward<VisitNotNull>(visit_not_null),
540
+ std::forward<VisitNull>(visit_null));
541
+ }
542
+ }
543
+ BinaryBitBlockCounter bit_counter(left_bitmap, left_offset, right_bitmap, right_offset,
544
+ length);
545
+ int64_t position = 0;
546
+ while (position < length) {
547
+ BitBlockCount block = bit_counter.NextAndWord();
548
+ if (block.AllSet()) {
549
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
550
+ visit_not_null(position);
551
+ }
552
+ } else if (block.NoneSet()) {
553
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
554
+ visit_null();
555
+ }
556
+ } else {
557
+ for (int64_t i = 0; i < block.length; ++i, ++position) {
558
+ if (bit_util::GetBit(left_bitmap, left_offset + position) &&
559
+ bit_util::GetBit(right_bitmap, right_offset + position)) {
560
+ visit_not_null(position);
561
+ } else {
562
+ visit_null();
563
+ }
564
+ }
565
+ }
566
+ }
567
+ }
568
+
569
+ } // namespace internal
570
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_util.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
+ #if defined(_MSC_VER)
21
+ #if defined(_M_AMD64) || defined(_M_X64)
22
+ #include <intrin.h> // IWYU pragma: keep
23
+ #include <nmmintrin.h>
24
+ #endif
25
+
26
+ #pragma intrinsic(_BitScanReverse)
27
+ #pragma intrinsic(_BitScanForward)
28
+ #define ARROW_POPCOUNT64 __popcnt64
29
+ #define ARROW_POPCOUNT32 __popcnt
30
+ #else
31
+ #define ARROW_POPCOUNT64 __builtin_popcountll
32
+ #define ARROW_POPCOUNT32 __builtin_popcount
33
+ #endif
34
+
35
+ #include <cstdint>
36
+ #include <type_traits>
37
+
38
+ #include "arrow/util/macros.h"
39
+ #include "arrow/util/visibility.h"
40
+
41
+ namespace arrow {
42
+ namespace detail {
43
+
44
+ template <typename Integer>
45
+ typename std::make_unsigned<Integer>::type as_unsigned(Integer x) {
46
+ return static_cast<typename std::make_unsigned<Integer>::type>(x);
47
+ }
48
+
49
+ } // namespace detail
50
+
51
+ namespace bit_util {
52
+
53
+ // The number of set bits in a given unsigned byte value, pre-computed
54
+ //
55
+ // Generated with the following Python code
56
+ // output = 'static constexpr uint8_t kBytePopcount[] = {{{0}}};'
57
+ // popcounts = [str(bin(i).count('1')) for i in range(0, 256)]
58
+ // print(output.format(', '.join(popcounts)))
59
+ static constexpr uint8_t kBytePopcount[] = {
60
+ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3,
61
+ 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4,
62
+ 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4,
63
+ 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5,
64
+ 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2,
65
+ 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5,
66
+ 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4,
67
+ 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6,
68
+ 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
69
+
70
+ static inline uint64_t PopCount(uint64_t bitmap) { return ARROW_POPCOUNT64(bitmap); }
71
+ static inline uint32_t PopCount(uint32_t bitmap) { return ARROW_POPCOUNT32(bitmap); }
72
+
73
+ //
74
+ // Bit-related computations on integer values
75
+ //
76
+
77
+ // Returns the ceil of value/divisor
78
+ constexpr int64_t CeilDiv(int64_t value, int64_t divisor) {
79
+ return (value == 0) ? 0 : 1 + (value - 1) / divisor;
80
+ }
81
+
82
+ // Return the number of bytes needed to fit the given number of bits
83
+ constexpr int64_t BytesForBits(int64_t bits) {
84
+ // This formula avoids integer overflow on very large `bits`
85
+ return (bits >> 3) + ((bits & 7) != 0);
86
+ }
87
+
88
+ constexpr bool IsPowerOf2(int64_t value) {
89
+ return value > 0 && (value & (value - 1)) == 0;
90
+ }
91
+
92
+ constexpr bool IsPowerOf2(uint64_t value) {
93
+ return value > 0 && (value & (value - 1)) == 0;
94
+ }
95
+
96
+ // Returns the smallest power of two that contains v. If v is already a
97
+ // power of two, it is returned as is.
98
+ static inline int64_t NextPower2(int64_t n) {
99
+ // Taken from
100
+ // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
101
+ n--;
102
+ n |= n >> 1;
103
+ n |= n >> 2;
104
+ n |= n >> 4;
105
+ n |= n >> 8;
106
+ n |= n >> 16;
107
+ n |= n >> 32;
108
+ n++;
109
+ return n;
110
+ }
111
+
112
+ constexpr bool IsMultipleOf64(int64_t n) { return (n & 63) == 0; }
113
+
114
+ constexpr bool IsMultipleOf8(int64_t n) { return (n & 7) == 0; }
115
+
116
+ // Returns a mask for the bit_index lower order bits.
117
+ // Only valid for bit_index in the range [0, 64).
118
+ constexpr uint64_t LeastSignificantBitMask(int64_t bit_index) {
119
+ return (static_cast<uint64_t>(1) << bit_index) - 1;
120
+ }
121
+
122
+ // Returns 'value' rounded up to the nearest multiple of 'factor'
123
+ constexpr int64_t RoundUp(int64_t value, int64_t factor) {
124
+ return CeilDiv(value, factor) * factor;
125
+ }
126
+
127
+ // Returns 'value' rounded down to the nearest multiple of 'factor'
128
+ constexpr int64_t RoundDown(int64_t value, int64_t factor) {
129
+ return (value / factor) * factor;
130
+ }
131
+
132
+ // Returns 'value' rounded up to the nearest multiple of 'factor' when factor
133
+ // is a power of two.
134
+ // The result is undefined on overflow, i.e. if `value > 2**64 - factor`,
135
+ // since we cannot return the correct result which would be 2**64.
136
+ constexpr int64_t RoundUpToPowerOf2(int64_t value, int64_t factor) {
137
+ // DCHECK(value >= 0);
138
+ // DCHECK(IsPowerOf2(factor));
139
+ return (value + (factor - 1)) & ~(factor - 1);
140
+ }
141
+
142
+ constexpr uint64_t RoundUpToPowerOf2(uint64_t value, uint64_t factor) {
143
+ // DCHECK(IsPowerOf2(factor));
144
+ return (value + (factor - 1)) & ~(factor - 1);
145
+ }
146
+
147
+ constexpr int64_t RoundUpToMultipleOf8(int64_t num) { return RoundUpToPowerOf2(num, 8); }
148
+
149
+ constexpr int64_t RoundUpToMultipleOf64(int64_t num) {
150
+ return RoundUpToPowerOf2(num, 64);
151
+ }
152
+
153
+ // Returns the number of bytes covering a sliced bitmap. Find the length
154
+ // rounded to cover full bytes on both extremities.
155
+ //
156
+ // The following example represents a slice (offset=10, length=9)
157
+ //
158
+ // 0 8 16 24
159
+ // |-------|-------|------|
160
+ // [ ] (slice)
161
+ // [ ] (same slice aligned to bytes bounds, length=16)
162
+ //
163
+ // The covering bytes is the length (in bytes) of this new aligned slice.
164
+ constexpr int64_t CoveringBytes(int64_t offset, int64_t length) {
165
+ return (bit_util::RoundUp(length + offset, 8) - bit_util::RoundDown(offset, 8)) / 8;
166
+ }
167
+
168
+ // Returns the 'num_bits' least-significant bits of 'v'.
169
+ static inline uint64_t TrailingBits(uint64_t v, int num_bits) {
170
+ if (ARROW_PREDICT_FALSE(num_bits == 0)) return 0;
171
+ if (ARROW_PREDICT_FALSE(num_bits >= 64)) return v;
172
+ int n = 64 - num_bits;
173
+ return (v << n) >> n;
174
+ }
175
+
176
+ /// \brief Count the number of leading zeros in an unsigned integer.
177
+ static inline int CountLeadingZeros(uint32_t value) {
178
+ #if defined(__clang__) || defined(__GNUC__)
179
+ if (value == 0) return 32;
180
+ return static_cast<int>(__builtin_clz(value));
181
+ #elif defined(_MSC_VER)
182
+ unsigned long index; // NOLINT
183
+ if (_BitScanReverse(&index, static_cast<unsigned long>(value))) { // NOLINT
184
+ return 31 - static_cast<int>(index);
185
+ } else {
186
+ return 32;
187
+ }
188
+ #else
189
+ int bitpos = 0;
190
+ while (value != 0) {
191
+ value >>= 1;
192
+ ++bitpos;
193
+ }
194
+ return 32 - bitpos;
195
+ #endif
196
+ }
197
+
198
+ static inline int CountLeadingZeros(uint64_t value) {
199
+ #if defined(__clang__) || defined(__GNUC__)
200
+ if (value == 0) return 64;
201
+ return static_cast<int>(__builtin_clzll(value));
202
+ #elif defined(_MSC_VER)
203
+ unsigned long index; // NOLINT
204
+ if (_BitScanReverse64(&index, value)) { // NOLINT
205
+ return 63 - static_cast<int>(index);
206
+ } else {
207
+ return 64;
208
+ }
209
+ #else
210
+ int bitpos = 0;
211
+ while (value != 0) {
212
+ value >>= 1;
213
+ ++bitpos;
214
+ }
215
+ return 64 - bitpos;
216
+ #endif
217
+ }
218
+
219
+ static inline int CountTrailingZeros(uint32_t value) {
220
+ #if defined(__clang__) || defined(__GNUC__)
221
+ if (value == 0) return 32;
222
+ return static_cast<int>(__builtin_ctzl(value));
223
+ #elif defined(_MSC_VER)
224
+ unsigned long index; // NOLINT
225
+ if (_BitScanForward(&index, value)) {
226
+ return static_cast<int>(index);
227
+ } else {
228
+ return 32;
229
+ }
230
+ #else
231
+ int bitpos = 0;
232
+ if (value) {
233
+ while (value & 1 == 0) {
234
+ value >>= 1;
235
+ ++bitpos;
236
+ }
237
+ } else {
238
+ bitpos = 32;
239
+ }
240
+ return bitpos;
241
+ #endif
242
+ }
243
+
244
+ static inline int CountTrailingZeros(uint64_t value) {
245
+ #if defined(__clang__) || defined(__GNUC__)
246
+ if (value == 0) return 64;
247
+ return static_cast<int>(__builtin_ctzll(value));
248
+ #elif defined(_MSC_VER)
249
+ unsigned long index; // NOLINT
250
+ if (_BitScanForward64(&index, value)) {
251
+ return static_cast<int>(index);
252
+ } else {
253
+ return 64;
254
+ }
255
+ #else
256
+ int bitpos = 0;
257
+ if (value) {
258
+ while (value & 1 == 0) {
259
+ value >>= 1;
260
+ ++bitpos;
261
+ }
262
+ } else {
263
+ bitpos = 64;
264
+ }
265
+ return bitpos;
266
+ #endif
267
+ }
268
+
269
+ // Returns the minimum number of bits needed to represent an unsigned value
270
+ static inline int NumRequiredBits(uint64_t x) { return 64 - CountLeadingZeros(x); }
271
+
272
+ // Returns ceil(log2(x)).
273
+ static inline int Log2(uint64_t x) {
274
+ // DCHECK_GT(x, 0);
275
+ return NumRequiredBits(x - 1);
276
+ }
277
+
278
+ //
279
+ // Utilities for reading and writing individual bits by their index
280
+ // in a memory area.
281
+ //
282
+
283
+ // Bitmask selecting the k-th bit in a byte
284
+ static constexpr uint8_t kBitmask[] = {1, 2, 4, 8, 16, 32, 64, 128};
285
+
286
+ // the bitwise complement version of kBitmask
287
+ static constexpr uint8_t kFlippedBitmask[] = {254, 253, 251, 247, 239, 223, 191, 127};
288
+
289
+ // Bitmask selecting the (k - 1) preceding bits in a byte
290
+ static constexpr uint8_t kPrecedingBitmask[] = {0, 1, 3, 7, 15, 31, 63, 127};
291
+ static constexpr uint8_t kPrecedingWrappingBitmask[] = {255, 1, 3, 7, 15, 31, 63, 127};
292
+
293
+ // the bitwise complement version of kPrecedingBitmask
294
+ static constexpr uint8_t kTrailingBitmask[] = {255, 254, 252, 248, 240, 224, 192, 128};
295
+
296
+ static constexpr bool GetBit(const uint8_t* bits, uint64_t i) {
297
+ return (bits[i >> 3] >> (i & 0x07)) & 1;
298
+ }
299
+
300
+ // Gets the i-th bit from a byte. Should only be used with i <= 7.
301
+ static constexpr bool GetBitFromByte(uint8_t byte, uint8_t i) {
302
+ return byte & kBitmask[i];
303
+ }
304
+
305
+ static inline void ClearBit(uint8_t* bits, int64_t i) {
306
+ bits[i / 8] &= kFlippedBitmask[i % 8];
307
+ }
308
+
309
+ static inline void SetBit(uint8_t* bits, int64_t i) { bits[i / 8] |= kBitmask[i % 8]; }
310
+
311
+ static inline void SetBitTo(uint8_t* bits, int64_t i, bool bit_is_set) {
312
+ // https://graphics.stanford.edu/~seander/bithacks.html
313
+ // "Conditionally set or clear bits without branching"
314
+ // NOTE: this seems to confuse Valgrind as it reads from potentially
315
+ // uninitialized memory
316
+ bits[i / 8] ^= static_cast<uint8_t>(-static_cast<uint8_t>(bit_is_set) ^ bits[i / 8]) &
317
+ kBitmask[i % 8];
318
+ }
319
+
320
+ /// \brief set or clear a range of bits quickly
321
+ ARROW_EXPORT
322
+ void SetBitsTo(uint8_t* bits, int64_t start_offset, int64_t length, bool bits_are_set);
323
+
324
+ /// \brief Sets all bits in the bitmap to true
325
+ ARROW_EXPORT
326
+ void SetBitmap(uint8_t* data, int64_t offset, int64_t length);
327
+
328
+ /// \brief Clears all bits in the bitmap (set to false)
329
+ ARROW_EXPORT
330
+ void ClearBitmap(uint8_t* data, int64_t offset, int64_t length);
331
+
332
+ /// Returns a mask with lower i bits set to 1. If i >= sizeof(Word)*8, all-ones will be
333
+ /// returned
334
+ /// ex:
335
+ /// ref: https://stackoverflow.com/a/59523400
336
+ template <typename Word>
337
+ constexpr Word PrecedingWordBitmask(unsigned int const i) {
338
+ return static_cast<Word>(static_cast<Word>(i < sizeof(Word) * 8)
339
+ << (i & (sizeof(Word) * 8 - 1))) -
340
+ 1;
341
+ }
342
+ static_assert(PrecedingWordBitmask<uint8_t>(0) == 0x00, "");
343
+ static_assert(PrecedingWordBitmask<uint8_t>(4) == 0x0f, "");
344
+ static_assert(PrecedingWordBitmask<uint8_t>(8) == 0xff, "");
345
+ static_assert(PrecedingWordBitmask<uint16_t>(8) == 0x00ff, "");
346
+
347
+ /// \brief Create a word with low `n` bits from `low` and high `sizeof(Word)-n` bits
348
+ /// from `high`.
349
+ /// Word ret
350
+ /// for (i = 0; i < sizeof(Word)*8; i++){
351
+ /// ret[i]= i < n ? low[i]: high[i];
352
+ /// }
353
+ template <typename Word>
354
+ constexpr Word SpliceWord(int n, Word low, Word high) {
355
+ return (high & ~PrecedingWordBitmask<Word>(n)) | (low & PrecedingWordBitmask<Word>(n));
356
+ }
357
+
358
+ /// \brief Pack integers into a bitmap in batches of 8
359
+ template <int batch_size>
360
+ void PackBits(const uint32_t* values, uint8_t* out) {
361
+ for (int i = 0; i < batch_size / 8; ++i) {
362
+ *out++ = static_cast<uint8_t>(values[0] | values[1] << 1 | values[2] << 2 |
363
+ values[3] << 3 | values[4] << 4 | values[5] << 5 |
364
+ values[6] << 6 | values[7] << 7);
365
+ values += 8;
366
+ }
367
+ }
368
+
369
+ } // namespace bit_util
370
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap.h ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <array>
22
+ #include <bitset>
23
+ #include <cassert>
24
+ #include <cstdint>
25
+ #include <cstring>
26
+ #include <memory>
27
+ #include <string>
28
+ #include <string_view>
29
+ #include <utility>
30
+
31
+ #include "arrow/buffer.h"
32
+ #include "arrow/util/bit_util.h"
33
+ #include "arrow/util/bitmap_ops.h"
34
+ #include "arrow/util/bitmap_reader.h"
35
+ #include "arrow/util/bitmap_writer.h"
36
+ #include "arrow/util/compare.h"
37
+ #include "arrow/util/endian.h"
38
+ #include "arrow/util/functional.h"
39
+ #include "arrow/util/span.h"
40
+ #include "arrow/util/string_builder.h"
41
+ #include "arrow/util/visibility.h"
42
+
43
+ namespace arrow {
44
+
45
+ class BooleanArray;
46
+
47
+ namespace internal {
48
+
49
+ class ARROW_EXPORT Bitmap : public util::ToStringOstreamable<Bitmap>,
50
+ public util::EqualityComparable<Bitmap> {
51
+ public:
52
+ Bitmap() = default;
53
+
54
+ Bitmap(const std::shared_ptr<Buffer>& buffer, int64_t offset, int64_t length)
55
+ : data_(buffer->data()), offset_(offset), length_(length) {
56
+ if (buffer->is_mutable()) {
57
+ mutable_data_ = buffer->mutable_data();
58
+ }
59
+ }
60
+
61
+ Bitmap(const void* data, int64_t offset, int64_t length)
62
+ : data_(reinterpret_cast<const uint8_t*>(data)), offset_(offset), length_(length) {}
63
+
64
+ Bitmap(void* data, int64_t offset, int64_t length)
65
+ : data_(reinterpret_cast<const uint8_t*>(data)),
66
+ mutable_data_(reinterpret_cast<uint8_t*>(data)),
67
+ offset_(offset),
68
+ length_(length) {}
69
+
70
+ Bitmap Slice(int64_t offset) const {
71
+ if (mutable_data_ != NULLPTR) {
72
+ return {mutable_data_, offset_ + offset, length_ - offset};
73
+ } else {
74
+ return {data_, offset_ + offset, length_ - offset};
75
+ }
76
+ }
77
+
78
+ Bitmap Slice(int64_t offset, int64_t length) const {
79
+ if (mutable_data_ != NULLPTR) {
80
+ return {mutable_data_, offset_ + offset, length};
81
+ } else {
82
+ return {data_, offset_ + offset, length};
83
+ }
84
+ }
85
+
86
+ std::string ToString() const;
87
+
88
+ bool Equals(const Bitmap& other) const;
89
+
90
+ std::string Diff(const Bitmap& other) const;
91
+
92
+ bool GetBit(int64_t i) const { return bit_util::GetBit(data_, i + offset_); }
93
+
94
+ bool operator[](int64_t i) const { return GetBit(i); }
95
+
96
+ void SetBitTo(int64_t i, bool v) const {
97
+ bit_util::SetBitTo(mutable_data_, i + offset_, v);
98
+ }
99
+
100
+ void SetBitsTo(bool v) { bit_util::SetBitsTo(mutable_data_, offset_, length_, v); }
101
+
102
+ void CopyFrom(const Bitmap& other);
103
+ void CopyFromInverted(const Bitmap& other);
104
+
105
+ /// \brief Visit bits from each bitmap as bitset<N>
106
+ ///
107
+ /// All bitmaps must have identical length.
108
+ template <size_t N, typename Visitor>
109
+ static void VisitBits(const Bitmap (&bitmaps)[N], Visitor&& visitor) {
110
+ int64_t bit_length = BitLength(bitmaps, N);
111
+ std::bitset<N> bits;
112
+ for (int64_t bit_i = 0; bit_i < bit_length; ++bit_i) {
113
+ for (size_t i = 0; i < N; ++i) {
114
+ bits[i] = bitmaps[i].GetBit(bit_i);
115
+ }
116
+ visitor(bits);
117
+ }
118
+ }
119
+
120
+ /// \brief Visit bits from each bitmap as bitset<N>
121
+ ///
122
+ /// All bitmaps must have identical length.
123
+ template <size_t N, typename Visitor>
124
+ static void VisitBits(const std::array<Bitmap, N>& bitmaps, Visitor&& visitor) {
125
+ int64_t bit_length = BitLength(bitmaps);
126
+ std::bitset<N> bits;
127
+ for (int64_t bit_i = 0; bit_i < bit_length; ++bit_i) {
128
+ for (size_t i = 0; i < N; ++i) {
129
+ bits[i] = bitmaps[i].GetBit(bit_i);
130
+ }
131
+ visitor(bits);
132
+ }
133
+ }
134
+
135
+ /// \brief Visit words of bits from each bitmap as array<Word, N>
136
+ ///
137
+ /// All bitmaps must have identical length. The first bit in a visited bitmap
138
+ /// may be offset within the first visited word, but words will otherwise contain
139
+ /// densely packed bits loaded from the bitmap. That offset within the first word is
140
+ /// returned.
141
+ ///
142
+ /// TODO(bkietz) allow for early termination
143
+ // NOTE: this function is efficient on 3+ sufficiently large bitmaps.
144
+ // It also has a large prolog / epilog overhead and should be used
145
+ // carefully in other cases.
146
+ // For 2 bitmaps or less, and/or smaller bitmaps, see also VisitTwoBitBlocksVoid
147
+ // and BitmapUInt64Reader.
148
+ template <size_t N, typename Visitor,
149
+ typename Word = typename std::decay<
150
+ internal::call_traits::argument_type<0, Visitor&&>>::type::value_type>
151
+ static int64_t VisitWords(const Bitmap (&bitmaps_arg)[N], Visitor&& visitor) {
152
+ constexpr int64_t kBitWidth = sizeof(Word) * 8;
153
+
154
+ // local, mutable variables which will be sliced/decremented to represent consumption:
155
+ Bitmap bitmaps[N];
156
+ int64_t offsets[N];
157
+ int64_t bit_length = BitLength(bitmaps_arg, N);
158
+ util::span<const Word> words[N];
159
+ for (size_t i = 0; i < N; ++i) {
160
+ bitmaps[i] = bitmaps_arg[i];
161
+ offsets[i] = bitmaps[i].template word_offset<Word>();
162
+ assert(offsets[i] >= 0 && offsets[i] < kBitWidth);
163
+ words[i] = bitmaps[i].template words<Word>();
164
+ }
165
+
166
+ auto consume = [&](int64_t consumed_bits) {
167
+ for (size_t i = 0; i < N; ++i) {
168
+ bitmaps[i] = bitmaps[i].Slice(consumed_bits, bit_length - consumed_bits);
169
+ offsets[i] = bitmaps[i].template word_offset<Word>();
170
+ assert(offsets[i] >= 0 && offsets[i] < kBitWidth);
171
+ words[i] = bitmaps[i].template words<Word>();
172
+ }
173
+ bit_length -= consumed_bits;
174
+ };
175
+
176
+ std::array<Word, N> visited_words;
177
+ visited_words.fill(0);
178
+
179
+ if (bit_length <= kBitWidth * 2) {
180
+ // bitmaps fit into one or two words so don't bother with optimization
181
+ while (bit_length > 0) {
182
+ auto leading_bits = std::min(bit_length, kBitWidth);
183
+ SafeLoadWords(bitmaps, 0, leading_bits, false, &visited_words);
184
+ visitor(visited_words);
185
+ consume(leading_bits);
186
+ }
187
+ return 0;
188
+ }
189
+
190
+ int64_t max_offset = *std::max_element(offsets, offsets + N);
191
+ int64_t min_offset = *std::min_element(offsets, offsets + N);
192
+ if (max_offset > 0) {
193
+ // consume leading bits
194
+ auto leading_bits = kBitWidth - min_offset;
195
+ SafeLoadWords(bitmaps, 0, leading_bits, true, &visited_words);
196
+ visitor(visited_words);
197
+ consume(leading_bits);
198
+ }
199
+ assert(*std::min_element(offsets, offsets + N) == 0);
200
+
201
+ int64_t whole_word_count = bit_length / kBitWidth;
202
+ assert(whole_word_count >= 1);
203
+
204
+ if (min_offset == max_offset) {
205
+ // all offsets were identical, all leading bits have been consumed
206
+ assert(
207
+ std::all_of(offsets, offsets + N, [](int64_t offset) { return offset == 0; }));
208
+
209
+ for (int64_t word_i = 0; word_i < whole_word_count; ++word_i) {
210
+ for (size_t i = 0; i < N; ++i) {
211
+ visited_words[i] = words[i][word_i];
212
+ }
213
+ visitor(visited_words);
214
+ }
215
+ consume(whole_word_count * kBitWidth);
216
+ } else {
217
+ // leading bits from potentially incomplete words have been consumed
218
+
219
+ // word_i such that words[i][word_i] and words[i][word_i + 1] are lie entirely
220
+ // within the bitmap for all i
221
+ for (int64_t word_i = 0; word_i < whole_word_count - 1; ++word_i) {
222
+ for (size_t i = 0; i < N; ++i) {
223
+ if (offsets[i] == 0) {
224
+ visited_words[i] = words[i][word_i];
225
+ } else {
226
+ auto words0 = bit_util::ToLittleEndian(words[i][word_i]);
227
+ auto words1 = bit_util::ToLittleEndian(words[i][word_i + 1]);
228
+ visited_words[i] = bit_util::FromLittleEndian(
229
+ (words0 >> offsets[i]) | (words1 << (kBitWidth - offsets[i])));
230
+ }
231
+ }
232
+ visitor(visited_words);
233
+ }
234
+ consume((whole_word_count - 1) * kBitWidth);
235
+
236
+ SafeLoadWords(bitmaps, 0, kBitWidth, false, &visited_words);
237
+
238
+ visitor(visited_words);
239
+ consume(kBitWidth);
240
+ }
241
+
242
+ // load remaining bits
243
+ if (bit_length > 0) {
244
+ SafeLoadWords(bitmaps, 0, bit_length, false, &visited_words);
245
+ visitor(visited_words);
246
+ }
247
+
248
+ return min_offset;
249
+ }
250
+
251
+ template <size_t N, size_t M, typename ReaderT, typename WriterT, typename Visitor,
252
+ typename Word = typename std::decay<
253
+ internal::call_traits::argument_type<0, Visitor&&>>::type::value_type>
254
+ static void RunVisitWordsAndWriteLoop(int64_t bit_length,
255
+ std::array<ReaderT, N>& readers,
256
+ std::array<WriterT, M>& writers,
257
+ Visitor&& visitor) {
258
+ constexpr int64_t kBitWidth = sizeof(Word) * 8;
259
+
260
+ std::array<Word, N> visited_words;
261
+ std::array<Word, M> output_words;
262
+
263
+ // every reader will have same number of words, since they are same length'ed
264
+ // TODO($JIRA) this will be inefficient in some cases. When there are offsets beyond
265
+ // Word boundary, every Word would have to be created from 2 adjoining Words
266
+ auto n_words = readers[0].words();
267
+ bit_length -= n_words * kBitWidth;
268
+ while (n_words--) {
269
+ // first collect all words to visited_words array
270
+ for (size_t i = 0; i < N; i++) {
271
+ visited_words[i] = readers[i].NextWord();
272
+ }
273
+ visitor(visited_words, &output_words);
274
+ for (size_t i = 0; i < M; i++) {
275
+ writers[i].PutNextWord(output_words[i]);
276
+ }
277
+ }
278
+
279
+ // every reader will have same number of trailing bytes, because of the above reason
280
+ // tailing portion could be more than one word! (ref: BitmapWordReader constructor)
281
+ // remaining full/ partial words to write
282
+
283
+ if (bit_length) {
284
+ // convert the word visitor lambda to a byte_visitor
285
+ auto byte_visitor = [&](const std::array<uint8_t, N>& in,
286
+ std::array<uint8_t, M>* out) {
287
+ std::array<Word, N> in_words;
288
+ std::array<Word, M> out_words;
289
+ std::copy(in.begin(), in.end(), in_words.begin());
290
+ visitor(in_words, &out_words);
291
+ for (size_t i = 0; i < M; i++) {
292
+ out->at(i) = static_cast<uint8_t>(out_words[i]);
293
+ }
294
+ };
295
+
296
+ std::array<uint8_t, N> visited_bytes;
297
+ std::array<uint8_t, M> output_bytes;
298
+ int n_bytes = readers[0].trailing_bytes();
299
+ while (n_bytes--) {
300
+ visited_bytes.fill(0);
301
+ output_bytes.fill(0);
302
+ int valid_bits;
303
+ for (size_t i = 0; i < N; i++) {
304
+ visited_bytes[i] = readers[i].NextTrailingByte(valid_bits);
305
+ }
306
+ byte_visitor(visited_bytes, &output_bytes);
307
+ for (size_t i = 0; i < M; i++) {
308
+ writers[i].PutNextTrailingByte(output_bytes[i], valid_bits);
309
+ }
310
+ }
311
+ }
312
+ }
313
+
314
+ /// \brief Visit words of bits from each input bitmap as array<Word, N> and collects
315
+ /// outputs to an array<Word, M>, to be written into the output bitmaps accordingly.
316
+ ///
317
+ /// All bitmaps must have identical length. The first bit in a visited bitmap
318
+ /// may be offset within the first visited word, but words will otherwise contain
319
+ /// densely packed bits loaded from the bitmap. That offset within the first word is
320
+ /// returned.
321
+ /// Visitor is expected to have the following signature
322
+ /// [](const std::array<Word, N>& in_words, std::array<Word, M>* out_words){...}
323
+ ///
324
+ // NOTE: this function is efficient on 3+ sufficiently large bitmaps.
325
+ // It also has a large prolog / epilog overhead and should be used
326
+ // carefully in other cases.
327
+ // For 2 bitmaps or less, and/or smaller bitmaps, see also VisitTwoBitBlocksVoid
328
+ // and BitmapUInt64Reader.
329
+ template <size_t N, size_t M, typename Visitor,
330
+ typename Word = typename std::decay<
331
+ internal::call_traits::argument_type<0, Visitor&&>>::type::value_type>
332
+ static void VisitWordsAndWrite(const std::array<Bitmap, N>& bitmaps_arg,
333
+ std::array<Bitmap, M>* out_bitmaps_arg,
334
+ Visitor&& visitor) {
335
+ int64_t bit_length = BitLength(bitmaps_arg);
336
+ assert(bit_length == BitLength(*out_bitmaps_arg));
337
+
338
+ // if both input and output bitmaps have no byte offset, then use special template
339
+ if (std::all_of(bitmaps_arg.begin(), bitmaps_arg.end(),
340
+ [](const Bitmap& b) { return b.offset_ % 8 == 0; }) &&
341
+ std::all_of(out_bitmaps_arg->begin(), out_bitmaps_arg->end(),
342
+ [](const Bitmap& b) { return b.offset_ % 8 == 0; })) {
343
+ std::array<BitmapWordReader<Word, /*may_have_byte_offset=*/false>, N> readers;
344
+ for (size_t i = 0; i < N; ++i) {
345
+ const Bitmap& in_bitmap = bitmaps_arg[i];
346
+ readers[i] = BitmapWordReader<Word, /*may_have_byte_offset=*/false>(
347
+ in_bitmap.data_, in_bitmap.offset_, in_bitmap.length_);
348
+ }
349
+
350
+ std::array<BitmapWordWriter<Word, /*may_have_byte_offset=*/false>, M> writers;
351
+ for (size_t i = 0; i < M; ++i) {
352
+ const Bitmap& out_bitmap = out_bitmaps_arg->at(i);
353
+ writers[i] = BitmapWordWriter<Word, /*may_have_byte_offset=*/false>(
354
+ out_bitmap.mutable_data_, out_bitmap.offset_, out_bitmap.length_);
355
+ }
356
+
357
+ RunVisitWordsAndWriteLoop(bit_length, readers, writers, visitor);
358
+ } else {
359
+ std::array<BitmapWordReader<Word>, N> readers;
360
+ for (size_t i = 0; i < N; ++i) {
361
+ const Bitmap& in_bitmap = bitmaps_arg[i];
362
+ readers[i] =
363
+ BitmapWordReader<Word>(in_bitmap.data_, in_bitmap.offset_, in_bitmap.length_);
364
+ }
365
+
366
+ std::array<BitmapWordWriter<Word>, M> writers;
367
+ for (size_t i = 0; i < M; ++i) {
368
+ const Bitmap& out_bitmap = out_bitmaps_arg->at(i);
369
+ writers[i] = BitmapWordWriter<Word>(out_bitmap.mutable_data_, out_bitmap.offset_,
370
+ out_bitmap.length_);
371
+ }
372
+
373
+ RunVisitWordsAndWriteLoop(bit_length, readers, writers, visitor);
374
+ }
375
+ }
376
+
377
+ const uint8_t* data() const { return data_; }
378
+ uint8_t* mutable_data() { return mutable_data_; }
379
+
380
+ /// offset of first bit relative to buffer().data()
381
+ int64_t offset() const { return offset_; }
382
+
383
+ /// number of bits in this Bitmap
384
+ int64_t length() const { return length_; }
385
+
386
+ /// span of all bytes which contain any bit in this Bitmap
387
+ util::span<const uint8_t> bytes() const {
388
+ auto byte_offset = offset_ / 8;
389
+ auto byte_count = bit_util::CeilDiv(offset_ + length_, 8) - byte_offset;
390
+ return {data_ + byte_offset, static_cast<size_t>(byte_count)};
391
+ }
392
+
393
+ private:
394
+ /// span of all Words which contain any bit in this Bitmap
395
+ ///
396
+ /// For example, given Word=uint16_t and a bitmap spanning bits [20, 36)
397
+ /// words() would span bits [16, 48).
398
+ ///
399
+ /// 0 16 32 48 64
400
+ /// |-------|-------|------|------| (buffer)
401
+ /// [ ] (bitmap)
402
+ /// |-------|------| (returned words)
403
+ ///
404
+ /// \warning The words may contain bytes which lie outside the buffer or are
405
+ /// uninitialized.
406
+ template <typename Word>
407
+ util::span<const Word> words() const {
408
+ auto bytes_addr = reinterpret_cast<intptr_t>(bytes().data());
409
+ auto words_addr = bytes_addr - bytes_addr % sizeof(Word);
410
+ auto word_byte_count =
411
+ bit_util::RoundUpToPowerOf2(static_cast<int64_t>(bytes_addr + bytes().size()),
412
+ static_cast<int64_t>(sizeof(Word))) -
413
+ words_addr;
414
+ return {reinterpret_cast<const Word*>(words_addr),
415
+ static_cast<size_t>(word_byte_count / sizeof(Word))};
416
+ }
417
+
418
+ /// offset of first bit relative to words<Word>().data()
419
+ template <typename Word>
420
+ int64_t word_offset() const {
421
+ return offset_ + 8 * (reinterpret_cast<intptr_t>(data_) -
422
+ reinterpret_cast<intptr_t>(words<Word>().data()));
423
+ }
424
+
425
+ /// load words from bitmaps bitwise
426
+ template <size_t N, typename Word>
427
+ static void SafeLoadWords(const Bitmap (&bitmaps)[N], int64_t offset,
428
+ int64_t out_length, bool set_trailing_bits,
429
+ std::array<Word, N>* out) {
430
+ out->fill(0);
431
+
432
+ int64_t out_offset = set_trailing_bits ? sizeof(Word) * 8 - out_length : 0;
433
+
434
+ Bitmap slices[N], out_bitmaps[N];
435
+ for (size_t i = 0; i < N; ++i) {
436
+ slices[i] = bitmaps[i].Slice(offset, out_length);
437
+ out_bitmaps[i] = Bitmap(&out->at(i), out_offset, out_length);
438
+ }
439
+
440
+ int64_t bit_i = 0;
441
+ Bitmap::VisitBits(slices, [&](std::bitset<N> bits) {
442
+ for (size_t i = 0; i < N; ++i) {
443
+ out_bitmaps[i].SetBitTo(bit_i, bits[i]);
444
+ }
445
+ ++bit_i;
446
+ });
447
+ }
448
+
449
+ /// assert bitmaps have identical length and return that length
450
+ static int64_t BitLength(const Bitmap* bitmaps, size_t N);
451
+
452
+ template <size_t N>
453
+ static int64_t BitLength(const std::array<Bitmap, N>& bitmaps) {
454
+ for (size_t i = 1; i < N; ++i) {
455
+ assert(bitmaps[i].length() == bitmaps[0].length());
456
+ }
457
+ return bitmaps[0].length();
458
+ }
459
+
460
+ const uint8_t* data_ = NULLPTR;
461
+ uint8_t* mutable_data_ = NULLPTR;
462
+ int64_t offset_ = 0, length_ = 0;
463
+ };
464
+
465
+ } // namespace internal
466
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_builders.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/result.h"
25
+ #include "arrow/type_fwd.h"
26
+ #include "arrow/util/visibility.h"
27
+
28
+ namespace arrow {
29
+ namespace internal {
30
+
31
+ /// \brief Generate Bitmap with all position to `value` except for one found
32
+ /// at `straggler_pos`.
33
+ ARROW_EXPORT
34
+ Result<std::shared_ptr<Buffer>> BitmapAllButOne(MemoryPool* pool, int64_t length,
35
+ int64_t straggler_pos, bool value = true);
36
+
37
+ /// \brief Convert vector of bytes to bitmap buffer
38
+ ARROW_EXPORT
39
+ Result<std::shared_ptr<Buffer>> BytesToBits(const std::vector<uint8_t>&,
40
+ MemoryPool* pool = default_memory_pool());
41
+
42
+ } // namespace internal
43
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_generate.h ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/buffer.h"
24
+ #include "arrow/memory_pool.h"
25
+ #include "arrow/result.h"
26
+ #include "arrow/util/bit_util.h"
27
+ #include "arrow/util/visibility.h"
28
+
29
+ namespace arrow {
30
+ namespace internal {
31
+
32
+ // A std::generate() like function to write sequential bits into a bitmap area.
33
+ // Bits preceding the bitmap area are preserved, bits following the bitmap
34
+ // area may be clobbered.
35
+
36
+ template <class Generator>
37
+ void GenerateBits(uint8_t* bitmap, int64_t start_offset, int64_t length, Generator&& g) {
38
+ if (length == 0) {
39
+ return;
40
+ }
41
+ uint8_t* cur = bitmap + start_offset / 8;
42
+ uint8_t bit_mask = bit_util::kBitmask[start_offset % 8];
43
+ uint8_t current_byte = *cur & bit_util::kPrecedingBitmask[start_offset % 8];
44
+
45
+ for (int64_t index = 0; index < length; ++index) {
46
+ const bool bit = g();
47
+ current_byte = bit ? (current_byte | bit_mask) : current_byte;
48
+ bit_mask = static_cast<uint8_t>(bit_mask << 1);
49
+ if (bit_mask == 0) {
50
+ bit_mask = 1;
51
+ *cur++ = current_byte;
52
+ current_byte = 0;
53
+ }
54
+ }
55
+ if (bit_mask != 1) {
56
+ *cur++ = current_byte;
57
+ }
58
+ }
59
+
60
+ // Like GenerateBits(), but unrolls its main loop for higher performance.
61
+
62
+ template <class Generator>
63
+ void GenerateBitsUnrolled(uint8_t* bitmap, int64_t start_offset, int64_t length,
64
+ Generator&& g) {
65
+ static_assert(std::is_same<decltype(std::declval<Generator>()()), bool>::value,
66
+ "Functor passed to GenerateBitsUnrolled must return bool");
67
+
68
+ if (length == 0) {
69
+ return;
70
+ }
71
+ uint8_t current_byte;
72
+ uint8_t* cur = bitmap + start_offset / 8;
73
+ const uint64_t start_bit_offset = start_offset % 8;
74
+ uint8_t bit_mask = bit_util::kBitmask[start_bit_offset];
75
+ int64_t remaining = length;
76
+
77
+ if (bit_mask != 0x01) {
78
+ current_byte = *cur & bit_util::kPrecedingBitmask[start_bit_offset];
79
+ while (bit_mask != 0 && remaining > 0) {
80
+ current_byte |= g() * bit_mask;
81
+ bit_mask = static_cast<uint8_t>(bit_mask << 1);
82
+ --remaining;
83
+ }
84
+ *cur++ = current_byte;
85
+ }
86
+
87
+ int64_t remaining_bytes = remaining / 8;
88
+ uint8_t out_results[8];
89
+ while (remaining_bytes-- > 0) {
90
+ for (int i = 0; i < 8; ++i) {
91
+ out_results[i] = g();
92
+ }
93
+ *cur++ = static_cast<uint8_t>(out_results[0] | out_results[1] << 1 |
94
+ out_results[2] << 2 | out_results[3] << 3 |
95
+ out_results[4] << 4 | out_results[5] << 5 |
96
+ out_results[6] << 6 | out_results[7] << 7);
97
+ }
98
+
99
+ int64_t remaining_bits = remaining % 8;
100
+ if (remaining_bits) {
101
+ current_byte = 0;
102
+ bit_mask = 0x01;
103
+ while (remaining_bits-- > 0) {
104
+ current_byte |= g() * bit_mask;
105
+ bit_mask = static_cast<uint8_t>(bit_mask << 1);
106
+ }
107
+ *cur++ = current_byte;
108
+ }
109
+ }
110
+
111
+ } // namespace internal
112
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_ops.h ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/result.h"
24
+ #include "arrow/util/visibility.h"
25
+
26
+ namespace arrow {
27
+
28
+ class Buffer;
29
+ class MemoryPool;
30
+
31
+ namespace internal {
32
+
33
+ // ----------------------------------------------------------------------
34
+ // Bitmap utilities
35
+
36
+ /// Copy a bit range of an existing bitmap
37
+ ///
38
+ /// \param[in] pool memory pool to allocate memory from
39
+ /// \param[in] bitmap source data
40
+ /// \param[in] offset bit offset into the source data
41
+ /// \param[in] length number of bits to copy
42
+ ///
43
+ /// \return Status message
44
+ ARROW_EXPORT
45
+ Result<std::shared_ptr<Buffer>> CopyBitmap(MemoryPool* pool, const uint8_t* bitmap,
46
+ int64_t offset, int64_t length);
47
+
48
+ /// Copy a bit range of an existing bitmap into an existing bitmap
49
+ ///
50
+ /// \param[in] bitmap source data
51
+ /// \param[in] offset bit offset into the source data
52
+ /// \param[in] length number of bits to copy
53
+ /// \param[in] dest_offset bit offset into the destination
54
+ /// \param[out] dest the destination buffer, must have at least space for
55
+ /// (offset + length) bits
56
+ ARROW_EXPORT
57
+ void CopyBitmap(const uint8_t* bitmap, int64_t offset, int64_t length, uint8_t* dest,
58
+ int64_t dest_offset);
59
+
60
+ /// Invert a bit range of an existing bitmap into an existing bitmap
61
+ ///
62
+ /// \param[in] bitmap source data
63
+ /// \param[in] offset bit offset into the source data
64
+ /// \param[in] length number of bits to copy
65
+ /// \param[in] dest_offset bit offset into the destination
66
+ /// \param[out] dest the destination buffer, must have at least space for
67
+ /// (offset + length) bits
68
+ ARROW_EXPORT
69
+ void InvertBitmap(const uint8_t* bitmap, int64_t offset, int64_t length, uint8_t* dest,
70
+ int64_t dest_offset);
71
+
72
+ /// Invert a bit range of an existing bitmap
73
+ ///
74
+ /// \param[in] pool memory pool to allocate memory from
75
+ /// \param[in] bitmap source data
76
+ /// \param[in] offset bit offset into the source data
77
+ /// \param[in] length number of bits to copy
78
+ ///
79
+ /// \return Status message
80
+ ARROW_EXPORT
81
+ Result<std::shared_ptr<Buffer>> InvertBitmap(MemoryPool* pool, const uint8_t* bitmap,
82
+ int64_t offset, int64_t length);
83
+
84
+ /// Reverse a bit range of an existing bitmap into an existing bitmap
85
+ ///
86
+ /// \param[in] bitmap source data
87
+ /// \param[in] offset bit offset into the source data
88
+ /// \param[in] length number of bits to reverse
89
+ /// \param[in] dest_offset bit offset into the destination
90
+ /// \param[out] dest the destination buffer, must have at least space for
91
+ /// (offset + length) bits
92
+ ARROW_EXPORT
93
+ void ReverseBitmap(const uint8_t* bitmap, int64_t offset, int64_t length, uint8_t* dest,
94
+ int64_t dest_offset);
95
+
96
+ /// Reverse a bit range of an existing bitmap
97
+ ///
98
+ /// \param[in] pool memory pool to allocate memory from
99
+ /// \param[in] bitmap source data
100
+ /// \param[in] offset bit offset into the source data
101
+ /// \param[in] length number of bits to reverse
102
+ ///
103
+ /// \return Status message
104
+ ARROW_EXPORT
105
+ Result<std::shared_ptr<Buffer>> ReverseBitmap(MemoryPool* pool, const uint8_t* bitmap,
106
+ int64_t offset, int64_t length);
107
+
108
+ /// Compute the number of 1's in the given data array
109
+ ///
110
+ /// \param[in] data a packed LSB-ordered bitmap as a byte array
111
+ /// \param[in] bit_offset a bitwise offset into the bitmap
112
+ /// \param[in] length the number of bits to inspect in the bitmap relative to
113
+ /// the offset
114
+ ///
115
+ /// \return The number of set (1) bits in the range
116
+ ARROW_EXPORT
117
+ int64_t CountSetBits(const uint8_t* data, int64_t bit_offset, int64_t length);
118
+
119
+ /// Compute the number of 1's in the result of an "and" (&) of two bitmaps
120
+ ///
121
+ /// \param[in] left_bitmap a packed LSB-ordered bitmap as a byte array
122
+ /// \param[in] left_offset a bitwise offset into the left bitmap
123
+ /// \param[in] right_bitmap a packed LSB-ordered bitmap as a byte array
124
+ /// \param[in] right_offset a bitwise offset into the right bitmap
125
+ /// \param[in] length the length of the bitmaps (must be the same)
126
+ ///
127
+ /// \return The number of set (1) bits in the "and" of the two bitmaps
128
+ ARROW_EXPORT
129
+ int64_t CountAndSetBits(const uint8_t* left_bitmap, int64_t left_offset,
130
+ const uint8_t* right_bitmap, int64_t right_offset,
131
+ int64_t length);
132
+
133
+ ARROW_EXPORT
134
+ bool BitmapEquals(const uint8_t* left, int64_t left_offset, const uint8_t* right,
135
+ int64_t right_offset, int64_t length);
136
+
137
+ // Same as BitmapEquals, but considers a NULL bitmap pointer the same as an
138
+ // all-ones bitmap.
139
+ ARROW_EXPORT
140
+ bool OptionalBitmapEquals(const uint8_t* left, int64_t left_offset, const uint8_t* right,
141
+ int64_t right_offset, int64_t length);
142
+
143
+ ARROW_EXPORT
144
+ bool OptionalBitmapEquals(const std::shared_ptr<Buffer>& left, int64_t left_offset,
145
+ const std::shared_ptr<Buffer>& right, int64_t right_offset,
146
+ int64_t length);
147
+
148
+ /// \brief Do a "bitmap and" on right and left buffers starting at
149
+ /// their respective bit-offsets for the given bit-length and put
150
+ /// the results in out_buffer starting at the given bit-offset.
151
+ ///
152
+ /// out_buffer will be allocated and initialized to zeros using pool before
153
+ /// the operation.
154
+ ARROW_EXPORT
155
+ Result<std::shared_ptr<Buffer>> BitmapAnd(MemoryPool* pool, const uint8_t* left,
156
+ int64_t left_offset, const uint8_t* right,
157
+ int64_t right_offset, int64_t length,
158
+ int64_t out_offset);
159
+
160
+ /// \brief Do a "bitmap and" on right and left buffers starting at
161
+ /// their respective bit-offsets for the given bit-length and put
162
+ /// the results in out starting at the given bit-offset.
163
+ ARROW_EXPORT
164
+ void BitmapAnd(const uint8_t* left, int64_t left_offset, const uint8_t* right,
165
+ int64_t right_offset, int64_t length, int64_t out_offset, uint8_t* out);
166
+
167
+ /// \brief Do a "bitmap or" for the given bit length on right and left buffers
168
+ /// starting at their respective bit-offsets and put the results in out_buffer
169
+ /// starting at the given bit-offset.
170
+ ///
171
+ /// out_buffer will be allocated and initialized to zeros using pool before
172
+ /// the operation.
173
+ ARROW_EXPORT
174
+ Result<std::shared_ptr<Buffer>> BitmapOr(MemoryPool* pool, const uint8_t* left,
175
+ int64_t left_offset, const uint8_t* right,
176
+ int64_t right_offset, int64_t length,
177
+ int64_t out_offset);
178
+
179
+ /// \brief Do a "bitmap or" for the given bit length on right and left buffers
180
+ /// starting at their respective bit-offsets and put the results in out
181
+ /// starting at the given bit-offset.
182
+ ARROW_EXPORT
183
+ void BitmapOr(const uint8_t* left, int64_t left_offset, const uint8_t* right,
184
+ int64_t right_offset, int64_t length, int64_t out_offset, uint8_t* out);
185
+
186
+ /// \brief Do a "bitmap xor" for the given bit-length on right and left
187
+ /// buffers starting at their respective bit-offsets and put the results in
188
+ /// out_buffer starting at the given bit offset.
189
+ ///
190
+ /// out_buffer will be allocated and initialized to zeros using pool before
191
+ /// the operation.
192
+ ARROW_EXPORT
193
+ Result<std::shared_ptr<Buffer>> BitmapXor(MemoryPool* pool, const uint8_t* left,
194
+ int64_t left_offset, const uint8_t* right,
195
+ int64_t right_offset, int64_t length,
196
+ int64_t out_offset);
197
+
198
+ /// \brief Do a "bitmap xor" for the given bit-length on right and left
199
+ /// buffers starting at their respective bit-offsets and put the results in
200
+ /// out starting at the given bit offset.
201
+ ARROW_EXPORT
202
+ void BitmapXor(const uint8_t* left, int64_t left_offset, const uint8_t* right,
203
+ int64_t right_offset, int64_t length, int64_t out_offset, uint8_t* out);
204
+
205
+ /// \brief Do a "bitmap and not" on right and left buffers starting at
206
+ /// their respective bit-offsets for the given bit-length and put
207
+ /// the results in out_buffer starting at the given bit-offset.
208
+ ///
209
+ /// out_buffer will be allocated and initialized to zeros using pool before
210
+ /// the operation.
211
+ ARROW_EXPORT
212
+ Result<std::shared_ptr<Buffer>> BitmapAndNot(MemoryPool* pool, const uint8_t* left,
213
+ int64_t left_offset, const uint8_t* right,
214
+ int64_t right_offset, int64_t length,
215
+ int64_t out_offset);
216
+
217
+ /// \brief Do a "bitmap and not" on right and left buffers starting at
218
+ /// their respective bit-offsets for the given bit-length and put
219
+ /// the results in out starting at the given bit-offset.
220
+ ARROW_EXPORT
221
+ void BitmapAndNot(const uint8_t* left, int64_t left_offset, const uint8_t* right,
222
+ int64_t right_offset, int64_t length, int64_t out_offset, uint8_t* out);
223
+
224
+ /// \brief Do a "bitmap or not" on right and left buffers starting at
225
+ /// their respective bit-offsets for the given bit-length and put
226
+ /// the results in out_buffer starting at the given bit-offset.
227
+ ///
228
+ /// out_buffer will be allocated and initialized to zeros using pool before
229
+ /// the operation.
230
+ ARROW_EXPORT
231
+ Result<std::shared_ptr<Buffer>> BitmapOrNot(MemoryPool* pool, const uint8_t* left,
232
+ int64_t left_offset, const uint8_t* right,
233
+ int64_t right_offset, int64_t length,
234
+ int64_t out_offset);
235
+
236
+ /// \brief Do a "bitmap or not" on right and left buffers starting at
237
+ /// their respective bit-offsets for the given bit-length and put
238
+ /// the results in out starting at the given bit-offset.
239
+ ARROW_EXPORT
240
+ void BitmapOrNot(const uint8_t* left, int64_t left_offset, const uint8_t* right,
241
+ int64_t right_offset, int64_t length, int64_t out_offset, uint8_t* out);
242
+
243
+ } // namespace internal
244
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_reader.h ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <cstdint>
22
+ #include <cstring>
23
+
24
+ #include "arrow/buffer.h"
25
+ #include "arrow/util/bit_util.h"
26
+ #include "arrow/util/endian.h"
27
+ #include "arrow/util/macros.h"
28
+
29
+ namespace arrow {
30
+ namespace internal {
31
+
32
+ class BitmapReader {
33
+ public:
34
+ BitmapReader(const uint8_t* bitmap, int64_t start_offset, int64_t length)
35
+ : bitmap_(bitmap), position_(0), length_(length) {
36
+ current_byte_ = 0;
37
+ byte_offset_ = start_offset / 8;
38
+ bit_offset_ = start_offset % 8;
39
+ if (length > 0) {
40
+ current_byte_ = bitmap[byte_offset_];
41
+ }
42
+ }
43
+
44
+ bool IsSet() const { return (current_byte_ & (1 << bit_offset_)) != 0; }
45
+
46
+ bool IsNotSet() const { return (current_byte_ & (1 << bit_offset_)) == 0; }
47
+
48
+ void Next() {
49
+ ++bit_offset_;
50
+ ++position_;
51
+ if (ARROW_PREDICT_FALSE(bit_offset_ == 8)) {
52
+ bit_offset_ = 0;
53
+ ++byte_offset_;
54
+ if (ARROW_PREDICT_TRUE(position_ < length_)) {
55
+ current_byte_ = bitmap_[byte_offset_];
56
+ }
57
+ }
58
+ }
59
+
60
+ int64_t position() const { return position_; }
61
+
62
+ int64_t length() const { return length_; }
63
+
64
+ private:
65
+ const uint8_t* bitmap_;
66
+ int64_t position_;
67
+ int64_t length_;
68
+
69
+ uint8_t current_byte_;
70
+ int64_t byte_offset_;
71
+ int64_t bit_offset_;
72
+ };
73
+
74
+ // XXX Cannot name it BitmapWordReader because the name is already used
75
+ // in bitmap_ops.cc
76
+
77
+ class BitmapUInt64Reader {
78
+ public:
79
+ BitmapUInt64Reader(const uint8_t* bitmap, int64_t start_offset, int64_t length)
80
+ : bitmap_(util::MakeNonNull(bitmap) + start_offset / 8),
81
+ num_carry_bits_(8 - start_offset % 8),
82
+ length_(length),
83
+ remaining_length_(length_),
84
+ carry_bits_(0) {
85
+ if (length_ > 0) {
86
+ // Load carry bits from the first byte's MSBs
87
+ if (length_ >= num_carry_bits_) {
88
+ carry_bits_ =
89
+ LoadPartialWord(static_cast<int8_t>(8 - num_carry_bits_), num_carry_bits_);
90
+ } else {
91
+ carry_bits_ = LoadPartialWord(static_cast<int8_t>(8 - num_carry_bits_), length_);
92
+ }
93
+ }
94
+ }
95
+
96
+ uint64_t NextWord() {
97
+ if (ARROW_PREDICT_TRUE(remaining_length_ >= 64 + num_carry_bits_)) {
98
+ // We can load a full word
99
+ uint64_t next_word = LoadFullWord();
100
+ // Carry bits come first, then the (64 - num_carry_bits_) LSBs from next_word
101
+ uint64_t word = carry_bits_ | (next_word << num_carry_bits_);
102
+ carry_bits_ = next_word >> (64 - num_carry_bits_);
103
+ remaining_length_ -= 64;
104
+ return word;
105
+ } else if (remaining_length_ > num_carry_bits_) {
106
+ // We can load a partial word
107
+ uint64_t next_word =
108
+ LoadPartialWord(/*bit_offset=*/0, remaining_length_ - num_carry_bits_);
109
+ uint64_t word = carry_bits_ | (next_word << num_carry_bits_);
110
+ carry_bits_ = next_word >> (64 - num_carry_bits_);
111
+ remaining_length_ = std::max<int64_t>(remaining_length_ - 64, 0);
112
+ return word;
113
+ } else {
114
+ remaining_length_ = 0;
115
+ return carry_bits_;
116
+ }
117
+ }
118
+
119
+ int64_t position() const { return length_ - remaining_length_; }
120
+
121
+ int64_t length() const { return length_; }
122
+
123
+ private:
124
+ uint64_t LoadFullWord() {
125
+ uint64_t word;
126
+ memcpy(&word, bitmap_, 8);
127
+ bitmap_ += 8;
128
+ return bit_util::ToLittleEndian(word);
129
+ }
130
+
131
+ uint64_t LoadPartialWord(int8_t bit_offset, int64_t num_bits) {
132
+ uint64_t word = 0;
133
+ const int64_t num_bytes = bit_util::BytesForBits(num_bits);
134
+ memcpy(&word, bitmap_, num_bytes);
135
+ bitmap_ += num_bytes;
136
+ return (bit_util::ToLittleEndian(word) >> bit_offset) &
137
+ bit_util::LeastSignificantBitMask(num_bits);
138
+ }
139
+
140
+ const uint8_t* bitmap_;
141
+ const int64_t num_carry_bits_; // in [1, 8]
142
+ const int64_t length_;
143
+ int64_t remaining_length_;
144
+ uint64_t carry_bits_;
145
+ };
146
+
147
+ // BitmapWordReader here is faster than BitmapUInt64Reader (in bitmap_reader.h)
148
+ // on sufficiently large inputs. However, it has a larger prolog / epilog overhead
149
+ // and should probably not be used for small bitmaps.
150
+
151
+ template <typename Word, bool may_have_byte_offset = true>
152
+ class BitmapWordReader {
153
+ public:
154
+ BitmapWordReader() = default;
155
+ BitmapWordReader(const uint8_t* bitmap, int64_t offset, int64_t length)
156
+ : offset_(static_cast<int64_t>(may_have_byte_offset) * (offset % 8)),
157
+ bitmap_(bitmap + offset / 8),
158
+ bitmap_end_(bitmap_ + bit_util::BytesForBits(offset_ + length)) {
159
+ // decrement word count by one as we may touch two adjacent words in one iteration
160
+ nwords_ = length / (sizeof(Word) * 8) - 1;
161
+ if (nwords_ < 0) {
162
+ nwords_ = 0;
163
+ }
164
+ trailing_bits_ = static_cast<int>(length - nwords_ * sizeof(Word) * 8);
165
+ trailing_bytes_ = static_cast<int>(bit_util::BytesForBits(trailing_bits_));
166
+
167
+ if (nwords_ > 0) {
168
+ current_data.word_ = load<Word>(bitmap_);
169
+ } else if (length > 0) {
170
+ current_data.epi.byte_ = load<uint8_t>(bitmap_);
171
+ }
172
+ }
173
+
174
+ Word NextWord() {
175
+ bitmap_ += sizeof(Word);
176
+ const Word next_word = load<Word>(bitmap_);
177
+ Word word = current_data.word_;
178
+ if (may_have_byte_offset && offset_) {
179
+ // combine two adjacent words into one word
180
+ // |<------ next ----->|<---- current ---->|
181
+ // +-------------+-----+-------------+-----+
182
+ // | --- | A | B | --- |
183
+ // +-------------+-----+-------------+-----+
184
+ // | | offset
185
+ // v v
186
+ // +-----+-------------+
187
+ // | A | B |
188
+ // +-----+-------------+
189
+ // |<------ word ----->|
190
+ word >>= offset_;
191
+ word |= next_word << (sizeof(Word) * 8 - offset_);
192
+ }
193
+ current_data.word_ = next_word;
194
+ return word;
195
+ }
196
+
197
+ uint8_t NextTrailingByte(int& valid_bits) {
198
+ uint8_t byte;
199
+ assert(trailing_bits_ > 0);
200
+
201
+ if (trailing_bits_ <= 8) {
202
+ // last byte
203
+ valid_bits = trailing_bits_;
204
+ trailing_bits_ = 0;
205
+ byte = 0;
206
+ internal::BitmapReader reader(bitmap_, offset_, valid_bits);
207
+ for (int i = 0; i < valid_bits; ++i) {
208
+ byte >>= 1;
209
+ if (reader.IsSet()) {
210
+ byte |= 0x80;
211
+ }
212
+ reader.Next();
213
+ }
214
+ byte >>= (8 - valid_bits);
215
+ } else {
216
+ ++bitmap_;
217
+ const uint8_t next_byte = load<uint8_t>(bitmap_);
218
+ byte = current_data.epi.byte_;
219
+ if (may_have_byte_offset && offset_) {
220
+ byte >>= offset_;
221
+ byte |= next_byte << (8 - offset_);
222
+ }
223
+ current_data.epi.byte_ = next_byte;
224
+ trailing_bits_ -= 8;
225
+ trailing_bytes_--;
226
+ valid_bits = 8;
227
+ }
228
+ return byte;
229
+ }
230
+
231
+ int64_t words() const { return nwords_; }
232
+ int trailing_bytes() const { return trailing_bytes_; }
233
+
234
+ private:
235
+ int64_t offset_;
236
+ const uint8_t* bitmap_;
237
+
238
+ const uint8_t* bitmap_end_;
239
+ int64_t nwords_;
240
+ int trailing_bits_;
241
+ int trailing_bytes_;
242
+ union {
243
+ Word word_;
244
+ struct {
245
+ #if ARROW_LITTLE_ENDIAN == 0
246
+ uint8_t padding_bytes_[sizeof(Word) - 1];
247
+ #endif
248
+ uint8_t byte_;
249
+ } epi;
250
+ } current_data;
251
+
252
+ template <typename DType>
253
+ DType load(const uint8_t* bitmap) {
254
+ assert(bitmap + sizeof(DType) <= bitmap_end_);
255
+ return bit_util::ToLittleEndian(util::SafeLoadAs<DType>(bitmap));
256
+ }
257
+ };
258
+
259
+ /// \brief Index into a possibly nonexistent bitmap
260
+ struct OptionalBitIndexer {
261
+ const uint8_t* bitmap;
262
+ const int64_t offset;
263
+
264
+ explicit OptionalBitIndexer(const uint8_t* buffer = NULLPTR, int64_t offset = 0)
265
+ : bitmap(buffer), offset(offset) {}
266
+
267
+ bool operator[](int64_t i) const {
268
+ return bitmap == NULLPTR || bit_util::GetBit(bitmap, offset + i);
269
+ }
270
+ };
271
+
272
+ } // namespace internal
273
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking64_default.h ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx2.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <stdint.h>
21
+
22
+ namespace arrow {
23
+ namespace internal {
24
+
25
+ int unpack32_avx2(const uint32_t* in, uint32_t* out, int batch_size, int num_bits);
26
+
27
+ } // namespace internal
28
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx512.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <stdint.h>
21
+
22
+ namespace arrow {
23
+ namespace internal {
24
+
25
+ int unpack32_avx512(const uint32_t* in, uint32_t* out, int batch_size, int num_bits);
26
+
27
+ } // namespace internal
28
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_default.h ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_neon.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <stdint.h>
21
+
22
+ namespace arrow {
23
+ namespace internal {
24
+
25
+ int unpack32_neon(const uint32_t* in, uint32_t* out, int batch_size, int num_bits);
26
+
27
+ } // namespace internal
28
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/cancel.h ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <functional>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "arrow/status.h"
26
+ #include "arrow/type_fwd.h"
27
+ #include "arrow/util/macros.h"
28
+ #include "arrow/util/visibility.h"
29
+
30
+ namespace arrow {
31
+
32
+ class StopToken;
33
+
34
+ struct StopSourceImpl;
35
+
36
+ /// EXPERIMENTAL
37
+ class ARROW_EXPORT StopSource {
38
+ public:
39
+ StopSource();
40
+ ~StopSource();
41
+
42
+ // Consumer API (the side that stops)
43
+ void RequestStop();
44
+ void RequestStop(Status error);
45
+ // Async-signal-safe. TODO Deprecate this?
46
+ void RequestStopFromSignal(int signum);
47
+
48
+ StopToken token();
49
+
50
+ // For internal use only
51
+ void Reset();
52
+
53
+ protected:
54
+ std::shared_ptr<StopSourceImpl> impl_;
55
+ };
56
+
57
+ /// EXPERIMENTAL
58
+ class ARROW_EXPORT StopToken {
59
+ public:
60
+ // Public for Cython
61
+ StopToken() {}
62
+
63
+ explicit StopToken(std::shared_ptr<StopSourceImpl> impl) : impl_(std::move(impl)) {}
64
+
65
+ // A trivial token that never propagates any stop request
66
+ static StopToken Unstoppable() { return StopToken(); }
67
+
68
+ /// \brief Check if the stop source has been cancelled.
69
+ ///
70
+ /// Producers should call this method, whenever convenient, to check and
71
+ /// see if they should stop producing early (i.e. have been cancelled).
72
+ /// Failure to call this method often enough will lead to an unresponsive
73
+ /// cancellation.
74
+ ///
75
+ /// This is part of the producer API (the side that gets asked to stop)
76
+ /// This method is thread-safe
77
+ ///
78
+ /// \return An OK status if the stop source has not been cancelled or a
79
+ /// cancel error if the source has been cancelled.
80
+ Status Poll() const;
81
+ bool IsStopRequested() const;
82
+
83
+ protected:
84
+ std::shared_ptr<StopSourceImpl> impl_;
85
+ };
86
+
87
+ /// EXPERIMENTAL: Set a global StopSource that can receive signals
88
+ ///
89
+ /// The only allowed order of calls is the following:
90
+ /// - SetSignalStopSource()
91
+ /// - any number of pairs of (RegisterCancellingSignalHandler,
92
+ /// UnregisterCancellingSignalHandler) calls
93
+ /// - ResetSignalStopSource()
94
+ ///
95
+ /// Beware that these settings are process-wide. Typically, only one
96
+ /// thread should call these APIs, even in a multithreaded setting.
97
+ ARROW_EXPORT
98
+ Result<StopSource*> SetSignalStopSource();
99
+
100
+ /// EXPERIMENTAL: Reset the global signal-receiving StopSource
101
+ ///
102
+ /// This will invalidate the pointer returned by SetSignalStopSource.
103
+ ARROW_EXPORT
104
+ void ResetSignalStopSource();
105
+
106
+ /// EXPERIMENTAL: Register signal handler triggering the signal-receiving StopSource
107
+ ///
108
+ /// Note that those handlers are automatically un-registered in a fork()ed process,
109
+ /// therefore the child process will need to call RegisterCancellingSignalHandler()
110
+ /// if desired.
111
+ ARROW_EXPORT
112
+ Status RegisterCancellingSignalHandler(const std::vector<int>& signals);
113
+
114
+ /// EXPERIMENTAL: Unregister signal handler set up by RegisterCancellingSignalHandler
115
+ ARROW_EXPORT
116
+ void UnregisterCancellingSignalHandler();
117
+
118
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/compare.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <type_traits>
22
+ #include <utility>
23
+
24
+ #include "arrow/util/macros.h"
25
+
26
+ namespace arrow {
27
+ namespace util {
28
+
29
+ /// CRTP helper for declaring equality comparison. Defines operator== and operator!=
30
+ template <typename T>
31
+ class EqualityComparable {
32
+ public:
33
+ ~EqualityComparable() {
34
+ static_assert(
35
+ std::is_same<decltype(std::declval<const T>().Equals(std::declval<const T>())),
36
+ bool>::value,
37
+ "EqualityComparable depends on the method T::Equals(const T&) const");
38
+ }
39
+
40
+ template <typename... Extra>
41
+ bool Equals(const std::shared_ptr<T>& other, Extra&&... extra) const {
42
+ if (other == NULLPTR) {
43
+ return false;
44
+ }
45
+ return cast().Equals(*other, std::forward<Extra>(extra)...);
46
+ }
47
+
48
+ struct PtrsEqual {
49
+ bool operator()(const std::shared_ptr<T>& l, const std::shared_ptr<T>& r) const {
50
+ return l->Equals(*r);
51
+ }
52
+ };
53
+
54
+ friend bool operator==(T const& a, T const& b) { return a.Equals(b); }
55
+ friend bool operator!=(T const& a, T const& b) { return !(a == b); }
56
+
57
+ private:
58
+ const T& cast() const { return static_cast<const T&>(*this); }
59
+ };
60
+
61
+ } // namespace util
62
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/compression.h ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <optional>
24
+ #include <string>
25
+
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/util/type_fwd.h"
29
+ #include "arrow/util/visibility.h"
30
+
31
+ namespace arrow {
32
+ namespace util {
33
+
34
+ constexpr int kUseDefaultCompressionLevel = std::numeric_limits<int>::min();
35
+
36
+ /// \brief Streaming compressor interface
37
+ ///
38
+ class ARROW_EXPORT Compressor {
39
+ public:
40
+ virtual ~Compressor() = default;
41
+
42
+ struct CompressResult {
43
+ int64_t bytes_read;
44
+ int64_t bytes_written;
45
+ };
46
+ struct FlushResult {
47
+ int64_t bytes_written;
48
+ bool should_retry;
49
+ };
50
+ struct EndResult {
51
+ int64_t bytes_written;
52
+ bool should_retry;
53
+ };
54
+
55
+ /// \brief Compress some input.
56
+ ///
57
+ /// If bytes_read is 0 on return, then a larger output buffer should be supplied.
58
+ virtual Result<CompressResult> Compress(int64_t input_len, const uint8_t* input,
59
+ int64_t output_len, uint8_t* output) = 0;
60
+
61
+ /// \brief Flush part of the compressed output.
62
+ ///
63
+ /// If should_retry is true on return, Flush() should be called again
64
+ /// with a larger buffer.
65
+ virtual Result<FlushResult> Flush(int64_t output_len, uint8_t* output) = 0;
66
+
67
+ /// \brief End compressing, doing whatever is necessary to end the stream.
68
+ ///
69
+ /// If should_retry is true on return, End() should be called again
70
+ /// with a larger buffer. Otherwise, the Compressor should not be used anymore.
71
+ ///
72
+ /// End() implies Flush().
73
+ virtual Result<EndResult> End(int64_t output_len, uint8_t* output) = 0;
74
+
75
+ // XXX add methods for buffer size heuristics?
76
+ };
77
+
78
+ /// \brief Streaming decompressor interface
79
+ ///
80
+ class ARROW_EXPORT Decompressor {
81
+ public:
82
+ virtual ~Decompressor() = default;
83
+
84
+ struct DecompressResult {
85
+ // XXX is need_more_output necessary? (Brotli?)
86
+ int64_t bytes_read;
87
+ int64_t bytes_written;
88
+ bool need_more_output;
89
+ };
90
+
91
+ /// \brief Decompress some input.
92
+ ///
93
+ /// If need_more_output is true on return, a larger output buffer needs
94
+ /// to be supplied.
95
+ virtual Result<DecompressResult> Decompress(int64_t input_len, const uint8_t* input,
96
+ int64_t output_len, uint8_t* output) = 0;
97
+
98
+ /// \brief Return whether the compressed stream is finished.
99
+ ///
100
+ /// This is a heuristic. If true is returned, then it is guaranteed
101
+ /// that the stream is finished. If false is returned, however, it may
102
+ /// simply be that the underlying library isn't able to provide the information.
103
+ virtual bool IsFinished() = 0;
104
+
105
+ /// \brief Reinitialize decompressor, making it ready for a new compressed stream.
106
+ virtual Status Reset() = 0;
107
+
108
+ // XXX add methods for buffer size heuristics?
109
+ };
110
+
111
+ /// \brief Compression codec options
112
+ class ARROW_EXPORT CodecOptions {
113
+ public:
114
+ explicit CodecOptions(int compression_level = kUseDefaultCompressionLevel)
115
+ : compression_level(compression_level) {}
116
+
117
+ virtual ~CodecOptions() = default;
118
+
119
+ int compression_level;
120
+ };
121
+
122
+ // ----------------------------------------------------------------------
123
+ // GZip codec options implementation
124
+
125
+ enum class GZipFormat {
126
+ ZLIB,
127
+ DEFLATE,
128
+ GZIP,
129
+ };
130
+
131
+ class ARROW_EXPORT GZipCodecOptions : public CodecOptions {
132
+ public:
133
+ GZipFormat gzip_format = GZipFormat::GZIP;
134
+ std::optional<int> window_bits;
135
+ };
136
+
137
+ // ----------------------------------------------------------------------
138
+ // brotli codec options implementation
139
+
140
+ class ARROW_EXPORT BrotliCodecOptions : public CodecOptions {
141
+ public:
142
+ std::optional<int> window_bits;
143
+ };
144
+
145
+ /// \brief Compression codec
146
+ class ARROW_EXPORT Codec {
147
+ public:
148
+ virtual ~Codec() = default;
149
+
150
+ /// \brief Return special value to indicate that a codec implementation
151
+ /// should use its default compression level
152
+ static int UseDefaultCompressionLevel();
153
+
154
+ /// \brief Return a string name for compression type
155
+ static const std::string& GetCodecAsString(Compression::type t);
156
+
157
+ /// \brief Return compression type for name (all lower case)
158
+ static Result<Compression::type> GetCompressionType(const std::string& name);
159
+
160
+ /// \brief Create a codec for the given compression algorithm with CodecOptions
161
+ static Result<std::unique_ptr<Codec>> Create(
162
+ Compression::type codec, const CodecOptions& codec_options = CodecOptions{});
163
+
164
+ /// \brief Create a codec for the given compression algorithm
165
+ static Result<std::unique_ptr<Codec>> Create(Compression::type codec,
166
+ int compression_level);
167
+
168
+ /// \brief Return true if support for indicated codec has been enabled
169
+ static bool IsAvailable(Compression::type codec);
170
+
171
+ /// \brief Return true if indicated codec supports setting a compression level
172
+ static bool SupportsCompressionLevel(Compression::type codec);
173
+
174
+ /// \brief Return the smallest supported compression level for the codec
175
+ /// Note: This function creates a temporary Codec instance
176
+ static Result<int> MinimumCompressionLevel(Compression::type codec);
177
+
178
+ /// \brief Return the largest supported compression level for the codec
179
+ /// Note: This function creates a temporary Codec instance
180
+ static Result<int> MaximumCompressionLevel(Compression::type codec);
181
+
182
+ /// \brief Return the default compression level
183
+ /// Note: This function creates a temporary Codec instance
184
+ static Result<int> DefaultCompressionLevel(Compression::type codec);
185
+
186
+ /// \brief Return the smallest supported compression level
187
+ virtual int minimum_compression_level() const = 0;
188
+
189
+ /// \brief Return the largest supported compression level
190
+ virtual int maximum_compression_level() const = 0;
191
+
192
+ /// \brief Return the default compression level
193
+ virtual int default_compression_level() const = 0;
194
+
195
+ /// \brief One-shot decompression function
196
+ ///
197
+ /// output_buffer_len must be correct and therefore be obtained in advance.
198
+ /// The actual decompressed length is returned.
199
+ ///
200
+ /// \note One-shot decompression is not always compatible with streaming
201
+ /// compression. Depending on the codec (e.g. LZ4), different formats may
202
+ /// be used.
203
+ virtual Result<int64_t> Decompress(int64_t input_len, const uint8_t* input,
204
+ int64_t output_buffer_len,
205
+ uint8_t* output_buffer) = 0;
206
+
207
+ /// \brief One-shot compression function
208
+ ///
209
+ /// output_buffer_len must first have been computed using MaxCompressedLen().
210
+ /// The actual compressed length is returned.
211
+ ///
212
+ /// \note One-shot compression is not always compatible with streaming
213
+ /// decompression. Depending on the codec (e.g. LZ4), different formats may
214
+ /// be used.
215
+ virtual Result<int64_t> Compress(int64_t input_len, const uint8_t* input,
216
+ int64_t output_buffer_len, uint8_t* output_buffer) = 0;
217
+
218
+ virtual int64_t MaxCompressedLen(int64_t input_len, const uint8_t* input) = 0;
219
+
220
+ /// \brief Create a streaming compressor instance
221
+ virtual Result<std::shared_ptr<Compressor>> MakeCompressor() = 0;
222
+
223
+ /// \brief Create a streaming compressor instance
224
+ virtual Result<std::shared_ptr<Decompressor>> MakeDecompressor() = 0;
225
+
226
+ /// \brief This Codec's compression type
227
+ virtual Compression::type compression_type() const = 0;
228
+
229
+ /// \brief The name of this Codec's compression type
230
+ const std::string& name() const { return GetCodecAsString(compression_type()); }
231
+
232
+ /// \brief This Codec's compression level, if applicable
233
+ virtual int compression_level() const { return UseDefaultCompressionLevel(); }
234
+
235
+ private:
236
+ /// \brief Initializes the codec's resources.
237
+ virtual Status Init();
238
+ };
239
+
240
+ } // namespace util
241
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/concurrent_map.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 <unordered_map>
21
+ #include <utility>
22
+
23
+ #include "arrow/util/mutex.h"
24
+
25
+ namespace arrow {
26
+ namespace util {
27
+
28
+ template <typename K, typename V>
29
+ class ConcurrentMap {
30
+ public:
31
+ void Insert(const K& key, const V& value) {
32
+ auto lock = mutex_.Lock();
33
+ map_.insert({key, value});
34
+ }
35
+
36
+ template <typename ValueFunc>
37
+ V GetOrInsert(const K& key, ValueFunc&& compute_value_func) {
38
+ auto lock = mutex_.Lock();
39
+ auto it = map_.find(key);
40
+ if (it == map_.end()) {
41
+ auto pair = map_.emplace(key, compute_value_func());
42
+ it = pair.first;
43
+ }
44
+ return it->second;
45
+ }
46
+
47
+ void Erase(const K& key) {
48
+ auto lock = mutex_.Lock();
49
+ map_.erase(key);
50
+ }
51
+
52
+ void Clear() {
53
+ auto lock = mutex_.Lock();
54
+ map_.clear();
55
+ }
56
+
57
+ size_t size() const {
58
+ auto lock = mutex_.Lock();
59
+ return map_.size();
60
+ }
61
+
62
+ private:
63
+ std::unordered_map<K, V> map_;
64
+ mutable arrow::util::Mutex mutex_;
65
+ };
66
+
67
+ } // namespace util
68
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/config.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #define ARROW_VERSION_MAJOR 16
19
+ #define ARROW_VERSION_MINOR 0
20
+ #define ARROW_VERSION_PATCH 0
21
+ #define ARROW_VERSION ((ARROW_VERSION_MAJOR * 1000) + ARROW_VERSION_MINOR) * 1000 + ARROW_VERSION_PATCH
22
+
23
+ #define ARROW_VERSION_STRING "16.0.0"
24
+
25
+ #define ARROW_SO_VERSION "1600"
26
+ #define ARROW_FULL_SO_VERSION "1600.0.0"
27
+
28
+ #define ARROW_CXX_COMPILER_ID "GNU"
29
+ #define ARROW_CXX_COMPILER_VERSION "12.2.1"
30
+ #define ARROW_CXX_COMPILER_FLAGS " -fdiagnostics-color=always"
31
+
32
+ #define ARROW_BUILD_TYPE "RELEASE"
33
+
34
+ #define ARROW_GIT_ID ""
35
+ #define ARROW_GIT_DESCRIPTION ""
36
+
37
+ #define ARROW_PACKAGE_KIND "python-wheel-manylinux228"
38
+
39
+ #define ARROW_COMPUTE
40
+ #define ARROW_CSV
41
+ /* #undef ARROW_CUDA */
42
+ #define ARROW_DATASET
43
+ #define ARROW_FILESYSTEM
44
+ #define ARROW_FLIGHT
45
+ /* #undef ARROW_FLIGHT_SQL */
46
+ #define ARROW_IPC
47
+ #define ARROW_JEMALLOC
48
+ #define ARROW_JEMALLOC_VENDORED
49
+ #define ARROW_JSON
50
+ #define ARROW_MIMALLOC
51
+ #define ARROW_ORC
52
+ #define ARROW_PARQUET
53
+ #define ARROW_SUBSTRAIT
54
+
55
+ #define ARROW_AZURE
56
+ #define ARROW_ENABLE_THREADING
57
+ #define ARROW_GCS
58
+ #define ARROW_HDFS
59
+ #define ARROW_S3
60
+ /* #undef ARROW_USE_GLOG */
61
+ #define ARROW_USE_NATIVE_INT128
62
+ #define ARROW_WITH_BROTLI
63
+ #define ARROW_WITH_BZ2
64
+ #define ARROW_WITH_LZ4
65
+ /* #undef ARROW_WITH_MUSL */
66
+ /* #undef ARROW_WITH_OPENTELEMETRY */
67
+ #define ARROW_WITH_RE2
68
+ #define ARROW_WITH_SNAPPY
69
+ /* #undef ARROW_WITH_UCX */
70
+ #define ARROW_WITH_UTF8PROC
71
+ #define ARROW_WITH_ZLIB
72
+ #define ARROW_WITH_ZSTD
73
+ #define PARQUET_REQUIRE_ENCRYPTION
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/converter.h ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <memory>
19
+ #include <string>
20
+ #include <utility>
21
+ #include <vector>
22
+
23
+ #include "arrow/array.h"
24
+ #include "arrow/chunked_array.h"
25
+ #include "arrow/status.h"
26
+ #include "arrow/type.h"
27
+ #include "arrow/type_traits.h"
28
+ #include "arrow/util/checked_cast.h"
29
+ #include "arrow/visit_type_inline.h"
30
+
31
+ namespace arrow {
32
+ namespace internal {
33
+
34
+ template <typename BaseConverter, template <typename...> class ConverterTrait>
35
+ static Result<std::unique_ptr<BaseConverter>> MakeConverter(
36
+ std::shared_ptr<DataType> type, typename BaseConverter::OptionsType options,
37
+ MemoryPool* pool);
38
+
39
+ template <typename Input, typename Options>
40
+ class Converter {
41
+ public:
42
+ using Self = Converter<Input, Options>;
43
+ using InputType = Input;
44
+ using OptionsType = Options;
45
+
46
+ virtual ~Converter() = default;
47
+
48
+ Status Construct(std::shared_ptr<DataType> type, OptionsType options,
49
+ MemoryPool* pool) {
50
+ type_ = std::move(type);
51
+ options_ = std::move(options);
52
+ return Init(pool);
53
+ }
54
+
55
+ virtual Status Append(InputType value) { return Status::NotImplemented("Append"); }
56
+
57
+ virtual Status Extend(InputType values, int64_t size, int64_t offset = 0) {
58
+ return Status::NotImplemented("Extend");
59
+ }
60
+
61
+ virtual Status ExtendMasked(InputType values, InputType mask, int64_t size,
62
+ int64_t offset = 0) {
63
+ return Status::NotImplemented("ExtendMasked");
64
+ }
65
+
66
+ const std::shared_ptr<ArrayBuilder>& builder() const { return builder_; }
67
+
68
+ const std::shared_ptr<DataType>& type() const { return type_; }
69
+
70
+ OptionsType options() const { return options_; }
71
+
72
+ bool may_overflow() const { return may_overflow_; }
73
+
74
+ bool rewind_on_overflow() const { return rewind_on_overflow_; }
75
+
76
+ virtual Status Reserve(int64_t additional_capacity) {
77
+ return builder_->Reserve(additional_capacity);
78
+ }
79
+
80
+ Status AppendNull() { return builder_->AppendNull(); }
81
+
82
+ virtual Result<std::shared_ptr<Array>> ToArray() { return builder_->Finish(); }
83
+
84
+ virtual Result<std::shared_ptr<Array>> ToArray(int64_t length) {
85
+ ARROW_ASSIGN_OR_RAISE(auto arr, this->ToArray());
86
+ return arr->Slice(0, length);
87
+ }
88
+
89
+ virtual Result<std::shared_ptr<ChunkedArray>> ToChunkedArray() {
90
+ ARROW_ASSIGN_OR_RAISE(auto array, ToArray());
91
+ std::vector<std::shared_ptr<Array>> chunks = {std::move(array)};
92
+ return std::make_shared<ChunkedArray>(chunks);
93
+ }
94
+
95
+ protected:
96
+ virtual Status Init(MemoryPool* pool) { return Status::OK(); }
97
+
98
+ std::shared_ptr<DataType> type_;
99
+ std::shared_ptr<ArrayBuilder> builder_;
100
+ OptionsType options_;
101
+ bool may_overflow_ = false;
102
+ bool rewind_on_overflow_ = false;
103
+ };
104
+
105
+ template <typename ArrowType, typename BaseConverter>
106
+ class PrimitiveConverter : public BaseConverter {
107
+ public:
108
+ using BuilderType = typename TypeTraits<ArrowType>::BuilderType;
109
+
110
+ protected:
111
+ Status Init(MemoryPool* pool) override {
112
+ this->builder_ = std::make_shared<BuilderType>(this->type_, pool);
113
+ // Narrow variable-sized binary types may overflow
114
+ this->may_overflow_ = is_binary_like(this->type_->id());
115
+ primitive_type_ = checked_cast<const ArrowType*>(this->type_.get());
116
+ primitive_builder_ = checked_cast<BuilderType*>(this->builder_.get());
117
+ return Status::OK();
118
+ }
119
+
120
+ const ArrowType* primitive_type_;
121
+ BuilderType* primitive_builder_;
122
+ };
123
+
124
+ template <typename ArrowType, typename BaseConverter,
125
+ template <typename...> class ConverterTrait>
126
+ class ListConverter : public BaseConverter {
127
+ public:
128
+ using BuilderType = typename TypeTraits<ArrowType>::BuilderType;
129
+ using ConverterType = typename ConverterTrait<ArrowType>::type;
130
+
131
+ protected:
132
+ Status Init(MemoryPool* pool) override {
133
+ list_type_ = checked_cast<const ArrowType*>(this->type_.get());
134
+ ARROW_ASSIGN_OR_RAISE(value_converter_,
135
+ (MakeConverter<BaseConverter, ConverterTrait>(
136
+ list_type_->value_type(), this->options_, pool)));
137
+ this->builder_ =
138
+ std::make_shared<BuilderType>(pool, value_converter_->builder(), this->type_);
139
+ list_builder_ = checked_cast<BuilderType*>(this->builder_.get());
140
+ // Narrow list types may overflow
141
+ this->may_overflow_ = this->rewind_on_overflow_ =
142
+ sizeof(typename ArrowType::offset_type) < sizeof(int64_t);
143
+ return Status::OK();
144
+ }
145
+
146
+ const ArrowType* list_type_;
147
+ BuilderType* list_builder_;
148
+ std::unique_ptr<BaseConverter> value_converter_;
149
+ };
150
+
151
+ template <typename BaseConverter, template <typename...> class ConverterTrait>
152
+ class StructConverter : public BaseConverter {
153
+ public:
154
+ using ConverterType = typename ConverterTrait<StructType>::type;
155
+
156
+ Status Reserve(int64_t additional_capacity) override {
157
+ ARROW_RETURN_NOT_OK(this->builder_->Reserve(additional_capacity));
158
+ for (const auto& child : children_) {
159
+ ARROW_RETURN_NOT_OK(child->Reserve(additional_capacity));
160
+ }
161
+ return Status::OK();
162
+ }
163
+
164
+ protected:
165
+ Status Init(MemoryPool* pool) override {
166
+ std::unique_ptr<BaseConverter> child_converter;
167
+ std::vector<std::shared_ptr<ArrayBuilder>> child_builders;
168
+
169
+ struct_type_ = checked_cast<const StructType*>(this->type_.get());
170
+ for (const auto& field : struct_type_->fields()) {
171
+ ARROW_ASSIGN_OR_RAISE(child_converter,
172
+ (MakeConverter<BaseConverter, ConverterTrait>(
173
+ field->type(), this->options_, pool)));
174
+ this->may_overflow_ |= child_converter->may_overflow();
175
+ this->rewind_on_overflow_ = this->may_overflow_;
176
+ child_builders.push_back(child_converter->builder());
177
+ children_.push_back(std::move(child_converter));
178
+ }
179
+
180
+ this->builder_ =
181
+ std::make_shared<StructBuilder>(this->type_, pool, std::move(child_builders));
182
+ struct_builder_ = checked_cast<StructBuilder*>(this->builder_.get());
183
+
184
+ return Status::OK();
185
+ }
186
+
187
+ const StructType* struct_type_;
188
+ StructBuilder* struct_builder_;
189
+ std::vector<std::unique_ptr<BaseConverter>> children_;
190
+ };
191
+
192
+ template <typename ValueType, typename BaseConverter>
193
+ class DictionaryConverter : public BaseConverter {
194
+ public:
195
+ using BuilderType = DictionaryBuilder<ValueType>;
196
+
197
+ protected:
198
+ Status Init(MemoryPool* pool) override {
199
+ std::unique_ptr<ArrayBuilder> builder;
200
+ ARROW_RETURN_NOT_OK(MakeDictionaryBuilder(pool, this->type_, NULLPTR, &builder));
201
+ this->builder_ = std::move(builder);
202
+ this->may_overflow_ = false;
203
+ dict_type_ = checked_cast<const DictionaryType*>(this->type_.get());
204
+ value_type_ = checked_cast<const ValueType*>(dict_type_->value_type().get());
205
+ value_builder_ = checked_cast<BuilderType*>(this->builder_.get());
206
+ return Status::OK();
207
+ }
208
+
209
+ const DictionaryType* dict_type_;
210
+ const ValueType* value_type_;
211
+ BuilderType* value_builder_;
212
+ };
213
+
214
+ template <typename BaseConverter, template <typename...> class ConverterTrait>
215
+ struct MakeConverterImpl {
216
+ template <typename T, typename ConverterType = typename ConverterTrait<T>::type>
217
+ Status Visit(const T&) {
218
+ out.reset(new ConverterType());
219
+ return out->Construct(std::move(type), std::move(options), pool);
220
+ }
221
+
222
+ Status Visit(const DictionaryType& t) {
223
+ switch (t.value_type()->id()) {
224
+ #define DICTIONARY_CASE(TYPE) \
225
+ case TYPE::type_id: \
226
+ out = std::make_unique< \
227
+ typename ConverterTrait<DictionaryType>::template dictionary_type<TYPE>>(); \
228
+ break;
229
+ DICTIONARY_CASE(BooleanType);
230
+ DICTIONARY_CASE(Int8Type);
231
+ DICTIONARY_CASE(Int16Type);
232
+ DICTIONARY_CASE(Int32Type);
233
+ DICTIONARY_CASE(Int64Type);
234
+ DICTIONARY_CASE(UInt8Type);
235
+ DICTIONARY_CASE(UInt16Type);
236
+ DICTIONARY_CASE(UInt32Type);
237
+ DICTIONARY_CASE(UInt64Type);
238
+ DICTIONARY_CASE(FloatType);
239
+ DICTIONARY_CASE(DoubleType);
240
+ DICTIONARY_CASE(BinaryType);
241
+ DICTIONARY_CASE(StringType);
242
+ DICTIONARY_CASE(FixedSizeBinaryType);
243
+ #undef DICTIONARY_CASE
244
+ default:
245
+ return Status::NotImplemented("DictionaryArray converter for type ", t.ToString(),
246
+ " not implemented");
247
+ }
248
+ return out->Construct(std::move(type), std::move(options), pool);
249
+ }
250
+
251
+ Status Visit(const DataType& t) { return Status::NotImplemented(t.name()); }
252
+
253
+ std::shared_ptr<DataType> type;
254
+ typename BaseConverter::OptionsType options;
255
+ MemoryPool* pool;
256
+ std::unique_ptr<BaseConverter> out;
257
+ };
258
+
259
+ template <typename BaseConverter, template <typename...> class ConverterTrait>
260
+ static Result<std::unique_ptr<BaseConverter>> MakeConverter(
261
+ std::shared_ptr<DataType> type, typename BaseConverter::OptionsType options,
262
+ MemoryPool* pool) {
263
+ MakeConverterImpl<BaseConverter, ConverterTrait> visitor{
264
+ std::move(type), std::move(options), pool, NULLPTR};
265
+ ARROW_RETURN_NOT_OK(VisitTypeInline(*visitor.type, &visitor));
266
+ return std::move(visitor.out);
267
+ }
268
+
269
+ template <typename Converter>
270
+ class Chunker {
271
+ public:
272
+ using InputType = typename Converter::InputType;
273
+
274
+ explicit Chunker(std::unique_ptr<Converter> converter)
275
+ : converter_(std::move(converter)) {}
276
+
277
+ Status Reserve(int64_t additional_capacity) {
278
+ ARROW_RETURN_NOT_OK(converter_->Reserve(additional_capacity));
279
+ reserved_ += additional_capacity;
280
+ return Status::OK();
281
+ }
282
+
283
+ Status AppendNull() {
284
+ auto status = converter_->AppendNull();
285
+ if (ARROW_PREDICT_FALSE(status.IsCapacityError())) {
286
+ if (converter_->builder()->length() == 0) {
287
+ // Builder length == 0 means the individual element is too large to append.
288
+ // In this case, no need to try again.
289
+ return status;
290
+ }
291
+ ARROW_RETURN_NOT_OK(FinishChunk());
292
+ return converter_->AppendNull();
293
+ }
294
+ ++length_;
295
+ return status;
296
+ }
297
+
298
+ Status Append(InputType value) {
299
+ auto status = converter_->Append(value);
300
+ if (ARROW_PREDICT_FALSE(status.IsCapacityError())) {
301
+ if (converter_->builder()->length() == 0) {
302
+ return status;
303
+ }
304
+ ARROW_RETURN_NOT_OK(FinishChunk());
305
+ return Append(value);
306
+ }
307
+ ++length_;
308
+ return status;
309
+ }
310
+
311
+ Status Extend(InputType values, int64_t size, int64_t offset = 0) {
312
+ while (offset < size) {
313
+ auto length_before = converter_->builder()->length();
314
+ auto status = converter_->Extend(values, size, offset);
315
+ auto length_after = converter_->builder()->length();
316
+ auto num_converted = length_after - length_before;
317
+
318
+ offset += num_converted;
319
+ length_ += num_converted;
320
+
321
+ if (status.IsCapacityError()) {
322
+ if (converter_->builder()->length() == 0) {
323
+ // Builder length == 0 means the individual element is too large to append.
324
+ // In this case, no need to try again.
325
+ return status;
326
+ } else if (converter_->rewind_on_overflow()) {
327
+ // The list-like and binary-like conversion paths may raise a capacity error,
328
+ // we need to handle them differently. While the binary-like converters check
329
+ // the capacity before append/extend the list-like converters just check after
330
+ // append/extend. Thus depending on the implementation semantics we may need
331
+ // to rewind (slice) the output chunk by one.
332
+ length_ -= 1;
333
+ offset -= 1;
334
+ }
335
+ ARROW_RETURN_NOT_OK(FinishChunk());
336
+ } else if (!status.ok()) {
337
+ return status;
338
+ }
339
+ }
340
+ return Status::OK();
341
+ }
342
+
343
+ Status ExtendMasked(InputType values, InputType mask, int64_t size,
344
+ int64_t offset = 0) {
345
+ while (offset < size) {
346
+ auto length_before = converter_->builder()->length();
347
+ auto status = converter_->ExtendMasked(values, mask, size, offset);
348
+ auto length_after = converter_->builder()->length();
349
+ auto num_converted = length_after - length_before;
350
+
351
+ offset += num_converted;
352
+ length_ += num_converted;
353
+
354
+ if (status.IsCapacityError()) {
355
+ if (converter_->builder()->length() == 0) {
356
+ // Builder length == 0 means the individual element is too large to append.
357
+ // In this case, no need to try again.
358
+ return status;
359
+ } else if (converter_->rewind_on_overflow()) {
360
+ // The list-like and binary-like conversion paths may raise a capacity error,
361
+ // we need to handle them differently. While the binary-like converters check
362
+ // the capacity before append/extend the list-like converters just check after
363
+ // append/extend. Thus depending on the implementation semantics we may need
364
+ // to rewind (slice) the output chunk by one.
365
+ length_ -= 1;
366
+ offset -= 1;
367
+ }
368
+ ARROW_RETURN_NOT_OK(FinishChunk());
369
+ } else if (!status.ok()) {
370
+ return status;
371
+ }
372
+ }
373
+ return Status::OK();
374
+ }
375
+
376
+ Status FinishChunk() {
377
+ ARROW_ASSIGN_OR_RAISE(auto chunk, converter_->ToArray(length_));
378
+ chunks_.push_back(chunk);
379
+ // Reserve space for the remaining items.
380
+ // Besides being an optimization, it is also required if the converter's
381
+ // implementation relies on unsafe builder methods in converter->Append().
382
+ auto remaining = reserved_ - length_;
383
+ Reset();
384
+ return Reserve(remaining);
385
+ }
386
+
387
+ Result<std::shared_ptr<ChunkedArray>> ToChunkedArray() {
388
+ ARROW_RETURN_NOT_OK(FinishChunk());
389
+ return std::make_shared<ChunkedArray>(chunks_);
390
+ }
391
+
392
+ protected:
393
+ void Reset() {
394
+ converter_->builder()->Reset();
395
+ length_ = 0;
396
+ reserved_ = 0;
397
+ }
398
+
399
+ int64_t length_ = 0;
400
+ int64_t reserved_ = 0;
401
+ std::unique_ptr<Converter> converter_;
402
+ std::vector<std::shared_ptr<Array>> chunks_;
403
+ };
404
+
405
+ template <typename T>
406
+ static Result<std::unique_ptr<Chunker<T>>> MakeChunker(std::unique_ptr<T> converter) {
407
+ return std::make_unique<Chunker<T>>(std::move(converter));
408
+ }
409
+
410
+ } // namespace internal
411
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/counting_semaphore.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef ARROW_COUNTING_SEMAPHORE_H
19
+ #define ARROW_COUNTING_SEMAPHORE_H
20
+
21
+ #include <memory>
22
+
23
+ #include "arrow/status.h"
24
+
25
+ namespace arrow {
26
+ namespace util {
27
+
28
+ /// \brief Simple mutex-based counting semaphore with timeout
29
+ class ARROW_EXPORT CountingSemaphore {
30
+ public:
31
+ /// \brief Create an instance with initial_avail starting permits
32
+ ///
33
+ /// \param[in] initial_avail The semaphore will start with this many permits available
34
+ /// \param[in] timeout_seconds A timeout to be applied to all operations. Operations
35
+ /// will return Status::Invalid if this timeout elapses
36
+ explicit CountingSemaphore(uint32_t initial_avail = 0, double timeout_seconds = 10);
37
+ ~CountingSemaphore();
38
+ /// \brief Block until num_permits permits are available
39
+ Status Acquire(uint32_t num_permits);
40
+ /// \brief Make num_permits permits available
41
+ Status Release(uint32_t num_permits);
42
+ /// \brief Wait until num_waiters are waiting on permits
43
+ ///
44
+ /// This method is non-standard but useful in unit tests to ensure sequencing
45
+ Status WaitForWaiters(uint32_t num_waiters);
46
+ /// \brief Immediately time out any waiters
47
+ ///
48
+ /// This method will return Status::OK only if there were no waiters to time out.
49
+ /// Once closed any operation on this instance will return an invalid status.
50
+ Status Close();
51
+
52
+ private:
53
+ class Impl;
54
+ std::unique_ptr<Impl> impl_;
55
+ };
56
+
57
+ } // namespace util
58
+ } // namespace arrow
59
+
60
+ #endif // ARROW_COUNTING_SEMAPHORE_H
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/debug.h ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/util/visibility.h"
21
+
22
+ namespace arrow {
23
+ namespace internal {
24
+
25
+ ARROW_EXPORT
26
+ void DebugTrap();
27
+
28
+ } // namespace internal
29
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/decimal.h ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <limits>
23
+ #include <string>
24
+ #include <string_view>
25
+ #include <utility>
26
+
27
+ #include "arrow/result.h"
28
+ #include "arrow/status.h"
29
+ #include "arrow/type_fwd.h"
30
+ #include "arrow/util/basic_decimal.h"
31
+
32
+ namespace arrow {
33
+
34
+ /// Represents a signed 128-bit integer in two's complement.
35
+ /// Calculations wrap around and overflow is ignored.
36
+ /// The max decimal precision that can be safely represented is
37
+ /// 38 significant digits.
38
+ ///
39
+ /// For a discussion of the algorithms, look at Knuth's volume 2,
40
+ /// Semi-numerical Algorithms section 4.3.1.
41
+ ///
42
+ /// Adapted from the Apache ORC C++ implementation
43
+ ///
44
+ /// The implementation is split into two parts :
45
+ ///
46
+ /// 1. BasicDecimal128
47
+ /// - can be safely compiled to IR without references to libstdc++.
48
+ /// 2. Decimal128
49
+ /// - has additional functionality on top of BasicDecimal128 to deal with
50
+ /// strings and streams.
51
+ class ARROW_EXPORT Decimal128 : public BasicDecimal128 {
52
+ public:
53
+ /// \cond FALSE
54
+ // (need to avoid a duplicate definition in Sphinx)
55
+ using BasicDecimal128::BasicDecimal128;
56
+ /// \endcond
57
+
58
+ /// \brief constructor creates a Decimal128 from a BasicDecimal128.
59
+ constexpr Decimal128(const BasicDecimal128& value) noexcept // NOLINT runtime/explicit
60
+ : BasicDecimal128(value) {}
61
+
62
+ /// \brief Parse the number from a base 10 string representation.
63
+ explicit Decimal128(const std::string& value);
64
+
65
+ /// \brief Empty constructor creates a Decimal128 with a value of 0.
66
+ // This is required on some older compilers.
67
+ constexpr Decimal128() noexcept : BasicDecimal128() {}
68
+
69
+ /// Divide this number by right and return the result.
70
+ ///
71
+ /// This operation is not destructive.
72
+ /// The answer rounds to zero. Signs work like:
73
+ /// 21 / 5 -> 4, 1
74
+ /// -21 / 5 -> -4, -1
75
+ /// 21 / -5 -> -4, 1
76
+ /// -21 / -5 -> 4, -1
77
+ /// \param[in] divisor the number to divide by
78
+ /// \return the pair of the quotient and the remainder
79
+ Result<std::pair<Decimal128, Decimal128>> Divide(const Decimal128& divisor) const {
80
+ std::pair<Decimal128, Decimal128> result;
81
+ auto dstatus = BasicDecimal128::Divide(divisor, &result.first, &result.second);
82
+ ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus));
83
+ return std::move(result);
84
+ }
85
+
86
+ /// \brief Convert the Decimal128 value to a base 10 decimal string with the given
87
+ /// scale.
88
+ std::string ToString(int32_t scale) const;
89
+
90
+ /// \brief Convert the value to an integer string
91
+ std::string ToIntegerString() const;
92
+
93
+ /// \brief Cast this value to an int64_t.
94
+ explicit operator int64_t() const;
95
+
96
+ /// \brief Convert a decimal string to a Decimal128 value, optionally including
97
+ /// precision and scale if they're passed in and not null.
98
+ static Status FromString(std::string_view s, Decimal128* out, int32_t* precision,
99
+ int32_t* scale = NULLPTR);
100
+ static Status FromString(const std::string& s, Decimal128* out, int32_t* precision,
101
+ int32_t* scale = NULLPTR);
102
+ static Status FromString(const char* s, Decimal128* out, int32_t* precision,
103
+ int32_t* scale = NULLPTR);
104
+ static Result<Decimal128> FromString(std::string_view s);
105
+ static Result<Decimal128> FromString(const std::string& s);
106
+ static Result<Decimal128> FromString(const char* s);
107
+
108
+ static Result<Decimal128> FromReal(double real, int32_t precision, int32_t scale);
109
+ static Result<Decimal128> FromReal(float real, int32_t precision, int32_t scale);
110
+
111
+ /// \brief Convert from a big-endian byte representation. The length must be
112
+ /// between 1 and 16.
113
+ /// \return error status if the length is an invalid value
114
+ static Result<Decimal128> FromBigEndian(const uint8_t* data, int32_t length);
115
+
116
+ /// \brief Convert Decimal128 from one scale to another
117
+ Result<Decimal128> Rescale(int32_t original_scale, int32_t new_scale) const {
118
+ Decimal128 out;
119
+ auto dstatus = BasicDecimal128::Rescale(original_scale, new_scale, &out);
120
+ ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus));
121
+ return std::move(out);
122
+ }
123
+
124
+ /// \brief Convert to a signed integer
125
+ template <typename T, typename = internal::EnableIfIsOneOf<T, int32_t, int64_t>>
126
+ Result<T> ToInteger() const {
127
+ constexpr auto min_value = std::numeric_limits<T>::min();
128
+ constexpr auto max_value = std::numeric_limits<T>::max();
129
+ const auto& self = *this;
130
+ if (self < min_value || self > max_value) {
131
+ return Status::Invalid("Invalid cast from Decimal128 to ", sizeof(T),
132
+ " byte integer");
133
+ }
134
+ return static_cast<T>(low_bits());
135
+ }
136
+
137
+ /// \brief Convert to a signed integer
138
+ template <typename T, typename = internal::EnableIfIsOneOf<T, int32_t, int64_t>>
139
+ Status ToInteger(T* out) const {
140
+ return ToInteger<T>().Value(out);
141
+ }
142
+
143
+ /// \brief Convert to a floating-point number (scaled)
144
+ float ToFloat(int32_t scale) const;
145
+ /// \brief Convert to a floating-point number (scaled)
146
+ double ToDouble(int32_t scale) const;
147
+
148
+ /// \brief Convert to a floating-point number (scaled)
149
+ template <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
150
+ T ToReal(int32_t scale) const {
151
+ static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>,
152
+ "Unexpected floating-point type");
153
+ if constexpr (std::is_same_v<T, float>) {
154
+ return ToFloat(scale);
155
+ } else {
156
+ return ToDouble(scale);
157
+ }
158
+ }
159
+
160
+ ARROW_FRIEND_EXPORT friend std::ostream& operator<<(std::ostream& os,
161
+ const Decimal128& decimal);
162
+
163
+ private:
164
+ /// Converts internal error code to Status
165
+ Status ToArrowStatus(DecimalStatus dstatus) const;
166
+ };
167
+
168
+ /// Represents a signed 256-bit integer in two's complement.
169
+ /// The max decimal precision that can be safely represented is
170
+ /// 76 significant digits.
171
+ ///
172
+ /// The implementation is split into two parts :
173
+ ///
174
+ /// 1. BasicDecimal256
175
+ /// - can be safely compiled to IR without references to libstdc++.
176
+ /// 2. Decimal256
177
+ /// - (TODO) has additional functionality on top of BasicDecimal256 to deal with
178
+ /// strings and streams.
179
+ class ARROW_EXPORT Decimal256 : public BasicDecimal256 {
180
+ public:
181
+ /// \cond FALSE
182
+ // (need to avoid a duplicate definition in Sphinx)
183
+ using BasicDecimal256::BasicDecimal256;
184
+ /// \endcond
185
+
186
+ /// \brief constructor creates a Decimal256 from a BasicDecimal256.
187
+ constexpr Decimal256(const BasicDecimal256& value) noexcept // NOLINT(runtime/explicit)
188
+ : BasicDecimal256(value) {}
189
+
190
+ /// \brief Parse the number from a base 10 string representation.
191
+ explicit Decimal256(const std::string& value);
192
+
193
+ /// \brief Empty constructor creates a Decimal256 with a value of 0.
194
+ // This is required on some older compilers.
195
+ constexpr Decimal256() noexcept : BasicDecimal256() {}
196
+
197
+ /// \brief Convert the Decimal256 value to a base 10 decimal string with the given
198
+ /// scale.
199
+ std::string ToString(int32_t scale) const;
200
+
201
+ /// \brief Convert the value to an integer string
202
+ std::string ToIntegerString() const;
203
+
204
+ /// \brief Convert a decimal string to a Decimal256 value, optionally including
205
+ /// precision and scale if they're passed in and not null.
206
+ static Status FromString(std::string_view s, Decimal256* out, int32_t* precision,
207
+ int32_t* scale = NULLPTR);
208
+ static Status FromString(const std::string& s, Decimal256* out, int32_t* precision,
209
+ int32_t* scale = NULLPTR);
210
+ static Status FromString(const char* s, Decimal256* out, int32_t* precision,
211
+ int32_t* scale = NULLPTR);
212
+ static Result<Decimal256> FromString(std::string_view s);
213
+ static Result<Decimal256> FromString(const std::string& s);
214
+ static Result<Decimal256> FromString(const char* s);
215
+
216
+ /// \brief Convert Decimal256 from one scale to another
217
+ Result<Decimal256> Rescale(int32_t original_scale, int32_t new_scale) const {
218
+ Decimal256 out;
219
+ auto dstatus = BasicDecimal256::Rescale(original_scale, new_scale, &out);
220
+ ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus));
221
+ return std::move(out);
222
+ }
223
+
224
+ /// Divide this number by right and return the result.
225
+ ///
226
+ /// This operation is not destructive.
227
+ /// The answer rounds to zero. Signs work like:
228
+ /// 21 / 5 -> 4, 1
229
+ /// -21 / 5 -> -4, -1
230
+ /// 21 / -5 -> -4, 1
231
+ /// -21 / -5 -> 4, -1
232
+ /// \param[in] divisor the number to divide by
233
+ /// \return the pair of the quotient and the remainder
234
+ Result<std::pair<Decimal256, Decimal256>> Divide(const Decimal256& divisor) const {
235
+ std::pair<Decimal256, Decimal256> result;
236
+ auto dstatus = BasicDecimal256::Divide(divisor, &result.first, &result.second);
237
+ ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus));
238
+ return std::move(result);
239
+ }
240
+
241
+ /// \brief Convert from a big-endian byte representation. The length must be
242
+ /// between 1 and 32.
243
+ /// \return error status if the length is an invalid value
244
+ static Result<Decimal256> FromBigEndian(const uint8_t* data, int32_t length);
245
+
246
+ static Result<Decimal256> FromReal(double real, int32_t precision, int32_t scale);
247
+ static Result<Decimal256> FromReal(float real, int32_t precision, int32_t scale);
248
+
249
+ /// \brief Convert to a floating-point number (scaled).
250
+ /// May return infinity in case of overflow.
251
+ float ToFloat(int32_t scale) const;
252
+ /// \brief Convert to a floating-point number (scaled)
253
+ double ToDouble(int32_t scale) const;
254
+
255
+ /// \brief Convert to a floating-point number (scaled)
256
+ template <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
257
+ T ToReal(int32_t scale) const {
258
+ static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>,
259
+ "Unexpected floating-point type");
260
+ if constexpr (std::is_same_v<T, float>) {
261
+ return ToFloat(scale);
262
+ } else {
263
+ return ToDouble(scale);
264
+ }
265
+ }
266
+
267
+ ARROW_FRIEND_EXPORT friend std::ostream& operator<<(std::ostream& os,
268
+ const Decimal256& decimal);
269
+
270
+ private:
271
+ /// Converts internal error code to Status
272
+ Status ToArrowStatus(DecimalStatus dstatus) const;
273
+ };
274
+
275
+ /// For an integer type, return the max number of decimal digits
276
+ /// (=minimal decimal precision) it can represent.
277
+ inline Result<int32_t> MaxDecimalDigitsForInteger(Type::type type_id) {
278
+ switch (type_id) {
279
+ case Type::INT8:
280
+ case Type::UINT8:
281
+ return 3;
282
+ case Type::INT16:
283
+ case Type::UINT16:
284
+ return 5;
285
+ case Type::INT32:
286
+ case Type::UINT32:
287
+ return 10;
288
+ case Type::INT64:
289
+ return 19;
290
+ case Type::UINT64:
291
+ return 20;
292
+ default:
293
+ break;
294
+ }
295
+ return Status::Invalid("Not an integer type: ", type_id);
296
+ }
297
+
298
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/formatting.h ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 is a private header for number-to-string formatting utilities
19
+
20
+ #pragma once
21
+
22
+ #include <array>
23
+ #include <cassert>
24
+ #include <chrono>
25
+ #include <limits>
26
+ #include <memory>
27
+ #include <string>
28
+ #include <string_view>
29
+ #include <type_traits>
30
+ #include <utility>
31
+
32
+ #include "arrow/status.h"
33
+ #include "arrow/type.h"
34
+ #include "arrow/type_traits.h"
35
+ #include "arrow/util/double_conversion.h"
36
+ #include "arrow/util/macros.h"
37
+ #include "arrow/util/string.h"
38
+ #include "arrow/util/time.h"
39
+ #include "arrow/util/visibility.h"
40
+ #include "arrow/vendored/datetime.h"
41
+
42
+ namespace arrow {
43
+ namespace internal {
44
+
45
+ /// \brief The entry point for conversion to strings.
46
+ template <typename ARROW_TYPE, typename Enable = void>
47
+ class StringFormatter;
48
+
49
+ template <typename T>
50
+ struct is_formattable {
51
+ template <typename U, typename = typename StringFormatter<U>::value_type>
52
+ static std::true_type Test(U*);
53
+
54
+ template <typename U>
55
+ static std::false_type Test(...);
56
+
57
+ static constexpr bool value = decltype(Test<T>(NULLPTR))::value;
58
+ };
59
+
60
+ template <typename T, typename R = void>
61
+ using enable_if_formattable = enable_if_t<is_formattable<T>::value, R>;
62
+
63
+ template <typename Appender>
64
+ using Return = decltype(std::declval<Appender>()(std::string_view{}));
65
+
66
+ /////////////////////////////////////////////////////////////////////////
67
+ // Boolean formatting
68
+
69
+ template <>
70
+ class StringFormatter<BooleanType> {
71
+ public:
72
+ explicit StringFormatter(const DataType* = NULLPTR) {}
73
+
74
+ using value_type = bool;
75
+
76
+ template <typename Appender>
77
+ Return<Appender> operator()(bool value, Appender&& append) {
78
+ if (value) {
79
+ const char string[] = "true";
80
+ return append(std::string_view(string));
81
+ } else {
82
+ const char string[] = "false";
83
+ return append(std::string_view(string));
84
+ }
85
+ }
86
+ };
87
+
88
+ /////////////////////////////////////////////////////////////////////////
89
+ // Decimals formatting
90
+
91
+ template <typename ARROW_TYPE>
92
+ class DecimalToStringFormatterMixin {
93
+ public:
94
+ explicit DecimalToStringFormatterMixin(const DataType* type)
95
+ : scale_(static_cast<const ARROW_TYPE*>(type)->scale()) {}
96
+
97
+ using value_type = typename TypeTraits<ARROW_TYPE>::CType;
98
+
99
+ template <typename Appender>
100
+ Return<Appender> operator()(const value_type& value, Appender&& append) {
101
+ return append(value.ToString(scale_));
102
+ }
103
+
104
+ private:
105
+ int32_t scale_;
106
+ };
107
+
108
+ template <>
109
+ class StringFormatter<Decimal128Type>
110
+ : public DecimalToStringFormatterMixin<Decimal128Type> {
111
+ using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin;
112
+ };
113
+
114
+ template <>
115
+ class StringFormatter<Decimal256Type>
116
+ : public DecimalToStringFormatterMixin<Decimal256Type> {
117
+ using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin;
118
+ };
119
+
120
+ /////////////////////////////////////////////////////////////////////////
121
+ // Integer formatting
122
+
123
+ namespace detail {
124
+
125
+ // A 2x100 direct table mapping integers in [0..99] to their decimal representations.
126
+ ARROW_EXPORT extern const char digit_pairs[];
127
+
128
+ // Based on fmtlib's format_int class:
129
+ // Write digits from right to left into a stack allocated buffer.
130
+ // \pre *cursor points to the byte after the one that will be written.
131
+ // \post *cursor points to the byte that was written.
132
+ inline void FormatOneChar(char c, char** cursor) { *(--(*cursor)) = c; }
133
+
134
+ template <typename Int>
135
+ void FormatOneDigit(Int value, char** cursor) {
136
+ assert(value >= 0 && value <= 9);
137
+ FormatOneChar(static_cast<char>('0' + value), cursor);
138
+ }
139
+
140
+ // GH-35662: I don't know why but the following combination causes SEGV:
141
+ // * template implementation without inline
142
+ // * MinGW
143
+ // * Release build
144
+ template <typename Int>
145
+ inline void FormatTwoDigits(Int value, char** cursor) {
146
+ assert(value >= 0 && value <= 99);
147
+ auto digit_pair = &digit_pairs[value * 2];
148
+ FormatOneChar(digit_pair[1], cursor);
149
+ FormatOneChar(digit_pair[0], cursor);
150
+ }
151
+
152
+ template <typename Int>
153
+ void FormatAllDigits(Int value, char** cursor) {
154
+ assert(value >= 0);
155
+ while (value >= 100) {
156
+ FormatTwoDigits(value % 100, cursor);
157
+ value /= 100;
158
+ }
159
+
160
+ if (value >= 10) {
161
+ FormatTwoDigits(value, cursor);
162
+ } else {
163
+ FormatOneDigit(value, cursor);
164
+ }
165
+ }
166
+
167
+ template <typename Int>
168
+ void FormatAllDigitsLeftPadded(Int value, size_t pad, char pad_char, char** cursor) {
169
+ auto end = *cursor - pad;
170
+ FormatAllDigits(value, cursor);
171
+ while (*cursor > end) {
172
+ FormatOneChar(pad_char, cursor);
173
+ }
174
+ }
175
+
176
+ template <size_t BUFFER_SIZE>
177
+ std::string_view ViewDigitBuffer(const std::array<char, BUFFER_SIZE>& buffer,
178
+ char* cursor) {
179
+ auto buffer_end = buffer.data() + BUFFER_SIZE;
180
+ return {cursor, static_cast<size_t>(buffer_end - cursor)};
181
+ }
182
+
183
+ template <typename Int, typename UInt = typename std::make_unsigned<Int>::type>
184
+ constexpr UInt Abs(Int value) {
185
+ return value < 0 ? ~static_cast<UInt>(value) + 1 : static_cast<UInt>(value);
186
+ }
187
+
188
+ template <typename Int>
189
+ constexpr size_t Digits10(Int value) {
190
+ return value <= 9 ? 1 : Digits10(value / 10) + 1;
191
+ }
192
+
193
+ } // namespace detail
194
+
195
+ template <typename ARROW_TYPE>
196
+ class IntToStringFormatterMixin {
197
+ public:
198
+ explicit IntToStringFormatterMixin(const DataType* = NULLPTR) {}
199
+
200
+ using value_type = typename ARROW_TYPE::c_type;
201
+
202
+ template <typename Appender>
203
+ Return<Appender> operator()(value_type value, Appender&& append) {
204
+ constexpr size_t buffer_size =
205
+ detail::Digits10(std::numeric_limits<value_type>::max()) + 1;
206
+
207
+ std::array<char, buffer_size> buffer;
208
+ char* cursor = buffer.data() + buffer_size;
209
+ detail::FormatAllDigits(detail::Abs(value), &cursor);
210
+ if (value < 0) {
211
+ detail::FormatOneChar('-', &cursor);
212
+ }
213
+ return append(detail::ViewDigitBuffer(buffer, cursor));
214
+ }
215
+ };
216
+
217
+ template <>
218
+ class StringFormatter<Int8Type> : public IntToStringFormatterMixin<Int8Type> {
219
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
220
+ };
221
+
222
+ template <>
223
+ class StringFormatter<Int16Type> : public IntToStringFormatterMixin<Int16Type> {
224
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
225
+ };
226
+
227
+ template <>
228
+ class StringFormatter<Int32Type> : public IntToStringFormatterMixin<Int32Type> {
229
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
230
+ };
231
+
232
+ template <>
233
+ class StringFormatter<Int64Type> : public IntToStringFormatterMixin<Int64Type> {
234
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
235
+ };
236
+
237
+ template <>
238
+ class StringFormatter<UInt8Type> : public IntToStringFormatterMixin<UInt8Type> {
239
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
240
+ };
241
+
242
+ template <>
243
+ class StringFormatter<UInt16Type> : public IntToStringFormatterMixin<UInt16Type> {
244
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
245
+ };
246
+
247
+ template <>
248
+ class StringFormatter<UInt32Type> : public IntToStringFormatterMixin<UInt32Type> {
249
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
250
+ };
251
+
252
+ template <>
253
+ class StringFormatter<UInt64Type> : public IntToStringFormatterMixin<UInt64Type> {
254
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
255
+ };
256
+
257
+ /////////////////////////////////////////////////////////////////////////
258
+ // Floating-point formatting
259
+
260
+ class ARROW_EXPORT FloatToStringFormatter {
261
+ public:
262
+ FloatToStringFormatter();
263
+ FloatToStringFormatter(int flags, const char* inf_symbol, const char* nan_symbol,
264
+ char exp_character, int decimal_in_shortest_low,
265
+ int decimal_in_shortest_high,
266
+ int max_leading_padding_zeroes_in_precision_mode,
267
+ int max_trailing_padding_zeroes_in_precision_mode);
268
+ ~FloatToStringFormatter();
269
+
270
+ // Returns the number of characters written
271
+ int FormatFloat(float v, char* out_buffer, int out_size);
272
+ int FormatFloat(double v, char* out_buffer, int out_size);
273
+ int FormatFloat(uint16_t v, char* out_buffer, int out_size);
274
+
275
+ protected:
276
+ struct Impl;
277
+ std::unique_ptr<Impl> impl_;
278
+ };
279
+
280
+ template <typename ARROW_TYPE>
281
+ class FloatToStringFormatterMixin : public FloatToStringFormatter {
282
+ public:
283
+ using value_type = typename ARROW_TYPE::c_type;
284
+
285
+ static constexpr int buffer_size = 50;
286
+
287
+ explicit FloatToStringFormatterMixin(const DataType* = NULLPTR) {}
288
+
289
+ FloatToStringFormatterMixin(int flags, const char* inf_symbol, const char* nan_symbol,
290
+ char exp_character, int decimal_in_shortest_low,
291
+ int decimal_in_shortest_high,
292
+ int max_leading_padding_zeroes_in_precision_mode,
293
+ int max_trailing_padding_zeroes_in_precision_mode)
294
+ : FloatToStringFormatter(flags, inf_symbol, nan_symbol, exp_character,
295
+ decimal_in_shortest_low, decimal_in_shortest_high,
296
+ max_leading_padding_zeroes_in_precision_mode,
297
+ max_trailing_padding_zeroes_in_precision_mode) {}
298
+
299
+ template <typename Appender>
300
+ Return<Appender> operator()(value_type value, Appender&& append) {
301
+ char buffer[buffer_size];
302
+ int size = FormatFloat(value, buffer, buffer_size);
303
+ return append(std::string_view(buffer, size));
304
+ }
305
+ };
306
+
307
+ template <>
308
+ class StringFormatter<HalfFloatType> : public FloatToStringFormatterMixin<HalfFloatType> {
309
+ public:
310
+ using FloatToStringFormatterMixin::FloatToStringFormatterMixin;
311
+ };
312
+
313
+ template <>
314
+ class StringFormatter<FloatType> : public FloatToStringFormatterMixin<FloatType> {
315
+ public:
316
+ using FloatToStringFormatterMixin::FloatToStringFormatterMixin;
317
+ };
318
+
319
+ template <>
320
+ class StringFormatter<DoubleType> : public FloatToStringFormatterMixin<DoubleType> {
321
+ public:
322
+ using FloatToStringFormatterMixin::FloatToStringFormatterMixin;
323
+ };
324
+
325
+ /////////////////////////////////////////////////////////////////////////
326
+ // Temporal formatting
327
+
328
+ namespace detail {
329
+
330
+ constexpr size_t BufferSizeYYYY_MM_DD() {
331
+ // "-"? "99999-12-31"
332
+ return 1 + detail::Digits10(99999) + 1 + detail::Digits10(12) + 1 +
333
+ detail::Digits10(31);
334
+ }
335
+
336
+ inline void FormatYYYY_MM_DD(arrow_vendored::date::year_month_day ymd, char** cursor) {
337
+ FormatTwoDigits(static_cast<unsigned>(ymd.day()), cursor);
338
+ FormatOneChar('-', cursor);
339
+ FormatTwoDigits(static_cast<unsigned>(ymd.month()), cursor);
340
+ FormatOneChar('-', cursor);
341
+ auto year = static_cast<int>(ymd.year());
342
+ const auto is_neg_year = year < 0;
343
+ year = std::abs(year);
344
+ assert(year <= 99999);
345
+ FormatTwoDigits(year % 100, cursor);
346
+ year /= 100;
347
+ FormatTwoDigits(year % 100, cursor);
348
+ if (year >= 100) {
349
+ FormatOneDigit(year / 100, cursor);
350
+ }
351
+ if (is_neg_year) {
352
+ FormatOneChar('-', cursor);
353
+ }
354
+ }
355
+
356
+ template <typename Duration>
357
+ constexpr size_t BufferSizeHH_MM_SS() {
358
+ // "23:59:59" ("." "9"+)?
359
+ return detail::Digits10(23) + 1 + detail::Digits10(59) + 1 + detail::Digits10(59) + 1 +
360
+ detail::Digits10(Duration::period::den) - 1;
361
+ }
362
+
363
+ template <typename Duration>
364
+ void FormatHH_MM_SS(arrow_vendored::date::hh_mm_ss<Duration> hms, char** cursor) {
365
+ constexpr size_t subsecond_digits = Digits10(Duration::period::den) - 1;
366
+ if (subsecond_digits != 0) {
367
+ FormatAllDigitsLeftPadded(hms.subseconds().count(), subsecond_digits, '0', cursor);
368
+ FormatOneChar('.', cursor);
369
+ }
370
+ FormatTwoDigits(hms.seconds().count(), cursor);
371
+ FormatOneChar(':', cursor);
372
+ FormatTwoDigits(hms.minutes().count(), cursor);
373
+ FormatOneChar(':', cursor);
374
+ FormatTwoDigits(hms.hours().count(), cursor);
375
+ }
376
+
377
+ // Some out-of-bound datetime values would result in erroneous printing
378
+ // because of silent integer wraparound in the `arrow_vendored::date` library.
379
+ //
380
+ // To avoid such misprinting, we must therefore check the bounds explicitly.
381
+ // The bounds correspond to start of year -32767 and end of year 32767,
382
+ // respectively (-32768 is an invalid year value in `arrow_vendored::date`).
383
+ //
384
+ // Note these values are the same as documented for C++20:
385
+ // https://en.cppreference.com/w/cpp/chrono/year_month_day/operator_days
386
+ template <typename Unit>
387
+ bool IsDateTimeInRange(Unit duration) {
388
+ constexpr Unit kMinIncl =
389
+ std::chrono::duration_cast<Unit>(arrow_vendored::date::days{-12687428});
390
+ constexpr Unit kMaxExcl =
391
+ std::chrono::duration_cast<Unit>(arrow_vendored::date::days{11248738});
392
+ return duration >= kMinIncl && duration < kMaxExcl;
393
+ }
394
+
395
+ // IsDateTimeInRange() specialization for nanoseconds: a 64-bit number of
396
+ // nanoseconds cannot represent years outside of the [-32767, 32767]
397
+ // range, and the {kMinIncl, kMaxExcl} constants above would overflow.
398
+ constexpr bool IsDateTimeInRange(std::chrono::nanoseconds duration) { return true; }
399
+
400
+ template <typename Unit>
401
+ bool IsTimeInRange(Unit duration) {
402
+ constexpr Unit kMinIncl = std::chrono::duration_cast<Unit>(std::chrono::seconds{0});
403
+ constexpr Unit kMaxExcl = std::chrono::duration_cast<Unit>(std::chrono::seconds{86400});
404
+ return duration >= kMinIncl && duration < kMaxExcl;
405
+ }
406
+
407
+ template <typename RawValue, typename Appender>
408
+ Return<Appender> FormatOutOfRange(RawValue&& raw_value, Appender&& append) {
409
+ // XXX locale-sensitive but good enough for now
410
+ std::string formatted = "<value out of range: " + ToChars(raw_value) + ">";
411
+ return append(std::move(formatted));
412
+ }
413
+
414
+ const auto kEpoch = arrow_vendored::date::sys_days{arrow_vendored::date::jan / 1 / 1970};
415
+
416
+ } // namespace detail
417
+
418
+ template <>
419
+ class StringFormatter<DurationType> : public IntToStringFormatterMixin<DurationType> {
420
+ using IntToStringFormatterMixin::IntToStringFormatterMixin;
421
+ };
422
+
423
+ class DateToStringFormatterMixin {
424
+ public:
425
+ explicit DateToStringFormatterMixin(const DataType* = NULLPTR) {}
426
+
427
+ protected:
428
+ template <typename Appender>
429
+ Return<Appender> FormatDays(arrow_vendored::date::days since_epoch, Appender&& append) {
430
+ arrow_vendored::date::sys_days timepoint_days{since_epoch};
431
+
432
+ constexpr size_t buffer_size = detail::BufferSizeYYYY_MM_DD();
433
+
434
+ std::array<char, buffer_size> buffer;
435
+ char* cursor = buffer.data() + buffer_size;
436
+
437
+ detail::FormatYYYY_MM_DD(arrow_vendored::date::year_month_day{timepoint_days},
438
+ &cursor);
439
+ return append(detail::ViewDigitBuffer(buffer, cursor));
440
+ }
441
+ };
442
+
443
+ template <>
444
+ class StringFormatter<Date32Type> : public DateToStringFormatterMixin {
445
+ public:
446
+ using value_type = typename Date32Type::c_type;
447
+
448
+ using DateToStringFormatterMixin::DateToStringFormatterMixin;
449
+
450
+ template <typename Appender>
451
+ Return<Appender> operator()(value_type value, Appender&& append) {
452
+ const auto since_epoch = arrow_vendored::date::days{value};
453
+ if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) {
454
+ return detail::FormatOutOfRange(value, append);
455
+ }
456
+ return FormatDays(since_epoch, std::forward<Appender>(append));
457
+ }
458
+ };
459
+
460
+ template <>
461
+ class StringFormatter<Date64Type> : public DateToStringFormatterMixin {
462
+ public:
463
+ using value_type = typename Date64Type::c_type;
464
+
465
+ using DateToStringFormatterMixin::DateToStringFormatterMixin;
466
+
467
+ template <typename Appender>
468
+ Return<Appender> operator()(value_type value, Appender&& append) {
469
+ const auto since_epoch = std::chrono::milliseconds{value};
470
+ if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) {
471
+ return detail::FormatOutOfRange(value, append);
472
+ }
473
+ return FormatDays(std::chrono::duration_cast<arrow_vendored::date::days>(since_epoch),
474
+ std::forward<Appender>(append));
475
+ }
476
+ };
477
+
478
+ template <>
479
+ class StringFormatter<TimestampType> {
480
+ public:
481
+ using value_type = int64_t;
482
+
483
+ explicit StringFormatter(const DataType* type)
484
+ : unit_(checked_cast<const TimestampType&>(*type).unit()),
485
+ timezone_(checked_cast<const TimestampType&>(*type).timezone()) {}
486
+
487
+ template <typename Duration, typename Appender>
488
+ Return<Appender> operator()(Duration, value_type value, Appender&& append) {
489
+ using arrow_vendored::date::days;
490
+
491
+ const Duration since_epoch{value};
492
+ if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) {
493
+ return detail::FormatOutOfRange(value, append);
494
+ }
495
+
496
+ const auto timepoint = detail::kEpoch + since_epoch;
497
+ // Round days towards zero
498
+ // (the naive approach of using arrow_vendored::date::floor() would
499
+ // result in UB for very large negative timestamps, similarly as
500
+ // https://github.com/HowardHinnant/date/issues/696)
501
+ auto timepoint_days = std::chrono::time_point_cast<days>(timepoint);
502
+ Duration since_midnight;
503
+ if (timepoint_days <= timepoint) {
504
+ // Year >= 1970
505
+ since_midnight = timepoint - timepoint_days;
506
+ } else {
507
+ // Year < 1970
508
+ since_midnight = days(1) - (timepoint_days - timepoint);
509
+ timepoint_days -= days(1);
510
+ }
511
+
512
+ // YYYY_MM_DD " " HH_MM_SS "Z"?
513
+ constexpr size_t buffer_size =
514
+ detail::BufferSizeYYYY_MM_DD() + 1 + detail::BufferSizeHH_MM_SS<Duration>() + 1;
515
+
516
+ std::array<char, buffer_size> buffer;
517
+ char* cursor = buffer.data() + buffer_size;
518
+
519
+ if (timezone_.size() > 0) {
520
+ detail::FormatOneChar('Z', &cursor);
521
+ }
522
+ detail::FormatHH_MM_SS(arrow_vendored::date::make_time(since_midnight), &cursor);
523
+ detail::FormatOneChar(' ', &cursor);
524
+ detail::FormatYYYY_MM_DD(timepoint_days, &cursor);
525
+ return append(detail::ViewDigitBuffer(buffer, cursor));
526
+ }
527
+
528
+ template <typename Appender>
529
+ Return<Appender> operator()(value_type value, Appender&& append) {
530
+ return util::VisitDuration(unit_, *this, value, std::forward<Appender>(append));
531
+ }
532
+
533
+ private:
534
+ TimeUnit::type unit_;
535
+ std::string timezone_;
536
+ };
537
+
538
+ template <typename T>
539
+ class StringFormatter<T, enable_if_time<T>> {
540
+ public:
541
+ using value_type = typename T::c_type;
542
+
543
+ explicit StringFormatter(const DataType* type)
544
+ : unit_(checked_cast<const T&>(*type).unit()) {}
545
+
546
+ template <typename Duration, typename Appender>
547
+ Return<Appender> operator()(Duration, value_type count, Appender&& append) {
548
+ const Duration since_midnight{count};
549
+ if (!ARROW_PREDICT_TRUE(detail::IsTimeInRange(since_midnight))) {
550
+ return detail::FormatOutOfRange(count, append);
551
+ }
552
+
553
+ constexpr size_t buffer_size = detail::BufferSizeHH_MM_SS<Duration>();
554
+
555
+ std::array<char, buffer_size> buffer;
556
+ char* cursor = buffer.data() + buffer_size;
557
+
558
+ detail::FormatHH_MM_SS(arrow_vendored::date::make_time(since_midnight), &cursor);
559
+ return append(detail::ViewDigitBuffer(buffer, cursor));
560
+ }
561
+
562
+ template <typename Appender>
563
+ Return<Appender> operator()(value_type value, Appender&& append) {
564
+ return util::VisitDuration(unit_, *this, value, std::forward<Appender>(append));
565
+ }
566
+
567
+ private:
568
+ TimeUnit::type unit_;
569
+ };
570
+
571
+ template <>
572
+ class StringFormatter<MonthIntervalType> {
573
+ public:
574
+ using value_type = MonthIntervalType::c_type;
575
+
576
+ explicit StringFormatter(const DataType*) {}
577
+
578
+ template <typename Appender>
579
+ Return<Appender> operator()(value_type interval, Appender&& append) {
580
+ constexpr size_t buffer_size =
581
+ /*'m'*/ 3 + /*negative signs*/ 1 +
582
+ /*months*/ detail::Digits10(std::numeric_limits<value_type>::max());
583
+ std::array<char, buffer_size> buffer;
584
+ char* cursor = buffer.data() + buffer_size;
585
+
586
+ detail::FormatOneChar('M', &cursor);
587
+ detail::FormatAllDigits(detail::Abs(interval), &cursor);
588
+ if (interval < 0) detail::FormatOneChar('-', &cursor);
589
+
590
+ return append(detail::ViewDigitBuffer(buffer, cursor));
591
+ }
592
+ };
593
+
594
+ template <>
595
+ class StringFormatter<DayTimeIntervalType> {
596
+ public:
597
+ using value_type = DayTimeIntervalType::DayMilliseconds;
598
+
599
+ explicit StringFormatter(const DataType*) {}
600
+
601
+ template <typename Appender>
602
+ Return<Appender> operator()(value_type interval, Appender&& append) {
603
+ constexpr size_t buffer_size =
604
+ /*d, ms*/ 3 + /*negative signs*/ 2 +
605
+ /*days/milliseconds*/ 2 * detail::Digits10(std::numeric_limits<int32_t>::max());
606
+ std::array<char, buffer_size> buffer;
607
+ char* cursor = buffer.data() + buffer_size;
608
+
609
+ detail::FormatOneChar('s', &cursor);
610
+ detail::FormatOneChar('m', &cursor);
611
+ detail::FormatAllDigits(detail::Abs(interval.milliseconds), &cursor);
612
+ if (interval.milliseconds < 0) detail::FormatOneChar('-', &cursor);
613
+
614
+ detail::FormatOneChar('d', &cursor);
615
+ detail::FormatAllDigits(detail::Abs(interval.days), &cursor);
616
+ if (interval.days < 0) detail::FormatOneChar('-', &cursor);
617
+
618
+ return append(detail::ViewDigitBuffer(buffer, cursor));
619
+ }
620
+ };
621
+
622
+ template <>
623
+ class StringFormatter<MonthDayNanoIntervalType> {
624
+ public:
625
+ using value_type = MonthDayNanoIntervalType::MonthDayNanos;
626
+
627
+ explicit StringFormatter(const DataType*) {}
628
+
629
+ template <typename Appender>
630
+ Return<Appender> operator()(value_type interval, Appender&& append) {
631
+ constexpr size_t buffer_size =
632
+ /*m, d, ns*/ 4 + /*negative signs*/ 3 +
633
+ /*months/days*/ 2 * detail::Digits10(std::numeric_limits<int32_t>::max()) +
634
+ /*nanoseconds*/ detail::Digits10(std::numeric_limits<int64_t>::max());
635
+ std::array<char, buffer_size> buffer;
636
+ char* cursor = buffer.data() + buffer_size;
637
+
638
+ detail::FormatOneChar('s', &cursor);
639
+ detail::FormatOneChar('n', &cursor);
640
+ detail::FormatAllDigits(detail::Abs(interval.nanoseconds), &cursor);
641
+ if (interval.nanoseconds < 0) detail::FormatOneChar('-', &cursor);
642
+
643
+ detail::FormatOneChar('d', &cursor);
644
+ detail::FormatAllDigits(detail::Abs(interval.days), &cursor);
645
+ if (interval.days < 0) detail::FormatOneChar('-', &cursor);
646
+
647
+ detail::FormatOneChar('M', &cursor);
648
+ detail::FormatAllDigits(detail::Abs(interval.months), &cursor);
649
+ if (interval.months < 0) detail::FormatOneChar('-', &cursor);
650
+
651
+ return append(detail::ViewDigitBuffer(buffer, cursor));
652
+ }
653
+ };
654
+
655
+ } // namespace internal
656
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/hash_util.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
+ #pragma once
19
+
20
+ namespace arrow {
21
+ namespace internal {
22
+
23
+ // ----------------------------------------------------------------------
24
+ // BEGIN Hash utilities from Boost
25
+
26
+ namespace detail {
27
+
28
+ #if defined(_MSC_VER)
29
+ #define ARROW_HASH_ROTL32(x, r) _rotl(x, r)
30
+ #else
31
+ #define ARROW_HASH_ROTL32(x, r) (x << r) | (x >> (32 - r))
32
+ #endif
33
+
34
+ template <typename SizeT>
35
+ inline void hash_combine_impl(SizeT& seed, SizeT value) {
36
+ seed ^= value + 0x9e3779b9 + (seed << 6) + (seed >> 2);
37
+ }
38
+
39
+ inline void hash_combine_impl(uint32_t& h1, uint32_t k1) {
40
+ const uint32_t c1 = 0xcc9e2d51;
41
+ const uint32_t c2 = 0x1b873593;
42
+
43
+ k1 *= c1;
44
+ k1 = ARROW_HASH_ROTL32(k1, 15);
45
+ k1 *= c2;
46
+
47
+ h1 ^= k1;
48
+ h1 = ARROW_HASH_ROTL32(h1, 13);
49
+ h1 = h1 * 5 + 0xe6546b64;
50
+ }
51
+
52
+ #undef ARROW_HASH_ROTL32
53
+
54
+ } // namespace detail
55
+
56
+ template <class T>
57
+ inline void hash_combine(std::size_t& seed, T const& v) {
58
+ std::hash<T> hasher;
59
+ return ::arrow::internal::detail::hash_combine_impl(seed, hasher(v));
60
+ }
61
+
62
+ // END Hash utilities from Boost
63
+ // ----------------------------------------------------------------------
64
+
65
+ } // namespace internal
66
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util_overflow.h ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <type_traits>
23
+
24
+ #include "arrow/status.h"
25
+ #include "arrow/util/macros.h"
26
+ #include "arrow/util/visibility.h"
27
+
28
+ // "safe-math.h" includes <intsafe.h> from the Windows headers.
29
+ #include "arrow/util/windows_compatibility.h"
30
+ #include "arrow/vendored/portable-snippets/safe-math.h"
31
+ // clang-format off (avoid include reordering)
32
+ #include "arrow/util/windows_fixup.h"
33
+ // clang-format on
34
+
35
+ namespace arrow {
36
+ namespace internal {
37
+
38
+ // Define functions AddWithOverflow, SubtractWithOverflow, MultiplyWithOverflow
39
+ // with the signature `bool(T u, T v, T* out)` where T is an integer type.
40
+ // On overflow, these functions return true. Otherwise, false is returned
41
+ // and `out` is updated with the result of the operation.
42
+
43
+ #define OP_WITH_OVERFLOW(_func_name, _psnip_op, _type, _psnip_type) \
44
+ [[nodiscard]] static inline bool _func_name(_type u, _type v, _type* out) { \
45
+ return !psnip_safe_##_psnip_type##_##_psnip_op(out, u, v); \
46
+ }
47
+
48
+ #define OPS_WITH_OVERFLOW(_func_name, _psnip_op) \
49
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, int8_t, int8) \
50
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, int16_t, int16) \
51
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, int32_t, int32) \
52
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, int64_t, int64) \
53
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, uint8_t, uint8) \
54
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, uint16_t, uint16) \
55
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, uint32_t, uint32) \
56
+ OP_WITH_OVERFLOW(_func_name, _psnip_op, uint64_t, uint64)
57
+
58
+ OPS_WITH_OVERFLOW(AddWithOverflow, add)
59
+ OPS_WITH_OVERFLOW(SubtractWithOverflow, sub)
60
+ OPS_WITH_OVERFLOW(MultiplyWithOverflow, mul)
61
+ OPS_WITH_OVERFLOW(DivideWithOverflow, div)
62
+
63
+ #undef OP_WITH_OVERFLOW
64
+ #undef OPS_WITH_OVERFLOW
65
+
66
+ // Define function NegateWithOverflow with the signature `bool(T u, T* out)`
67
+ // where T is a signed integer type. On overflow, these functions return true.
68
+ // Otherwise, false is returned and `out` is updated with the result of the
69
+ // operation.
70
+
71
+ #define UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, _type, _psnip_type) \
72
+ [[nodiscard]] static inline bool _func_name(_type u, _type* out) { \
73
+ return !psnip_safe_##_psnip_type##_##_psnip_op(out, u); \
74
+ }
75
+
76
+ #define SIGNED_UNARY_OPS_WITH_OVERFLOW(_func_name, _psnip_op) \
77
+ UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int8_t, int8) \
78
+ UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int16_t, int16) \
79
+ UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int32_t, int32) \
80
+ UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int64_t, int64)
81
+
82
+ SIGNED_UNARY_OPS_WITH_OVERFLOW(NegateWithOverflow, neg)
83
+
84
+ #undef UNARY_OP_WITH_OVERFLOW
85
+ #undef SIGNED_UNARY_OPS_WITH_OVERFLOW
86
+
87
+ /// Signed addition with well-defined behaviour on overflow (as unsigned)
88
+ template <typename SignedInt>
89
+ SignedInt SafeSignedAdd(SignedInt u, SignedInt v) {
90
+ using UnsignedInt = typename std::make_unsigned<SignedInt>::type;
91
+ return static_cast<SignedInt>(static_cast<UnsignedInt>(u) +
92
+ static_cast<UnsignedInt>(v));
93
+ }
94
+
95
+ /// Signed subtraction with well-defined behaviour on overflow (as unsigned)
96
+ template <typename SignedInt>
97
+ SignedInt SafeSignedSubtract(SignedInt u, SignedInt v) {
98
+ using UnsignedInt = typename std::make_unsigned<SignedInt>::type;
99
+ return static_cast<SignedInt>(static_cast<UnsignedInt>(u) -
100
+ static_cast<UnsignedInt>(v));
101
+ }
102
+
103
+ /// Signed negation with well-defined behaviour on overflow (as unsigned)
104
+ template <typename SignedInt>
105
+ SignedInt SafeSignedNegate(SignedInt u) {
106
+ using UnsignedInt = typename std::make_unsigned<SignedInt>::type;
107
+ return static_cast<SignedInt>(~static_cast<UnsignedInt>(u) + 1);
108
+ }
109
+
110
+ /// Signed left shift with well-defined behaviour on negative numbers or overflow
111
+ template <typename SignedInt, typename Shift>
112
+ SignedInt SafeLeftShift(SignedInt u, Shift shift) {
113
+ using UnsignedInt = typename std::make_unsigned<SignedInt>::type;
114
+ return static_cast<SignedInt>(static_cast<UnsignedInt>(u) << shift);
115
+ }
116
+
117
+ } // namespace internal
118
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/io_util.h ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef _WIN32
21
+ #define ARROW_HAVE_SIGACTION 1
22
+ #endif
23
+
24
+ #include <atomic>
25
+ #include <memory>
26
+ #include <optional>
27
+ #include <string>
28
+ #include <utility>
29
+ #include <vector>
30
+
31
+ #if ARROW_HAVE_SIGACTION
32
+ #include <csignal> // Needed for struct sigaction
33
+ #endif
34
+
35
+ #include "arrow/result.h"
36
+ #include "arrow/status.h"
37
+ #include "arrow/type_fwd.h"
38
+ #include "arrow/util/macros.h"
39
+ #include "arrow/util/windows_fixup.h"
40
+
41
+ namespace arrow::internal {
42
+
43
+ // NOTE: 8-bit path strings on Windows are encoded using UTF-8.
44
+ // Using MBCS would fail encoding some paths.
45
+
46
+ #if defined(_WIN32)
47
+ using NativePathString = std::wstring;
48
+ #else
49
+ using NativePathString = std::string;
50
+ #endif
51
+
52
+ class ARROW_EXPORT PlatformFilename {
53
+ public:
54
+ struct Impl;
55
+
56
+ ~PlatformFilename();
57
+ PlatformFilename();
58
+ PlatformFilename(const PlatformFilename&);
59
+ PlatformFilename(PlatformFilename&&);
60
+ PlatformFilename& operator=(const PlatformFilename&);
61
+ PlatformFilename& operator=(PlatformFilename&&);
62
+ explicit PlatformFilename(NativePathString path);
63
+ explicit PlatformFilename(const NativePathString::value_type* path);
64
+
65
+ const NativePathString& ToNative() const;
66
+ std::string ToString() const;
67
+
68
+ PlatformFilename Parent() const;
69
+ Result<PlatformFilename> Real() const;
70
+
71
+ // These functions can fail for character encoding reasons.
72
+ static Result<PlatformFilename> FromString(std::string_view file_name);
73
+ Result<PlatformFilename> Join(std::string_view child_name) const;
74
+
75
+ PlatformFilename Join(const PlatformFilename& child_name) const;
76
+
77
+ bool operator==(const PlatformFilename& other) const;
78
+ bool operator!=(const PlatformFilename& other) const;
79
+
80
+ // Made public to avoid the proliferation of friend declarations.
81
+ const Impl* impl() const { return impl_.get(); }
82
+
83
+ private:
84
+ std::unique_ptr<Impl> impl_;
85
+
86
+ explicit PlatformFilename(Impl impl);
87
+ };
88
+
89
+ /// Create a directory if it doesn't exist.
90
+ ///
91
+ /// Return whether the directory was created.
92
+ ARROW_EXPORT
93
+ Result<bool> CreateDir(const PlatformFilename& dir_path);
94
+
95
+ /// Create a directory and its parents if it doesn't exist.
96
+ ///
97
+ /// Return whether the directory was created.
98
+ ARROW_EXPORT
99
+ Result<bool> CreateDirTree(const PlatformFilename& dir_path);
100
+
101
+ /// Delete a directory's contents (but not the directory itself) if it exists.
102
+ ///
103
+ /// Return whether the directory existed.
104
+ ARROW_EXPORT
105
+ Result<bool> DeleteDirContents(const PlatformFilename& dir_path,
106
+ bool allow_not_found = true);
107
+
108
+ /// Delete a directory tree if it exists.
109
+ ///
110
+ /// Return whether the directory existed.
111
+ ARROW_EXPORT
112
+ Result<bool> DeleteDirTree(const PlatformFilename& dir_path, bool allow_not_found = true);
113
+
114
+ // Non-recursively list the contents of the given directory.
115
+ // The returned names are the children's base names, not including dir_path.
116
+ ARROW_EXPORT
117
+ Result<std::vector<PlatformFilename>> ListDir(const PlatformFilename& dir_path);
118
+
119
+ /// Delete a file if it exists.
120
+ ///
121
+ /// Return whether the file existed.
122
+ ARROW_EXPORT
123
+ Result<bool> DeleteFile(const PlatformFilename& file_path, bool allow_not_found = true);
124
+
125
+ /// Return whether a file exists.
126
+ ARROW_EXPORT
127
+ Result<bool> FileExists(const PlatformFilename& path);
128
+
129
+ // TODO expose this more publicly to make it available from io/file.h?
130
+ /// A RAII wrapper for a file descriptor.
131
+ ///
132
+ /// The underlying file descriptor is automatically closed on destruction.
133
+ /// Moving is supported with well-defined semantics.
134
+ /// Furthermore, closing is idempotent.
135
+ class ARROW_EXPORT FileDescriptor {
136
+ public:
137
+ FileDescriptor() = default;
138
+ explicit FileDescriptor(int fd) : fd_(fd) {}
139
+ FileDescriptor(FileDescriptor&&);
140
+ FileDescriptor& operator=(FileDescriptor&&);
141
+
142
+ ~FileDescriptor();
143
+
144
+ Status Close();
145
+
146
+ /// May return -1 if closed or default-initialized
147
+ int fd() const { return fd_.load(); }
148
+
149
+ /// Detach and return the underlying file descriptor
150
+ int Detach();
151
+
152
+ bool closed() const { return fd_.load() == -1; }
153
+
154
+ protected:
155
+ static void CloseFromDestructor(int fd);
156
+
157
+ std::atomic<int> fd_{-1};
158
+ };
159
+
160
+ /// Open a file for reading and return a file descriptor.
161
+ ARROW_EXPORT
162
+ Result<FileDescriptor> FileOpenReadable(const PlatformFilename& file_name);
163
+
164
+ /// Open a file for writing and return a file descriptor.
165
+ ARROW_EXPORT
166
+ Result<FileDescriptor> FileOpenWritable(const PlatformFilename& file_name,
167
+ bool write_only = true, bool truncate = true,
168
+ bool append = false);
169
+
170
+ /// Read from current file position. Return number of bytes read.
171
+ ARROW_EXPORT
172
+ Result<int64_t> FileRead(int fd, uint8_t* buffer, int64_t nbytes);
173
+ /// Read from given file position. Return number of bytes read.
174
+ ARROW_EXPORT
175
+ Result<int64_t> FileReadAt(int fd, uint8_t* buffer, int64_t position, int64_t nbytes);
176
+
177
+ ARROW_EXPORT
178
+ Status FileWrite(int fd, const uint8_t* buffer, const int64_t nbytes);
179
+ ARROW_EXPORT
180
+ Status FileTruncate(int fd, const int64_t size);
181
+
182
+ ARROW_EXPORT
183
+ Status FileSeek(int fd, int64_t pos);
184
+ ARROW_EXPORT
185
+ Status FileSeek(int fd, int64_t pos, int whence);
186
+ ARROW_EXPORT
187
+ Result<int64_t> FileTell(int fd);
188
+ ARROW_EXPORT
189
+ Result<int64_t> FileGetSize(int fd);
190
+
191
+ ARROW_EXPORT
192
+ Status FileClose(int fd);
193
+
194
+ struct Pipe {
195
+ FileDescriptor rfd;
196
+ FileDescriptor wfd;
197
+
198
+ Status Close() { return rfd.Close() & wfd.Close(); }
199
+ };
200
+
201
+ ARROW_EXPORT
202
+ Result<Pipe> CreatePipe();
203
+
204
+ ARROW_EXPORT
205
+ Status SetPipeFileDescriptorNonBlocking(int fd);
206
+
207
+ class ARROW_EXPORT SelfPipe {
208
+ public:
209
+ static Result<std::shared_ptr<SelfPipe>> Make(bool signal_safe);
210
+ virtual ~SelfPipe();
211
+
212
+ /// \brief Wait for a wakeup.
213
+ ///
214
+ /// Status::Invalid is returned if the pipe has been shutdown.
215
+ /// Otherwise the next sent payload is returned.
216
+ virtual Result<uint64_t> Wait() = 0;
217
+
218
+ /// \brief Wake up the pipe by sending a payload.
219
+ ///
220
+ /// This method is async-signal-safe if `signal_safe` was set to true.
221
+ virtual void Send(uint64_t payload) = 0;
222
+
223
+ /// \brief Wake up the pipe and shut it down.
224
+ virtual Status Shutdown() = 0;
225
+ };
226
+
227
+ ARROW_EXPORT
228
+ int64_t GetPageSize();
229
+
230
+ struct MemoryRegion {
231
+ void* addr;
232
+ size_t size;
233
+ };
234
+
235
+ ARROW_EXPORT
236
+ Status MemoryMapRemap(void* addr, size_t old_size, size_t new_size, int fildes,
237
+ void** new_addr);
238
+ ARROW_EXPORT
239
+ Status MemoryAdviseWillNeed(const std::vector<MemoryRegion>& regions);
240
+
241
+ ARROW_EXPORT
242
+ Result<std::string> GetEnvVar(const char* name);
243
+ ARROW_EXPORT
244
+ Result<std::string> GetEnvVar(const std::string& name);
245
+ ARROW_EXPORT
246
+ Result<NativePathString> GetEnvVarNative(const char* name);
247
+ ARROW_EXPORT
248
+ Result<NativePathString> GetEnvVarNative(const std::string& name);
249
+
250
+ ARROW_EXPORT
251
+ Status SetEnvVar(const char* name, const char* value);
252
+ ARROW_EXPORT
253
+ Status SetEnvVar(const std::string& name, const std::string& value);
254
+ ARROW_EXPORT
255
+ Status DelEnvVar(const char* name);
256
+ ARROW_EXPORT
257
+ Status DelEnvVar(const std::string& name);
258
+
259
+ ARROW_EXPORT
260
+ std::string ErrnoMessage(int errnum);
261
+ #if _WIN32
262
+ ARROW_EXPORT
263
+ std::string WinErrorMessage(int errnum);
264
+ #endif
265
+
266
+ ARROW_EXPORT
267
+ std::shared_ptr<StatusDetail> StatusDetailFromErrno(int errnum);
268
+ ARROW_EXPORT
269
+ std::optional<int> ErrnoFromStatusDetail(const StatusDetail& detail);
270
+ #if _WIN32
271
+ ARROW_EXPORT
272
+ std::shared_ptr<StatusDetail> StatusDetailFromWinError(int errnum);
273
+ #endif
274
+ ARROW_EXPORT
275
+ std::shared_ptr<StatusDetail> StatusDetailFromSignal(int signum);
276
+
277
+ template <typename... Args>
278
+ Status StatusFromErrno(int errnum, StatusCode code, Args&&... args) {
279
+ return Status::FromDetailAndArgs(code, StatusDetailFromErrno(errnum),
280
+ std::forward<Args>(args)...);
281
+ }
282
+
283
+ template <typename... Args>
284
+ Status IOErrorFromErrno(int errnum, Args&&... args) {
285
+ return StatusFromErrno(errnum, StatusCode::IOError, std::forward<Args>(args)...);
286
+ }
287
+
288
+ #if _WIN32
289
+ template <typename... Args>
290
+ Status StatusFromWinError(int errnum, StatusCode code, Args&&... args) {
291
+ return Status::FromDetailAndArgs(code, StatusDetailFromWinError(errnum),
292
+ std::forward<Args>(args)...);
293
+ }
294
+
295
+ template <typename... Args>
296
+ Status IOErrorFromWinError(int errnum, Args&&... args) {
297
+ return StatusFromWinError(errnum, StatusCode::IOError, std::forward<Args>(args)...);
298
+ }
299
+ #endif
300
+
301
+ template <typename... Args>
302
+ Status StatusFromSignal(int signum, StatusCode code, Args&&... args) {
303
+ return Status::FromDetailAndArgs(code, StatusDetailFromSignal(signum),
304
+ std::forward<Args>(args)...);
305
+ }
306
+
307
+ template <typename... Args>
308
+ Status CancelledFromSignal(int signum, Args&&... args) {
309
+ return StatusFromSignal(signum, StatusCode::Cancelled, std::forward<Args>(args)...);
310
+ }
311
+
312
+ ARROW_EXPORT
313
+ int ErrnoFromStatus(const Status&);
314
+
315
+ // Always returns 0 on non-Windows platforms (for Python).
316
+ ARROW_EXPORT
317
+ int WinErrorFromStatus(const Status&);
318
+
319
+ ARROW_EXPORT
320
+ int SignalFromStatus(const Status&);
321
+
322
+ class ARROW_EXPORT TemporaryDir {
323
+ public:
324
+ ~TemporaryDir();
325
+
326
+ /// '/'-terminated path to the temporary dir
327
+ const PlatformFilename& path() { return path_; }
328
+
329
+ /// Create a temporary subdirectory in the system temporary dir,
330
+ /// named starting with `prefix`.
331
+ static Result<std::unique_ptr<TemporaryDir>> Make(const std::string& prefix);
332
+
333
+ private:
334
+ PlatformFilename path_;
335
+
336
+ explicit TemporaryDir(PlatformFilename&&);
337
+ };
338
+
339
+ class ARROW_EXPORT SignalHandler {
340
+ public:
341
+ using Callback = void (*)(int);
342
+
343
+ SignalHandler();
344
+ explicit SignalHandler(Callback cb);
345
+ #if ARROW_HAVE_SIGACTION
346
+ explicit SignalHandler(const struct sigaction& sa);
347
+ #endif
348
+
349
+ Callback callback() const;
350
+ #if ARROW_HAVE_SIGACTION
351
+ const struct sigaction& action() const;
352
+ #endif
353
+
354
+ protected:
355
+ #if ARROW_HAVE_SIGACTION
356
+ // Storing the full sigaction allows to restore the entire signal handling
357
+ // configuration.
358
+ struct sigaction sa_;
359
+ #else
360
+ Callback cb_;
361
+ #endif
362
+ };
363
+
364
+ /// \brief Return the current handler for the given signal number.
365
+ ARROW_EXPORT
366
+ Result<SignalHandler> GetSignalHandler(int signum);
367
+
368
+ /// \brief Set a new handler for the given signal number.
369
+ ///
370
+ /// The old signal handler is returned.
371
+ ARROW_EXPORT
372
+ Result<SignalHandler> SetSignalHandler(int signum, const SignalHandler& handler);
373
+
374
+ /// \brief Reinstate the signal handler
375
+ ///
376
+ /// For use in signal handlers. This is needed on platforms without sigaction()
377
+ /// such as Windows, as the default signal handler is restored there as
378
+ /// soon as a signal is raised.
379
+ ARROW_EXPORT
380
+ void ReinstateSignalHandler(int signum, SignalHandler::Callback handler);
381
+
382
+ /// \brief Send a signal to the current process
383
+ ///
384
+ /// The thread which will receive the signal is unspecified.
385
+ ARROW_EXPORT
386
+ Status SendSignal(int signum);
387
+
388
+ /// \brief Send a signal to the given thread
389
+ ///
390
+ /// This function isn't supported on Windows.
391
+ ARROW_EXPORT
392
+ Status SendSignalToThread(int signum, uint64_t thread_id);
393
+
394
+ /// \brief Get an unpredictable random seed
395
+ ///
396
+ /// This function may be slightly costly, so should only be used to initialize
397
+ /// a PRNG, not to generate a large amount of random numbers.
398
+ /// It is better to use this function rather than std::random_device, unless
399
+ /// absolutely necessary (e.g. to generate a cryptographic secret).
400
+ ARROW_EXPORT
401
+ int64_t GetRandomSeed();
402
+
403
+ /// \brief Get the current thread id
404
+ ///
405
+ /// In addition to having the same properties as std::thread, the returned value
406
+ /// is a regular integer value, which is more convenient than an opaque type.
407
+ ARROW_EXPORT
408
+ uint64_t GetThreadId();
409
+
410
+ /// \brief Get the current memory used by the current process in bytes
411
+ ///
412
+ /// This function supports Windows, Linux, and Mac and will return 0 otherwise
413
+ ARROW_EXPORT
414
+ int64_t GetCurrentRSS();
415
+
416
+ /// \brief Get the total memory available to the system in bytes
417
+ ///
418
+ /// This function supports Windows, Linux, and Mac and will return 0 otherwise
419
+ ARROW_EXPORT
420
+ int64_t GetTotalMemoryBytes();
421
+
422
+ /// \brief Load a dynamic library
423
+ ///
424
+ /// This wraps dlopen() except on Windows, where LoadLibrary() is called.
425
+ /// These two platforms handle absolute paths consistently; relative paths
426
+ /// or the library's bare name may be handled but inconsistently.
427
+ ///
428
+ /// \return An opaque handle for the dynamic library, which can be used for
429
+ /// subsequent symbol lookup. Nullptr will never be returned; instead
430
+ /// an error will be raised.
431
+ ARROW_EXPORT Result<void*> LoadDynamicLibrary(const PlatformFilename& path);
432
+
433
+ /// \brief Load a dynamic library
434
+ ///
435
+ /// An overload taking null terminated string.
436
+ ARROW_EXPORT Result<void*> LoadDynamicLibrary(const char* path);
437
+
438
+ /// \brief Retrieve a symbol by name from a library handle.
439
+ ///
440
+ /// This wraps dlsym() except on Windows, where GetProcAddress() is called.
441
+ ///
442
+ /// \return The address associated with the named symbol. Nullptr will never be
443
+ /// returned; instead an error will be raised.
444
+ ARROW_EXPORT Result<void*> GetSymbol(void* handle, const char* name);
445
+
446
+ template <typename T>
447
+ Result<T*> GetSymbolAs(void* handle, const char* name) {
448
+ ARROW_ASSIGN_OR_RAISE(void* sym, GetSymbol(handle, name));
449
+ return reinterpret_cast<T*>(sym);
450
+ }
451
+
452
+ } // namespace arrow::internal
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/iterator.h ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <functional>
22
+ #include <memory>
23
+ #include <optional>
24
+ #include <tuple>
25
+ #include <type_traits>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ #include "arrow/result.h"
30
+ #include "arrow/status.h"
31
+ #include "arrow/util/compare.h"
32
+ #include "arrow/util/functional.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ template <typename T>
39
+ class Iterator;
40
+
41
+ template <typename T>
42
+ struct IterationTraits {
43
+ /// \brief a reserved value which indicates the end of iteration. By
44
+ /// default this is NULLPTR since most iterators yield pointer types.
45
+ /// Specialize IterationTraits if different end semantics are required.
46
+ ///
47
+ /// Note: This should not be used to determine if a given value is a
48
+ /// terminal value. Use IsIterationEnd (which uses IsEnd) instead. This
49
+ /// is only for returning terminal values.
50
+ static T End() { return T(NULLPTR); }
51
+
52
+ /// \brief Checks to see if the value is a terminal value.
53
+ /// A method is used here since T is not necessarily comparable in many
54
+ /// cases even though it has a distinct final value
55
+ static bool IsEnd(const T& val) { return val == End(); }
56
+ };
57
+
58
+ template <typename T>
59
+ T IterationEnd() {
60
+ return IterationTraits<T>::End();
61
+ }
62
+
63
+ template <typename T>
64
+ bool IsIterationEnd(const T& val) {
65
+ return IterationTraits<T>::IsEnd(val);
66
+ }
67
+
68
+ template <typename T>
69
+ struct IterationTraits<std::optional<T>> {
70
+ /// \brief by default when iterating through a sequence of optional,
71
+ /// nullopt indicates the end of iteration.
72
+ /// Specialize IterationTraits if different end semantics are required.
73
+ static std::optional<T> End() { return std::nullopt; }
74
+
75
+ /// \brief by default when iterating through a sequence of optional,
76
+ /// nullopt (!has_value()) indicates the end of iteration.
77
+ /// Specialize IterationTraits if different end semantics are required.
78
+ static bool IsEnd(const std::optional<T>& val) { return !val.has_value(); }
79
+
80
+ // TODO(bkietz) The range-for loop over Iterator<optional<T>> yields
81
+ // Result<optional<T>> which is unnecessary (since only the unyielded end optional
82
+ // is nullopt. Add IterationTraits::GetRangeElement() to handle this case
83
+ };
84
+
85
+ /// \brief A generic Iterator that can return errors
86
+ template <typename T>
87
+ class Iterator : public util::EqualityComparable<Iterator<T>> {
88
+ public:
89
+ /// \brief Iterator may be constructed from any type which has a member function
90
+ /// with signature Result<T> Next();
91
+ /// End of iterator is signalled by returning IteratorTraits<T>::End();
92
+ ///
93
+ /// The argument is moved or copied to the heap and kept in a unique_ptr<void>. Only
94
+ /// its destructor and its Next method (which are stored in function pointers) are
95
+ /// referenced after construction.
96
+ ///
97
+ /// This approach is used to dodge MSVC linkage hell (ARROW-6244, ARROW-6558) when using
98
+ /// an abstract template base class: instead of being inlined as usual for a template
99
+ /// function the base's virtual destructor will be exported, leading to multiple
100
+ /// definition errors when linking to any other TU where the base is instantiated.
101
+ template <typename Wrapped>
102
+ explicit Iterator(Wrapped has_next)
103
+ : ptr_(new Wrapped(std::move(has_next)), Delete<Wrapped>), next_(Next<Wrapped>) {}
104
+
105
+ Iterator() : ptr_(NULLPTR, [](void*) {}) {}
106
+
107
+ /// \brief Return the next element of the sequence, IterationTraits<T>::End() when the
108
+ /// iteration is completed. Calling this on a default constructed Iterator
109
+ /// will result in undefined behavior.
110
+ Result<T> Next() { return next_(ptr_.get()); }
111
+
112
+ /// Pass each element of the sequence to a visitor. Will return any error status
113
+ /// returned by the visitor, terminating iteration.
114
+ template <typename Visitor>
115
+ Status Visit(Visitor&& visitor) {
116
+ for (;;) {
117
+ ARROW_ASSIGN_OR_RAISE(auto value, Next());
118
+
119
+ if (IsIterationEnd(value)) break;
120
+
121
+ ARROW_RETURN_NOT_OK(visitor(std::move(value)));
122
+ }
123
+
124
+ return Status::OK();
125
+ }
126
+
127
+ /// Iterators will only compare equal if they are both null.
128
+ /// Equality comparability is required to make an Iterator of Iterators
129
+ /// (to check for the end condition).
130
+ bool Equals(const Iterator& other) const { return ptr_ == other.ptr_; }
131
+
132
+ explicit operator bool() const { return ptr_ != NULLPTR; }
133
+
134
+ class RangeIterator {
135
+ public:
136
+ RangeIterator() : value_(IterationTraits<T>::End()) {}
137
+
138
+ explicit RangeIterator(Iterator i)
139
+ : value_(IterationTraits<T>::End()),
140
+ iterator_(std::make_shared<Iterator>(std::move(i))) {
141
+ Next();
142
+ }
143
+
144
+ bool operator!=(const RangeIterator& other) const { return value_ != other.value_; }
145
+
146
+ RangeIterator& operator++() {
147
+ Next();
148
+ return *this;
149
+ }
150
+
151
+ Result<T> operator*() {
152
+ ARROW_RETURN_NOT_OK(value_.status());
153
+
154
+ auto value = std::move(value_);
155
+ value_ = IterationTraits<T>::End();
156
+ return value;
157
+ }
158
+
159
+ private:
160
+ void Next() {
161
+ if (!value_.ok()) {
162
+ value_ = IterationTraits<T>::End();
163
+ return;
164
+ }
165
+ value_ = iterator_->Next();
166
+ }
167
+
168
+ Result<T> value_;
169
+ std::shared_ptr<Iterator> iterator_;
170
+ };
171
+
172
+ RangeIterator begin() { return RangeIterator(std::move(*this)); }
173
+
174
+ RangeIterator end() { return RangeIterator(); }
175
+
176
+ /// \brief Move every element of this iterator into a vector.
177
+ Result<std::vector<T>> ToVector() {
178
+ std::vector<T> out;
179
+ for (auto maybe_element : *this) {
180
+ ARROW_ASSIGN_OR_RAISE(auto element, maybe_element);
181
+ out.push_back(std::move(element));
182
+ }
183
+ // ARROW-8193: On gcc-4.8 without the explicit move it tries to use the
184
+ // copy constructor, which may be deleted on the elements of type T
185
+ return std::move(out);
186
+ }
187
+
188
+ private:
189
+ /// Implementation of deleter for ptr_: Casts from void* to the wrapped type and
190
+ /// deletes that.
191
+ template <typename HasNext>
192
+ static void Delete(void* ptr) {
193
+ delete static_cast<HasNext*>(ptr);
194
+ }
195
+
196
+ /// Implementation of Next: Casts from void* to the wrapped type and invokes that
197
+ /// type's Next member function.
198
+ template <typename HasNext>
199
+ static Result<T> Next(void* ptr) {
200
+ return static_cast<HasNext*>(ptr)->Next();
201
+ }
202
+
203
+ /// ptr_ is a unique_ptr to void with a custom deleter: a function pointer which first
204
+ /// casts from void* to a pointer to the wrapped type then deletes that.
205
+ std::unique_ptr<void, void (*)(void*)> ptr_;
206
+
207
+ /// next_ is a function pointer which first casts from void* to a pointer to the wrapped
208
+ /// type then invokes its Next member function.
209
+ Result<T> (*next_)(void*) = NULLPTR;
210
+ };
211
+
212
+ template <typename T>
213
+ struct TransformFlow {
214
+ using YieldValueType = T;
215
+
216
+ TransformFlow(YieldValueType value, bool ready_for_next)
217
+ : finished_(false),
218
+ ready_for_next_(ready_for_next),
219
+ yield_value_(std::move(value)) {}
220
+ TransformFlow(bool finished, bool ready_for_next)
221
+ : finished_(finished), ready_for_next_(ready_for_next), yield_value_() {}
222
+
223
+ bool HasValue() const { return yield_value_.has_value(); }
224
+ bool Finished() const { return finished_; }
225
+ bool ReadyForNext() const { return ready_for_next_; }
226
+ T Value() const { return *yield_value_; }
227
+
228
+ bool finished_ = false;
229
+ bool ready_for_next_ = false;
230
+ std::optional<YieldValueType> yield_value_;
231
+ };
232
+
233
+ struct TransformFinish {
234
+ template <typename T>
235
+ operator TransformFlow<T>() && { // NOLINT explicit
236
+ return TransformFlow<T>(true, true);
237
+ }
238
+ };
239
+
240
+ struct TransformSkip {
241
+ template <typename T>
242
+ operator TransformFlow<T>() && { // NOLINT explicit
243
+ return TransformFlow<T>(false, true);
244
+ }
245
+ };
246
+
247
+ template <typename T>
248
+ TransformFlow<T> TransformYield(T value = {}, bool ready_for_next = true) {
249
+ return TransformFlow<T>(std::move(value), ready_for_next);
250
+ }
251
+
252
+ template <typename T, typename V>
253
+ using Transformer = std::function<Result<TransformFlow<V>>(T)>;
254
+
255
+ template <typename T, typename V>
256
+ class TransformIterator {
257
+ public:
258
+ explicit TransformIterator(Iterator<T> it, Transformer<T, V> transformer)
259
+ : it_(std::move(it)),
260
+ transformer_(std::move(transformer)),
261
+ last_value_(),
262
+ finished_() {}
263
+
264
+ Result<V> Next() {
265
+ while (!finished_) {
266
+ ARROW_ASSIGN_OR_RAISE(std::optional<V> next, Pump());
267
+ if (next.has_value()) {
268
+ return std::move(*next);
269
+ }
270
+ ARROW_ASSIGN_OR_RAISE(last_value_, it_.Next());
271
+ }
272
+ return IterationTraits<V>::End();
273
+ }
274
+
275
+ private:
276
+ // Calls the transform function on the current value. Can return in several ways
277
+ // * If the next value is requested (e.g. skip) it will return an empty optional
278
+ // * If an invalid status is encountered that will be returned
279
+ // * If finished it will return IterationTraits<V>::End()
280
+ // * If a value is returned by the transformer that will be returned
281
+ Result<std::optional<V>> Pump() {
282
+ if (!finished_ && last_value_.has_value()) {
283
+ auto next_res = transformer_(*last_value_);
284
+ if (!next_res.ok()) {
285
+ finished_ = true;
286
+ return next_res.status();
287
+ }
288
+ auto next = *next_res;
289
+ if (next.ReadyForNext()) {
290
+ if (IsIterationEnd(*last_value_)) {
291
+ finished_ = true;
292
+ }
293
+ last_value_.reset();
294
+ }
295
+ if (next.Finished()) {
296
+ finished_ = true;
297
+ }
298
+ if (next.HasValue()) {
299
+ return next.Value();
300
+ }
301
+ }
302
+ if (finished_) {
303
+ return IterationTraits<V>::End();
304
+ }
305
+ return std::nullopt;
306
+ }
307
+
308
+ Iterator<T> it_;
309
+ Transformer<T, V> transformer_;
310
+ std::optional<T> last_value_;
311
+ bool finished_ = false;
312
+ };
313
+
314
+ /// \brief Transforms an iterator according to a transformer, returning a new Iterator.
315
+ ///
316
+ /// The transformer will be called on each element of the source iterator and for each
317
+ /// call it can yield a value, skip, or finish the iteration. When yielding a value the
318
+ /// transformer can choose to consume the source item (the default, ready_for_next = true)
319
+ /// or to keep it and it will be called again on the same value.
320
+ ///
321
+ /// This is essentially a more generic form of the map operation that can return 0, 1, or
322
+ /// many values for each of the source items.
323
+ ///
324
+ /// The transformer will be exposed to the end of the source sequence
325
+ /// (IterationTraits::End) in case it needs to return some penultimate item(s).
326
+ ///
327
+ /// Any invalid status returned by the transformer will be returned immediately.
328
+ template <typename T, typename V>
329
+ Iterator<V> MakeTransformedIterator(Iterator<T> it, Transformer<T, V> op) {
330
+ return Iterator<V>(TransformIterator<T, V>(std::move(it), std::move(op)));
331
+ }
332
+
333
+ template <typename T>
334
+ struct IterationTraits<Iterator<T>> {
335
+ // The end condition for an Iterator of Iterators is a default constructed (null)
336
+ // Iterator.
337
+ static Iterator<T> End() { return Iterator<T>(); }
338
+ static bool IsEnd(const Iterator<T>& val) { return !val; }
339
+ };
340
+
341
+ template <typename Fn, typename T>
342
+ class FunctionIterator {
343
+ public:
344
+ explicit FunctionIterator(Fn fn) : fn_(std::move(fn)) {}
345
+
346
+ Result<T> Next() { return fn_(); }
347
+
348
+ private:
349
+ Fn fn_;
350
+ };
351
+
352
+ /// \brief Construct an Iterator which invokes a callable on Next()
353
+ template <typename Fn,
354
+ typename Ret = typename internal::call_traits::return_type<Fn>::ValueType>
355
+ Iterator<Ret> MakeFunctionIterator(Fn fn) {
356
+ return Iterator<Ret>(FunctionIterator<Fn, Ret>(std::move(fn)));
357
+ }
358
+
359
+ template <typename T>
360
+ Iterator<T> MakeEmptyIterator() {
361
+ return MakeFunctionIterator([]() -> Result<T> { return IterationTraits<T>::End(); });
362
+ }
363
+
364
+ template <typename T>
365
+ Iterator<T> MakeErrorIterator(Status s) {
366
+ return MakeFunctionIterator([s]() -> Result<T> {
367
+ ARROW_RETURN_NOT_OK(s);
368
+ return IterationTraits<T>::End();
369
+ });
370
+ }
371
+
372
+ /// \brief Simple iterator which yields the elements of a std::vector
373
+ template <typename T>
374
+ class VectorIterator {
375
+ public:
376
+ explicit VectorIterator(std::vector<T> v) : elements_(std::move(v)) {}
377
+
378
+ Result<T> Next() {
379
+ if (i_ == elements_.size()) {
380
+ return IterationTraits<T>::End();
381
+ }
382
+ return std::move(elements_[i_++]);
383
+ }
384
+
385
+ private:
386
+ std::vector<T> elements_;
387
+ size_t i_ = 0;
388
+ };
389
+
390
+ template <typename T>
391
+ Iterator<T> MakeVectorIterator(std::vector<T> v) {
392
+ return Iterator<T>(VectorIterator<T>(std::move(v)));
393
+ }
394
+
395
+ /// \brief Simple iterator which yields *pointers* to the elements of a std::vector<T>.
396
+ /// This is provided to support T where IterationTraits<T>::End is not specialized
397
+ template <typename T>
398
+ class VectorPointingIterator {
399
+ public:
400
+ explicit VectorPointingIterator(std::vector<T> v) : elements_(std::move(v)) {}
401
+
402
+ Result<T*> Next() {
403
+ if (i_ == elements_.size()) {
404
+ return NULLPTR;
405
+ }
406
+ return &elements_[i_++];
407
+ }
408
+
409
+ private:
410
+ std::vector<T> elements_;
411
+ size_t i_ = 0;
412
+ };
413
+
414
+ template <typename T>
415
+ Iterator<T*> MakeVectorPointingIterator(std::vector<T> v) {
416
+ return Iterator<T*>(VectorPointingIterator<T>(std::move(v)));
417
+ }
418
+
419
+ /// \brief MapIterator takes ownership of an iterator and a function to apply
420
+ /// on every element. The mapped function is not allowed to fail.
421
+ template <typename Fn, typename I, typename O>
422
+ class MapIterator {
423
+ public:
424
+ explicit MapIterator(Fn map, Iterator<I> it)
425
+ : map_(std::move(map)), it_(std::move(it)) {}
426
+
427
+ Result<O> Next() {
428
+ ARROW_ASSIGN_OR_RAISE(I i, it_.Next());
429
+
430
+ if (IsIterationEnd(i)) {
431
+ return IterationTraits<O>::End();
432
+ }
433
+
434
+ return map_(std::move(i));
435
+ }
436
+
437
+ private:
438
+ Fn map_;
439
+ Iterator<I> it_;
440
+ };
441
+
442
+ /// \brief MapIterator takes ownership of an iterator and a function to apply
443
+ /// on every element. The mapped function is not allowed to fail.
444
+ template <typename Fn, typename From = internal::call_traits::argument_type<0, Fn>,
445
+ typename To = internal::call_traits::return_type<Fn>>
446
+ Iterator<To> MakeMapIterator(Fn map, Iterator<From> it) {
447
+ return Iterator<To>(MapIterator<Fn, From, To>(std::move(map), std::move(it)));
448
+ }
449
+
450
+ /// \brief Like MapIterator, but where the function can fail.
451
+ template <typename Fn, typename From = internal::call_traits::argument_type<0, Fn>,
452
+ typename To = typename internal::call_traits::return_type<Fn>::ValueType>
453
+ Iterator<To> MakeMaybeMapIterator(Fn map, Iterator<From> it) {
454
+ return Iterator<To>(MapIterator<Fn, From, To>(std::move(map), std::move(it)));
455
+ }
456
+
457
+ struct FilterIterator {
458
+ enum Action { ACCEPT, REJECT };
459
+
460
+ template <typename To>
461
+ static Result<std::pair<To, Action>> Reject() {
462
+ return std::make_pair(IterationTraits<To>::End(), REJECT);
463
+ }
464
+
465
+ template <typename To>
466
+ static Result<std::pair<To, Action>> Accept(To out) {
467
+ return std::make_pair(std::move(out), ACCEPT);
468
+ }
469
+
470
+ template <typename To>
471
+ static Result<std::pair<To, Action>> MaybeAccept(Result<To> maybe_out) {
472
+ return std::move(maybe_out).Map(Accept<To>);
473
+ }
474
+
475
+ template <typename To>
476
+ static Result<std::pair<To, Action>> Error(Status s) {
477
+ return s;
478
+ }
479
+
480
+ template <typename Fn, typename From, typename To>
481
+ class Impl {
482
+ public:
483
+ explicit Impl(Fn filter, Iterator<From> it) : filter_(filter), it_(std::move(it)) {}
484
+
485
+ Result<To> Next() {
486
+ To out = IterationTraits<To>::End();
487
+ Action action;
488
+
489
+ for (;;) {
490
+ ARROW_ASSIGN_OR_RAISE(From i, it_.Next());
491
+
492
+ if (IsIterationEnd(i)) {
493
+ return IterationTraits<To>::End();
494
+ }
495
+
496
+ ARROW_ASSIGN_OR_RAISE(std::tie(out, action), filter_(std::move(i)));
497
+
498
+ if (action == ACCEPT) return out;
499
+ }
500
+ }
501
+
502
+ private:
503
+ Fn filter_;
504
+ Iterator<From> it_;
505
+ };
506
+ };
507
+
508
+ /// \brief Like MapIterator, but where the function can fail or reject elements.
509
+ template <
510
+ typename Fn, typename From = typename internal::call_traits::argument_type<0, Fn>,
511
+ typename Ret = typename internal::call_traits::return_type<Fn>::ValueType,
512
+ typename To = typename std::tuple_element<0, Ret>::type,
513
+ typename Enable = typename std::enable_if<std::is_same<
514
+ typename std::tuple_element<1, Ret>::type, FilterIterator::Action>::value>::type>
515
+ Iterator<To> MakeFilterIterator(Fn filter, Iterator<From> it) {
516
+ return Iterator<To>(
517
+ FilterIterator::Impl<Fn, From, To>(std::move(filter), std::move(it)));
518
+ }
519
+
520
+ /// \brief FlattenIterator takes an iterator generating iterators and yields a
521
+ /// unified iterator that flattens/concatenates in a single stream.
522
+ template <typename T>
523
+ class FlattenIterator {
524
+ public:
525
+ explicit FlattenIterator(Iterator<Iterator<T>> it) : parent_(std::move(it)) {}
526
+
527
+ Result<T> Next() {
528
+ if (IsIterationEnd(child_)) {
529
+ // Pop from parent's iterator.
530
+ ARROW_ASSIGN_OR_RAISE(child_, parent_.Next());
531
+
532
+ // Check if final iteration reached.
533
+ if (IsIterationEnd(child_)) {
534
+ return IterationTraits<T>::End();
535
+ }
536
+
537
+ return Next();
538
+ }
539
+
540
+ // Pop from child_ and check for depletion.
541
+ ARROW_ASSIGN_OR_RAISE(T out, child_.Next());
542
+ if (IsIterationEnd(out)) {
543
+ // Reset state such that we pop from parent on the recursive call
544
+ child_ = IterationTraits<Iterator<T>>::End();
545
+
546
+ return Next();
547
+ }
548
+
549
+ return out;
550
+ }
551
+
552
+ private:
553
+ Iterator<Iterator<T>> parent_;
554
+ Iterator<T> child_ = IterationTraits<Iterator<T>>::End();
555
+ };
556
+
557
+ template <typename T>
558
+ Iterator<T> MakeFlattenIterator(Iterator<Iterator<T>> it) {
559
+ return Iterator<T>(FlattenIterator<T>(std::move(it)));
560
+ }
561
+
562
+ template <typename Reader>
563
+ Iterator<typename Reader::ValueType> MakeIteratorFromReader(
564
+ const std::shared_ptr<Reader>& reader) {
565
+ return MakeFunctionIterator([reader] { return reader->Next(); });
566
+ }
567
+
568
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/key_value_metadata.h ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <string_view>
24
+ #include <unordered_map>
25
+ #include <utility>
26
+ #include <vector>
27
+
28
+ #include "arrow/result.h"
29
+ #include "arrow/status.h"
30
+ #include "arrow/util/macros.h"
31
+ #include "arrow/util/visibility.h"
32
+
33
+ namespace arrow {
34
+
35
+ /// \brief A container for key-value pair type metadata. Not thread-safe
36
+ class ARROW_EXPORT KeyValueMetadata {
37
+ public:
38
+ KeyValueMetadata();
39
+ KeyValueMetadata(std::vector<std::string> keys, std::vector<std::string> values);
40
+ explicit KeyValueMetadata(const std::unordered_map<std::string, std::string>& map);
41
+
42
+ static std::shared_ptr<KeyValueMetadata> Make(std::vector<std::string> keys,
43
+ std::vector<std::string> values);
44
+
45
+ void ToUnorderedMap(std::unordered_map<std::string, std::string>* out) const;
46
+ void Append(std::string key, std::string value);
47
+
48
+ Result<std::string> Get(std::string_view key) const;
49
+ bool Contains(std::string_view key) const;
50
+ // Note that deleting may invalidate known indices
51
+ Status Delete(std::string_view key);
52
+ Status Delete(int64_t index);
53
+ Status DeleteMany(std::vector<int64_t> indices);
54
+ Status Set(std::string key, std::string value);
55
+
56
+ void reserve(int64_t n);
57
+
58
+ int64_t size() const;
59
+ const std::string& key(int64_t i) const;
60
+ const std::string& value(int64_t i) const;
61
+ const std::vector<std::string>& keys() const { return keys_; }
62
+ const std::vector<std::string>& values() const { return values_; }
63
+
64
+ std::vector<std::pair<std::string, std::string>> sorted_pairs() const;
65
+
66
+ /// \brief Perform linear search for key, returning -1 if not found
67
+ int FindKey(std::string_view key) const;
68
+
69
+ std::shared_ptr<KeyValueMetadata> Copy() const;
70
+
71
+ /// \brief Return a new KeyValueMetadata by combining the passed metadata
72
+ /// with this KeyValueMetadata. Colliding keys will be overridden by the
73
+ /// passed metadata. Assumes keys in both containers are unique
74
+ std::shared_ptr<KeyValueMetadata> Merge(const KeyValueMetadata& other) const;
75
+
76
+ bool Equals(const KeyValueMetadata& other) const;
77
+ std::string ToString() const;
78
+
79
+ private:
80
+ std::vector<std::string> keys_;
81
+ std::vector<std::string> values_;
82
+
83
+ ARROW_DISALLOW_COPY_AND_ASSIGN(KeyValueMetadata);
84
+ };
85
+
86
+ /// \brief Create a KeyValueMetadata instance
87
+ ///
88
+ /// \param pairs key-value mapping
89
+ ARROW_EXPORT std::shared_ptr<KeyValueMetadata> key_value_metadata(
90
+ const std::unordered_map<std::string, std::string>& pairs);
91
+
92
+ /// \brief Create a KeyValueMetadata instance
93
+ ///
94
+ /// \param keys sequence of metadata keys
95
+ /// \param values sequence of corresponding metadata values
96
+ ARROW_EXPORT std::shared_ptr<KeyValueMetadata> key_value_metadata(
97
+ std::vector<std::string> keys, std::vector<std::string> values);
98
+
99
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/launder.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
+ #include <new>
21
+
22
+ namespace arrow {
23
+ namespace internal {
24
+
25
+ #if __cpp_lib_launder
26
+ using std::launder;
27
+ #else
28
+ template <class T>
29
+ constexpr T* launder(T* p) noexcept {
30
+ return p;
31
+ }
32
+ #endif
33
+
34
+ } // namespace internal
35
+ } // namespace arrow
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/math_constants.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
22
+ // Not provided by default in MSVC,
23
+ // and _USE_MATH_DEFINES is not reliable with unity builds
24
+ #ifndef M_PI
25
+ #define M_PI 3.14159265358979323846
26
+ #endif
27
+ #ifndef M_PI_2
28
+ #define M_PI_2 1.57079632679489661923
29
+ #endif
30
+ #ifndef M_PI_4
31
+ #define M_PI_4 0.785398163397448309616
32
+ #endif
llmeval-env/lib/python3.10/site-packages/pyarrow/include/arrow/util/memory.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/util/macros.h"
24
+
25
+ namespace arrow {
26
+ namespace internal {
27
+
28
+ // A helper function for doing memcpy with multiple threads. This is required
29
+ // to saturate the memory bandwidth of modern cpus.
30
+ void parallel_memcopy(uint8_t* dst, const uint8_t* src, int64_t nbytes,
31
+ uintptr_t block_size, int num_threads);
32
+
33
+ // A helper function for checking if two wrapped objects implementing `Equals`
34
+ // are equal.
35
+ template <typename T>
36
+ bool SharedPtrEquals(const std::shared_ptr<T>& left, const std::shared_ptr<T>& right) {
37
+ if (left == right) return true;
38
+ if (left == NULLPTR || right == NULLPTR) return false;
39
+ return left->Equals(*right);
40
+ }
41
+
42
+ } // namespace internal
43
+ } // namespace arrow