diff --git a/.gitattributes b/.gitattributes index f83429917b7f21487e162946f582ef1be42b4af6..dfb7f5822deaf9f7fde762e1765cac442045be7c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -181,3 +181,4 @@ env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_python.so filter=lfs d env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_dataset.so.1500 filter=lfs diff=lfs merge=lfs -text env-llmeval/lib/python3.10/site-packages/pyarrow/_flight.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text env-llmeval/lib/python3.10/site-packages/pyarrow/libparquet.so.1500 filter=lfs diff=lfs merge=lfs -text +env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1500 filter=lfs diff=lfs merge=lfs -text diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/api.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/api.h new file mode 100644 index 0000000000000000000000000000000000000000..c2ebd9d300727a1a60523ddd5aa483c5cc5ba99f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/api.h @@ -0,0 +1,39 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include "arrow/compute/expression.h" +#include "arrow/dataset/dataset.h" +#include "arrow/dataset/discovery.h" +#include "arrow/dataset/file_base.h" +#ifdef ARROW_CSV +#include "arrow/dataset/file_csv.h" +#endif +#ifdef ARROW_JSON +#include "arrow/dataset/file_json.h" +#endif +#include "arrow/dataset/file_ipc.h" +#ifdef ARROW_ORC +#include "arrow/dataset/file_orc.h" +#endif +#ifdef ARROW_PARQUET +#include "arrow/dataset/file_parquet.h" +#endif +#include "arrow/dataset/scanner.h" diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/dataset.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/dataset.h new file mode 100644 index 0000000000000000000000000000000000000000..1cdd92d5c42f2717c00b7bdeb2c7adc6117754b5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/dataset.h @@ -0,0 +1,481 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/compute/expression.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/util/async_generator_fwd.h" +#include "arrow/util/future.h" +#include "arrow/util/macros.h" +#include "arrow/util/mutex.h" + +namespace arrow { + +namespace internal { +class Executor; +} // namespace internal + +namespace dataset { + +using RecordBatchGenerator = std::function>()>; + +/// \brief Description of a column to scan +struct ARROW_DS_EXPORT FragmentSelectionColumn { + /// \brief The path to the column to load + FieldPath path; + /// \brief The type of the column in the dataset schema + /// + /// A format may choose to ignore this field completely. For example, when + /// reading from IPC the reader can just return the column in the data type + /// that is stored on disk. There is no point in doing anything special. + /// + /// However, some formats may be capable of casting on the fly. For example, + /// when reading from CSV, if we know the target type of the column, we can + /// convert from string to the target type as we read. + DataType* requested_type; +}; + +/// \brief A list of columns that should be loaded from a fragment +/// +/// The paths in this selection should be referring to the fragment schema. This class +/// contains a virtual destructor as it is expected evolution strategies will need to +/// extend this to add any information needed to later evolve the batches. +/// +/// For example, in the basic evolution strategy, we keep track of which columns +/// were missing from the file so that we can fill those in with null when evolving. +class ARROW_DS_EXPORT FragmentSelection { + public: + explicit FragmentSelection(std::vector columns) + : columns_(std::move(columns)) {} + virtual ~FragmentSelection() = default; + /// The columns that should be loaded from the fragment + const std::vector& columns() const { return columns_; } + + private: + std::vector columns_; +}; + +/// \brief Instructions for scanning a particular fragment +/// +/// The fragment scan request is derived from ScanV2Options. The main +/// difference is that the scan options are based on the dataset schema +/// while the fragment request is based on the fragment schema. +struct ARROW_DS_EXPORT FragmentScanRequest { + /// \brief A row filter + /// + /// The filter expression should be written against the fragment schema. + /// + /// \see ScanV2Options for details on how this filter should be applied + compute::Expression filter = compute::literal(true); + + /// \brief The columns to scan + /// + /// These indices refer to the fragment schema + /// + /// Note: This is NOT a simple list of top-level column indices. + /// For more details \see ScanV2Options + /// + /// If possible a fragment should only read from disk the data needed + /// to satisfy these columns. If a format cannot partially read a nested + /// column (e.g. JSON) then it must apply the column selection (in memory) + /// before returning the scanned batch. + std::shared_ptr fragment_selection; + /// \brief Options specific to the format being scanned + const FragmentScanOptions* format_scan_options; +}; + +/// \brief An iterator-like object that can yield batches created from a fragment +class ARROW_DS_EXPORT FragmentScanner { + public: + /// This instance will only be destroyed after all ongoing scan futures + /// have been completed. + /// + /// This means any callbacks created as part of the scan can safely + /// capture `this` + virtual ~FragmentScanner() = default; + /// \brief Scan a batch of data from the file + /// \param batch_number The index of the batch to read + virtual Future> ScanBatch(int batch_number) = 0; + /// \brief Calculate an estimate of how many data bytes the given batch will represent + /// + /// "Data bytes" should be the total size of all the buffers once the data has been + /// decoded into the Arrow format. + virtual int64_t EstimatedDataBytes(int batch_number) = 0; + /// \brief The number of batches in the fragment to scan + virtual int NumBatches() = 0; +}; + +/// \brief Information learned about a fragment through inspection +/// +/// This information can be used to figure out which fields need +/// to be read from a file and how the data read in should be evolved +/// to match the dataset schema. +/// +/// For example, from a CSV file we can inspect and learn the column +/// names and use those column names to determine which columns to load +/// from the CSV file. +struct ARROW_DS_EXPORT InspectedFragment { + explicit InspectedFragment(std::vector column_names) + : column_names(std::move(column_names)) {} + std::vector column_names; +}; + +/// \brief A granular piece of a Dataset, such as an individual file. +/// +/// A Fragment can be read/scanned separately from other fragments. It yields a +/// collection of RecordBatches when scanned +/// +/// Note that Fragments have well defined physical schemas which are reconciled by +/// the Datasets which contain them; these physical schemas may differ from a parent +/// Dataset's schema and the physical schemas of sibling Fragments. +class ARROW_DS_EXPORT Fragment : public std::enable_shared_from_this { + public: + /// \brief An expression that represents no known partition information + static const compute::Expression kNoPartitionInformation; + + /// \brief Return the physical schema of the Fragment. + /// + /// The physical schema is also called the writer schema. + /// This method is blocking and may suffer from high latency filesystem. + /// The schema is cached after being read once, or may be specified at construction. + Result> ReadPhysicalSchema(); + + /// An asynchronous version of Scan + virtual Result ScanBatchesAsync( + const std::shared_ptr& options) = 0; + + /// \brief Inspect a fragment to learn basic information + /// + /// This will be called before a scan and a fragment should attach whatever + /// information will be needed to figure out an evolution strategy. This information + /// will then be passed to the call to BeginScan + virtual Future> InspectFragment( + const FragmentScanOptions* format_options, compute::ExecContext* exec_context); + + /// \brief Start a scan operation + virtual Future> BeginScan( + const FragmentScanRequest& request, const InspectedFragment& inspected_fragment, + const FragmentScanOptions* format_options, compute::ExecContext* exec_context); + + /// \brief Count the number of rows in this fragment matching the filter using metadata + /// only. That is, this method may perform I/O, but will not load data. + /// + /// If this is not possible, resolve with an empty optional. The fragment can perform + /// I/O (e.g. to read metadata) before it deciding whether it can satisfy the request. + virtual Future> CountRows( + compute::Expression predicate, const std::shared_ptr& options); + + virtual std::string type_name() const = 0; + virtual std::string ToString() const { return type_name(); } + + /// \brief An expression which evaluates to true for all data viewed by this + /// Fragment. + const compute::Expression& partition_expression() const { + return partition_expression_; + } + + virtual ~Fragment() = default; + + protected: + Fragment() = default; + explicit Fragment(compute::Expression partition_expression, + std::shared_ptr physical_schema); + + virtual Result> ReadPhysicalSchemaImpl() = 0; + + util::Mutex physical_schema_mutex_; + compute::Expression partition_expression_ = compute::literal(true); + std::shared_ptr physical_schema_; +}; + +/// \brief Per-scan options for fragment(s) in a dataset. +/// +/// These options are not intrinsic to the format or fragment itself, but do affect +/// the results of a scan. These are options which make sense to change between +/// repeated reads of the same dataset, such as format-specific conversion options +/// (that do not affect the schema). +/// +/// \ingroup dataset-scanning +class ARROW_DS_EXPORT FragmentScanOptions { + public: + virtual std::string type_name() const = 0; + virtual std::string ToString() const { return type_name(); } + virtual ~FragmentScanOptions() = default; +}; + +/// \defgroup dataset-implementations Concrete implementations +/// +/// @{ + +/// \brief A trivial Fragment that yields ScanTask out of a fixed set of +/// RecordBatch. +class ARROW_DS_EXPORT InMemoryFragment : public Fragment { + public: + class Scanner; + InMemoryFragment(std::shared_ptr schema, RecordBatchVector record_batches, + compute::Expression = compute::literal(true)); + explicit InMemoryFragment(RecordBatchVector record_batches, + compute::Expression = compute::literal(true)); + + Result ScanBatchesAsync( + const std::shared_ptr& options) override; + Future> CountRows( + compute::Expression predicate, + const std::shared_ptr& options) override; + + Future> InspectFragment( + const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) override; + Future> BeginScan( + const FragmentScanRequest& request, const InspectedFragment& inspected_fragment, + const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) override; + + std::string type_name() const override { return "in-memory"; } + + protected: + Result> ReadPhysicalSchemaImpl() override; + + RecordBatchVector record_batches_; +}; + +/// @} + +using FragmentGenerator = AsyncGenerator>; + +/// \brief Rules for converting the dataset schema to and from fragment schemas +class ARROW_DS_EXPORT FragmentEvolutionStrategy { + public: + /// This instance will only be destroyed when all scan operations for the + /// fragment have completed. + virtual ~FragmentEvolutionStrategy() = default; + /// \brief A guarantee that applies to all batches of this fragment + /// + /// For example, if a fragment is missing one of the fields in the dataset + /// schema then a typical evolution strategy is to set that field to null. + /// + /// So if the column at index 3 is missing then the guarantee is + /// FieldRef(3) == null + /// + /// Individual field guarantees should be AND'd together and returned + /// as a single expression. + virtual Result GetGuarantee( + const std::vector& dataset_schema_selection) const = 0; + + /// \brief Return a fragment schema selection given a dataset schema selection + /// + /// For example, if the user wants fields 2 & 4 of the dataset schema and + /// in this fragment the field 2 is missing and the field 4 is at index 1 then + /// this should return {1} + virtual Result> DevolveSelection( + const std::vector& dataset_schema_selection) const = 0; + + /// \brief Return a filter expression bound to the fragment schema given + /// a filter expression bound to the dataset schema + /// + /// The dataset scan filter will first be simplified by the guarantee returned + /// by GetGuarantee. This means an evolution that only handles dropping or casting + /// fields doesn't need to do anything here except return the given filter. + /// + /// On the other hand, an evolution that is doing some kind of aliasing will likely + /// need to convert field references in the filter to the aliased field references + /// where appropriate. + virtual Result DevolveFilter( + const compute::Expression& filter) const = 0; + + /// \brief Convert a batch from the fragment schema to the dataset schema + /// + /// Typically this involves casting columns from the data type stored on disk + /// to the data type of the dataset schema. For example, this fragment might + /// have columns stored as int32 and the dataset schema might have int64 for + /// the column. In this case we should cast the column from int32 to int64. + /// + /// Note: A fragment may perform this cast as the data is read from disk. In + /// that case a cast might not be needed. + virtual Result EvolveBatch( + const std::shared_ptr& batch, + const std::vector& dataset_selection, + const FragmentSelection& selection) const = 0; + + /// \brief Return a string description of this strategy + virtual std::string ToString() const = 0; +}; + +/// \brief Lookup to create a FragmentEvolutionStrategy for a given fragment +class ARROW_DS_EXPORT DatasetEvolutionStrategy { + public: + virtual ~DatasetEvolutionStrategy() = default; + /// \brief Create a strategy for evolving from the given fragment + /// to the schema of the given dataset + virtual std::unique_ptr GetStrategy( + const Dataset& dataset, const Fragment& fragment, + const InspectedFragment& inspected_fragment) = 0; + + /// \brief Return a string description of this strategy + virtual std::string ToString() const = 0; +}; + +ARROW_DS_EXPORT std::unique_ptr +MakeBasicDatasetEvolutionStrategy(); + +/// \brief A container of zero or more Fragments. +/// +/// A Dataset acts as a union of Fragments, e.g. files deeply nested in a +/// directory. A Dataset has a schema to which Fragments must align during a +/// scan operation. This is analogous to Avro's reader and writer schema. +class ARROW_DS_EXPORT Dataset : public std::enable_shared_from_this { + public: + /// \brief Begin to build a new Scan operation against this Dataset + Result> NewScan(); + + /// \brief GetFragments returns an iterator of Fragments given a predicate. + Result GetFragments(compute::Expression predicate); + Result GetFragments(); + + /// \brief Async versions of `GetFragments`. + Result GetFragmentsAsync(compute::Expression predicate); + Result GetFragmentsAsync(); + + const std::shared_ptr& schema() const { return schema_; } + + /// \brief An expression which evaluates to true for all data viewed by this Dataset. + /// May be null, which indicates no information is available. + const compute::Expression& partition_expression() const { + return partition_expression_; + } + + /// \brief The name identifying the kind of Dataset + virtual std::string type_name() const = 0; + + /// \brief Return a copy of this Dataset with a different schema. + /// + /// The copy will view the same Fragments. If the new schema is not compatible with the + /// original dataset's schema then an error will be raised. + virtual Result> ReplaceSchema( + std::shared_ptr schema) const = 0; + + /// \brief Rules used by this dataset to handle schema evolution + DatasetEvolutionStrategy* evolution_strategy() { return evolution_strategy_.get(); } + + virtual ~Dataset() = default; + + protected: + explicit Dataset(std::shared_ptr schema) : schema_(std::move(schema)) {} + + Dataset(std::shared_ptr schema, compute::Expression partition_expression); + + virtual Result GetFragmentsImpl(compute::Expression predicate) = 0; + /// \brief Default non-virtual implementation method for the base + /// `GetFragmentsAsyncImpl` method, which creates a fragment generator for + /// the dataset, possibly filtering results with a predicate (forwarding to + /// the synchronous `GetFragmentsImpl` method and moving the computations + /// to the background, using the IO thread pool). + /// + /// Currently, `executor` is always the same as `internal::GetCPUThreadPool()`, + /// which means the results from the underlying fragment generator will be + /// transferred to the default CPU thread pool. The generator itself is + /// offloaded to run on the default IO thread pool. + virtual Result GetFragmentsAsyncImpl( + compute::Expression predicate, arrow::internal::Executor* executor); + + std::shared_ptr schema_; + compute::Expression partition_expression_ = compute::literal(true); + std::unique_ptr evolution_strategy_ = + MakeBasicDatasetEvolutionStrategy(); +}; + +/// \addtogroup dataset-implementations +/// +/// @{ + +/// \brief A Source which yields fragments wrapping a stream of record batches. +/// +/// The record batches must match the schema provided to the source at construction. +class ARROW_DS_EXPORT InMemoryDataset : public Dataset { + public: + class RecordBatchGenerator { + public: + virtual ~RecordBatchGenerator() = default; + virtual RecordBatchIterator Get() const = 0; + }; + + /// Construct a dataset from a schema and a factory of record batch iterators. + InMemoryDataset(std::shared_ptr schema, + std::shared_ptr get_batches) + : Dataset(std::move(schema)), get_batches_(std::move(get_batches)) {} + + /// Convenience constructor taking a fixed list of batches + InMemoryDataset(std::shared_ptr schema, RecordBatchVector batches); + + /// Convenience constructor taking a Table + explicit InMemoryDataset(std::shared_ptr table); + + std::string type_name() const override { return "in-memory"; } + + Result> ReplaceSchema( + std::shared_ptr schema) const override; + + protected: + Result GetFragmentsImpl(compute::Expression predicate) override; + + std::shared_ptr get_batches_; +}; + +/// \brief A Dataset wrapping child Datasets. +class ARROW_DS_EXPORT UnionDataset : public Dataset { + public: + /// \brief Construct a UnionDataset wrapping child Datasets. + /// + /// \param[in] schema the schema of the resulting dataset. + /// \param[in] children one or more child Datasets. Their schemas must be identical to + /// schema. + static Result> Make(std::shared_ptr schema, + DatasetVector children); + + const DatasetVector& children() const { return children_; } + + std::string type_name() const override { return "union"; } + + Result> ReplaceSchema( + std::shared_ptr schema) const override; + + protected: + Result GetFragmentsImpl(compute::Expression predicate) override; + + explicit UnionDataset(std::shared_ptr schema, DatasetVector children) + : Dataset(std::move(schema)), children_(std::move(children)) {} + + DatasetVector children_; + + friend class UnionDatasetFactory; +}; + +/// @} + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/dataset_writer.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/dataset_writer.h new file mode 100644 index 0000000000000000000000000000000000000000..edb1649b5f196aa3c6cd923c9e6540c4173fc102 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/dataset_writer.h @@ -0,0 +1,103 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/dataset/file_base.h" +#include "arrow/record_batch.h" +#include "arrow/status.h" +#include "arrow/util/async_util.h" +#include "arrow/util/future.h" + +namespace arrow { +namespace dataset { +namespace internal { + +// This lines up with our other defaults in the scanner and execution plan +constexpr uint64_t kDefaultDatasetWriterMaxRowsQueued = 8 * 1024 * 1024; + +/// \brief Utility class that manages a set of writers to different paths +/// +/// Writers may be closed and reopened (and a new file created) based on the dataset +/// write options (for example, max_rows_per_file or max_open_files) +/// +/// The dataset writer enforces its own back pressure based on the # of rows (as opposed +/// to # of batches which is how it is typically enforced elsewhere) and # of files. +class ARROW_DS_EXPORT DatasetWriter { + public: + /// \brief Create a dataset writer + /// + /// Will fail if basename_template is invalid or if there is existing data and + /// existing_data_behavior is kError + /// + /// \param write_options options to control how the data should be written + /// \param max_rows_queued max # of rows allowed to be queued before the dataset_writer + /// will ask for backpressure + static Result> Make( + FileSystemDatasetWriteOptions write_options, util::AsyncTaskScheduler* scheduler, + std::function pause_callback, std::function resume_callback, + std::function finish_callback, + uint64_t max_rows_queued = kDefaultDatasetWriterMaxRowsQueued); + + ~DatasetWriter(); + + /// \brief Write a batch to the dataset + /// \param[in] batch The batch to write + /// \param[in] directory The directory to write to + /// + /// Note: The written filename will be {directory}/{filename_factory(i)} where i is a + /// counter controlled by `max_open_files` and `max_rows_per_file` + /// + /// If multiple WriteRecordBatch calls arrive with the same `directory` then the batches + /// may be written to the same file. + /// + /// The returned future will be marked finished when the record batch has been queued + /// to be written. If the returned future is unfinished then this indicates the dataset + /// writer's queue is full and the data provider should pause. + /// + /// This method is NOT async reentrant. The returned future will only be unfinished + /// if back pressure needs to be applied. Async reentrancy is not necessary for + /// concurrent writes to happen. Calling this method again before the previous future + /// completes will not just violate max_rows_queued but likely lead to race conditions. + /// + /// One thing to note is that the ordering of your data can affect your maximum + /// potential parallelism. If this seems odd then consider a dataset where the first + /// 1000 batches go to the same directory and then the 1001st batch goes to a different + /// directory. The only way to get two parallel writes immediately would be to queue + /// all 1000 pending writes to the first directory. + void WriteRecordBatch(std::shared_ptr batch, const std::string& directory, + const std::string& prefix = ""); + + /// Finish all pending writes and close any open files + void Finish(); + + protected: + DatasetWriter(FileSystemDatasetWriteOptions write_options, + util::AsyncTaskScheduler* scheduler, std::function pause_callback, + std::function resume_callback, + std::function finish_callback, + uint64_t max_rows_queued = kDefaultDatasetWriterMaxRowsQueued); + + class DatasetWriterImpl; + std::unique_ptr impl_; +}; + +} // namespace internal +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_base.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_base.h new file mode 100644 index 0000000000000000000000000000000000000000..46fc8ebc40db097a0bb3fc25f00351c68e36991f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_base.h @@ -0,0 +1,495 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/dataset/dataset.h" +#include "arrow/dataset/partition.h" +#include "arrow/dataset/scanner.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/filesystem/filesystem.h" +#include "arrow/io/file.h" +#include "arrow/type_fwd.h" +#include "arrow/util/compression.h" + +namespace arrow { + +namespace dataset { + +/// \defgroup dataset-file-formats File formats for reading and writing datasets +/// \defgroup dataset-filesystem File system datasets +/// +/// @{ + +/// \brief The path and filesystem where an actual file is located or a buffer which can +/// be read like a file +class ARROW_DS_EXPORT FileSource : public util::EqualityComparable { + public: + FileSource(std::string path, std::shared_ptr filesystem, + Compression::type compression = Compression::UNCOMPRESSED) + : file_info_(std::move(path)), + filesystem_(std::move(filesystem)), + compression_(compression) {} + + FileSource(fs::FileInfo info, std::shared_ptr filesystem, + Compression::type compression = Compression::UNCOMPRESSED) + : file_info_(std::move(info)), + filesystem_(std::move(filesystem)), + compression_(compression) {} + + explicit FileSource(std::shared_ptr buffer, + Compression::type compression = Compression::UNCOMPRESSED) + : buffer_(std::move(buffer)), compression_(compression) {} + + using CustomOpen = std::function>()>; + FileSource(CustomOpen open, int64_t size) + : custom_open_(std::move(open)), custom_size_(size) {} + + using CustomOpenWithCompression = + std::function>(Compression::type)>; + FileSource(CustomOpenWithCompression open_with_compression, int64_t size, + Compression::type compression = Compression::UNCOMPRESSED) + : custom_open_(std::bind(std::move(open_with_compression), compression)), + custom_size_(size), + compression_(compression) {} + + FileSource(std::shared_ptr file, int64_t size, + Compression::type compression = Compression::UNCOMPRESSED) + : custom_open_([=] { return ToResult(file); }), + custom_size_(size), + compression_(compression) {} + + explicit FileSource(std::shared_ptr file, + Compression::type compression = Compression::UNCOMPRESSED); + + FileSource() : custom_open_(CustomOpen{&InvalidOpen}) {} + + static std::vector FromPaths(const std::shared_ptr& fs, + std::vector paths) { + std::vector sources; + for (auto&& path : paths) { + sources.emplace_back(std::move(path), fs); + } + return sources; + } + + /// \brief Return the type of raw compression on the file, if any. + Compression::type compression() const { return compression_; } + + /// \brief Return the file path, if any. Only valid when file source wraps a path. + const std::string& path() const { + static std::string buffer_path = ""; + static std::string custom_open_path = ""; + return filesystem_ ? file_info_.path() : buffer_ ? buffer_path : custom_open_path; + } + + /// \brief Return the filesystem, if any. Otherwise returns nullptr + const std::shared_ptr& filesystem() const { return filesystem_; } + + /// \brief Return the buffer containing the file, if any. Otherwise returns nullptr + const std::shared_ptr& buffer() const { return buffer_; } + + /// \brief Get a RandomAccessFile which views this file source + Result> Open() const; + Future> OpenAsync() const; + + /// \brief Get the size (in bytes) of the file or buffer + /// If the file is compressed this should be the compressed (on-disk) size. + int64_t Size() const; + + /// \brief Get an InputStream which views this file source (and decompresses if needed) + /// \param[in] compression If nullopt, guess the compression scheme from the + /// filename, else decompress with the given codec + Result> OpenCompressed( + std::optional compression = std::nullopt) const; + + /// \brief equality comparison with another FileSource + bool Equals(const FileSource& other) const; + + private: + static Result> InvalidOpen() { + return Status::Invalid("Called Open() on an uninitialized FileSource"); + } + + fs::FileInfo file_info_; + std::shared_ptr filesystem_; + std::shared_ptr buffer_; + CustomOpen custom_open_; + int64_t custom_size_ = 0; + Compression::type compression_ = Compression::UNCOMPRESSED; +}; + +/// \brief Base class for file format implementation +class ARROW_DS_EXPORT FileFormat : public std::enable_shared_from_this { + public: + /// Options affecting how this format is scanned. + /// + /// The options here can be overridden at scan time. + std::shared_ptr default_fragment_scan_options; + + virtual ~FileFormat() = default; + + /// \brief The name identifying the kind of file format + virtual std::string type_name() const = 0; + + virtual bool Equals(const FileFormat& other) const = 0; + + /// \brief Indicate if the FileSource is supported/readable by this format. + virtual Result IsSupported(const FileSource& source) const = 0; + + /// \brief Return the schema of the file if possible. + virtual Result> Inspect(const FileSource& source) const = 0; + + /// \brief Learn what we need about the file before we start scanning it + virtual Future> InspectFragment( + const FileSource& source, const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) const; + + virtual Result ScanBatchesAsync( + const std::shared_ptr& options, + const std::shared_ptr& file) const = 0; + + virtual Future> CountRows( + const std::shared_ptr& file, compute::Expression predicate, + const std::shared_ptr& options); + + virtual Future> BeginScan( + const FragmentScanRequest& request, const InspectedFragment& inspected_fragment, + const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) const; + + /// \brief Open a fragment + virtual Result> MakeFragment( + FileSource source, compute::Expression partition_expression, + std::shared_ptr physical_schema); + + /// \brief Create a FileFragment for a FileSource. + Result> MakeFragment( + FileSource source, compute::Expression partition_expression); + + /// \brief Create a FileFragment for a FileSource. + Result> MakeFragment( + FileSource source, std::shared_ptr physical_schema = NULLPTR); + + /// \brief Create a writer for this format. + virtual Result> MakeWriter( + std::shared_ptr destination, std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator) const = 0; + + /// \brief Get default write options for this format. + /// + /// May return null shared_ptr if this file format does not yet support + /// writing datasets. + virtual std::shared_ptr DefaultWriteOptions() = 0; + + protected: + explicit FileFormat(std::shared_ptr default_fragment_scan_options) + : default_fragment_scan_options(std::move(default_fragment_scan_options)) {} +}; + +/// \brief A Fragment that is stored in a file with a known format +class ARROW_DS_EXPORT FileFragment : public Fragment, + public util::EqualityComparable { + public: + Result ScanBatchesAsync( + const std::shared_ptr& options) override; + Future> CountRows( + compute::Expression predicate, + const std::shared_ptr& options) override; + Future> BeginScan( + const FragmentScanRequest& request, const InspectedFragment& inspected_fragment, + const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) override; + Future> InspectFragment( + const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) override; + + std::string type_name() const override { return format_->type_name(); } + std::string ToString() const override { return source_.path(); }; + + const FileSource& source() const { return source_; } + const std::shared_ptr& format() const { return format_; } + + bool Equals(const FileFragment& other) const; + + protected: + FileFragment(FileSource source, std::shared_ptr format, + compute::Expression partition_expression, + std::shared_ptr physical_schema) + : Fragment(std::move(partition_expression), std::move(physical_schema)), + source_(std::move(source)), + format_(std::move(format)) {} + + Result> ReadPhysicalSchemaImpl() override; + + FileSource source_; + std::shared_ptr format_; + + friend class FileFormat; +}; + +/// \brief A Dataset of FileFragments. +/// +/// A FileSystemDataset is composed of one or more FileFragment. The fragments +/// are independent and don't need to share the same format and/or filesystem. +class ARROW_DS_EXPORT FileSystemDataset : public Dataset { + public: + /// \brief Create a FileSystemDataset. + /// + /// \param[in] schema the schema of the dataset + /// \param[in] root_partition the partition expression of the dataset + /// \param[in] format the format of each FileFragment. + /// \param[in] filesystem the filesystem of each FileFragment, or nullptr if the + /// fragments wrap buffers. + /// \param[in] fragments list of fragments to create the dataset from. + /// \param[in] partitioning the Partitioning object in case the dataset is created + /// with a known partitioning (e.g. from a discovered partitioning + /// through a DatasetFactory), or nullptr if not known. + /// + /// Note that fragments wrapping files resident in differing filesystems are not + /// permitted; to work with multiple filesystems use a UnionDataset. + /// + /// \return A constructed dataset. + static Result> Make( + std::shared_ptr schema, compute::Expression root_partition, + std::shared_ptr format, std::shared_ptr filesystem, + std::vector> fragments, + std::shared_ptr partitioning = NULLPTR); + + /// \brief Write a dataset. + static Status Write(const FileSystemDatasetWriteOptions& write_options, + std::shared_ptr scanner); + + /// \brief Return the type name of the dataset. + std::string type_name() const override { return "filesystem"; } + + /// \brief Replace the schema of the dataset. + Result> ReplaceSchema( + std::shared_ptr schema) const override; + + /// \brief Return the path of files. + std::vector files() const; + + /// \brief Return the format. + const std::shared_ptr& format() const { return format_; } + + /// \brief Return the filesystem. May be nullptr if the fragments wrap buffers. + const std::shared_ptr& filesystem() const { return filesystem_; } + + /// \brief Return the partitioning. May be nullptr if the dataset was not constructed + /// with a partitioning. + const std::shared_ptr& partitioning() const { return partitioning_; } + + std::string ToString() const; + + protected: + struct FragmentSubtrees; + + explicit FileSystemDataset(std::shared_ptr schema) + : Dataset(std::move(schema)) {} + + FileSystemDataset(std::shared_ptr schema, + compute::Expression partition_expression) + : Dataset(std::move(schema), partition_expression) {} + + Result GetFragmentsImpl(compute::Expression predicate) override; + + void SetupSubtreePruning(); + + std::shared_ptr format_; + std::shared_ptr filesystem_; + std::vector> fragments_; + std::shared_ptr partitioning_; + + std::shared_ptr subtrees_; +}; + +/// \brief Options for writing a file of this format. +class ARROW_DS_EXPORT FileWriteOptions { + public: + virtual ~FileWriteOptions() = default; + + const std::shared_ptr& format() const { return format_; } + + std::string type_name() const { return format_->type_name(); } + + protected: + explicit FileWriteOptions(std::shared_ptr format) + : format_(std::move(format)) {} + + std::shared_ptr format_; +}; + +/// \brief A writer for this format. +class ARROW_DS_EXPORT FileWriter { + public: + virtual ~FileWriter() = default; + + /// \brief Write the given batch. + virtual Status Write(const std::shared_ptr& batch) = 0; + + /// \brief Write all batches from the reader. + Status Write(RecordBatchReader* batches); + + /// \brief Indicate that writing is done. + virtual Future<> Finish(); + + const std::shared_ptr& format() const { return options_->format(); } + const std::shared_ptr& schema() const { return schema_; } + const std::shared_ptr& options() const { return options_; } + const fs::FileLocator& destination() const { return destination_locator_; } + + /// \brief After Finish() is called, provides number of bytes written to file. + Result GetBytesWritten() const; + + protected: + FileWriter(std::shared_ptr schema, std::shared_ptr options, + std::shared_ptr destination, + fs::FileLocator destination_locator) + : schema_(std::move(schema)), + options_(std::move(options)), + destination_(std::move(destination)), + destination_locator_(std::move(destination_locator)) {} + + virtual Future<> FinishInternal() = 0; + + std::shared_ptr schema_; + std::shared_ptr options_; + std::shared_ptr destination_; + fs::FileLocator destination_locator_; + std::optional bytes_written_; +}; + +/// \brief Options for writing a dataset. +struct ARROW_DS_EXPORT FileSystemDatasetWriteOptions { + /// Options for individual fragment writing. + std::shared_ptr file_write_options; + + /// FileSystem into which a dataset will be written. + std::shared_ptr filesystem; + + /// Root directory into which the dataset will be written. + std::string base_dir; + + /// Partitioning used to generate fragment paths. + std::shared_ptr partitioning; + + /// Maximum number of partitions any batch may be written into, default is 1K. + int max_partitions = 1024; + + /// Template string used to generate fragment basenames. + /// {i} will be replaced by an auto incremented integer. + std::string basename_template; + + /// A functor which will be applied on an incremented counter. The result will be + /// inserted into the basename_template in place of {i}. + /// + /// This can be used, for example, to left-pad the file counter. + std::function basename_template_functor; + + /// If greater than 0 then this will limit the maximum number of files that can be left + /// open. If an attempt is made to open too many files then the least recently used file + /// will be closed. If this setting is set too low you may end up fragmenting your data + /// into many small files. + /// + /// The default is 900 which also allows some # of files to be open by the scanner + /// before hitting the default Linux limit of 1024 + uint32_t max_open_files = 900; + + /// If greater than 0 then this will limit how many rows are placed in any single file. + /// Otherwise there will be no limit and one file will be created in each output + /// directory unless files need to be closed to respect max_open_files + uint64_t max_rows_per_file = 0; + + /// If greater than 0 then this will cause the dataset writer to batch incoming data + /// and only write the row groups to the disk when sufficient rows have accumulated. + /// The final row group size may be less than this value and other options such as + /// `max_open_files` or `max_rows_per_file` lead to smaller row group sizes. + uint64_t min_rows_per_group = 0; + + /// If greater than 0 then the dataset writer may split up large incoming batches into + /// multiple row groups. If this value is set then min_rows_per_group should also be + /// set or else you may end up with very small row groups (e.g. if the incoming row + /// group size is just barely larger than this value). + uint64_t max_rows_per_group = 1 << 20; + + /// Controls what happens if an output directory already exists. + ExistingDataBehavior existing_data_behavior = ExistingDataBehavior::kError; + + /// \brief If false the dataset writer will not create directories + /// This is mainly intended for filesystems that do not require directories such as S3. + bool create_dir = true; + + /// Callback to be invoked against all FileWriters before + /// they are finalized with FileWriter::Finish(). + std::function writer_pre_finish = [](FileWriter*) { + return Status::OK(); + }; + + /// Callback to be invoked against all FileWriters after they have + /// called FileWriter::Finish(). + std::function writer_post_finish = [](FileWriter*) { + return Status::OK(); + }; + + const std::shared_ptr& format() const { + return file_write_options->format(); + } +}; + +/// \brief Wraps FileSystemDatasetWriteOptions for consumption as compute::ExecNodeOptions +class ARROW_DS_EXPORT WriteNodeOptions : public acero::ExecNodeOptions { + public: + explicit WriteNodeOptions( + FileSystemDatasetWriteOptions options, + std::shared_ptr custom_metadata = NULLPTR) + : write_options(std::move(options)), custom_metadata(std::move(custom_metadata)) {} + + /// \brief Options to control how to write the dataset + FileSystemDatasetWriteOptions write_options; + /// \brief Optional schema to attach to all written batches + /// + /// By default, we will use the output schema of the input. + /// + /// This can be used to alter schema metadata, field nullability, or field metadata. + /// However, this cannot be used to change the type of data. If the custom schema does + /// not have the same number of fields and the same data types as the input then the + /// plan will fail. + std::shared_ptr custom_schema; + /// \brief Optional metadata to attach to written batches + std::shared_ptr custom_metadata; +}; + +/// @} + +namespace internal { +ARROW_DS_EXPORT void InitializeDatasetWriter(arrow::acero::ExecFactoryRegistry* registry); +} + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_csv.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_csv.h new file mode 100644 index 0000000000000000000000000000000000000000..42e3fd7246988e625e0d2e69a29bd40c553e3219 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_csv.h @@ -0,0 +1,144 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/csv/options.h" +#include "arrow/dataset/dataset.h" +#include "arrow/dataset/file_base.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/ipc/type_fwd.h" +#include "arrow/status.h" +#include "arrow/util/compression.h" + +namespace arrow { +namespace dataset { + +constexpr char kCsvTypeName[] = "csv"; + +/// \addtogroup dataset-file-formats +/// +/// @{ + +/// \brief A FileFormat implementation that reads from and writes to Csv files +class ARROW_DS_EXPORT CsvFileFormat : public FileFormat { + public: + // TODO(ARROW-18328) Remove this, moved to CsvFragmentScanOptions + /// Options affecting the parsing of CSV files + csv::ParseOptions parse_options = csv::ParseOptions::Defaults(); + + CsvFileFormat(); + + std::string type_name() const override { return kCsvTypeName; } + + bool Equals(const FileFormat& other) const override; + + Result IsSupported(const FileSource& source) const override; + + /// \brief Return the schema of the file if possible. + Result> Inspect(const FileSource& source) const override; + + Future> BeginScan( + const FragmentScanRequest& request, const InspectedFragment& inspected_fragment, + const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) const override; + + Result ScanBatchesAsync( + const std::shared_ptr& scan_options, + const std::shared_ptr& file) const override; + + Future> InspectFragment( + const FileSource& source, const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) const override; + + Future> CountRows( + const std::shared_ptr& file, compute::Expression predicate, + const std::shared_ptr& options) override; + + Result> MakeWriter( + std::shared_ptr destination, std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator) const override; + + std::shared_ptr DefaultWriteOptions() override; +}; + +/// \brief Per-scan options for CSV fragments +struct ARROW_DS_EXPORT CsvFragmentScanOptions : public FragmentScanOptions { + std::string type_name() const override { return kCsvTypeName; } + + using StreamWrapFunc = std::function>( + std::shared_ptr)>; + + /// CSV conversion options + csv::ConvertOptions convert_options = csv::ConvertOptions::Defaults(); + + /// CSV reading options + /// + /// Note that use_threads is always ignored. + csv::ReadOptions read_options = csv::ReadOptions::Defaults(); + + /// CSV parse options + csv::ParseOptions parse_options = csv::ParseOptions::Defaults(); + + /// Optional stream wrapping function + /// + /// If defined, all open dataset file fragments will be passed + /// through this function. One possible use case is to transparently + /// transcode all input files from a given character set to utf8. + StreamWrapFunc stream_transform_func{}; +}; + +class ARROW_DS_EXPORT CsvFileWriteOptions : public FileWriteOptions { + public: + /// Options passed to csv::MakeCSVWriter. + std::shared_ptr write_options; + + protected: + explicit CsvFileWriteOptions(std::shared_ptr format) + : FileWriteOptions(std::move(format)) {} + + friend class CsvFileFormat; +}; + +class ARROW_DS_EXPORT CsvFileWriter : public FileWriter { + public: + Status Write(const std::shared_ptr& batch) override; + + private: + CsvFileWriter(std::shared_ptr destination, + std::shared_ptr writer, + std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator); + + Future<> FinishInternal() override; + + std::shared_ptr destination_; + std::shared_ptr batch_writer_; + + friend class CsvFileFormat; +}; + +/// @} + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_ipc.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..0f7da82a0af5b1e58b724646853e8f482781778b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_ipc.h @@ -0,0 +1,123 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include + +#include "arrow/dataset/file_base.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/io/type_fwd.h" +#include "arrow/ipc/type_fwd.h" +#include "arrow/result.h" + +namespace arrow { +namespace dataset { + +/// \addtogroup dataset-file-formats +/// +/// @{ + +constexpr char kIpcTypeName[] = "ipc"; + +/// \brief A FileFormat implementation that reads from and writes to Ipc files +class ARROW_DS_EXPORT IpcFileFormat : public FileFormat { + public: + std::string type_name() const override { return kIpcTypeName; } + + IpcFileFormat(); + + bool Equals(const FileFormat& other) const override { + return type_name() == other.type_name(); + } + + Result IsSupported(const FileSource& source) const override; + + /// \brief Return the schema of the file if possible. + Result> Inspect(const FileSource& source) const override; + + Result ScanBatchesAsync( + const std::shared_ptr& options, + const std::shared_ptr& file) const override; + + Future> CountRows( + const std::shared_ptr& file, compute::Expression predicate, + const std::shared_ptr& options) override; + + Result> MakeWriter( + std::shared_ptr destination, std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator) const override; + + std::shared_ptr DefaultWriteOptions() override; +}; + +/// \brief Per-scan options for IPC fragments +class ARROW_DS_EXPORT IpcFragmentScanOptions : public FragmentScanOptions { + public: + std::string type_name() const override { return kIpcTypeName; } + + /// Options passed to the IPC file reader. + /// included_fields, memory_pool, and use_threads are ignored. + std::shared_ptr options; + /// If present, the async scanner will enable I/O coalescing. + /// This is ignored by the sync scanner. + std::shared_ptr cache_options; +}; + +class ARROW_DS_EXPORT IpcFileWriteOptions : public FileWriteOptions { + public: + /// Options passed to ipc::MakeFileWriter. use_threads is ignored + std::shared_ptr options; + + /// custom_metadata written to the file's footer + std::shared_ptr metadata; + + protected: + explicit IpcFileWriteOptions(std::shared_ptr format) + : FileWriteOptions(std::move(format)) {} + + friend class IpcFileFormat; +}; + +class ARROW_DS_EXPORT IpcFileWriter : public FileWriter { + public: + Status Write(const std::shared_ptr& batch) override; + + private: + IpcFileWriter(std::shared_ptr destination, + std::shared_ptr writer, + std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator); + + Future<> FinishInternal() override; + + std::shared_ptr destination_; + std::shared_ptr batch_writer_; + + friend class IpcFileFormat; +}; + +/// @} + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_json.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_json.h new file mode 100644 index 0000000000000000000000000000000000000000..4b8112d87095ccc9d02b0c52b4df2b1e674b8cc5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_json.h @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/dataset/dataset.h" +#include "arrow/dataset/file_base.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/ipc/type_fwd.h" +#include "arrow/json/options.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/future.h" +#include "arrow/util/macros.h" + +namespace arrow::dataset { + +/// \addtogroup dataset-file-formats +/// +/// @{ + +constexpr char kJsonTypeName[] = "json"; + +/// \brief A FileFormat implementation that reads from JSON files +class ARROW_DS_EXPORT JsonFileFormat : public FileFormat { + public: + JsonFileFormat(); + + std::string type_name() const override { return kJsonTypeName; } + + bool Equals(const FileFormat& other) const override; + + Result IsSupported(const FileSource& source) const override; + + Result> Inspect(const FileSource& source) const override; + + Future> InspectFragment( + const FileSource& source, const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) const override; + + Future> BeginScan( + const FragmentScanRequest& scan_request, const InspectedFragment& inspected, + const FragmentScanOptions* format_options, + compute::ExecContext* exec_context) const override; + + Result ScanBatchesAsync( + const std::shared_ptr& scan_options, + const std::shared_ptr& file) const override; + + Future> CountRows( + const std::shared_ptr& file, compute::Expression predicate, + const std::shared_ptr& scan_options) override; + + Result> MakeWriter( + std::shared_ptr destination, std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator) const override { + return Status::NotImplemented("Writing JSON files is not currently supported"); + } + + std::shared_ptr DefaultWriteOptions() override { return NULLPTR; } +}; + +/// \brief Per-scan options for JSON fragments +struct ARROW_DS_EXPORT JsonFragmentScanOptions : public FragmentScanOptions { + std::string type_name() const override { return kJsonTypeName; } + + /// @brief Options that affect JSON parsing + /// + /// Note: `explicit_schema` and `unexpected_field_behavior` are ignored. + json::ParseOptions parse_options = json::ParseOptions::Defaults(); + + /// @brief Options that affect JSON reading + json::ReadOptions read_options = json::ReadOptions::Defaults(); +}; + +/// @} + +} // namespace arrow::dataset diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_orc.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_orc.h new file mode 100644 index 0000000000000000000000000000000000000000..5bfefd1e02b5cccf74cf8ade579a937341aef013 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_orc.h @@ -0,0 +1,75 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include + +#include "arrow/dataset/file_base.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/io/type_fwd.h" +#include "arrow/result.h" + +namespace arrow { +namespace dataset { + +/// \addtogroup dataset-file-formats +/// +/// @{ + +constexpr char kOrcTypeName[] = "orc"; + +/// \brief A FileFormat implementation that reads from and writes to ORC files +class ARROW_DS_EXPORT OrcFileFormat : public FileFormat { + public: + OrcFileFormat(); + + std::string type_name() const override { return kOrcTypeName; } + + bool Equals(const FileFormat& other) const override { + return type_name() == other.type_name(); + } + + Result IsSupported(const FileSource& source) const override; + + /// \brief Return the schema of the file if possible. + Result> Inspect(const FileSource& source) const override; + + Result ScanBatchesAsync( + const std::shared_ptr& options, + const std::shared_ptr& file) const override; + + Future> CountRows( + const std::shared_ptr& file, compute::Expression predicate, + const std::shared_ptr& options) override; + + Result> MakeWriter( + std::shared_ptr destination, std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator) const override; + + std::shared_ptr DefaultWriteOptions() override; +}; + +/// @} + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_parquet.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_parquet.h new file mode 100644 index 0000000000000000000000000000000000000000..63d8fd729223cdf8813d074c731784368e01a89e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/file_parquet.h @@ -0,0 +1,404 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/dataset/discovery.h" +#include "arrow/dataset/file_base.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/io/caching.h" + +namespace parquet { +class ParquetFileReader; +class Statistics; +class ColumnChunkMetaData; +class RowGroupMetaData; +class FileMetaData; +class FileDecryptionProperties; +class FileEncryptionProperties; + +class ReaderProperties; +class ArrowReaderProperties; + +class WriterProperties; +class ArrowWriterProperties; + +namespace arrow { +class FileReader; +class FileWriter; +struct SchemaManifest; +} // namespace arrow +} // namespace parquet + +namespace arrow { +namespace dataset { + +struct ParquetDecryptionConfig; +struct ParquetEncryptionConfig; + +/// \addtogroup dataset-file-formats +/// +/// @{ + +constexpr char kParquetTypeName[] = "parquet"; + +/// \brief A FileFormat implementation that reads from Parquet files +class ARROW_DS_EXPORT ParquetFileFormat : public FileFormat { + public: + ParquetFileFormat(); + + /// Convenience constructor which copies properties from a parquet::ReaderProperties. + /// memory_pool will be ignored. + explicit ParquetFileFormat(const parquet::ReaderProperties& reader_properties); + + std::string type_name() const override { return kParquetTypeName; } + + bool Equals(const FileFormat& other) const override; + + struct ReaderOptions { + /// \defgroup parquet-file-format-arrow-reader-properties properties which correspond + /// to members of parquet::ArrowReaderProperties. + /// + /// We don't embed parquet::ReaderProperties directly because column names (rather + /// than indices) are used to indicate dictionary columns, and other options are + /// deferred to scan time. + /// + /// @{ + std::unordered_set dict_columns; + arrow::TimeUnit::type coerce_int96_timestamp_unit = arrow::TimeUnit::NANO; + /// @} + } reader_options; + + Result IsSupported(const FileSource& source) const override; + + /// \brief Return the schema of the file if possible. + Result> Inspect(const FileSource& source) const override; + + Result ScanBatchesAsync( + const std::shared_ptr& options, + const std::shared_ptr& file) const override; + + Future> CountRows( + const std::shared_ptr& file, compute::Expression predicate, + const std::shared_ptr& options) override; + + using FileFormat::MakeFragment; + + /// \brief Create a Fragment targeting all RowGroups. + Result> MakeFragment( + FileSource source, compute::Expression partition_expression, + std::shared_ptr physical_schema) override; + + /// \brief Create a Fragment, restricted to the specified row groups. + Result> MakeFragment( + FileSource source, compute::Expression partition_expression, + std::shared_ptr physical_schema, std::vector row_groups); + + /// \brief Return a FileReader on the given source. + Result> GetReader( + const FileSource& source, const std::shared_ptr& options) const; + + Result> GetReader( + const FileSource& source, const std::shared_ptr& options, + const std::shared_ptr& metadata) const; + + Future> GetReaderAsync( + const FileSource& source, const std::shared_ptr& options) const; + + Future> GetReaderAsync( + const FileSource& source, const std::shared_ptr& options, + const std::shared_ptr& metadata) const; + + Result> MakeWriter( + std::shared_ptr destination, std::shared_ptr schema, + std::shared_ptr options, + fs::FileLocator destination_locator) const override; + + std::shared_ptr DefaultWriteOptions() override; +}; + +/// \brief A FileFragment with parquet logic. +/// +/// ParquetFileFragment provides a lazy (with respect to IO) interface to +/// scan parquet files. Any heavy IO calls are deferred to the Scan() method. +/// +/// The caller can provide an optional list of selected RowGroups to limit the +/// number of scanned RowGroups, or to partition the scans across multiple +/// threads. +/// +/// Metadata can be explicitly provided, enabling pushdown predicate benefits without +/// the potentially heavy IO of loading Metadata from the file system. This can induce +/// significant performance boost when scanning high latency file systems. +class ARROW_DS_EXPORT ParquetFileFragment : public FileFragment { + public: + Result SplitByRowGroup(compute::Expression predicate); + + /// \brief Return the RowGroups selected by this fragment. + const std::vector& row_groups() const { + if (row_groups_) return *row_groups_; + static std::vector empty; + return empty; + } + + /// \brief Return the FileMetaData associated with this fragment. + std::shared_ptr metadata(); + + /// \brief Ensure this fragment's FileMetaData is in memory. + Status EnsureCompleteMetadata(parquet::arrow::FileReader* reader = NULLPTR); + + /// \brief Return fragment which selects a filtered subset of this fragment's RowGroups. + Result> Subset(compute::Expression predicate); + Result> Subset(std::vector row_group_ids); + + static std::optional EvaluateStatisticsAsExpression( + const Field& field, const parquet::Statistics& statistics); + + static std::optional EvaluateStatisticsAsExpression( + const Field& field, const FieldRef& field_ref, + const parquet::Statistics& statistics); + + private: + ParquetFileFragment(FileSource source, std::shared_ptr format, + compute::Expression partition_expression, + std::shared_ptr physical_schema, + std::optional> row_groups); + + Status SetMetadata(std::shared_ptr metadata, + std::shared_ptr manifest, + std::shared_ptr original_metadata = {}); + + // Overridden to opportunistically set metadata since a reader must be opened anyway. + Result> ReadPhysicalSchemaImpl() override { + ARROW_RETURN_NOT_OK(EnsureCompleteMetadata()); + return physical_schema_; + } + + /// Return a filtered subset of row group indices. + Result> FilterRowGroups(compute::Expression predicate); + /// Simplify the predicate against the statistics of each row group. + Result> TestRowGroups(compute::Expression predicate); + /// Try to count rows matching the predicate using metadata. Expects + /// metadata to be present, and expects the predicate to have been + /// simplified against the partition expression already. + Result> TryCountRows(compute::Expression predicate); + + ParquetFileFormat& parquet_format_; + + /// Indices of row groups selected by this fragment, + /// or std::nullopt if all row groups are selected. + std::optional> row_groups_; + + // the expressions (combined for all columns for which statistics have been + // processed) are stored per column group + std::vector statistics_expressions_; + // statistics status are kept track of by Parquet Schema column indices + // (i.e. not Arrow schema field index) + std::vector statistics_expressions_complete_; + std::shared_ptr metadata_; + std::shared_ptr manifest_; + // The FileMetaData that owns the SchemaDescriptor pointed by SchemaManifest. + std::shared_ptr original_metadata_; + + friend class ParquetFileFormat; + friend class ParquetDatasetFactory; +}; + +/// \brief Per-scan options for Parquet fragments +class ARROW_DS_EXPORT ParquetFragmentScanOptions : public FragmentScanOptions { + public: + ParquetFragmentScanOptions(); + std::string type_name() const override { return kParquetTypeName; } + + /// Reader properties. Not all properties are respected: memory_pool comes from + /// ScanOptions. + std::shared_ptr reader_properties; + /// Arrow reader properties. Not all properties are respected: batch_size comes from + /// ScanOptions. Additionally, dictionary columns come from + /// ParquetFileFormat::ReaderOptions::dict_columns. + std::shared_ptr arrow_reader_properties; + /// A configuration structure that provides decryption properties for a dataset + std::shared_ptr parquet_decryption_config = NULLPTR; +}; + +class ARROW_DS_EXPORT ParquetFileWriteOptions : public FileWriteOptions { + public: + /// \brief Parquet writer properties. + std::shared_ptr writer_properties; + + /// \brief Parquet Arrow writer properties. + std::shared_ptr arrow_writer_properties; + + // A configuration structure that provides encryption properties for a dataset + std::shared_ptr parquet_encryption_config = NULLPTR; + + protected: + explicit ParquetFileWriteOptions(std::shared_ptr format) + : FileWriteOptions(std::move(format)) {} + + friend class ParquetFileFormat; +}; + +class ARROW_DS_EXPORT ParquetFileWriter : public FileWriter { + public: + const std::shared_ptr& parquet_writer() const { + return parquet_writer_; + } + + Status Write(const std::shared_ptr& batch) override; + + private: + ParquetFileWriter(std::shared_ptr destination, + std::shared_ptr writer, + std::shared_ptr options, + fs::FileLocator destination_locator); + + Future<> FinishInternal() override; + + std::shared_ptr parquet_writer_; + + friend class ParquetFileFormat; +}; + +/// \brief Options for making a FileSystemDataset from a Parquet _metadata file. +struct ParquetFactoryOptions { + /// Either an explicit Partitioning or a PartitioningFactory to discover one. + /// + /// If a factory is provided, it will be used to infer a schema for partition fields + /// based on file and directory paths then construct a Partitioning. The default + /// is a Partitioning which will yield no partition information. + /// + /// The (explicit or discovered) partitioning will be applied to discovered files + /// and the resulting partition information embedded in the Dataset. + PartitioningOrFactory partitioning{Partitioning::Default()}; + + /// For the purposes of applying the partitioning, paths will be stripped + /// of the partition_base_dir. Files not matching the partition_base_dir + /// prefix will be skipped for partition discovery. The ignored files will still + /// be part of the Dataset, but will not have partition information. + /// + /// Example: + /// partition_base_dir = "/dataset"; + /// + /// - "/dataset/US/sales.csv" -> "US/sales.csv" will be given to the partitioning + /// + /// - "/home/john/late_sales.csv" -> Will be ignored for partition discovery. + /// + /// This is useful for partitioning which parses directory when ordering + /// is important, e.g. DirectoryPartitioning. + std::string partition_base_dir; + + /// Assert that all ColumnChunk paths are consistent. The parquet spec allows for + /// ColumnChunk data to be stored in multiple files, but ParquetDatasetFactory + /// supports only a single file with all ColumnChunk data. If this flag is set + /// construction of a ParquetDatasetFactory will raise an error if ColumnChunk + /// data is not resident in a single file. + bool validate_column_chunk_paths = false; +}; + +/// \brief Create FileSystemDataset from custom `_metadata` cache file. +/// +/// Dask and other systems will generate a cache metadata file by concatenating +/// the RowGroupMetaData of multiple parquet files into a single parquet file +/// that only contains metadata and no ColumnChunk data. +/// +/// ParquetDatasetFactory creates a FileSystemDataset composed of +/// ParquetFileFragment where each fragment is pre-populated with the exact +/// number of row groups and statistics for each columns. +class ARROW_DS_EXPORT ParquetDatasetFactory : public DatasetFactory { + public: + /// \brief Create a ParquetDatasetFactory from a metadata path. + /// + /// The `metadata_path` will be read from `filesystem`. Each RowGroup + /// contained in the metadata file will be relative to `dirname(metadata_path)`. + /// + /// \param[in] metadata_path path of the metadata parquet file + /// \param[in] filesystem from which to open/read the path + /// \param[in] format to read the file with. + /// \param[in] options see ParquetFactoryOptions + static Result> Make( + const std::string& metadata_path, std::shared_ptr filesystem, + std::shared_ptr format, ParquetFactoryOptions options); + + /// \brief Create a ParquetDatasetFactory from a metadata source. + /// + /// Similar to the previous Make definition, but the metadata can be a Buffer + /// and the base_path is explicit instead of inferred from the metadata + /// path. + /// + /// \param[in] metadata source to open the metadata parquet file from + /// \param[in] base_path used as the prefix of every parquet files referenced + /// \param[in] filesystem from which to read the files referenced. + /// \param[in] format to read the file with. + /// \param[in] options see ParquetFactoryOptions + static Result> Make( + const FileSource& metadata, const std::string& base_path, + std::shared_ptr filesystem, + std::shared_ptr format, ParquetFactoryOptions options); + + Result>> InspectSchemas( + InspectOptions options) override; + + Result> Finish(FinishOptions options) override; + + protected: + ParquetDatasetFactory( + std::shared_ptr filesystem, + std::shared_ptr format, + std::shared_ptr metadata, + std::shared_ptr manifest, + std::shared_ptr physical_schema, std::string base_path, + ParquetFactoryOptions options, + std::vector>> paths_with_row_group_ids) + : filesystem_(std::move(filesystem)), + format_(std::move(format)), + metadata_(std::move(metadata)), + manifest_(std::move(manifest)), + physical_schema_(std::move(physical_schema)), + base_path_(std::move(base_path)), + options_(std::move(options)), + paths_with_row_group_ids_(std::move(paths_with_row_group_ids)) {} + + std::shared_ptr filesystem_; + std::shared_ptr format_; + std::shared_ptr metadata_; + std::shared_ptr manifest_; + std::shared_ptr physical_schema_; + std::string base_path_; + ParquetFactoryOptions options_; + std::vector>> paths_with_row_group_ids_; + + private: + Result>> CollectParquetFragments( + const Partitioning& partitioning); + + Result> PartitionSchema(); +}; + +/// @} + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/parquet_encryption_config.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/parquet_encryption_config.h new file mode 100644 index 0000000000000000000000000000000000000000..96200b8a3118b82c92977d222ba8775f61a02b0b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/parquet_encryption_config.h @@ -0,0 +1,75 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/dataset/type_fwd.h" + +namespace parquet::encryption { +class CryptoFactory; +struct KmsConnectionConfig; +struct EncryptionConfiguration; +struct DecryptionConfiguration; +} // namespace parquet::encryption + +namespace arrow { +namespace dataset { + +/// \brief Core configuration class encapsulating parameters for high-level encryption +/// within Parquet framework. +/// +/// ParquetEncryptionConfig serves as a bridge, passing encryption-related +/// parameters to appropriate components within the Parquet library. It holds references +/// to objects defining encryption strategy, Key Management Service (KMS) configuration, +/// and specific encryption configurations for Parquet data. +struct ARROW_DS_EXPORT ParquetEncryptionConfig { + /// Shared pointer to CryptoFactory object, responsible for creating cryptographic + /// components like encryptors and decryptors. + std::shared_ptr crypto_factory; + + /// Shared pointer to KmsConnectionConfig object, holding configuration parameters for + /// connecting to a Key Management Service (KMS). + std::shared_ptr kms_connection_config; + + /// Shared pointer to EncryptionConfiguration object, defining specific encryption + /// settings for Parquet data, like keys for different columns. + std::shared_ptr encryption_config; +}; + +/// \brief Core configuration class encapsulating parameters for high-level decryption +/// within Parquet framework. +/// +/// ParquetDecryptionConfig is designed to pass decryption-related parameters to +/// appropriate decryption components within Parquet library. It holds references to +/// objects defining decryption strategy, Key Management Service (KMS) configuration, +/// and specific decryption configurations for reading encrypted Parquet data. +struct ARROW_DS_EXPORT ParquetDecryptionConfig { + /// Shared pointer to CryptoFactory object, pivotal in creating cryptographic + /// components for decryption process. + std::shared_ptr crypto_factory; + + /// Shared pointer to KmsConnectionConfig object, containing parameters for connecting + /// to a Key Management Service (KMS) during decryption. + std::shared_ptr kms_connection_config; + + /// Shared pointer to DecryptionConfiguration object, specifying decryption settings + /// for reading encrypted Parquet data. + std::shared_ptr decryption_config; +}; + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/partition.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/partition.h new file mode 100644 index 0000000000000000000000000000000000000000..315a3d384d28c1b313bf1483fb38ad99c6713663 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/partition.h @@ -0,0 +1,432 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/compute/expression.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/util/compare.h" + +namespace arrow { + +namespace dataset { + +constexpr char kFilenamePartitionSep = '_'; + +struct ARROW_DS_EXPORT PartitionPathFormat { + std::string directory, filename; +}; + +// ---------------------------------------------------------------------- +// Partitioning + +/// \defgroup dataset-partitioning Partitioning API +/// +/// @{ + +/// \brief Interface for parsing partition expressions from string partition +/// identifiers. +/// +/// For example, the identifier "foo=5" might be parsed to an equality expression +/// between the "foo" field and the value 5. +/// +/// Some partitionings may store the field names in a metadata +/// store instead of in file paths, for example +/// dataset_root/2009/11/... could be used when the partition fields +/// are "year" and "month" +/// +/// Paths are consumed from left to right. Paths must be relative to +/// the root of a partition; path prefixes must be removed before passing +/// the path to a partitioning for parsing. +class ARROW_DS_EXPORT Partitioning : public util::EqualityComparable { + public: + virtual ~Partitioning() = default; + + /// \brief The name identifying the kind of partitioning + virtual std::string type_name() const = 0; + + //// \brief Return whether the partitionings are equal + virtual bool Equals(const Partitioning& other) const { + return schema_->Equals(other.schema_, /*check_metadata=*/false); + } + + /// \brief If the input batch shares any fields with this partitioning, + /// produce sub-batches which satisfy mutually exclusive Expressions. + struct PartitionedBatches { + RecordBatchVector batches; + std::vector expressions; + }; + virtual Result Partition( + const std::shared_ptr& batch) const = 0; + + /// \brief Parse a path into a partition expression + virtual Result Parse(const std::string& path) const = 0; + + virtual Result Format(const compute::Expression& expr) const = 0; + + /// \brief A default Partitioning which is a DirectoryPartitioning + /// with an empty schema. + static std::shared_ptr Default(); + + /// \brief The partition schema. + const std::shared_ptr& schema() const { return schema_; } + + protected: + explicit Partitioning(std::shared_ptr schema) : schema_(std::move(schema)) {} + + std::shared_ptr schema_; +}; + +/// \brief The encoding of partition segments. +enum class SegmentEncoding : int8_t { + /// No encoding. + None = 0, + /// Segment values are URL-encoded. + Uri = 1, +}; + +ARROW_DS_EXPORT +std::ostream& operator<<(std::ostream& os, SegmentEncoding segment_encoding); + +/// \brief Options for key-value based partitioning (hive/directory). +struct ARROW_DS_EXPORT KeyValuePartitioningOptions { + /// After splitting a path into components, decode the path components + /// before parsing according to this scheme. + SegmentEncoding segment_encoding = SegmentEncoding::Uri; +}; + +/// \brief Options for inferring a partitioning. +struct ARROW_DS_EXPORT PartitioningFactoryOptions { + /// When inferring a schema for partition fields, yield dictionary encoded types + /// instead of plain. This can be more efficient when materializing virtual + /// columns, and Expressions parsed by the finished Partitioning will include + /// dictionaries of all unique inspected values for each field. + bool infer_dictionary = false; + /// Optionally, an expected schema can be provided, in which case inference + /// will only check discovered fields against the schema and update internal + /// state (such as dictionaries). + std::shared_ptr schema; + /// After splitting a path into components, decode the path components + /// before parsing according to this scheme. + SegmentEncoding segment_encoding = SegmentEncoding::Uri; + + KeyValuePartitioningOptions AsPartitioningOptions() const; +}; + +/// \brief Options for inferring a hive-style partitioning. +struct ARROW_DS_EXPORT HivePartitioningFactoryOptions : PartitioningFactoryOptions { + /// The hive partitioning scheme maps null to a hard coded fallback string. + std::string null_fallback; + + HivePartitioningOptions AsHivePartitioningOptions() const; +}; + +/// \brief PartitioningFactory provides creation of a partitioning when the +/// specific schema must be inferred from available paths (no explicit schema is known). +class ARROW_DS_EXPORT PartitioningFactory { + public: + virtual ~PartitioningFactory() = default; + + /// \brief The name identifying the kind of partitioning + virtual std::string type_name() const = 0; + + /// Get the schema for the resulting Partitioning. + /// This may reset internal state, for example dictionaries of unique representations. + virtual Result> Inspect( + const std::vector& paths) = 0; + + /// Create a partitioning using the provided schema + /// (fields may be dropped). + virtual Result> Finish( + const std::shared_ptr& schema) const = 0; +}; + +/// \brief Subclass for the common case of a partitioning which yields an equality +/// expression for each segment +class ARROW_DS_EXPORT KeyValuePartitioning : public Partitioning { + public: + /// An unconverted equality expression consisting of a field name and the representation + /// of a scalar value + struct Key { + std::string name; + std::optional value; + }; + + Result Partition( + const std::shared_ptr& batch) const override; + + Result Parse(const std::string& path) const override; + + Result Format(const compute::Expression& expr) const override; + + const ArrayVector& dictionaries() const { return dictionaries_; } + + SegmentEncoding segment_encoding() const { return options_.segment_encoding; } + + bool Equals(const Partitioning& other) const override; + + protected: + KeyValuePartitioning(std::shared_ptr schema, ArrayVector dictionaries, + KeyValuePartitioningOptions options) + : Partitioning(std::move(schema)), + dictionaries_(std::move(dictionaries)), + options_(options) { + if (dictionaries_.empty()) { + dictionaries_.resize(schema_->num_fields()); + } + } + + virtual Result> ParseKeys(const std::string& path) const = 0; + + virtual Result FormatValues(const ScalarVector& values) const = 0; + + /// Convert a Key to a full expression. + Result ConvertKey(const Key& key) const; + + Result> FormatPartitionSegments( + const ScalarVector& values) const; + Result> ParsePartitionSegments( + const std::vector& segments) const; + + ArrayVector dictionaries_; + KeyValuePartitioningOptions options_; +}; + +/// \brief DirectoryPartitioning parses one segment of a path for each field in its +/// schema. All fields are required, so paths passed to DirectoryPartitioning::Parse +/// must contain segments for each field. +/// +/// For example given schema the path "/2009/11" would be +/// parsed to ("year"_ == 2009 and "month"_ == 11) +class ARROW_DS_EXPORT DirectoryPartitioning : public KeyValuePartitioning { + public: + /// If a field in schema is of dictionary type, the corresponding element of + /// dictionaries must be contain the dictionary of values for that field. + explicit DirectoryPartitioning(std::shared_ptr schema, + ArrayVector dictionaries = {}, + KeyValuePartitioningOptions options = {}); + + std::string type_name() const override { return "directory"; } + + bool Equals(const Partitioning& other) const override; + + /// \brief Create a factory for a directory partitioning. + /// + /// \param[in] field_names The names for the partition fields. Types will be + /// inferred. + static std::shared_ptr MakeFactory( + std::vector field_names, PartitioningFactoryOptions = {}); + + private: + Result> ParseKeys(const std::string& path) const override; + + Result FormatValues(const ScalarVector& values) const override; +}; + +/// \brief The default fallback used for null values in a Hive-style partitioning. +static constexpr char kDefaultHiveNullFallback[] = "__HIVE_DEFAULT_PARTITION__"; + +struct ARROW_DS_EXPORT HivePartitioningOptions : public KeyValuePartitioningOptions { + std::string null_fallback = kDefaultHiveNullFallback; + + static HivePartitioningOptions DefaultsWithNullFallback(std::string fallback) { + HivePartitioningOptions options; + options.null_fallback = std::move(fallback); + return options; + } +}; + +/// \brief Multi-level, directory based partitioning +/// originating from Apache Hive with all data files stored in the +/// leaf directories. Data is partitioned by static values of a +/// particular column in the schema. Partition keys are represented in +/// the form $key=$value in directory names. +/// Field order is ignored, as are missing or unrecognized field names. +/// +/// For example given schema the path +/// "/day=321/ignored=3.4/year=2009" parses to ("year"_ == 2009 and "day"_ == 321) +class ARROW_DS_EXPORT HivePartitioning : public KeyValuePartitioning { + public: + /// If a field in schema is of dictionary type, the corresponding element of + /// dictionaries must be contain the dictionary of values for that field. + explicit HivePartitioning(std::shared_ptr schema, ArrayVector dictionaries = {}, + std::string null_fallback = kDefaultHiveNullFallback) + : KeyValuePartitioning(std::move(schema), std::move(dictionaries), + KeyValuePartitioningOptions()), + hive_options_( + HivePartitioningOptions::DefaultsWithNullFallback(std::move(null_fallback))) { + } + + explicit HivePartitioning(std::shared_ptr schema, ArrayVector dictionaries, + HivePartitioningOptions options) + : KeyValuePartitioning(std::move(schema), std::move(dictionaries), options), + hive_options_(options) {} + + std::string type_name() const override { return "hive"; } + std::string null_fallback() const { return hive_options_.null_fallback; } + const HivePartitioningOptions& options() const { return hive_options_; } + + static Result> ParseKey(const std::string& segment, + const HivePartitioningOptions& options); + + bool Equals(const Partitioning& other) const override; + + /// \brief Create a factory for a hive partitioning. + static std::shared_ptr MakeFactory( + HivePartitioningFactoryOptions = {}); + + private: + const HivePartitioningOptions hive_options_; + Result> ParseKeys(const std::string& path) const override; + + Result FormatValues(const ScalarVector& values) const override; +}; + +/// \brief Implementation provided by lambda or other callable +class ARROW_DS_EXPORT FunctionPartitioning : public Partitioning { + public: + using ParseImpl = std::function(const std::string&)>; + + using FormatImpl = + std::function(const compute::Expression&)>; + + FunctionPartitioning(std::shared_ptr schema, ParseImpl parse_impl, + FormatImpl format_impl = NULLPTR, std::string name = "function") + : Partitioning(std::move(schema)), + parse_impl_(std::move(parse_impl)), + format_impl_(std::move(format_impl)), + name_(std::move(name)) {} + + std::string type_name() const override { return name_; } + + bool Equals(const Partitioning& other) const override { return false; } + + Result Parse(const std::string& path) const override { + return parse_impl_(path); + } + + Result Format(const compute::Expression& expr) const override { + if (format_impl_) { + return format_impl_(expr); + } + return Status::NotImplemented("formatting paths from ", type_name(), " Partitioning"); + } + + Result Partition( + const std::shared_ptr& batch) const override { + return Status::NotImplemented("partitioning batches from ", type_name(), + " Partitioning"); + } + + private: + ParseImpl parse_impl_; + FormatImpl format_impl_; + std::string name_; +}; + +class ARROW_DS_EXPORT FilenamePartitioning : public KeyValuePartitioning { + public: + /// \brief Construct a FilenamePartitioning from its components. + /// + /// If a field in schema is of dictionary type, the corresponding element of + /// dictionaries must be contain the dictionary of values for that field. + explicit FilenamePartitioning(std::shared_ptr schema, + ArrayVector dictionaries = {}, + KeyValuePartitioningOptions options = {}); + + std::string type_name() const override { return "filename"; } + + /// \brief Create a factory for a filename partitioning. + /// + /// \param[in] field_names The names for the partition fields. Types will be + /// inferred. + static std::shared_ptr MakeFactory( + std::vector field_names, PartitioningFactoryOptions = {}); + + bool Equals(const Partitioning& other) const override; + + private: + Result> ParseKeys(const std::string& path) const override; + + Result FormatValues(const ScalarVector& values) const override; +}; + +ARROW_DS_EXPORT std::string StripPrefix(const std::string& path, + const std::string& prefix); + +/// \brief Extracts the directory and filename and removes the prefix of a path +/// +/// e.g., `StripPrefixAndFilename("/data/year=2019/c.txt", "/data") -> +/// {"year=2019","c.txt"}` +ARROW_DS_EXPORT std::string StripPrefixAndFilename(const std::string& path, + const std::string& prefix); + +/// \brief Vector version of StripPrefixAndFilename. +ARROW_DS_EXPORT std::vector StripPrefixAndFilename( + const std::vector& paths, const std::string& prefix); + +/// \brief Vector version of StripPrefixAndFilename. +ARROW_DS_EXPORT std::vector StripPrefixAndFilename( + const std::vector& files, const std::string& prefix); + +/// \brief Either a Partitioning or a PartitioningFactory +class ARROW_DS_EXPORT PartitioningOrFactory { + public: + explicit PartitioningOrFactory(std::shared_ptr partitioning) + : partitioning_(std::move(partitioning)) {} + + explicit PartitioningOrFactory(std::shared_ptr factory) + : factory_(std::move(factory)) {} + + PartitioningOrFactory& operator=(std::shared_ptr partitioning) { + return *this = PartitioningOrFactory(std::move(partitioning)); + } + + PartitioningOrFactory& operator=(std::shared_ptr factory) { + return *this = PartitioningOrFactory(std::move(factory)); + } + + /// \brief The partitioning (if given). + const std::shared_ptr& partitioning() const { return partitioning_; } + + /// \brief The partition factory (if given). + const std::shared_ptr& factory() const { return factory_; } + + /// \brief Get the partition schema, inferring it with the given factory if needed. + Result> GetOrInferSchema(const std::vector& paths); + + private: + std::shared_ptr factory_; + std::shared_ptr partitioning_; +}; + +/// @} + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/pch.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/pch.h new file mode 100644 index 0000000000000000000000000000000000000000..a74fd96e3554e660c7bd01fcbd07974af8b68c98 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/pch.h @@ -0,0 +1,27 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Often-used headers, for precompiling. +// If updating this header, please make sure you check compilation speed +// before checking in. Adding headers which are not used extremely often +// may incur a slowdown, since it makes the precompiled header heavier to load. + +// This API is EXPERIMENTAL. + +#include "arrow/dataset/dataset.h" +#include "arrow/dataset/scanner.h" +#include "arrow/pch.h" diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/plan.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/plan.h new file mode 100644 index 0000000000000000000000000000000000000000..10260ccec81d159ffd40d86144e39c4d91739db1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/plan.h @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#include "arrow/dataset/visibility.h" + +namespace arrow { +namespace dataset { +namespace internal { + +/// Register dataset-based exec nodes with the exec node registry +/// +/// This function must be called before using dataset ExecNode factories +ARROW_DS_EXPORT void Initialize(); + +} // namespace internal +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/projector.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/projector.h new file mode 100644 index 0000000000000000000000000000000000000000..86d38f0af23522a08dcebc1c290fe6bc25ae014e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/projector.h @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include "arrow/dataset/visibility.h" +#include "arrow/type_fwd.h" + +namespace arrow { +namespace dataset { + +// FIXME this is superceded by compute::Expression::Bind +ARROW_DS_EXPORT Status CheckProjectable(const Schema& from, const Schema& to); + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/scanner.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/scanner.h new file mode 100644 index 0000000000000000000000000000000000000000..4479158ff20cc586866ce132eb436a2c483a5443 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/scanner.h @@ -0,0 +1,578 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/acero/options.h" +#include "arrow/compute/expression.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/dataset/dataset.h" +#include "arrow/dataset/projector.h" +#include "arrow/dataset/type_fwd.h" +#include "arrow/dataset/visibility.h" +#include "arrow/io/interfaces.h" +#include "arrow/memory_pool.h" +#include "arrow/type_fwd.h" +#include "arrow/util/async_generator.h" +#include "arrow/util/iterator.h" +#include "arrow/util/thread_pool.h" +#include "arrow/util/type_fwd.h" + +namespace arrow { + +using RecordBatchGenerator = std::function>()>; + +namespace dataset { + +/// \defgroup dataset-scanning Scanning API +/// +/// @{ + +constexpr int64_t kDefaultBatchSize = 1 << 17; // 128Ki rows +// This will yield 64 batches ~ 8Mi rows +constexpr int32_t kDefaultBatchReadahead = 16; +constexpr int32_t kDefaultFragmentReadahead = 4; +constexpr int32_t kDefaultBytesReadahead = 1 << 25; // 32MiB + +/// Scan-specific options, which can be changed between scans of the same dataset. +struct ARROW_DS_EXPORT ScanOptions { + /// A row filter (which will be pushed down to partitioning/reading if supported). + compute::Expression filter = compute::literal(true); + /// A projection expression (which can add/remove/rename columns). + compute::Expression projection; + + /// Schema with which batches will be read from fragments. This is also known as the + /// "reader schema" it will be used (for example) in constructing CSV file readers to + /// identify column types for parsing. Usually only a subset of its fields (see + /// MaterializedFields) will be materialized during a scan. + std::shared_ptr dataset_schema; + + /// Schema of projected record batches. This is independent of dataset_schema as its + /// fields are derived from the projection. For example, let + /// + /// dataset_schema = {"a": int32, "b": int32, "id": utf8} + /// projection = project({equal(field_ref("a"), field_ref("b"))}, {"a_plus_b"}) + /// + /// (no filter specified). In this case, the projected_schema would be + /// + /// {"a_plus_b": int32} + std::shared_ptr projected_schema; + + /// Maximum row count for scanned batches. + int64_t batch_size = kDefaultBatchSize; + + /// How many batches to read ahead within a fragment. + /// + /// Set to 0 to disable batch readahead + /// + /// Note: May not be supported by all formats + /// Note: Will be ignored if use_threads is set to false + int32_t batch_readahead = kDefaultBatchReadahead; + + /// How many files to read ahead + /// + /// Set to 0 to disable fragment readahead + /// + /// Note: May not be enforced by all scanners + /// Note: Will be ignored if use_threads is set to false + int32_t fragment_readahead = kDefaultFragmentReadahead; + + /// A pool from which materialized and scanned arrays will be allocated. + MemoryPool* pool = arrow::default_memory_pool(); + + /// IOContext for any IO tasks + /// + /// Note: The IOContext executor will be ignored if use_threads is set to false + io::IOContext io_context; + + /// If true the scanner will scan in parallel + /// + /// Note: If true, this will use threads from both the cpu_executor and the + /// io_context.executor + /// Note: This must be true in order for any readahead to happen + bool use_threads = false; + + /// Fragment-specific scan options. + std::shared_ptr fragment_scan_options; + + /// Return a vector of FieldRefs that require materialization. + /// + /// This is usually the union of the fields referenced in the projection and the + /// filter expression. Examples: + /// + /// - `SELECT a, b WHERE a < 2 && c > 1` => ["a", "b", "a", "c"] + /// - `SELECT a + b < 3 WHERE a > 1` => ["a", "b", "a"] + /// + /// This is needed for expression where a field may not be directly + /// used in the final projection but is still required to evaluate the + /// expression. + /// + /// This is used by Fragment implementations to apply the column + /// sub-selection optimization. + std::vector MaterializedFields() const; + + /// Parameters which control when the plan should pause for a slow consumer + acero::BackpressureOptions backpressure = + acero::BackpressureOptions::DefaultBackpressure(); +}; + +/// Scan-specific options, which can be changed between scans of the same dataset. +/// +/// A dataset consists of one or more individual fragments. A fragment is anything +/// that is independently scannable, often a file. +/// +/// Batches from all fragments will be converted to a single schema. This unified +/// schema is referred to as the "dataset schema" and is the output schema for +/// this node. +/// +/// Individual fragments may have schemas that are different from the dataset +/// schema. This is sometimes referred to as the physical or fragment schema. +/// Conversion from the fragment schema to the dataset schema is a process +/// known as evolution. +struct ARROW_DS_EXPORT ScanV2Options : public acero::ExecNodeOptions { + explicit ScanV2Options(std::shared_ptr dataset) + : dataset(std::move(dataset)) {} + + /// \brief The dataset to scan + std::shared_ptr dataset; + /// \brief A row filter + /// + /// The filter expression should be written against the dataset schema. + /// The filter must be unbound. + /// + /// This is an opportunistic pushdown filter. Filtering capabilities will + /// vary between formats. If a format is not capable of applying the filter + /// then it will ignore it. + /// + /// Each fragment will do its best to filter the data based on the information + /// (partitioning guarantees, statistics) available to it. If it is able to + /// apply some filtering then it will indicate what filtering it was able to + /// apply by attaching a guarantee to the batch. + /// + /// For example, if a filter is x < 50 && y > 40 then a batch may be able to + /// apply a guarantee x < 50. Post-scan filtering would then only need to + /// consider y > 40 (for this specific batch). The next batch may not be able + /// to attach any guarantee and both clauses would need to be applied to that batch. + /// + /// A single guarantee-aware filtering operation should generally be applied to all + /// resulting batches. The scan node is not responsible for this. + /// + /// Fields that are referenced by the filter should be included in the `columns` vector. + /// The scan node will not automatically fetch fields referenced by the filter + /// expression. \see AddFieldsNeededForFilter + /// + /// If the filter references fields that are not included in `columns` this may or may + /// not be an error, depending on the format. + compute::Expression filter = compute::literal(true); + + /// \brief The columns to scan + /// + /// This is not a simple list of top-level column indices but instead a set of paths + /// allowing for partial selection of columns + /// + /// These paths refer to the dataset schema + /// + /// For example, consider the following dataset schema: + /// schema({ + /// field("score", int32()), + /// "marker", struct_({ + /// field("color", utf8()), + /// field("location", struct_({ + /// field("x", float64()), + /// field("y", float64()) + /// }) + /// }) + /// }) + /// + /// If `columns` is {{0}, {1,1,0}} then the output schema is: + /// schema({field("score", int32()), field("x", float64())}) + /// + /// If `columns` is {{1,1,1}, {1,1}} then the output schema is: + /// schema({ + /// field("y", float64()), + /// field("location", struct_({ + /// field("x", float64()), + /// field("y", float64()) + /// }) + /// }) + std::vector columns; + + /// \brief Target number of bytes to read ahead in a fragment + /// + /// This limit involves some amount of estimation. Formats typically only know + /// batch boundaries in terms of rows (not decoded bytes) and so an estimation + /// must be done to guess the average row size. Other formats like CSV and JSON + /// must make even more generalized guesses. + /// + /// This is a best-effort guide. Some formats may need to read ahead further, + /// for example, if scanning a parquet file that has batches with 100MiB of data + /// then the actual readahead will be at least 100MiB + /// + /// Set to 0 to disable readahead. When disabled, the scanner will read the + /// dataset one batch at a time + /// + /// This limit applies across all fragments. If the limit is 32MiB and the + /// fragment readahead allows for 20 fragments to be read at once then the + /// total readahead will still be 32MiB and NOT 20 * 32MiB. + int32_t target_bytes_readahead = kDefaultBytesReadahead; + + /// \brief Number of fragments to read ahead + /// + /// Higher readahead will potentially lead to more efficient I/O but will lead + /// to the scan operation using more RAM. The default is fairly conservative + /// and designed for fast local disks (or slow local spinning disks which cannot + /// handle much parallelism anyways). When using a highly parallel remote filesystem + /// you will likely want to increase these values. + /// + /// Set to 0 to disable fragment readahead. When disabled the dataset will be scanned + /// one fragment at a time. + int32_t fragment_readahead = kDefaultFragmentReadahead; + /// \brief Options specific to the file format + const FragmentScanOptions* format_options = NULLPTR; + + /// \brief Utility method to get a selection representing all columns in a dataset + static std::vector AllColumns(const Schema& dataset_schema); + + /// \brief Utility method to add fields needed for the current filter + /// + /// This method adds any fields that are needed by `filter` which are not already + /// included in the list of columns. Any new fields added will be added to the end + /// in no particular order. + static Status AddFieldsNeededForFilter(ScanV2Options* options); +}; + +/// \brief Describes a projection +struct ARROW_DS_EXPORT ProjectionDescr { + /// \brief The projection expression itself + /// This expression must be a call to make_struct + compute::Expression expression; + /// \brief The output schema of the projection. + + /// This can be calculated from the input schema and the expression but it + /// is cached here for convenience. + std::shared_ptr schema; + + /// \brief Create a ProjectionDescr by binding an expression to the dataset schema + /// + /// expression must return a struct type + static Result FromStructExpression( + const compute::Expression& expression, const Schema& dataset_schema); + + /// \brief Create a ProjectionDescr from expressions/names for each field + static Result FromExpressions(std::vector exprs, + std::vector names, + const Schema& dataset_schema); + + /// \brief Create a default projection referencing fields in the dataset schema + static Result FromNames(std::vector names, + const Schema& dataset_schema); + + /// \brief Make a projection that projects every field in the dataset schema + static Result Default(const Schema& dataset_schema); +}; + +/// \brief Utility method to set the projection expression and schema +ARROW_DS_EXPORT void SetProjection(ScanOptions* options, ProjectionDescr projection); + +/// \brief Combines a record batch with the fragment that the record batch originated +/// from +/// +/// Knowing the source fragment can be useful for debugging & understanding loaded +/// data +struct TaggedRecordBatch { + std::shared_ptr record_batch; + std::shared_ptr fragment; +}; +using TaggedRecordBatchGenerator = std::function()>; +using TaggedRecordBatchIterator = Iterator; + +/// \brief Combines a tagged batch with positional information +/// +/// This is returned when scanning batches in an unordered fashion. This information is +/// needed if you ever want to reassemble the batches in order +struct EnumeratedRecordBatch { + Enumerated> record_batch; + Enumerated> fragment; +}; +using EnumeratedRecordBatchGenerator = std::function()>; +using EnumeratedRecordBatchIterator = Iterator; + +/// @} + +} // namespace dataset + +template <> +struct IterationTraits { + static dataset::TaggedRecordBatch End() { + return dataset::TaggedRecordBatch{NULLPTR, NULLPTR}; + } + static bool IsEnd(const dataset::TaggedRecordBatch& val) { + return val.record_batch == NULLPTR; + } +}; + +template <> +struct IterationTraits { + static dataset::EnumeratedRecordBatch End() { + return dataset::EnumeratedRecordBatch{ + IterationEnd>>(), + IterationEnd>>()}; + } + static bool IsEnd(const dataset::EnumeratedRecordBatch& val) { + return IsIterationEnd(val.fragment); + } +}; + +namespace dataset { + +/// \defgroup dataset-scanning Scanning API +/// +/// @{ + +/// \brief A scanner glues together several dataset classes to load in data. +/// The dataset contains a collection of fragments and partitioning rules. +/// +/// The fragments identify independently loadable units of data (i.e. each fragment has +/// a potentially unique schema and possibly even format. It should be possible to read +/// fragments in parallel if desired). +/// +/// The fragment's format contains the logic necessary to actually create a task to load +/// the fragment into memory. That task may or may not support parallel execution of +/// its own. +/// +/// The scanner is then responsible for creating scan tasks from every fragment in the +/// dataset and (potentially) sequencing the loaded record batches together. +/// +/// The scanner should not buffer the entire dataset in memory (unless asked) instead +/// yielding record batches as soon as they are ready to scan. Various readahead +/// properties control how much data is allowed to be scanned before pausing to let a +/// slow consumer catchup. +/// +/// Today the scanner also handles projection & filtering although that may change in +/// the future. +class ARROW_DS_EXPORT Scanner { + public: + virtual ~Scanner() = default; + + /// \brief Apply a visitor to each RecordBatch as it is scanned. If multiple threads + /// are used (via use_threads), the visitor will be invoked from those threads and is + /// responsible for any synchronization. + virtual Status Scan(std::function visitor) = 0; + /// \brief Convert a Scanner into a Table. + /// + /// Use this convenience utility with care. This will serially materialize the + /// Scan result in memory before creating the Table. + virtual Result> ToTable() = 0; + /// \brief Scan the dataset into a stream of record batches. Each batch is tagged + /// with the fragment it originated from. The batches will arrive in order. The + /// order of fragments is determined by the dataset. + /// + /// Note: The scanner will perform some readahead but will avoid materializing too + /// much in memory (this is goverended by the readahead options and use_threads option). + /// If the readahead queue fills up then I/O will pause until the calling thread catches + /// up. + virtual Result ScanBatches() = 0; + virtual Result ScanBatchesAsync() = 0; + virtual Result ScanBatchesAsync( + ::arrow::internal::Executor* cpu_thread_pool) = 0; + /// \brief Scan the dataset into a stream of record batches. Unlike ScanBatches this + /// method may allow record batches to be returned out of order. This allows for more + /// efficient scanning: some fragments may be accessed more quickly than others (e.g. + /// may be cached in RAM or just happen to get scheduled earlier by the I/O) + /// + /// To make up for the out-of-order iteration each batch is further tagged with + /// positional information. + virtual Result ScanBatchesUnordered() = 0; + virtual Result ScanBatchesUnorderedAsync() = 0; + virtual Result ScanBatchesUnorderedAsync( + ::arrow::internal::Executor* cpu_thread_pool) = 0; + /// \brief A convenience to synchronously load the given rows by index. + /// + /// Will only consume as many batches as needed from ScanBatches(). + virtual Result> TakeRows(const Array& indices) = 0; + /// \brief Get the first N rows. + virtual Result> Head(int64_t num_rows) = 0; + /// \brief Count rows matching a predicate. + /// + /// This method will push down the predicate and compute the result based on fragment + /// metadata if possible. + virtual Result CountRows() = 0; + virtual Future CountRowsAsync() = 0; + /// \brief Convert the Scanner to a RecordBatchReader so it can be + /// easily used with APIs that expect a reader. + virtual Result> ToRecordBatchReader() = 0; + + /// \brief Get the options for this scan. + const std::shared_ptr& options() const { return scan_options_; } + /// \brief Get the dataset that this scanner will scan + virtual const std::shared_ptr& dataset() const = 0; + + protected: + explicit Scanner(std::shared_ptr scan_options) + : scan_options_(std::move(scan_options)) {} + + Result AddPositioningToInOrderScan( + TaggedRecordBatchIterator scan); + + const std::shared_ptr scan_options_; +}; + +/// \brief ScannerBuilder is a factory class to construct a Scanner. It is used +/// to pass information, notably a potential filter expression and a subset of +/// columns to materialize. +class ARROW_DS_EXPORT ScannerBuilder { + public: + explicit ScannerBuilder(std::shared_ptr dataset); + + ScannerBuilder(std::shared_ptr dataset, + std::shared_ptr scan_options); + + ScannerBuilder(std::shared_ptr schema, std::shared_ptr fragment, + std::shared_ptr scan_options); + + /// \brief Make a scanner from a record batch reader. + /// + /// The resulting scanner can be scanned only once. This is intended + /// to support writing data from streaming sources or other sources + /// that can be iterated only once. + static std::shared_ptr FromRecordBatchReader( + std::shared_ptr reader); + + /// \brief Set the subset of columns to materialize. + /// + /// Columns which are not referenced may not be read from fragments. + /// + /// \param[in] columns list of columns to project. Order and duplicates will + /// be preserved. + /// + /// \return Failure if any column name does not exists in the dataset's + /// Schema. + Status Project(std::vector columns); + + /// \brief Set expressions which will be evaluated to produce the materialized + /// columns. + /// + /// Columns which are not referenced may not be read from fragments. + /// + /// \param[in] exprs expressions to evaluate to produce columns. + /// \param[in] names list of names for the resulting columns. + /// + /// \return Failure if any referenced column does not exists in the dataset's + /// Schema. + Status Project(std::vector exprs, std::vector names); + + /// \brief Set the filter expression to return only rows matching the filter. + /// + /// The predicate will be passed down to Sources and corresponding + /// Fragments to exploit predicate pushdown if possible using + /// partition information or Fragment internal metadata, e.g. Parquet statistics. + /// Columns which are not referenced may not be read from fragments. + /// + /// \param[in] filter expression to filter rows with. + /// + /// \return Failure if any referenced columns does not exist in the dataset's + /// Schema. + Status Filter(const compute::Expression& filter); + + /// \brief Indicate if the Scanner should make use of the available + /// ThreadPool found in ScanOptions; + Status UseThreads(bool use_threads = true); + + /// \brief Set the maximum number of rows per RecordBatch. + /// + /// \param[in] batch_size the maximum number of rows. + /// \returns An error if the number for batch is not greater than 0. + /// + /// This option provides a control limiting the memory owned by any RecordBatch. + Status BatchSize(int64_t batch_size); + + /// \brief Set the number of batches to read ahead within a fragment. + /// + /// \param[in] batch_readahead How many batches to read ahead within a fragment + /// \returns an error if this number is less than 0. + /// + /// This option provides a control on the RAM vs I/O tradeoff. + /// It might not be supported by all file formats, in which case it will + /// simply be ignored. + Status BatchReadahead(int32_t batch_readahead); + + /// \brief Set the number of fragments to read ahead + /// + /// \param[in] fragment_readahead How many fragments to read ahead + /// \returns an error if this number is less than 0. + /// + /// This option provides a control on the RAM vs I/O tradeoff. + Status FragmentReadahead(int32_t fragment_readahead); + + /// \brief Set the pool from which materialized and scanned arrays will be allocated. + Status Pool(MemoryPool* pool); + + /// \brief Set fragment-specific scan options. + Status FragmentScanOptions(std::shared_ptr fragment_scan_options); + + /// \brief Override default backpressure configuration + Status Backpressure(acero::BackpressureOptions backpressure); + + /// \brief Return the current scan options for the builder. + Result> GetScanOptions(); + + /// \brief Return the constructed now-immutable Scanner object + Result> Finish(); + + const std::shared_ptr& schema() const; + const std::shared_ptr& projected_schema() const; + + private: + std::shared_ptr dataset_; + std::shared_ptr scan_options_ = std::make_shared(); +}; + +/// \brief Construct a source ExecNode which yields batches from a dataset scan. +/// +/// Does not construct associated filter or project nodes. +/// Yielded batches will be augmented with fragment/batch indices to enable stable +/// ordering for simple ExecPlans. +class ARROW_DS_EXPORT ScanNodeOptions : public acero::ExecNodeOptions { + public: + explicit ScanNodeOptions(std::shared_ptr dataset, + std::shared_ptr scan_options, + bool require_sequenced_output = false) + : dataset(std::move(dataset)), + scan_options(std::move(scan_options)), + require_sequenced_output(require_sequenced_output) {} + + std::shared_ptr dataset; + std::shared_ptr scan_options; + bool require_sequenced_output; +}; + +/// @} + +namespace internal { +ARROW_DS_EXPORT void InitializeScanner(arrow::acero::ExecFactoryRegistry* registry); +ARROW_DS_EXPORT void InitializeScannerV2(arrow::acero::ExecFactoryRegistry* registry); +} // namespace internal +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/type_fwd.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..d58781e038de9ffc2686ebfda9f640eeacdd6668 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/type_fwd.h @@ -0,0 +1,113 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include + +#include "arrow/compute/type_fwd.h" // IWYU pragma: export +#include "arrow/dataset/visibility.h" +#include "arrow/filesystem/type_fwd.h" // IWYU pragma: export +#include "arrow/type_fwd.h" // IWYU pragma: export + +namespace arrow { +namespace dataset { + +class Dataset; +class DatasetFactory; +using DatasetVector = std::vector>; + +class UnionDataset; +class UnionDatasetFactory; + +class Fragment; +using FragmentIterator = Iterator>; +using FragmentVector = std::vector>; + +class FragmentScanOptions; + +class FileSource; +class FileFormat; +class FileFragment; +class FileWriter; +class FileWriteOptions; +class FileSystemDataset; +class FileSystemDatasetFactory; +struct FileSystemDatasetWriteOptions; +class WriteNodeOptions; + +/// \brief Controls what happens if files exist in an output directory during a dataset +/// write +enum class ExistingDataBehavior : int8_t { + /// Deletes all files in a directory the first time that directory is encountered + kDeleteMatchingPartitions, + /// Ignores existing files, overwriting any that happen to have the same name as an + /// output file + kOverwriteOrIgnore, + /// Returns an error if there are any files or subdirectories in the output directory + kError, +}; + +class InMemoryDataset; + +class CsvFileFormat; +class CsvFileWriter; +class CsvFileWriteOptions; +struct CsvFragmentScanOptions; + +class JsonFileFormat; +class JsonFileWriter; +class JsonFileWriteOptions; +struct JsonFragmentScanOptions; + +class IpcFileFormat; +class IpcFileWriter; +class IpcFileWriteOptions; +class IpcFragmentScanOptions; + +class ParquetFileFormat; +class ParquetFileFragment; +class ParquetFragmentScanOptions; +class ParquetFileWriter; +class ParquetFileWriteOptions; + +class Partitioning; +class PartitioningFactory; +class PartitioningOrFactory; +struct KeyValuePartitioningOptions; +class DirectoryPartitioning; +class HivePartitioning; +struct HivePartitioningOptions; +class FilenamePartitioning; +struct FilenamePartitioningOptions; + +class ScanNodeOptions; +struct ScanOptions; + +class Scanner; + +class ScannerBuilder; + +class ScanTask; +using ScanTaskVector = std::vector>; +using ScanTaskIterator = Iterator>; + +} // namespace dataset +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/visibility.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/visibility.h new file mode 100644 index 0000000000000000000000000000000000000000..b43a253050fd834825b70136af9ddf8fd7907b46 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/dataset/visibility.h @@ -0,0 +1,50 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4251) +#else +#pragma GCC diagnostic ignored "-Wattributes" +#endif + +#ifdef ARROW_DS_STATIC +#define ARROW_DS_EXPORT +#elif defined(ARROW_DS_EXPORTING) +#define ARROW_DS_EXPORT __declspec(dllexport) +#else +#define ARROW_DS_EXPORT __declspec(dllimport) +#endif + +#define ARROW_DS_NO_EXPORT +#else // Not Windows +#ifndef ARROW_DS_EXPORT +#define ARROW_DS_EXPORT __attribute__((visibility("default"))) +#endif +#ifndef ARROW_DS_NO_EXPORT +#define ARROW_DS_NO_EXPORT __attribute__((visibility("hidden"))) +#endif +#endif // Non-Windows + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/object_parser.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/object_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..8035695e537cb9a022cd694993185f687ccdab04 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/object_parser.h @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace json { +namespace internal { + +/// This class is a helper to parse a json object from a string. +/// It uses rapidjson::Document in implementation. +class ARROW_EXPORT ObjectParser { + public: + ObjectParser(); + ~ObjectParser(); + + Status Parse(std::string_view json); + + Result GetString(const char* key) const; + + Result GetBool(const char* key) const; + + // Get all members of the object as a map from string keys to string values + Result> GetStringMap() const; + + private: + class Impl; + std::unique_ptr impl_; +}; + +} // namespace internal +} // namespace json +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/reader.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/reader.h new file mode 100644 index 0000000000000000000000000000000000000000..b7849a83ba1f88e54961df5a1e9739afe24ba026 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/reader.h @@ -0,0 +1,118 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/io/type_fwd.h" +#include "arrow/json/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/macros.h" +#include "arrow/util/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace json { + +/// A class that reads an entire JSON file into a Arrow Table +/// +/// The file is expected to consist of individual line-separated JSON objects +class ARROW_EXPORT TableReader { + public: + virtual ~TableReader() = default; + + /// Read the entire JSON file and convert it to a Arrow Table + virtual Result> Read() = 0; + + /// Create a TableReader instance + static Result> Make(MemoryPool* pool, + std::shared_ptr input, + const ReadOptions&, + const ParseOptions&); +}; + +ARROW_EXPORT Result> ParseOne(ParseOptions options, + std::shared_ptr json); + +/// \brief A class that reads a JSON file incrementally +/// +/// JSON data is read from a stream in fixed-size blocks (configurable with +/// `ReadOptions::block_size`). Each block is converted to a `RecordBatch`. Yielded +/// batches have a consistent schema but may differ in row count. +/// +/// The supplied `ParseOptions` are used to determine a schema, based either on a +/// provided explicit schema or inferred from the first non-empty block. +/// Afterwards, the target schema is frozen. If `UnexpectedFieldBehavior::InferType` is +/// specified, unexpected fields will only be inferred for the first block. Afterwards +/// they'll be treated as errors. +/// +/// If `ReadOptions::use_threads` is `true`, each block's parsing/decoding task will be +/// parallelized on the given `cpu_executor` (with readahead corresponding to the +/// executor's capacity). If an executor isn't provided, the global thread pool will be +/// used. +/// +/// If `ReadOptions::use_threads` is `false`, computations will be run on the calling +/// thread and `cpu_executor` will be ignored. +class ARROW_EXPORT StreamingReader : public RecordBatchReader { + public: + virtual ~StreamingReader() = default; + + /// \brief Read the next `RecordBatch` asynchronously + /// This function is async-reentrant (but not synchronously reentrant). However, if + /// threading is disabled, this will block until completion. + virtual Future> ReadNextAsync() = 0; + + /// Get the number of bytes which have been successfully converted to record batches + /// and consumed + [[nodiscard]] virtual int64_t bytes_processed() const = 0; + + /// \brief Create a `StreamingReader` from an `InputStream` + /// Blocks until the initial batch is loaded + /// + /// \param[in] stream JSON source stream + /// \param[in] read_options Options for reading + /// \param[in] parse_options Options for chunking, parsing, and conversion + /// \param[in] io_context Context for IO operations (optional) + /// \param[in] cpu_executor Executor for computation tasks (optional) + /// \return The initialized reader + static Result> Make( + std::shared_ptr stream, const ReadOptions& read_options, + const ParseOptions& parse_options, + const io::IOContext& io_context = io::default_io_context(), + ::arrow::internal::Executor* cpu_executor = NULLPTR); + + /// \brief Create a `StreamingReader` from an `InputStream` asynchronously + /// Returned future completes after loading the first batch + /// + /// \param[in] stream JSON source stream + /// \param[in] read_options Options for reading + /// \param[in] parse_options Options for chunking, parsing, and conversion + /// \param[in] io_context Context for IO operations (optional) + /// \param[in] cpu_executor Executor for computation tasks (optional) + /// \return Future for the initialized reader + static Future> MakeAsync( + std::shared_ptr stream, const ReadOptions& read_options, + const ParseOptions& parse_options, + const io::IOContext& io_context = io::default_io_context(), + ::arrow::internal::Executor* cpu_executor = NULLPTR); +}; + +} // namespace json +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/type_fwd.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..67e2e1bb4065d0bc238d04073f673a699c5da4ea --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/json/type_fwd.h @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace arrow { +namespace json { + +class TableReader; +struct ReadOptions; +struct ParseOptions; + +} // namespace json +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/executor_util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/executor_util.h new file mode 100644 index 0000000000000000000000000000000000000000..e34fc858d07f60ac31b73d1e84b5dc1cf4189b3f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/executor_util.h @@ -0,0 +1,55 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/util/thread_pool.h" + +namespace arrow { + +/// An executor which synchronously runs the task as part of the SpawnReal call. +class MockExecutor : public internal::Executor { + public: + int GetCapacity() override { return 0; } + + Status SpawnReal(internal::TaskHints hints, internal::FnOnce task, StopToken, + StopCallback&&) override { + spawn_count++; + std::move(task)(); + return Status::OK(); + } + + int spawn_count = 0; +}; + +/// An executor which does not actually run the task. Can be used to simulate situations +/// where the executor schedules a task in a long queue and doesn't get around to running +/// it for a while +class DelayedExecutor : public internal::Executor { + public: + int GetCapacity() override { return 0; } + + Status SpawnReal(internal::TaskHints hints, internal::FnOnce task, StopToken, + StopCallback&&) override { + captured_tasks.push_back(std::move(task)); + return Status::OK(); + } + + std::vector> captured_tasks; +}; + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/future_util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/future_util.h new file mode 100644 index 0000000000000000000000000000000000000000..2ca70d05402f92c71d8f86441eeccec1ebc6d156 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/future_util.h @@ -0,0 +1,142 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/testing/gtest_util.h" +#include "arrow/util/future.h" + +// This macro should be called by futures that are expected to +// complete pretty quickly. arrow::kDefaultAssertFinishesWaitSeconds is the +// default max wait here. Anything longer than that and it's a questionable unit test +// anyways. +#define ASSERT_FINISHES_IMPL(fut) \ + do { \ + ASSERT_TRUE(fut.Wait(::arrow::kDefaultAssertFinishesWaitSeconds)); \ + if (!fut.is_finished()) { \ + FAIL() << "Future did not finish in a timely fashion"; \ + } \ + } while (false) + +#define ASSERT_FINISHES_OK(expr) \ + do { \ + auto&& _fut = (expr); \ + ASSERT_TRUE(_fut.Wait(::arrow::kDefaultAssertFinishesWaitSeconds)); \ + if (!_fut.is_finished()) { \ + FAIL() << "Future did not finish in a timely fashion"; \ + } \ + auto& _st = _fut.status(); \ + if (!_st.ok()) { \ + FAIL() << "'" ARROW_STRINGIFY(expr) "' failed with " << _st.ToString(); \ + } \ + } while (false) + +#define ASSERT_FINISHES_AND_RAISES(ENUM, expr) \ + do { \ + auto&& _fut = (expr); \ + ASSERT_FINISHES_IMPL(_fut); \ + ASSERT_RAISES(ENUM, _fut.status()); \ + } while (false) + +#define EXPECT_FINISHES_AND_RAISES_WITH_MESSAGE_THAT(ENUM, matcher, expr) \ + do { \ + auto&& fut = (expr); \ + ASSERT_FINISHES_IMPL(fut); \ + EXPECT_RAISES_WITH_MESSAGE_THAT(ENUM, matcher, fut.status()); \ + } while (false) + +#define ASSERT_FINISHES_OK_AND_ASSIGN_IMPL(lhs, rexpr, _future_name) \ + auto _future_name = (rexpr); \ + ASSERT_FINISHES_IMPL(_future_name); \ + ASSERT_OK_AND_ASSIGN(lhs, _future_name.result()); + +#define ASSERT_FINISHES_OK_AND_ASSIGN(lhs, rexpr) \ + ASSERT_FINISHES_OK_AND_ASSIGN_IMPL(lhs, rexpr, \ + ARROW_ASSIGN_OR_RAISE_NAME(_fut, __COUNTER__)) + +#define ASSERT_FINISHES_OK_AND_EQ(expected, expr) \ + do { \ + ASSERT_FINISHES_OK_AND_ASSIGN(auto _actual, (expr)); \ + ASSERT_EQ(expected, _actual); \ + } while (0) + +#define EXPECT_FINISHES_IMPL(fut) \ + do { \ + EXPECT_TRUE(fut.Wait(::arrow::kDefaultAssertFinishesWaitSeconds)); \ + if (!fut.is_finished()) { \ + ADD_FAILURE() << "Future did not finish in a timely fashion"; \ + } \ + } while (false) + +#define ON_FINISH_ASSIGN_OR_HANDLE_ERROR_IMPL(handle_error, future_name, lhs, rexpr) \ + auto future_name = (rexpr); \ + EXPECT_FINISHES_IMPL(future_name); \ + handle_error(future_name.status()); \ + EXPECT_OK_AND_ASSIGN(lhs, future_name.result()); + +#define EXPECT_FINISHES(expr) \ + do { \ + EXPECT_FINISHES_IMPL(expr); \ + } while (0) + +#define EXPECT_FINISHES_OK_AND_ASSIGN(lhs, rexpr) \ + ON_FINISH_ASSIGN_OR_HANDLE_ERROR_IMPL( \ + ARROW_EXPECT_OK, ARROW_ASSIGN_OR_RAISE_NAME(_fut, __COUNTER__), lhs, rexpr); + +#define EXPECT_FINISHES_OK_AND_EQ(expected, expr) \ + do { \ + EXPECT_FINISHES_OK_AND_ASSIGN(auto _actual, (expr)); \ + EXPECT_EQ(expected, _actual); \ + } while (0) + +namespace arrow { + +constexpr double kDefaultAssertFinishesWaitSeconds = 64; + +template +void AssertNotFinished(const Future& fut) { + ASSERT_FALSE(IsFutureFinished(fut.state())); +} + +template +void AssertFinished(const Future& fut) { + ASSERT_TRUE(IsFutureFinished(fut.state())); +} + +// Assert the future is successful *now* +template +void AssertSuccessful(const Future& fut) { + if (IsFutureFinished(fut.state())) { + ASSERT_EQ(fut.state(), FutureState::SUCCESS); + ASSERT_OK(fut.status()); + } else { + FAIL() << "Expected future to be completed successfully but it was still pending"; + } +} + +// Assert the future is failed *now* +template +void AssertFailed(const Future& fut) { + if (IsFutureFinished(fut.state())) { + ASSERT_EQ(fut.state(), FutureState::FAILURE); + ASSERT_FALSE(fut.status().ok()); + } else { + FAIL() << "Expected future to have failed but it was still pending"; + } +} + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/generator.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/generator.h new file mode 100644 index 0000000000000000000000000000000000000000..4ec8845864b72807d7e68230b25256ba53127f17 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/generator.h @@ -0,0 +1,321 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/array/array_base.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/testing/gtest_util.h" +#include "arrow/testing/visibility.h" +#include "arrow/type_fwd.h" + +namespace arrow { + +class ARROW_TESTING_EXPORT ConstantArrayGenerator { + public: + /// \brief Generates a constant BooleanArray + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr Boolean(int64_t size, bool value = false); + + /// \brief Generates a constant UInt8Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr UInt8(int64_t size, uint8_t value = 0); + + /// \brief Generates a constant Int8Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr Int8(int64_t size, int8_t value = 0); + + /// \brief Generates a constant UInt16Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr UInt16(int64_t size, uint16_t value = 0); + + /// \brief Generates a constant UInt16Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr Int16(int64_t size, int16_t value = 0); + + /// \brief Generates a constant UInt32Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr UInt32(int64_t size, uint32_t value = 0); + + /// \brief Generates a constant UInt32Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr Int32(int64_t size, int32_t value = 0); + + /// \brief Generates a constant UInt64Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr UInt64(int64_t size, uint64_t value = 0); + + /// \brief Generates a constant UInt64Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr Int64(int64_t size, int64_t value = 0); + + /// \brief Generates a constant Float32Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr Float32(int64_t size, float value = 0); + + /// \brief Generates a constant Float64Array + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr Float64(int64_t size, double value = 0); + + /// \brief Generates a constant StringArray + /// + /// \param[in] size the size of the array to generate + /// \param[in] value to repeat + /// + /// \return a generated Array + static std::shared_ptr String(int64_t size, std::string value = ""); + + template + static std::shared_ptr Numeric(int64_t size, CType value = 0) { + switch (ArrowType::type_id) { + case Type::BOOL: + return Boolean(size, static_cast(value)); + case Type::UINT8: + return UInt8(size, static_cast(value)); + case Type::INT8: + return Int8(size, static_cast(value)); + case Type::UINT16: + return UInt16(size, static_cast(value)); + case Type::INT16: + return Int16(size, static_cast(value)); + case Type::UINT32: + return UInt32(size, static_cast(value)); + case Type::INT32: + return Int32(size, static_cast(value)); + case Type::UINT64: + return UInt64(size, static_cast(value)); + case Type::INT64: + return Int64(size, static_cast(value)); + case Type::FLOAT: + return Float32(size, static_cast(value)); + case Type::DOUBLE: + return Float64(size, static_cast(value)); + case Type::INTERVAL_DAY_TIME: + case Type::DATE32: { + EXPECT_OK_AND_ASSIGN(auto viewed, + Int32(size, static_cast(value))->View(date32())); + return viewed; + } + case Type::INTERVAL_MONTHS: { + EXPECT_OK_AND_ASSIGN(auto viewed, + Int32(size, static_cast(value)) + ->View(std::make_shared())); + return viewed; + } + case Type::TIME32: { + EXPECT_OK_AND_ASSIGN(auto viewed, + Int32(size, static_cast(value)) + ->View(std::make_shared(TimeUnit::SECOND))); + return viewed; + } + case Type::TIME64: { + EXPECT_OK_AND_ASSIGN(auto viewed, Int64(size, static_cast(value)) + ->View(std::make_shared())); + return viewed; + } + case Type::DATE64: { + EXPECT_OK_AND_ASSIGN(auto viewed, + Int64(size, static_cast(value))->View(date64())); + return viewed; + } + case Type::TIMESTAMP: { + EXPECT_OK_AND_ASSIGN( + auto viewed, Int64(size, static_cast(value)) + ->View(std::make_shared(TimeUnit::SECOND))); + return viewed; + } + default: + return nullptr; + } + } + + /// \brief Generates a constant Array of zeroes + /// + /// \param[in] size the size of the array to generate + /// \param[in] type the type of the Array + /// + /// \return a generated Array + static std::shared_ptr Zeroes(int64_t size, + const std::shared_ptr& type); + + /// \brief Generates a RecordBatch of zeroes + /// + /// \param[in] size the size of the array to generate + /// \param[in] schema to conform to + /// + /// This function is handy to return of RecordBatch of a desired shape. + /// + /// \return a generated RecordBatch + static std::shared_ptr Zeroes(int64_t size, + const std::shared_ptr& schema); + + /// \brief Generates a RecordBatchReader by repeating a RecordBatch + /// + /// \param[in] n_batch the number of times it repeats batch + /// \param[in] batch the RecordBatch to repeat + /// + /// \return a generated RecordBatchReader + static std::shared_ptr Repeat( + int64_t n_batch, const std::shared_ptr batch); + + /// \brief Generates a RecordBatchReader of zeroes batches + /// + /// \param[in] n_batch the number of RecordBatch + /// \param[in] batch_size the size of each RecordBatch + /// \param[in] schema to conform to + /// + /// \return a generated RecordBatchReader + static std::shared_ptr Zeroes(int64_t n_batch, int64_t batch_size, + const std::shared_ptr& schema); +}; + +ARROW_TESTING_EXPORT +Result> ScalarVectorToArray(const ScalarVector& scalars); + +namespace gen { + +class ARROW_TESTING_EXPORT ArrayGenerator { + public: + virtual ~ArrayGenerator() = default; + virtual Result> Generate(int64_t num_rows) = 0; + virtual std::shared_ptr type() const = 0; +}; + +// Same as DataGenerator below but instead of returning Result an ok status is EXPECT'd +class ARROW_TESTING_EXPORT GTestDataGenerator { + public: + virtual ~GTestDataGenerator() = default; + virtual std::shared_ptr<::arrow::RecordBatch> RecordBatch(int64_t num_rows) = 0; + virtual std::vector> RecordBatches( + int64_t rows_per_batch, int num_batches) = 0; + + virtual ::arrow::compute::ExecBatch ExecBatch(int64_t num_rows) = 0; + virtual std::vector<::arrow::compute::ExecBatch> ExecBatches(int64_t rows_per_batch, + int num_batches) = 0; + + virtual std::shared_ptr<::arrow::Table> Table(int64_t rows_per_chunk, + int num_chunks = 1) = 0; + virtual std::shared_ptr<::arrow::Schema> Schema() = 0; +}; + +class ARROW_TESTING_EXPORT DataGenerator { + public: + virtual ~DataGenerator() = default; + virtual Result> RecordBatch(int64_t num_rows) = 0; + virtual Result>> RecordBatches( + int64_t rows_per_batch, int num_batches) = 0; + + virtual Result<::arrow::compute::ExecBatch> ExecBatch(int64_t num_rows) = 0; + virtual Result> ExecBatches( + int64_t rows_per_batch, int num_batches) = 0; + + virtual Result> Table(int64_t rows_per_chunk, + int num_chunks = 1) = 0; + virtual std::shared_ptr<::arrow::Schema> Schema() = 0; + /// @brief Converts this generator to a variant that fails (in a googletest sense) + /// if any error is encountered. + virtual std::unique_ptr FailOnError() = 0; +}; + +/// @brief A potentially named field +/// +/// If name is not specified then a name will be generated automatically (e.g. f0, f1) +struct ARROW_TESTING_EXPORT GeneratorField { + public: + GeneratorField(std::shared_ptr gen) // NOLINT implicit conversion + : name(), gen(std::move(gen)) {} + GeneratorField(std::string name, std::shared_ptr gen) + : name(std::move(name)), gen(std::move(gen)) {} + + std::optional name; + std::shared_ptr gen; +}; + +/// Create a table generator with the given fields +ARROW_TESTING_EXPORT std::shared_ptr Gen( + std::vector column_gens); + +/// make a generator that returns a constant value +ARROW_TESTING_EXPORT std::shared_ptr Constant( + std::shared_ptr value); +/// make a generator that returns an incrementing value +/// +/// Note: overflow is not prevented standard unsigned integer overflow applies +ARROW_TESTING_EXPORT std::shared_ptr Step(uint32_t start = 0, + uint32_t step = 1, + bool signed_int = false); +/// make a generator that returns a random value +ARROW_TESTING_EXPORT std::shared_ptr Random( + std::shared_ptr type); +/// TODO(if-needed) could add a repeat-scalars generator, e.g. Repeat({1, 2, 3}) for +/// 1,2,3,1,2,3,1 +/// +/// TODO(if-needed) could add a repeat-from-json generator e.g. Repeat(int32(), "[1, 2, +/// 3]")), same behavior as repeat-scalars + +} // namespace gen + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/gtest_util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/gtest_util.h new file mode 100644 index 0000000000000000000000000000000000000000..916067d85b7536d31a00aa5f14d46d1cf61bc533 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/gtest_util.h @@ -0,0 +1,557 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "arrow/compare.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/testing/gtest_compat.h" +#include "arrow/testing/visibility.h" +#include "arrow/type_fwd.h" +#include "arrow/type_traits.h" +#include "arrow/util/macros.h" +#include "arrow/util/string_builder.h" +#include "arrow/util/type_fwd.h" + +// NOTE: failing must be inline in the macros below, to get correct file / line number +// reporting on test failures. + +// NOTE: using a for loop for this macro allows extra failure messages to be +// appended with operator<< +#define ASSERT_RAISES(ENUM, expr) \ + for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); \ + !_st.Is##ENUM();) \ + FAIL() << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " ARROW_STRINGIFY( \ + ENUM) ", but got " \ + << _st.ToString() + +#define ASSERT_RAISES_WITH_MESSAGE(ENUM, message, expr) \ + do { \ + auto _res = (expr); \ + ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \ + if (!_st.Is##ENUM()) { \ + FAIL() << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " ARROW_STRINGIFY( \ + ENUM) ", but got " \ + << _st.ToString(); \ + } \ + ASSERT_EQ((message), _st.ToStringWithoutContextLines()); \ + } while (false) + +#define EXPECT_RAISES_WITH_MESSAGE_THAT(ENUM, matcher, expr) \ + do { \ + auto _res = (expr); \ + ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \ + EXPECT_TRUE(_st.Is##ENUM()) << "Expected '" ARROW_STRINGIFY(expr) "' to fail with " \ + << ARROW_STRINGIFY(ENUM) ", but got " << _st.ToString(); \ + EXPECT_THAT(_st.ToStringWithoutContextLines(), (matcher)); \ + } while (false) + +#define EXPECT_RAISES_WITH_CODE_AND_MESSAGE_THAT(code, matcher, expr) \ + do { \ + auto _res = (expr); \ + ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \ + EXPECT_EQ(_st.CodeAsString(), Status::CodeAsString(code)); \ + EXPECT_THAT(_st.ToStringWithoutContextLines(), (matcher)); \ + } while (false) + +#define ASSERT_OK(expr) \ + for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); !_st.ok();) \ + FAIL() << "'" ARROW_STRINGIFY(expr) "' failed with " << _st.ToString() + +#define ASSERT_OK_NO_THROW(expr) ASSERT_NO_THROW(ASSERT_OK(expr)) + +#define ARROW_EXPECT_OK(expr) \ + do { \ + auto _res = (expr); \ + ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \ + EXPECT_TRUE(_st.ok()) << "'" ARROW_STRINGIFY(expr) "' failed with " \ + << _st.ToString(); \ + } while (false) + +#define ASSERT_NOT_OK(expr) \ + for (::arrow::Status _st = ::arrow::internal::GenericToStatus((expr)); _st.ok();) \ + FAIL() << "'" ARROW_STRINGIFY(expr) "' did not failed" << _st.ToString() + +#define ABORT_NOT_OK(expr) \ + do { \ + auto _res = (expr); \ + ::arrow::Status _st = ::arrow::internal::GenericToStatus(_res); \ + if (ARROW_PREDICT_FALSE(!_st.ok())) { \ + _st.Abort(); \ + } \ + } while (false); + +#define ASSIGN_OR_HANDLE_ERROR_IMPL(handle_error, status_name, lhs, rexpr) \ + auto&& status_name = (rexpr); \ + handle_error(status_name.status()); \ + lhs = std::move(status_name).ValueOrDie(); + +#define ASSERT_OK_AND_ASSIGN(lhs, rexpr) \ + ASSIGN_OR_HANDLE_ERROR_IMPL( \ + ASSERT_OK, ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), lhs, rexpr); + +#define ASSIGN_OR_ABORT(lhs, rexpr) \ + ASSIGN_OR_HANDLE_ERROR_IMPL(ABORT_NOT_OK, \ + ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \ + lhs, rexpr); + +#define EXPECT_OK_AND_ASSIGN(lhs, rexpr) \ + ASSIGN_OR_HANDLE_ERROR_IMPL(ARROW_EXPECT_OK, \ + ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \ + lhs, rexpr); + +#define ASSERT_OK_AND_EQ(expected, expr) \ + do { \ + ASSERT_OK_AND_ASSIGN(auto _actual, (expr)); \ + ASSERT_EQ(expected, _actual); \ + } while (0) + +// A generalized version of GTest's SCOPED_TRACE that takes arbitrary arguments. +// ARROW_SCOPED_TRACE("some variable = ", some_variable, ...) + +#define ARROW_SCOPED_TRACE(...) SCOPED_TRACE(::arrow::util::StringBuilder(__VA_ARGS__)) + +namespace arrow { + +// ---------------------------------------------------------------------- +// Useful testing::Types declarations + +inline void PrintTo(StatusCode code, std::ostream* os) { + *os << Status::CodeAsString(code); +} + +using NumericArrowTypes = + ::testing::Types; + +using RealArrowTypes = ::testing::Types; + +using IntegralArrowTypes = ::testing::Types; + +using PhysicalIntegralArrowTypes = + ::testing::Types; + +using PrimitiveArrowTypes = + ::testing::Types; + +using TemporalArrowTypes = + ::testing::Types; + +using DecimalArrowTypes = ::testing::Types; + +using BaseBinaryArrowTypes = + ::testing::Types; + +using BaseBinaryOrBinaryViewLikeArrowTypes = + ::testing::Types; + +using BinaryArrowTypes = ::testing::Types; + +using StringArrowTypes = ::testing::Types; + +using StringOrStringViewArrowTypes = + ::testing::Types; + +using ListArrowTypes = ::testing::Types; + +using UnionArrowTypes = ::testing::Types; + +class Array; +class ChunkedArray; +class RecordBatch; +class Table; +struct Datum; + +#define ASSERT_ARRAYS_EQUAL(lhs, rhs) AssertArraysEqual((lhs), (rhs)) +#define ASSERT_BATCHES_EQUAL(lhs, rhs) AssertBatchesEqual((lhs), (rhs)) +#define ASSERT_BATCHES_APPROX_EQUAL(lhs, rhs) AssertBatchesApproxEqual((lhs), (rhs)) +#define ASSERT_TABLES_EQUAL(lhs, rhs) AssertTablesEqual((lhs), (rhs)) + +// Default EqualOptions for testing +static inline EqualOptions TestingEqualOptions() { + return EqualOptions{}.nans_equal(true).signed_zeros_equal(false); +} + +// If verbose is true, then the arrays will be pretty printed +ARROW_TESTING_EXPORT void AssertArraysEqual( + const Array& expected, const Array& actual, bool verbose = false, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertArraysApproxEqual( + const Array& expected, const Array& actual, bool verbose = false, + const EqualOptions& options = TestingEqualOptions()); +// Returns true when values are both null +ARROW_TESTING_EXPORT void AssertScalarsEqual( + const Scalar& expected, const Scalar& actual, bool verbose = false, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertScalarsApproxEqual( + const Scalar& expected, const Scalar& actual, bool verbose = false, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertBatchesEqual( + const RecordBatch& expected, const RecordBatch& actual, bool check_metadata = false, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertBatchesApproxEqual( + const RecordBatch& expected, const RecordBatch& actual, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertChunkedEqual( + const ChunkedArray& expected, const ChunkedArray& actual, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertChunkedEqual( + const ChunkedArray& actual, const ArrayVector& expected, + const EqualOptions& options = TestingEqualOptions()); +// Like ChunkedEqual, but permits different chunk layout +ARROW_TESTING_EXPORT void AssertChunkedEquivalent( + const ChunkedArray& expected, const ChunkedArray& actual, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertChunkedApproxEquivalent( + const ChunkedArray& expected, const ChunkedArray& actual, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer, + const std::vector& expected); +ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer, + std::string_view expected); +ARROW_TESTING_EXPORT void AssertBufferEqual(const Buffer& buffer, const Buffer& expected); + +ARROW_TESTING_EXPORT void AssertTypeEqual(const DataType& lhs, const DataType& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertTypeEqual(const std::shared_ptr& lhs, + const std::shared_ptr& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertFieldEqual(const Field& lhs, const Field& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertFieldEqual(const std::shared_ptr& lhs, + const std::shared_ptr& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertSchemaEqual(const Schema& lhs, const Schema& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertSchemaEqual(const std::shared_ptr& lhs, + const std::shared_ptr& rhs, + bool check_metadata = false); + +ARROW_TESTING_EXPORT void AssertTypeNotEqual(const DataType& lhs, const DataType& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertTypeNotEqual(const std::shared_ptr& lhs, + const std::shared_ptr& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertFieldNotEqual(const Field& lhs, const Field& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertFieldNotEqual(const std::shared_ptr& lhs, + const std::shared_ptr& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertSchemaNotEqual(const Schema& lhs, const Schema& rhs, + bool check_metadata = false); +ARROW_TESTING_EXPORT void AssertSchemaNotEqual(const std::shared_ptr& lhs, + const std::shared_ptr& rhs, + bool check_metadata = false); + +ARROW_TESTING_EXPORT Result> PrintArrayDiff( + const ChunkedArray& expected, const ChunkedArray& actual); + +ARROW_TESTING_EXPORT void AssertTablesEqual( + const Table& expected, const Table& actual, bool same_chunk_layout = true, + bool flatten = false, const EqualOptions& options = TestingEqualOptions()); + +ARROW_TESTING_EXPORT void AssertDatumsEqual( + const Datum& expected, const Datum& actual, bool verbose = false, + const EqualOptions& options = TestingEqualOptions()); +ARROW_TESTING_EXPORT void AssertDatumsApproxEqual( + const Datum& expected, const Datum& actual, bool verbose = false, + const EqualOptions& options = TestingEqualOptions()); + +template +void AssertNumericDataEqual(const C_TYPE* raw_data, + const std::vector& expected_values) { + for (auto expected : expected_values) { + ASSERT_EQ(expected, *raw_data); + ++raw_data; + } +} + +ARROW_TESTING_EXPORT void CompareBatch( + const RecordBatch& left, const RecordBatch& right, bool compare_metadata = true, + const EqualOptions& options = TestingEqualOptions()); + +ARROW_TESTING_EXPORT void ApproxCompareBatch( + const RecordBatch& left, const RecordBatch& right, bool compare_metadata = true, + const EqualOptions& options = TestingEqualOptions()); + +// Check if the padding of the buffers of the array is zero. +// Also cause valgrind warnings if the padding bytes are uninitialized. +ARROW_TESTING_EXPORT void AssertZeroPadded(const Array& array); + +// Check if the valid buffer bytes are initialized +// and cause valgrind warnings otherwise. +ARROW_TESTING_EXPORT void TestInitialized(const ArrayData& array); +ARROW_TESTING_EXPORT void TestInitialized(const Array& array); + +#define DECL_T() typedef typename TestFixture::T T; + +#define DECL_TYPE() typedef typename TestFixture::Type Type; + +// ArrayFromJSON: construct an Array from a simple JSON representation + +ARROW_TESTING_EXPORT +std::shared_ptr ArrayFromJSON(const std::shared_ptr&, + std::string_view json); + +ARROW_TESTING_EXPORT +std::shared_ptr DictArrayFromJSON(const std::shared_ptr& type, + std::string_view indices_json, + std::string_view dictionary_json); + +ARROW_TESTING_EXPORT +std::shared_ptr RecordBatchFromJSON(const std::shared_ptr&, + std::string_view); + +ARROW_TESTING_EXPORT +std::shared_ptr ChunkedArrayFromJSON(const std::shared_ptr&, + const std::vector& json); + +ARROW_TESTING_EXPORT +std::shared_ptr ScalarFromJSON(const std::shared_ptr&, + std::string_view json); + +ARROW_TESTING_EXPORT +std::shared_ptr DictScalarFromJSON(const std::shared_ptr&, + std::string_view index_json, + std::string_view dictionary_json); + +ARROW_TESTING_EXPORT +std::shared_ptr
TableFromJSON(const std::shared_ptr&, + const std::vector& json); + +ARROW_TESTING_EXPORT +Result> RunEndEncodeTableColumns( + const Table& table, const std::vector& column_indices); + +// Given an array, return a new identical array except for one validity bit +// set to a new value. +// This is useful to force the underlying "value" of null entries to otherwise +// invalid data and check that errors don't get reported. +ARROW_TESTING_EXPORT +std::shared_ptr TweakValidityBit(const std::shared_ptr& array, + int64_t index, bool validity); + +ARROW_TESTING_EXPORT +void SleepFor(double seconds); + +// Sleeps for a very small amount of time. The thread will be yielded +// at least once ensuring that context switches could happen. It is intended +// to be used for stress testing parallel code and shouldn't be assumed to do any +// reliable timing. +ARROW_TESTING_EXPORT +void SleepABit(); + +// Wait until predicate is true or timeout in seconds expires. +ARROW_TESTING_EXPORT +void BusyWait(double seconds, std::function predicate); + +// \see SleepABit +ARROW_TESTING_EXPORT +Future<> SleepABitAsync(); + +ARROW_TESTING_EXPORT bool FileIsClosed(int fd); + +template +std::vector IteratorToVector(Iterator iterator) { + EXPECT_OK_AND_ASSIGN(auto out, iterator.ToVector()); + return out; +} + +ARROW_TESTING_EXPORT +bool LocaleExists(const char* locale); + +#ifndef _WIN32 +ARROW_TESTING_EXPORT +void AssertChildExit(int child_pid, int expected_exit_status = 0); +#endif + +// A RAII-style object that switches to a new locale, and switches back +// to the old locale when going out of scope. Doesn't do anything if the +// new locale doesn't exist on the local machine. +// ATTENTION: may crash with an assertion failure on Windows debug builds. +// See ARROW-6108, also https://gerrit.libreoffice.org/#/c/54110/ +class ARROW_TESTING_EXPORT LocaleGuard { + public: + explicit LocaleGuard(const char* new_locale); + ~LocaleGuard(); + + protected: + class Impl; + std::unique_ptr impl_; +}; + +class ARROW_TESTING_EXPORT EnvVarGuard { + public: + EnvVarGuard(const std::string& name, const std::string& value); + ~EnvVarGuard(); + + protected: + const std::string name_; + std::string old_value_; + bool was_set_; +}; + +namespace internal { +class SignalHandler; +} + +class ARROW_TESTING_EXPORT SignalHandlerGuard { + public: + typedef void (*Callback)(int); + + SignalHandlerGuard(int signum, Callback cb); + SignalHandlerGuard(int signum, const internal::SignalHandler& handler); + ~SignalHandlerGuard(); + + protected: + struct Impl; + std::unique_ptr impl_; +}; + +#ifndef ARROW_LARGE_MEMORY_TESTS +#define LARGE_MEMORY_TEST(name) DISABLED_##name +#else +#define LARGE_MEMORY_TEST(name) name +#endif + +inline void PrintTo(const Status& st, std::ostream* os) { *os << st.ToString(); } + +template +void PrintTo(const Result& result, std::ostream* os) { + if (result.ok()) { + ::testing::internal::UniversalPrint(result.ValueOrDie(), os); + } else { + *os << result.status(); + } +} + +// A data type with only move constructors (no copy, no default). +struct MoveOnlyDataType { + explicit MoveOnlyDataType(int x) : data(new int(x)) {} + + MoveOnlyDataType(const MoveOnlyDataType& other) = delete; + MoveOnlyDataType& operator=(const MoveOnlyDataType& other) = delete; + + MoveOnlyDataType(MoveOnlyDataType&& other) { MoveFrom(&other); } + MoveOnlyDataType& operator=(MoveOnlyDataType&& other) { + MoveFrom(&other); + return *this; + } + + MoveOnlyDataType& operator=(int x) { + if (data != nullptr) { + delete data; + } + data = new int(x); + return *this; + } + + ~MoveOnlyDataType() { Destroy(); } + + void Destroy() { + if (data != nullptr) { + delete data; + data = nullptr; + moves = -1; + } + } + + void MoveFrom(MoveOnlyDataType* other) { + Destroy(); + data = other->data; + other->data = nullptr; + moves = other->moves + 1; + } + + int ToInt() const { return data == nullptr ? -42 : *data; } + + bool operator==(const MoveOnlyDataType& other) const { + return data != nullptr && other.data != nullptr && *data == *other.data; + } + bool operator<(const MoveOnlyDataType& other) const { + return data == nullptr || (other.data != nullptr && *data < *other.data); + } + + bool operator==(int other) const { return data != nullptr && *data == other; } + friend bool operator==(int left, const MoveOnlyDataType& right) { + return right == left; + } + + int* data = nullptr; + int moves = 0; +}; + +// A task that blocks until unlocked. Useful for timing tests. +class ARROW_TESTING_EXPORT GatingTask { + public: + explicit GatingTask(double timeout_seconds = 10); + /// \brief During destruction we wait for all pending tasks to finish + ~GatingTask(); + + /// \brief Creates a new waiting task (presumably to spawn on a thread). It will return + /// invalid if the timeout arrived before the unlock. The task will not complete until + /// unlocked or timed out + /// + /// Note: The GatingTask must outlive any Task instances + std::function Task(); + /// \brief Creates a new waiting task as a future. The future will not complete + /// until unlocked. + Future<> AsyncTask(); + /// \brief Waits until at least count tasks are running. + Status WaitForRunning(int count); + /// \brief Unlocks all waiting tasks. Returns an invalid status if any waiting task has + /// timed out + Status Unlock(); + + static std::shared_ptr Make(double timeout_seconds = 10); + + private: + class Impl; + std::shared_ptr impl_; +}; + +/// \brief create an exact copy of the data where each buffer has a max alignment of 1 +/// +/// This method does not recurse into the dictionary or children +ARROW_TESTING_EXPORT std::shared_ptr UnalignBuffers(const ArrayData& array); +/// \brief create an exact copy of the array where each buffer has a max alignment of 1 +/// +/// This method does not recurse into the dictionary or children +ARROW_TESTING_EXPORT std::shared_ptr UnalignBuffers(const Array& array); + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/matchers.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/matchers.h new file mode 100644 index 0000000000000000000000000000000000000000..b4625b3922e86bc044e30c63c15ea5b1dbaca469 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/matchers.h @@ -0,0 +1,467 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include + +#include "arrow/datum.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/stl_iterator.h" +#include "arrow/testing/future_util.h" +#include "arrow/testing/gtest_util.h" +#include "arrow/util/future.h" +#include "arrow/util/unreachable.h" + +namespace arrow { + +class PointeesEqualMatcher { + public: + template + operator testing::Matcher() const { // NOLINT runtime/explicit + struct Impl : testing::MatcherInterface { + void DescribeTo(::std::ostream* os) const override { *os << "pointees are equal"; } + + void DescribeNegationTo(::std::ostream* os) const override { + *os << "pointees are not equal"; + } + + bool MatchAndExplain(const PtrPair& pair, + testing::MatchResultListener* listener) const override { + const auto& first = *std::get<0>(pair); + const auto& second = *std::get<1>(pair); + const bool match = first.Equals(second); + *listener << "whose pointees " << testing::PrintToString(first) << " and " + << testing::PrintToString(second) + << (match ? " are equal" : " are not equal"); + return match; + } + }; + + return testing::Matcher(new Impl()); + } +}; + +// A matcher that checks that the values pointed to are Equals(). +// Useful in conjunction with other googletest matchers. +inline PointeesEqualMatcher PointeesEqual() { return {}; } + +class AnyOfJSONMatcher { + public: + AnyOfJSONMatcher(std::shared_ptr type, std::string array_json) + : type_(std::move(type)), array_json_(std::move(array_json)) {} + + template + operator testing::Matcher() const { // NOLINT runtime/explicit + struct Impl : testing::MatcherInterface { + static_assert(std::is_same>(), + "AnyOfJSON only supported for std::shared_ptr"); + Impl(std::shared_ptr type, std::string array_json) + : type_(std::move(type)), array_json_(std::move(array_json)) { + array = ArrayFromJSON(type_, array_json_); + } + void DescribeTo(std::ostream* os) const override { + *os << "matches at least one scalar from "; + *os << array->ToString(); + } + void DescribeNegationTo(::std::ostream* os) const override { + *os << "matches no scalar from "; + *os << array->ToString(); + } + bool MatchAndExplain( + const arg_type& arg, + ::testing::MatchResultListener* result_listener) const override { + for (int64_t i = 0; i < array->length(); ++i) { + std::shared_ptr scalar; + auto maybe_scalar = array->GetScalar(i); + if (maybe_scalar.ok()) { + scalar = maybe_scalar.ValueOrDie(); + } else { + *result_listener << "GetScalar() had status " + << maybe_scalar.status().ToString() << "at index " << i + << " in the input JSON Array"; + return false; + } + + if (scalar->Equals(*arg)) return true; + } + *result_listener << "Argument scalar: '" << arg->ToString() + << "' matches no scalar from " << array->ToString(); + return false; + } + const std::shared_ptr type_; + const std::string array_json_; + std::shared_ptr array; + }; + + return testing::Matcher(new Impl(type_, array_json_)); + } + + private: + const std::shared_ptr type_; + const std::string array_json_; +}; + +inline AnyOfJSONMatcher AnyOfJSON(std::shared_ptr type, + std::string array_json) { + return {std::move(type), std::move(array_json)}; +} + +template +class FutureMatcher { + public: + explicit FutureMatcher(ResultMatcher result_matcher, double wait_seconds) + : result_matcher_(std::move(result_matcher)), wait_seconds_(wait_seconds) {} + + template ::type::ValueType> + operator testing::Matcher() const { // NOLINT runtime/explicit + struct Impl : testing::MatcherInterface { + explicit Impl(const ResultMatcher& result_matcher, double wait_seconds) + : result_matcher_(testing::MatcherCast>(result_matcher)), + wait_seconds_(wait_seconds) {} + + void DescribeTo(::std::ostream* os) const override { + *os << "value "; + result_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + *os << "value "; + result_matcher_.DescribeNegationTo(os); + } + + bool MatchAndExplain(const Fut& fut, + testing::MatchResultListener* listener) const override { + if (!fut.Wait(wait_seconds_)) { + *listener << "which didn't finish within " << wait_seconds_ << " seconds"; + return false; + } + return result_matcher_.MatchAndExplain(fut.result(), listener); + } + + const testing::Matcher> result_matcher_; + const double wait_seconds_; + }; + + return testing::Matcher(new Impl(result_matcher_, wait_seconds_)); + } + + private: + const ResultMatcher result_matcher_; + const double wait_seconds_; +}; + +template +class ResultMatcher { + public: + explicit ResultMatcher(ValueMatcher value_matcher) + : value_matcher_(std::move(value_matcher)) {} + + template ::type::ValueType> + operator testing::Matcher() const { // NOLINT runtime/explicit + struct Impl : testing::MatcherInterface { + explicit Impl(const ValueMatcher& value_matcher) + : value_matcher_(testing::MatcherCast(value_matcher)) {} + + void DescribeTo(::std::ostream* os) const override { + *os << "value "; + value_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + *os << "value "; + value_matcher_.DescribeNegationTo(os); + } + + bool MatchAndExplain(const Res& maybe_value, + testing::MatchResultListener* listener) const override { + if (!maybe_value.status().ok()) { + *listener << "whose error " + << testing::PrintToString(maybe_value.status().ToString()) + << " doesn't match"; + return false; + } + const ValueType& value = maybe_value.ValueOrDie(); + testing::StringMatchResultListener value_listener; + const bool match = value_matcher_.MatchAndExplain(value, &value_listener); + *listener << "whose value " << testing::PrintToString(value) + << (match ? " matches" : " doesn't match"); + testing::internal::PrintIfNotEmpty(value_listener.str(), listener->stream()); + return match; + } + + const testing::Matcher value_matcher_; + }; + + return testing::Matcher(new Impl(value_matcher_)); + } + + private: + const ValueMatcher value_matcher_; +}; + +class ErrorMatcher { + public: + explicit ErrorMatcher(StatusCode code, + std::optional> message_matcher) + : code_(code), message_matcher_(std::move(message_matcher)) {} + + template + operator testing::Matcher() const { // NOLINT runtime/explicit + struct Impl : testing::MatcherInterface { + explicit Impl(StatusCode code, + std::optional> message_matcher) + : code_(code), message_matcher_(std::move(message_matcher)) {} + + void DescribeTo(::std::ostream* os) const override { + *os << "raises StatusCode::" << Status::CodeAsString(code_); + if (message_matcher_) { + *os << " and message "; + message_matcher_->DescribeTo(os); + } + } + + void DescribeNegationTo(::std::ostream* os) const override { + *os << "does not raise StatusCode::" << Status::CodeAsString(code_); + if (message_matcher_) { + *os << " or message "; + message_matcher_->DescribeNegationTo(os); + } + } + + bool MatchAndExplain(const Res& maybe_value, + testing::MatchResultListener* listener) const override { + const Status& status = internal::GenericToStatus(maybe_value); + testing::StringMatchResultListener value_listener; + + bool match = status.code() == code_; + if (message_matcher_) { + match = match && + message_matcher_->MatchAndExplain(status.message(), &value_listener); + } + + if (match) { + *listener << "whose error matches"; + } else if (status.ok()) { + *listener << "whose non-error doesn't match"; + } else { + *listener << "whose error doesn't match"; + } + + testing::internal::PrintIfNotEmpty(value_listener.str(), listener->stream()); + return match; + } + + const StatusCode code_; + const std::optional> message_matcher_; + }; + + return testing::Matcher(new Impl(code_, message_matcher_)); + } + + private: + const StatusCode code_; + const std::optional> message_matcher_; +}; + +class OkMatcher { + public: + template + operator testing::Matcher() const { // NOLINT runtime/explicit + struct Impl : testing::MatcherInterface { + void DescribeTo(::std::ostream* os) const override { *os << "is ok"; } + + void DescribeNegationTo(::std::ostream* os) const override { *os << "is not ok"; } + + bool MatchAndExplain(const Res& maybe_value, + testing::MatchResultListener* listener) const override { + const Status& status = internal::GenericToStatus(maybe_value); + + const bool match = status.ok(); + *listener << "whose " << (match ? "non-error matches" : "error doesn't match"); + return match; + } + }; + + return testing::Matcher(new Impl()); + } +}; + +// Returns a matcher that waits on a Future (by default for 16 seconds) +// then applies a matcher to the result. +template +FutureMatcher Finishes( + const ResultMatcher& result_matcher, + double wait_seconds = kDefaultAssertFinishesWaitSeconds) { + return FutureMatcher(result_matcher, wait_seconds); +} + +// Returns a matcher that matches the value of a successful Result. +template +ResultMatcher ResultWith(const ValueMatcher& value_matcher) { + return ResultMatcher(value_matcher); +} + +// Returns a matcher that matches an ok Status or Result. +inline OkMatcher Ok() { return {}; } + +// Returns a matcher that matches the StatusCode of a Status or Result. +// Do not use Raises(StatusCode::OK) to match a non error code. +inline ErrorMatcher Raises(StatusCode code) { return ErrorMatcher(code, std::nullopt); } + +// Returns a matcher that matches the StatusCode and message of a Status or Result. +template +ErrorMatcher Raises(StatusCode code, const MessageMatcher& message_matcher) { + return ErrorMatcher(code, testing::MatcherCast(message_matcher)); +} + +class DataEqMatcher { + public: + // TODO(bkietz) support EqualOptions, ApproxEquals, etc + // Probably it's better to use something like config-through-key_value_metadata + // as with the random generators to decouple this from EqualOptions etc. + explicit DataEqMatcher(Datum expected) : expected_(std::move(expected)) {} + + template + operator testing::Matcher() const { // NOLINT runtime/explicit + struct Impl : testing::MatcherInterface { + explicit Impl(Datum expected) : expected_(std::move(expected)) {} + + void DescribeTo(::std::ostream* os) const override { + *os << "has data "; + PrintTo(expected_, os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + *os << "doesn't have data "; + PrintTo(expected_, os); + } + + bool MatchAndExplain(const Data& data, + testing::MatchResultListener* listener) const override { + Datum boxed(data); + + if (boxed.kind() != expected_.kind()) { + *listener << "whose Datum::kind " << boxed.ToString() << " doesn't match " + << expected_.ToString(); + return false; + } + + if (const auto& boxed_type = boxed.type()) { + if (*boxed_type != *expected_.type()) { + *listener << "whose DataType " << boxed_type->ToString() << " doesn't match " + << expected_.type()->ToString(); + return false; + } + } else if (const auto& boxed_schema = boxed.schema()) { + if (*boxed_schema != *expected_.schema()) { + *listener << "whose Schema " << boxed_schema->ToString() << " doesn't match " + << expected_.schema()->ToString(); + return false; + } + } else { + Unreachable(); + } + + if (boxed == expected_) { + *listener << "whose value matches"; + return true; + } + + if (listener->IsInterested() && boxed.kind() == Datum::ARRAY) { + *listener << "whose value differs from the expected value by " + << boxed.make_array()->Diff(*expected_.make_array()); + } else { + *listener << "whose value doesn't match"; + } + return false; + } + + Datum expected_; + }; + + return testing::Matcher(new Impl(expected_)); + } + + private: + Datum expected_; +}; + +/// Constructs a datum against which arguments are matched +template +DataEqMatcher DataEq(Data&& dat) { + return DataEqMatcher(Datum(std::forward(dat))); +} + +/// Constructs an array with ArrayFromJSON against which arguments are matched +inline DataEqMatcher DataEqArray(const std::shared_ptr& type, + std::string_view json) { + return DataEq(ArrayFromJSON(type, json)); +} + +/// Constructs an array from a vector of optionals against which arguments are matched +template ::ArrayType, + typename BuilderType = typename TypeTraits::BuilderType, + typename ValueType = + typename ::arrow::stl::detail::DefaultValueAccessor::ValueType> +DataEqMatcher DataEqArray(T type, const std::vector>& values) { + // FIXME(bkietz) broken until DataType is move constructible + BuilderType builder(std::make_shared(std::move(type)), default_memory_pool()); + DCHECK_OK(builder.Reserve(static_cast(values.size()))); + + // pseudo constexpr: + static const bool need_safe_append = !is_fixed_width(T::type_id); + + for (auto value : values) { + if (need_safe_append) { + DCHECK_OK(builder.AppendOrNull(value)); + } else { + builder.UnsafeAppendOrNull(value); + } + } + + return DataEq(builder.Finish().ValueOrDie()); +} + +/// Constructs a scalar with ScalarFromJSON against which arguments are matched +inline DataEqMatcher DataEqScalar(const std::shared_ptr& type, + std::string_view json) { + return DataEq(ScalarFromJSON(type, json)); +} + +/// Constructs a scalar against which arguments are matched +template ::ScalarType, + typename ValueType = typename ScalarType::ValueType> +DataEqMatcher DataEqScalar(T type, std::optional value) { + ScalarType expected(std::make_shared(std::move(type))); + + if (value) { + expected.is_valid = true; + expected.value = std::move(*value); + } + + return DataEq(std::move(expected)); +} + +// HasType, HasSchema matchers + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/pch.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/pch.h new file mode 100644 index 0000000000000000000000000000000000000000..e544ad806adc992691600b90ddd7174fb0447c4e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/pch.h @@ -0,0 +1,25 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Often-used headers, for precompiling. +// If updating this header, please make sure you check compilation speed +// before checking in. Adding headers which are not used extremely often +// may incur a slowdown, since it makes the precompiled header heavier to load. + +#include "arrow/pch.h" +#include "arrow/testing/gtest_util.h" +#include "arrow/testing/util.h" diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/uniform_real.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/uniform_real.h new file mode 100644 index 0000000000000000000000000000000000000000..8aa04a83288d9f8ce39a2d7c92b528ac9742bf98 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/uniform_real.h @@ -0,0 +1,84 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Random real generation is very slow on Arm if built with clang + libstdc++ +// due to software emulated long double arithmetic. +// This file ports some random real libs from llvm libc++ library, which are +// free from long double calculation. +// It improves performance significantly on both Arm (~100x) and x86 (~8x) in +// generating random reals when built with clang + gnu libstdc++. +// Based on: https://github.com/llvm/llvm-project/tree/main/libcxx + +#pragma once + +#include + +#include + +namespace arrow { +namespace random { + +namespace detail { + +// std::generate_canonical, simplified +// https://en.cppreference.com/w/cpp/numeric/random/generate_canonical +template +RealType generate_canonical(Rng& rng) { + const size_t b = std::numeric_limits::digits; + const size_t log2R = 63 - ::arrow::bit_util::CountLeadingZeros( + static_cast(Rng::max() - Rng::min()) + 1); + const size_t k = b / log2R + (b % log2R != 0) + (b == 0); + const RealType r = static_cast(Rng::max() - Rng::min()) + 1; + RealType base = r; + RealType sp = static_cast(rng() - Rng::min()); + for (size_t i = 1; i < k; ++i, base *= r) { + sp += (rng() - Rng::min()) * base; + } + return sp / base; +} + +} // namespace detail + +// std::uniform_real_distribution, simplified +// https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution +template +struct uniform_real_distribution { + const RealType a, b; + + explicit uniform_real_distribution(RealType a = 0, RealType b = 1) : a(a), b(b) {} + + template + RealType operator()(Rng& rng) { + return (b - a) * detail::generate_canonical(rng) + a; + } +}; + +// std::bernoulli_distribution, simplified +// https://en.cppreference.com/w/cpp/numeric/random/bernoulli_distribution +struct bernoulli_distribution { + const double p; + + explicit bernoulli_distribution(double p = 0.5) : p(p) {} + + template + bool operator()(Rng& rng) { + return detail::generate_canonical(rng) < p; + } +}; + +} // namespace random +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/util.h new file mode 100644 index 0000000000000000000000000000000000000000..b4b2785a36292df93777c2c4e76eea27f3c4a0c8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/util.h @@ -0,0 +1,140 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/record_batch.h" +#include "arrow/status.h" +#include "arrow/testing/visibility.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" + +namespace arrow { + +template +Status CopyBufferFromVector(const std::vector& values, MemoryPool* pool, + std::shared_ptr* result) { + int64_t nbytes = static_cast(values.size()) * sizeof(T); + + ARROW_ASSIGN_OR_RAISE(auto buffer, AllocateBuffer(nbytes, pool)); + auto immutable_data = reinterpret_cast(values.data()); + std::copy(immutable_data, immutable_data + nbytes, buffer->mutable_data()); + memset(buffer->mutable_data() + nbytes, 0, + static_cast(buffer->capacity() - nbytes)); + + *result = std::move(buffer); + return Status::OK(); +} + +// Sets approximately pct_null of the first n bytes in null_bytes to zero +// and the rest to non-zero (true) values. +ARROW_TESTING_EXPORT void random_null_bytes(int64_t n, double pct_null, + uint8_t* null_bytes); +ARROW_TESTING_EXPORT void random_is_valid(int64_t n, double pct_null, + std::vector* is_valid, + int random_seed = 0); +ARROW_TESTING_EXPORT void random_bytes(int64_t n, uint32_t seed, uint8_t* out); +ARROW_TESTING_EXPORT std::string random_string(int64_t n, uint32_t seed); +ARROW_TESTING_EXPORT int32_t DecimalSize(int32_t precision); +ARROW_TESTING_EXPORT void random_ascii(int64_t n, uint32_t seed, uint8_t* out); +ARROW_TESTING_EXPORT int64_t CountNulls(const std::vector& valid_bytes); + +ARROW_TESTING_EXPORT Status MakeRandomByteBuffer(int64_t length, MemoryPool* pool, + std::shared_ptr* out, + uint32_t seed = 0); + +ARROW_TESTING_EXPORT uint64_t random_seed(); + +#define DECL_T() typedef typename TestFixture::T T; + +#define DECL_TYPE() typedef typename TestFixture::Type Type; + +// ---------------------------------------------------------------------- +// A RecordBatchReader for serving a sequence of in-memory record batches + +class BatchIterator : public RecordBatchReader { + public: + BatchIterator(const std::shared_ptr& schema, + const std::vector>& batches) + : schema_(schema), batches_(batches), position_(0) {} + + std::shared_ptr schema() const override { return schema_; } + + Status ReadNext(std::shared_ptr* out) override { + if (position_ >= batches_.size()) { + *out = nullptr; + } else { + *out = batches_[position_++]; + } + return Status::OK(); + } + + private: + std::shared_ptr schema_; + std::vector> batches_; + size_t position_; +}; + +static inline std::vector (*)(FieldVector, std::vector)> +UnionTypeFactories() { + return {sparse_union, dense_union}; +} + +// Return the value of the ARROW_TEST_DATA environment variable or return error +// Status +ARROW_TESTING_EXPORT Status GetTestResourceRoot(std::string*); + +// Return the value of the ARROW_TIMEZONE_DATABASE environment variable +ARROW_TESTING_EXPORT std::optional GetTestTimezoneDatabaseRoot(); + +// Set the Timezone database based on the ARROW_TIMEZONE_DATABASE env variable +// This is only relevant on Windows, since other OSs have compatible databases built-in +ARROW_TESTING_EXPORT Status InitTestTimezoneDatabase(); + +// Get a TCP port number to listen on. This is a different number every time, +// as reusing the same port across tests can produce spurious bind errors on +// Windows. +ARROW_TESTING_EXPORT int GetListenPort(); + +// Get a IPv4 "address:port" to listen on. The address will be a loopback +// address. Compared to GetListenPort(), this will minimize the risk of +// port conflicts. +ARROW_TESTING_EXPORT std::string GetListenAddress(); + +ARROW_TESTING_EXPORT +const std::vector>& all_dictionary_index_types(); + +// Get a list of supported hardware flags from the given candidates. +// The result will always contain 0, meaning no optional CPU feature enabled at all. +ARROW_TESTING_EXPORT +std::vector GetSupportedHardwareFlags( + const std::vector& candidate_flags); + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/visibility.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/visibility.h new file mode 100644 index 0000000000000000000000000000000000000000..1b2aa7cd86fc65f3a1ad1b332f7c295aa3cc9c25 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/testing/visibility.h @@ -0,0 +1,48 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4251) +#else +#pragma GCC diagnostic ignored "-Wattributes" +#endif + +#ifdef ARROW_TESTING_STATIC +#define ARROW_TESTING_EXPORT +#elif defined(ARROW_TESTING_EXPORTING) +#define ARROW_TESTING_EXPORT __declspec(dllexport) +#else +#define ARROW_TESTING_EXPORT __declspec(dllimport) +#endif + +#define ARROW_TESTING_NO_EXPORT +#else // Not Windows +#ifndef ARROW_TESTING_EXPORT +#define ARROW_TESTING_EXPORT __attribute__((visibility("default"))) +#endif +#ifndef ARROW_TESTING_NO_EXPORT +#define ARROW_TESTING_NO_EXPORT __attribute__((visibility("hidden"))) +#endif +#endif // Non-Windows + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/aligned_storage.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/aligned_storage.h new file mode 100644 index 0000000000000000000000000000000000000000..01e3ced2d1f61b8eb3719208c13a5dc4e111e771 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/aligned_storage.h @@ -0,0 +1,145 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/util/launder.h" +#include "arrow/util/macros.h" + +namespace arrow { +namespace internal { + +template +class AlignedStorage { + public: + static constexpr bool can_memcpy = std::is_trivial::value; + + constexpr T* get() noexcept { + return arrow::internal::launder(reinterpret_cast(&data_)); + } + + constexpr const T* get() const noexcept { + // Use fully qualified name to avoid ambiguities with MSVC (ARROW-14800) + return arrow::internal::launder(reinterpret_cast(&data_)); + } + + void destroy() noexcept { + if (!std::is_trivially_destructible::value) { + get()->~T(); + } + } + + template + void construct(A&&... args) noexcept { + new (&data_) T(std::forward(args)...); + } + + template + void assign(V&& v) noexcept { + *get() = std::forward(v); + } + + void move_construct(AlignedStorage* other) noexcept { + new (&data_) T(std::move(*other->get())); + } + + void move_assign(AlignedStorage* other) noexcept { *get() = std::move(*other->get()); } + + template + static typename std::enable_if::type move_construct_several( + AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + memcpy(dest->get(), src->get(), memcpy_length * sizeof(T)); + } + + template + static typename std::enable_if::type + move_construct_several_and_destroy_source(AlignedStorage* ARROW_RESTRICT src, + AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + memcpy(dest->get(), src->get(), memcpy_length * sizeof(T)); + } + + template + static typename std::enable_if::type move_construct_several( + AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + for (size_t i = 0; i < n; ++i) { + new (dest[i].get()) T(std::move(*src[i].get())); + } + } + + template + static typename std::enable_if::type + move_construct_several_and_destroy_source(AlignedStorage* ARROW_RESTRICT src, + AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + for (size_t i = 0; i < n; ++i) { + new (dest[i].get()) T(std::move(*src[i].get())); + src[i].destroy(); + } + } + + static void move_construct_several(AlignedStorage* ARROW_RESTRICT src, + AlignedStorage* ARROW_RESTRICT dest, + size_t n) noexcept { + move_construct_several(src, dest, n, n); + } + + static void move_construct_several_and_destroy_source( + AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, + size_t n) noexcept { + move_construct_several_and_destroy_source(src, dest, n, n); + } + + static void destroy_several(AlignedStorage* p, size_t n) noexcept { + if (!std::is_trivially_destructible::value) { + for (size_t i = 0; i < n; ++i) { + p[i].destroy(); + } + } + } + + private: +#if !defined(__clang__) && defined(__GNUC__) && defined(__i386__) + // Workaround for GCC bug on i386: + // alignof(int64 | float64) can give different results depending on the + // compilation context, leading to internal ABI mismatch manifesting + // in incorrect propagation of Result between + // compilation units. + // (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88115) + static constexpr size_t alignment() { + if (std::is_integral_v && sizeof(T) == 8) { + return 4; + } else if (std::is_floating_point_v && sizeof(T) == 8) { + return 4; + } + return alignof(T); + } + + typename std::aligned_storage::type data_; +#else + typename std::aligned_storage::type data_; +#endif +}; + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator.h new file mode 100644 index 0000000000000000000000000000000000000000..f9bcd534567c6c231192cc174a717997583dfb3c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator.h @@ -0,0 +1,2058 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/util/async_generator_fwd.h" +#include "arrow/util/async_util.h" +#include "arrow/util/functional.h" +#include "arrow/util/future.h" +#include "arrow/util/io_util.h" +#include "arrow/util/iterator.h" +#include "arrow/util/mutex.h" +#include "arrow/util/queue.h" +#include "arrow/util/thread_pool.h" + +namespace arrow { + +// The methods in this file create, modify, and utilize AsyncGenerator which is an +// iterator of futures. This allows an asynchronous source (like file input) to be run +// through a pipeline in the same way that iterators can be used to create pipelined +// workflows. +// +// In order to support pipeline parallelism we introduce the concept of asynchronous +// reentrancy. This is different than synchronous reentrancy. With synchronous code a +// function is reentrant if the function can be called again while a previous call to that +// function is still running. Unless otherwise specified none of these generators are +// synchronously reentrant. Care should be taken to avoid calling them in such a way (and +// the utilities Visit/Collect/Await take care to do this). +// +// Asynchronous reentrancy on the other hand means the function is called again before the +// future returned by the function is marked finished (but after the call to get the +// future returns). Some of these generators are async-reentrant while others (e.g. +// those that depend on ordered processing like decompression) are not. Read the MakeXYZ +// function comments to determine which generators support async reentrancy. +// +// Note: Generators that are not asynchronously reentrant can still support readahead +// (\see MakeSerialReadaheadGenerator). +// +// Readahead operators, and some other operators, may introduce queueing. Any operators +// that introduce buffering should detail the amount of buffering they introduce in their +// MakeXYZ function comments. +// +// A generator should always be fully consumed before it is destroyed. +// A generator should not mark a future complete with an error status or a terminal value +// until all outstanding futures have completed. Generators that spawn multiple +// concurrent futures may need to hold onto an error while other concurrent futures wrap +// up. +template +struct IterationTraits> { + /// \brief by default when iterating through a sequence of AsyncGenerator, + /// an empty function indicates the end of iteration. + static AsyncGenerator End() { return AsyncGenerator(); } + + static bool IsEnd(const AsyncGenerator& val) { return !val; } +}; + +template +Future AsyncGeneratorEnd() { + return Future::MakeFinished(IterationTraits::End()); +} + +/// returning a future that completes when all have been visited +template +Future<> VisitAsyncGenerator(AsyncGenerator generator, Visitor visitor) { + struct LoopBody { + struct Callback { + Result> operator()(const T& next) { + if (IsIterationEnd(next)) { + return Break(); + } else { + auto visited = visitor(next); + if (visited.ok()) { + return Continue(); + } else { + return visited; + } + } + } + + Visitor visitor; + }; + + Future> operator()() { + Callback callback{visitor}; + auto next = generator(); + return next.Then(std::move(callback)); + } + + AsyncGenerator generator; + Visitor visitor; + }; + + return Loop(LoopBody{std::move(generator), std::move(visitor)}); +} + +/// \brief Wait for an async generator to complete, discarding results. +template +Future<> DiscardAllFromAsyncGenerator(AsyncGenerator generator) { + std::function visitor = [](const T&) { return Status::OK(); }; + return VisitAsyncGenerator(generator, visitor); +} + +/// \brief Collect the results of an async generator into a vector +template +Future> CollectAsyncGenerator(AsyncGenerator generator) { + auto vec = std::make_shared>(); + auto loop_body = [generator = std::move(generator), + vec = std::move(vec)]() -> Future>> { + auto next = generator(); + return next.Then([vec](const T& result) -> Result>> { + if (IsIterationEnd(result)) { + return Break(*vec); + } else { + vec->push_back(result); + return Continue(); + } + }); + }; + return Loop(std::move(loop_body)); +} + +/// \see MakeMappedGenerator +template +class MappingGenerator { + public: + MappingGenerator(AsyncGenerator source, std::function(const T&)> map) + : state_(std::make_shared(std::move(source), std::move(map))) {} + + Future operator()() { + auto future = Future::Make(); + bool should_trigger; + { + auto guard = state_->mutex.Lock(); + if (state_->finished) { + return AsyncGeneratorEnd(); + } + should_trigger = state_->waiting_jobs.empty(); + state_->waiting_jobs.push_back(future); + } + if (should_trigger) { + state_->source().AddCallback(Callback{state_}); + } + return future; + } + + private: + struct State { + State(AsyncGenerator source, std::function(const T&)> map) + : source(std::move(source)), + map(std::move(map)), + waiting_jobs(), + mutex(), + finished(false) {} + + void Purge() { + // This might be called by an original callback (if the source iterator fails or + // ends) or by a mapped callback (if the map function fails or ends prematurely). + // Either way it should only be called once and after finished is set so there is no + // need to guard access to `waiting_jobs`. + while (!waiting_jobs.empty()) { + waiting_jobs.front().MarkFinished(IterationTraits::End()); + waiting_jobs.pop_front(); + } + } + + AsyncGenerator source; + std::function(const T&)> map; + std::deque> waiting_jobs; + util::Mutex mutex; + bool finished; + }; + + struct Callback; + + struct MappedCallback { + void operator()(const Result& maybe_next) { + bool end = !maybe_next.ok() || IsIterationEnd(*maybe_next); + bool should_purge = false; + if (end) { + { + auto guard = state->mutex.Lock(); + should_purge = !state->finished; + state->finished = true; + } + } + sink.MarkFinished(maybe_next); + if (should_purge) { + state->Purge(); + } + } + std::shared_ptr state; + Future sink; + }; + + struct Callback { + void operator()(const Result& maybe_next) { + Future sink; + bool end = !maybe_next.ok() || IsIterationEnd(*maybe_next); + bool should_purge = false; + bool should_trigger; + { + auto guard = state->mutex.Lock(); + // A MappedCallback may have purged or be purging the queue; + // we shouldn't do anything here. + if (state->finished) return; + if (end) { + should_purge = !state->finished; + state->finished = true; + } + sink = state->waiting_jobs.front(); + state->waiting_jobs.pop_front(); + should_trigger = !end && !state->waiting_jobs.empty(); + } + if (should_purge) { + state->Purge(); + } + if (should_trigger) { + state->source().AddCallback(Callback{state}); + } + if (maybe_next.ok()) { + const T& val = maybe_next.ValueUnsafe(); + if (IsIterationEnd(val)) { + sink.MarkFinished(IterationTraits::End()); + } else { + Future mapped_fut = state->map(val); + mapped_fut.AddCallback(MappedCallback{std::move(state), std::move(sink)}); + } + } else { + sink.MarkFinished(maybe_next.status()); + } + } + + std::shared_ptr state; + }; + + std::shared_ptr state_; +}; + +/// \brief Create a generator that will apply the map function to each element of +/// source. The map function is not called on the end token. +/// +/// Note: This function makes a copy of `map` for each item +/// Note: Errors returned from the `map` function will be propagated +/// +/// If the source generator is async-reentrant then this generator will be also +template , + typename V = typename EnsureFuture::type::ValueType> +AsyncGenerator MakeMappedGenerator(AsyncGenerator source_generator, MapFn map) { + auto map_callback = [map = std::move(map)](const T& val) mutable -> Future { + return ToFuture(map(val)); + }; + return MappingGenerator(std::move(source_generator), std::move(map_callback)); +} + +/// \brief Create a generator that will apply the map function to +/// each element of source. The map function is not called on the end +/// token. The result of the map function should be another +/// generator; all these generators will then be flattened to produce +/// a single stream of items. +/// +/// Note: This function makes a copy of `map` for each item +/// Note: Errors returned from the `map` function will be propagated +/// +/// If the source generator is async-reentrant then this generator will be also +template , + typename V = typename EnsureFuture::type::ValueType> +AsyncGenerator MakeFlatMappedGenerator(AsyncGenerator source_generator, MapFn map) { + return MakeConcatenatedGenerator( + MakeMappedGenerator(std::move(source_generator), std::move(map))); +} + +/// \see MakeSequencingGenerator +template +class SequencingGenerator { + public: + SequencingGenerator(AsyncGenerator source, ComesAfter compare, IsNext is_next, + T initial_value) + : state_(std::make_shared(std::move(source), std::move(compare), + std::move(is_next), std::move(initial_value))) {} + + Future operator()() { + { + auto guard = state_->mutex.Lock(); + // We can send a result immediately if the top of the queue is either an + // error or the next item + if (!state_->queue.empty() && + (!state_->queue.top().ok() || + state_->is_next(state_->previous_value, *state_->queue.top()))) { + auto result = std::move(state_->queue.top()); + if (result.ok()) { + state_->previous_value = *result; + } + state_->queue.pop(); + return Future::MakeFinished(result); + } + if (state_->finished) { + return AsyncGeneratorEnd(); + } + // The next item is not in the queue so we will need to wait + auto new_waiting_fut = Future::Make(); + state_->waiting_future = new_waiting_fut; + guard.Unlock(); + state_->source().AddCallback(Callback{state_}); + return new_waiting_fut; + } + } + + private: + struct WrappedComesAfter { + bool operator()(const Result& left, const Result& right) { + if (!left.ok() || !right.ok()) { + // Should never happen + return false; + } + return compare(*left, *right); + } + ComesAfter compare; + }; + + struct State { + State(AsyncGenerator source, ComesAfter compare, IsNext is_next, T initial_value) + : source(std::move(source)), + is_next(std::move(is_next)), + previous_value(std::move(initial_value)), + waiting_future(), + queue(WrappedComesAfter{compare}), + finished(false), + mutex() {} + + AsyncGenerator source; + IsNext is_next; + T previous_value; + Future waiting_future; + std::priority_queue, std::vector>, WrappedComesAfter> queue; + bool finished; + util::Mutex mutex; + }; + + class Callback { + public: + explicit Callback(std::shared_ptr state) : state_(std::move(state)) {} + + void operator()(const Result result) { + Future to_deliver; + bool finished; + { + auto guard = state_->mutex.Lock(); + bool ready_to_deliver = false; + if (!result.ok()) { + // Clear any cached results + while (!state_->queue.empty()) { + state_->queue.pop(); + } + ready_to_deliver = true; + state_->finished = true; + } else if (IsIterationEnd(result.ValueUnsafe())) { + ready_to_deliver = state_->queue.empty(); + state_->finished = true; + } else { + ready_to_deliver = state_->is_next(state_->previous_value, *result); + } + + if (ready_to_deliver && state_->waiting_future.is_valid()) { + to_deliver = state_->waiting_future; + if (result.ok()) { + state_->previous_value = *result; + } + } else { + state_->queue.push(result); + } + // Capture state_->finished so we can access it outside the mutex + finished = state_->finished; + } + // Must deliver result outside of the mutex + if (to_deliver.is_valid()) { + to_deliver.MarkFinished(result); + } else { + // Otherwise, if we didn't get the next item (or a terminal item), we + // need to keep looking + if (!finished) { + state_->source().AddCallback(Callback{state_}); + } + } + } + + private: + const std::shared_ptr state_; + }; + + const std::shared_ptr state_; +}; + +/// \brief Buffer an AsyncGenerator to return values in sequence order ComesAfter +/// and IsNext determine the sequence order. +/// +/// ComesAfter should be a BinaryPredicate that only returns true if a comes after b +/// +/// IsNext should be a BinaryPredicate that returns true, given `a` and `b`, only if +/// `b` follows immediately after `a`. It should return true given `initial_value` and +/// `b` if `b` is the first item in the sequence. +/// +/// This operator will queue unboundedly while waiting for the next item. It is intended +/// for jittery sources that might scatter an ordered sequence. It is NOT intended to +/// sort. Using it to try and sort could result in excessive RAM usage. This generator +/// will queue up to N blocks where N is the max "out of order"ness of the source. +/// +/// For example, if the source is 1,6,2,5,4,3 it will queue 3 blocks because 3 is 3 +/// blocks beyond where it belongs. +/// +/// This generator is not async-reentrant but it consists only of a simple log(n) +/// insertion into a priority queue. +template +AsyncGenerator MakeSequencingGenerator(AsyncGenerator source_generator, + ComesAfter compare, IsNext is_next, + T initial_value) { + return SequencingGenerator( + std::move(source_generator), std::move(compare), std::move(is_next), + std::move(initial_value)); +} + +/// \see MakeTransformedGenerator +template +class TransformingGenerator { + // The transforming generator state will be referenced as an async generator but will + // also be referenced via callback to various futures. If the async generator owner + // moves it around we need the state to be consistent for future callbacks. + struct TransformingGeneratorState + : std::enable_shared_from_this { + TransformingGeneratorState(AsyncGenerator generator, Transformer transformer) + : generator_(std::move(generator)), + transformer_(std::move(transformer)), + last_value_(), + finished_() {} + + Future operator()() { + while (true) { + auto maybe_next_result = Pump(); + if (!maybe_next_result.ok()) { + return Future::MakeFinished(maybe_next_result.status()); + } + auto maybe_next = std::move(maybe_next_result).ValueUnsafe(); + if (maybe_next.has_value()) { + return Future::MakeFinished(*std::move(maybe_next)); + } + + auto next_fut = generator_(); + // If finished already, process results immediately inside the loop to avoid + // stack overflow + if (next_fut.is_finished()) { + auto next_result = next_fut.result(); + if (next_result.ok()) { + last_value_ = *next_result; + } else { + return Future::MakeFinished(next_result.status()); + } + // Otherwise, if not finished immediately, add callback to process results + } else { + auto self = this->shared_from_this(); + return next_fut.Then([self](const T& next_result) { + self->last_value_ = next_result; + return (*self)(); + }); + } + } + } + + // See comment on TransformingIterator::Pump + Result> Pump() { + if (!finished_ && last_value_.has_value()) { + ARROW_ASSIGN_OR_RAISE(TransformFlow next, transformer_(*last_value_)); + if (next.ReadyForNext()) { + if (IsIterationEnd(*last_value_)) { + finished_ = true; + } + last_value_.reset(); + } + if (next.Finished()) { + finished_ = true; + } + if (next.HasValue()) { + return next.Value(); + } + } + if (finished_) { + return IterationTraits::End(); + } + return std::nullopt; + } + + AsyncGenerator generator_; + Transformer transformer_; + std::optional last_value_; + bool finished_; + }; + + public: + explicit TransformingGenerator(AsyncGenerator generator, + Transformer transformer) + : state_(std::make_shared(std::move(generator), + std::move(transformer))) {} + + Future operator()() { return (*state_)(); } + + protected: + std::shared_ptr state_; +}; + +/// \brief Transform an async generator using a transformer function returning a new +/// AsyncGenerator +/// +/// The transform function here behaves exactly the same as the transform function in +/// MakeTransformedIterator and you can safely use the same transform function to +/// transform both synchronous and asynchronous streams. +/// +/// This generator is not async-reentrant +/// +/// This generator may queue up to 1 instance of T but will not delay +template +AsyncGenerator MakeTransformedGenerator(AsyncGenerator generator, + Transformer transformer) { + return TransformingGenerator(generator, transformer); +} + +/// \see MakeSerialReadaheadGenerator +template +class SerialReadaheadGenerator { + public: + SerialReadaheadGenerator(AsyncGenerator source_generator, int max_readahead) + : state_(std::make_shared(std::move(source_generator), max_readahead)) {} + + Future operator()() { + if (state_->first_) { + // Lazy generator, need to wait for the first ask to prime the pump + state_->first_ = false; + auto next = state_->source_(); + return next.Then(Callback{state_}, ErrCallback{state_}); + } + + // This generator is not async-reentrant. We won't be called until the last + // future finished so we know there is something in the queue + auto finished = state_->finished_.load(); + if (finished && state_->readahead_queue_.IsEmpty()) { + return AsyncGeneratorEnd(); + } + + std::shared_ptr> next; + if (!state_->readahead_queue_.Read(next)) { + return Status::UnknownError("Could not read from readahead_queue"); + } + + auto last_available = state_->spaces_available_.fetch_add(1); + if (last_available == 0 && !finished) { + // Reader idled out, we need to restart it + ARROW_RETURN_NOT_OK(state_->Pump(state_)); + } + return *next; + } + + private: + struct State { + State(AsyncGenerator source, int max_readahead) + : first_(true), + source_(std::move(source)), + finished_(false), + // There is one extra "space" for the in-flight request + spaces_available_(max_readahead + 1), + // The SPSC queue has size-1 "usable" slots so we need to overallocate 1 + readahead_queue_(max_readahead + 1) {} + + Status Pump(const std::shared_ptr& self) { + // Can't do readahead_queue.write(source().Then(...)) because then the + // callback might run immediately and add itself to the queue before this gets added + // to the queue messing up the order. + auto next_slot = std::make_shared>(); + auto written = readahead_queue_.Write(next_slot); + if (!written) { + return Status::UnknownError("Could not write to readahead_queue"); + } + // If this Pump is being called from a callback it is possible for the source to + // poll and read from the queue between the Write and this spot where we fill the + // value in. However, it is not possible for the future to read this value we are + // writing. That is because this callback (the callback for future X) must be + // finished before future X is marked complete and this source is not pulled + // reentrantly so it will not poll for future X+1 until this callback has completed. + *next_slot = source_().Then(Callback{self}, ErrCallback{self}); + return Status::OK(); + } + + // Only accessed by the consumer end + bool first_; + // Accessed by both threads + AsyncGenerator source_; + std::atomic finished_; + // The queue has a size but it is not atomic. We keep track of how many spaces are + // left in the queue here so we know if we've just written the last value and we need + // to stop reading ahead or if we've just read from a full queue and we need to + // restart reading ahead + std::atomic spaces_available_; + // Needs to be a queue of shared_ptr and not Future because we set the value of the + // future after we add it to the queue + util::SpscQueue>> readahead_queue_; + }; + + struct Callback { + Result operator()(const T& next) { + if (IsIterationEnd(next)) { + state_->finished_.store(true); + return next; + } + auto last_available = state_->spaces_available_.fetch_sub(1); + if (last_available > 1) { + ARROW_RETURN_NOT_OK(state_->Pump(state_)); + } + return next; + } + + std::shared_ptr state_; + }; + + struct ErrCallback { + Result operator()(const Status& st) { + state_->finished_.store(true); + return st; + } + + std::shared_ptr state_; + }; + + std::shared_ptr state_; +}; + +/// \see MakeFromFuture +template +class FutureFirstGenerator { + public: + explicit FutureFirstGenerator(Future> future) + : state_(std::make_shared(std::move(future))) {} + + Future operator()() { + if (state_->source_) { + return state_->source_(); + } else { + auto state = state_; + return state_->future_.Then([state](const AsyncGenerator& source) { + state->source_ = source; + return state->source_(); + }); + } + } + + private: + struct State { + explicit State(Future> future) : future_(future), source_() {} + + Future> future_; + AsyncGenerator source_; + }; + + std::shared_ptr state_; +}; + +/// \brief Transform a Future> into an AsyncGenerator +/// that waits for the future to complete as part of the first item. +/// +/// This generator is not async-reentrant (even if the generator yielded by future is) +/// +/// This generator does not queue +template +AsyncGenerator MakeFromFuture(Future> future) { + return FutureFirstGenerator(std::move(future)); +} + +/// \brief Create a generator that will pull from the source into a queue. Unlike +/// MakeReadaheadGenerator this will not pull reentrantly from the source. +/// +/// The source generator does not need to be async-reentrant +/// +/// This generator is not async-reentrant (even if the source is) +/// +/// This generator may queue up to max_readahead additional instances of T +template +AsyncGenerator MakeSerialReadaheadGenerator(AsyncGenerator source_generator, + int max_readahead) { + return SerialReadaheadGenerator(std::move(source_generator), max_readahead); +} + +/// \brief Create a generator that immediately pulls from the source +/// +/// Typical generators do not pull from their source until they themselves +/// are pulled. This generator does not follow that convention and will call +/// generator() once before it returns. The returned generator will otherwise +/// mirror the source. +/// +/// This generator forwards async-reentrant pressure to the source +/// This generator buffers one item (the first result) until it is delivered. +template +AsyncGenerator MakeAutoStartingGenerator(AsyncGenerator generator) { + struct AutostartGenerator { + Future operator()() { + if (first_future->is_valid()) { + Future result = *first_future; + *first_future = Future(); + return result; + } + return source(); + } + + std::shared_ptr> first_future; + AsyncGenerator source; + }; + + std::shared_ptr> first_future = std::make_shared>(generator()); + return AutostartGenerator{std::move(first_future), std::move(generator)}; +} + +/// \see MakeReadaheadGenerator +template +class ReadaheadGenerator { + public: + ReadaheadGenerator(AsyncGenerator source_generator, int max_readahead) + : state_(std::make_shared(std::move(source_generator), max_readahead)) {} + + Future AddMarkFinishedContinuation(Future fut) { + auto state = state_; + return fut.Then( + [state](const T& result) -> Future { + state->MarkFinishedIfDone(result); + if (state->finished.load()) { + if (state->num_running.fetch_sub(1) == 1) { + state->final_future.MarkFinished(); + } + } else { + state->num_running.fetch_sub(1); + } + return result; + }, + [state](const Status& err) -> Future { + // If there is an error we need to make sure all running + // tasks finish before we return the error. + state->finished.store(true); + if (state->num_running.fetch_sub(1) == 1) { + state->final_future.MarkFinished(); + } + return state->final_future.Then([err]() -> Result { return err; }); + }); + } + + Future operator()() { + if (state_->readahead_queue.empty()) { + // This is the first request, let's pump the underlying queue + state_->num_running.store(state_->max_readahead); + for (int i = 0; i < state_->max_readahead; i++) { + auto next = state_->source_generator(); + auto next_after_check = AddMarkFinishedContinuation(std::move(next)); + state_->readahead_queue.push(std::move(next_after_check)); + } + } + // Pop one and add one + auto result = state_->readahead_queue.front(); + state_->readahead_queue.pop(); + if (state_->finished.load()) { + state_->readahead_queue.push(AsyncGeneratorEnd()); + } else { + state_->num_running.fetch_add(1); + auto back_of_queue = state_->source_generator(); + auto back_of_queue_after_check = + AddMarkFinishedContinuation(std::move(back_of_queue)); + state_->readahead_queue.push(std::move(back_of_queue_after_check)); + } + return result; + } + + private: + struct State { + State(AsyncGenerator source_generator, int max_readahead) + : source_generator(std::move(source_generator)), max_readahead(max_readahead) {} + + void MarkFinishedIfDone(const T& next_result) { + if (IsIterationEnd(next_result)) { + finished.store(true); + } + } + + AsyncGenerator source_generator; + int max_readahead; + Future<> final_future = Future<>::Make(); + std::atomic num_running{0}; + std::atomic finished{false}; + std::queue> readahead_queue; + }; + + std::shared_ptr state_; +}; + +/// \brief A generator where the producer pushes items on a queue. +/// +/// No back-pressure is applied, so this generator is mostly useful when +/// producing the values is neither CPU- nor memory-expensive (e.g. fetching +/// filesystem metadata). +/// +/// This generator is not async-reentrant. +template +class PushGenerator { + struct State { + State() {} + + util::Mutex mutex; + std::deque> result_q; + std::optional> consumer_fut; + bool finished = false; + }; + + public: + /// Producer API for PushGenerator + class Producer { + public: + explicit Producer(const std::shared_ptr& state) : weak_state_(state) {} + + /// \brief Push a value on the queue + /// + /// True is returned if the value was pushed, false if the generator is + /// already closed or destroyed. If the latter, it is recommended to stop + /// producing any further values. + bool Push(Result result) { + auto state = weak_state_.lock(); + if (!state) { + // Generator was destroyed + return false; + } + auto lock = state->mutex.Lock(); + if (state->finished) { + // Closed early + return false; + } + if (state->consumer_fut.has_value()) { + auto fut = std::move(state->consumer_fut.value()); + state->consumer_fut.reset(); + lock.Unlock(); // unlock before potentially invoking a callback + fut.MarkFinished(std::move(result)); + } else { + state->result_q.push_back(std::move(result)); + } + return true; + } + + /// \brief Tell the consumer we have finished producing + /// + /// It is allowed to call this and later call Push() again ("early close"). + /// In this case, calls to Push() after the queue is closed are silently + /// ignored. This can help implementing non-trivial cancellation cases. + /// + /// True is returned on success, false if the generator is already closed + /// or destroyed. + bool Close() { + auto state = weak_state_.lock(); + if (!state) { + // Generator was destroyed + return false; + } + auto lock = state->mutex.Lock(); + if (state->finished) { + // Already closed + return false; + } + state->finished = true; + if (state->consumer_fut.has_value()) { + auto fut = std::move(state->consumer_fut.value()); + state->consumer_fut.reset(); + lock.Unlock(); // unlock before potentially invoking a callback + fut.MarkFinished(IterationTraits::End()); + } + return true; + } + + /// Return whether the generator was closed or destroyed. + bool is_closed() const { + auto state = weak_state_.lock(); + if (!state) { + // Generator was destroyed + return true; + } + auto lock = state->mutex.Lock(); + return state->finished; + } + + private: + const std::weak_ptr weak_state_; + }; + + PushGenerator() : state_(std::make_shared()) {} + + /// Read an item from the queue + Future operator()() const { + auto lock = state_->mutex.Lock(); + assert(!state_->consumer_fut.has_value()); // Non-reentrant + if (!state_->result_q.empty()) { + auto fut = Future::MakeFinished(std::move(state_->result_q.front())); + state_->result_q.pop_front(); + return fut; + } + if (state_->finished) { + return AsyncGeneratorEnd(); + } + auto fut = Future::Make(); + state_->consumer_fut = fut; + return fut; + } + + /// \brief Return producer-side interface + /// + /// The returned object must be used by the producer to push values on the queue. + /// Only a single Producer object should be instantiated. + Producer producer() { return Producer{state_}; } + + private: + const std::shared_ptr state_; +}; + +/// \brief Create a generator that pulls reentrantly from a source +/// This generator will pull reentrantly from a source, ensuring that max_readahead +/// requests are active at any given time. +/// +/// The source generator must be async-reentrant +/// +/// This generator itself is async-reentrant. +/// +/// This generator may queue up to max_readahead instances of T +template +AsyncGenerator MakeReadaheadGenerator(AsyncGenerator source_generator, + int max_readahead) { + return ReadaheadGenerator(std::move(source_generator), max_readahead); +} + +/// \brief Creates a generator that will yield finished futures from a vector +/// +/// This generator is async-reentrant +template +AsyncGenerator MakeVectorGenerator(std::vector vec) { + struct State { + explicit State(std::vector vec_) : vec(std::move(vec_)), vec_idx(0) {} + + std::vector vec; + std::atomic vec_idx; + }; + + auto state = std::make_shared(std::move(vec)); + return [state]() { + auto idx = state->vec_idx.fetch_add(1); + if (idx >= state->vec.size()) { + // Eagerly return memory + state->vec.clear(); + return AsyncGeneratorEnd(); + } + return Future::MakeFinished(state->vec[idx]); + }; +} + +/// \see MakeMergedGenerator +template +class MergedGenerator { + // Note, the implementation of this class is quite complex at the moment (PRs to + // simplify are always welcome) + // + // Terminology is borrowed from rxjs. This is a pull based implementation of the + // mergeAll operator. The "outer subscription" refers to the async + // generator that the caller provided when creating this. The outer subscription + // yields generators. + // + // Each of these generators is then subscribed to (up to max_subscriptions) and these + // are referred to as "inner subscriptions". + // + // As soon as we start we try and establish `max_subscriptions` inner subscriptions. For + // each inner subscription we will cache up to 1 value. This means we may have more + // values than we have been asked for. In our example, if a caller asks for one record + // batch we will start scanning `max_subscriptions` different files. For each file we + // will only queue up to 1 batch (so a separate readahead is needed on the file if batch + // readahead is desired). + // + // If the caller is slow we may accumulate ready-to-deliver items. These are stored + // in `delivered_jobs`. + // + // If the caller is very quick we may accumulate requests. These are stored in + // `waiting_jobs`. + // + // It may be helpful to consider an example, in the scanner the outer subscription + // is some kind of asynchronous directory listing. The inner subscription is + // then a scan on a file yielded by the directory listing. + // + // An "outstanding" request is when we have polled either the inner or outer + // subscription but that future hasn't completed yet. + // + // There are three possible "events" that can happen. + // * A caller could request the next future + // * An outer callback occurs when the next subscription is ready (e.g. the directory + // listing has produced a new file) + // * An inner callback occurs when one of the inner subscriptions emits a value (e.g. + // a file scan emits a record batch) + // + // Any time an event happens the logic is broken into two phases. First, we grab the + // lock and modify the shared state. While doing this we figure out what callbacks we + // will need to execute. Then, we give up the lock and execute these callbacks. It is + // important to execute these callbacks without the lock to avoid deadlock. + public: + explicit MergedGenerator(AsyncGenerator> source, + int max_subscriptions) + : state_(std::make_shared(std::move(source), max_subscriptions)) {} + + Future operator()() { + // A caller has requested a future + Future waiting_future; + std::shared_ptr delivered_job; + bool mark_generator_complete = false; + { + auto guard = state_->mutex.Lock(); + if (!state_->delivered_jobs.empty()) { + // If we have a job sitting around we can deliver it + delivered_job = std::move(state_->delivered_jobs.front()); + state_->delivered_jobs.pop_front(); + if (state_->IsCompleteUnlocked(guard)) { + // It's possible this waiting job was the only thing left to handle and + // we have now completed the generator. + mark_generator_complete = true; + } else { + // Since we had a job sitting around we also had an inner subscription + // that had paused. We are going to restart this inner subscription and + // so there will be a new outstanding request. + state_->outstanding_requests++; + } + } else if (state_->broken || + (!state_->first && state_->num_running_subscriptions == 0)) { + // If we are broken or exhausted then prepare a terminal item but + // we won't complete it until we've finished. + Result end_res = IterationEnd(); + if (!state_->final_error.ok()) { + end_res = state_->final_error; + state_->final_error = Status::OK(); + } + return state_->all_finished.Then([end_res]() -> Result { return end_res; }); + } else { + // Otherwise we just queue the request and it will be completed when one of the + // ongoing inner subscriptions delivers a result + waiting_future = Future::Make(); + state_->waiting_jobs.push_back(std::make_shared>(waiting_future)); + } + if (state_->first) { + // On the first request we are going to try and immediately fill our queue + // of subscriptions. We assume we are going to be able to start them all. + state_->outstanding_requests += + static_cast(state_->active_subscriptions.size()); + state_->num_running_subscriptions += + static_cast(state_->active_subscriptions.size()); + } + } + // If we grabbed a finished item from the delivered_jobs queue then we may need + // to mark the generator finished or issue a request for a new item to fill in + // the spot we just vacated. Notice that we issue that request to the same + // subscription that delivered it (deliverer). + if (delivered_job) { + if (mark_generator_complete) { + state_->all_finished.MarkFinished(); + } else { + delivered_job->deliverer().AddCallback( + InnerCallback(state_, delivered_job->index)); + } + return std::move(delivered_job->value); + } + // On the first call we try and fill up our subscriptions. It's possible the outer + // generator only has a few items and we can't fill up to what we were hoping. In + // that case we have to bail early. + if (state_->first) { + state_->first = false; + mark_generator_complete = false; + for (int i = 0; i < static_cast(state_->active_subscriptions.size()); i++) { + state_->PullSource().AddCallback( + OuterCallback{state_, static_cast(i)}); + // If we have to bail early then we need to update the shared state again so + // we need to reacquire the lock. + auto guard = state_->mutex.Lock(); + if (state_->source_exhausted) { + int excess_requests = + static_cast(state_->active_subscriptions.size()) - i - 1; + state_->outstanding_requests -= excess_requests; + state_->num_running_subscriptions -= excess_requests; + if (excess_requests > 0) { + // It's possible that we are completing the generator by reducing the number + // of outstanding requests (e.g. this happens when the outer subscription and + // all inner subscriptions are synchronous) + mark_generator_complete = state_->IsCompleteUnlocked(guard); + } + break; + } + } + if (mark_generator_complete) { + state_->MarkFinishedAndPurge(); + } + } + return waiting_future; + } + + private: + struct DeliveredJob { + explicit DeliveredJob(AsyncGenerator deliverer_, Result value_, + std::size_t index_) + : deliverer(deliverer_), value(std::move(value_)), index(index_) {} + + // The generator that delivered this result, we will request another item + // from this generator once the result is delivered + AsyncGenerator deliverer; + // The result we received from the generator + Result value; + // The index of the generator (in active_subscriptions) that delivered this + // result. This is used if we need to replace a finished generator. + std::size_t index; + }; + + struct State { + State(AsyncGenerator> source, int max_subscriptions) + : source(std::move(source)), + active_subscriptions(max_subscriptions), + delivered_jobs(), + waiting_jobs(), + mutex(), + first(true), + broken(false), + source_exhausted(false), + outstanding_requests(0), + num_running_subscriptions(0), + final_error(Status::OK()) {} + + Future> PullSource() { + // Need to guard access to source() so we don't pull sync-reentrantly which + // is never valid. + auto lock = mutex.Lock(); + return source(); + } + + void SignalErrorUnlocked(const util::Mutex::Guard& guard) { + broken = true; + // Empty any results that have arrived but not asked for. + while (!delivered_jobs.empty()) { + delivered_jobs.pop_front(); + } + } + + // This function is called outside the mutex but it will only ever be + // called once + void MarkFinishedAndPurge() { + all_finished.MarkFinished(); + while (!waiting_jobs.empty()) { + waiting_jobs.front()->MarkFinished(IterationEnd()); + waiting_jobs.pop_front(); + } + } + + // This is called outside the mutex but it is only ever called + // once and Future<>::AddCallback is thread-safe + void MarkFinalError(const Status& err, Future maybe_sink) { + if (maybe_sink.is_valid()) { + // Someone is waiting for this error so lets mark it complete when + // all the work is done + all_finished.AddCallback([maybe_sink, err](const Status& status) mutable { + maybe_sink.MarkFinished(err); + }); + } else { + // No one is waiting for this error right now so it will be delivered + // next. + final_error = err; + } + } + + bool IsCompleteUnlocked(const util::Mutex::Guard& guard) { + return outstanding_requests == 0 && + (broken || (source_exhausted && num_running_subscriptions == 0 && + delivered_jobs.empty())); + } + + bool MarkTaskFinishedUnlocked(const util::Mutex::Guard& guard) { + --outstanding_requests; + return IsCompleteUnlocked(guard); + } + + // The outer generator. Each item we pull from this will be its own generator + // and become an inner subscription + AsyncGenerator> source; + // active_subscriptions and delivered_jobs will be bounded by max_subscriptions + std::vector> active_subscriptions; + // Results delivered by the inner subscriptions that weren't yet asked for by the + // caller + std::deque> delivered_jobs; + // waiting_jobs is unbounded, reentrant pulls (e.g. AddReadahead) will provide the + // backpressure + std::deque>> waiting_jobs; + // A future that will be marked complete when the terminal item has arrived and all + // outstanding futures have completed. It is used to hold off emission of an error + // until all outstanding work is done. + Future<> all_finished = Future<>::Make(); + util::Mutex mutex; + // A flag cleared when the caller firsts asks for a future. Used to start polling. + bool first; + // A flag set when an error arrives, prevents us from issuing new requests. + bool broken; + // A flag set when the outer subscription has been exhausted. Prevents us from + // pulling it further (even though it would be generally harmless) and lets us know we + // are finishing up. + bool source_exhausted; + // The number of futures that we have requested from either the outer or inner + // subscriptions that have not yet completed. We cannot mark all_finished until this + // reaches 0. This will never be greater than max_subscriptions + int outstanding_requests; + // The number of running subscriptions. We ramp this up to `max_subscriptions` as + // soon as the first item is requested and then it stays at that level (each exhausted + // inner subscription is replaced by a new inner subscription) until the outer + // subscription is exhausted at which point this descends to 0 (and source_exhausted) + // is then set to true. + int num_running_subscriptions; + // If an error arrives, and the caller hasn't asked for that item, we store the error + // here. It is analagous to delivered_jobs but for errors instead of finished + // results. + Status final_error; + }; + + struct InnerCallback { + InnerCallback(std::shared_ptr state, std::size_t index, bool recursive = false) + : state(std::move(state)), index(index), recursive(recursive) {} + + void operator()(const Result& maybe_next_ref) { + // An item has been delivered by one of the inner subscriptions + Future next_fut; + const Result* maybe_next = &maybe_next_ref; + + // When an item is delivered (and the caller has asked for it) we grab the + // next item from the inner subscription. To avoid this behavior leading to an + // infinite loop (this can happen if the caller's callback asks for the next item) + // we use a while loop. + while (true) { + Future sink; + bool sub_finished = maybe_next->ok() && IsIterationEnd(**maybe_next); + bool pull_next_sub = false; + bool was_broken = false; + bool should_mark_gen_complete = false; + bool should_mark_final_error = false; + { + auto guard = state->mutex.Lock(); + if (state->broken) { + // We've errored out previously so ignore the result. If anyone was waiting + // for this they will get IterationEnd when we purge + was_broken = true; + } else { + if (!sub_finished) { + // There is a result to deliver. Either we can deliver it now or we will + // queue it up + if (state->waiting_jobs.empty()) { + state->delivered_jobs.push_back(std::make_shared( + state->active_subscriptions[index], *maybe_next, index)); + } else { + sink = std::move(*state->waiting_jobs.front()); + state->waiting_jobs.pop_front(); + } + } + + // If this is the first error then we transition the state to a broken state + if (!maybe_next->ok()) { + should_mark_final_error = true; + state->SignalErrorUnlocked(guard); + } + } + + // If we finished this inner subscription then we need to grab a new inner + // subscription to take its spot. If we can't (because we're broken or + // exhausted) then we aren't going to be starting any new futures and so + // the number of running subscriptions drops. + pull_next_sub = sub_finished && !state->source_exhausted && !was_broken; + if (sub_finished && !pull_next_sub) { + state->num_running_subscriptions--; + } + // There are three situations we won't pull again. If an error occurred or we + // are already finished or if no one was waiting for our result and so we queued + // it up. We will decrement outstanding_requests and possibly mark the + // generator completed. + if (state->broken || (!sink.is_valid() && !sub_finished) || + (sub_finished && state->source_exhausted)) { + if (state->MarkTaskFinishedUnlocked(guard)) { + should_mark_gen_complete = true; + } + } + } + + // Now we have given up the lock and we can take all the actions we decided we + // need to take. + if (should_mark_final_error) { + state->MarkFinalError(maybe_next->status(), std::move(sink)); + } + + if (should_mark_gen_complete) { + state->MarkFinishedAndPurge(); + } + + // An error occurred elsewhere so there is no need to mark any future + // finished (will happen during the purge) or pull from anything + if (was_broken) { + return; + } + + if (pull_next_sub) { + if (recursive) { + was_empty = true; + return; + } + // We pulled an end token so we need to start a new subscription + // in our spot + state->PullSource().AddCallback(OuterCallback{state, index}); + } else if (sink.is_valid()) { + // We pulled a valid result and there was someone waiting for it + // so lets fetch the next result from our subscription + sink.MarkFinished(*maybe_next); + next_fut = state->active_subscriptions[index](); + if (next_fut.TryAddCallback([this]() { return InnerCallback(state, index); })) { + return; + } + // Already completed. Avoid very deep recursion by looping + // here instead of relying on the callback. + maybe_next = &next_fut.result(); + continue; + } + // else: We pulled a valid result but no one was waiting for it so + // we can just stop. + return; + } + } + std::shared_ptr state; + std::size_t index; + bool recursive; + bool was_empty = false; + }; + + struct OuterCallback { + void operator()(const Result>& initial_maybe_next) { + Result> maybe_next = initial_maybe_next; + while (true) { + // We have been given a new inner subscription + bool should_continue = false; + bool should_mark_gen_complete = false; + bool should_deliver_error = false; + bool source_exhausted = maybe_next.ok() && IsIterationEnd(*maybe_next); + Future error_sink; + { + auto guard = state->mutex.Lock(); + if (!maybe_next.ok() || source_exhausted || state->broken) { + // If here then we will not pull any more from the outer source + if (!state->broken && !maybe_next.ok()) { + state->SignalErrorUnlocked(guard); + // If here then we are the first error so we need to deliver it + should_deliver_error = true; + if (!state->waiting_jobs.empty()) { + error_sink = std::move(*state->waiting_jobs.front()); + state->waiting_jobs.pop_front(); + } + } + if (source_exhausted) { + state->source_exhausted = true; + state->num_running_subscriptions--; + } + if (state->MarkTaskFinishedUnlocked(guard)) { + should_mark_gen_complete = true; + } + } else { + state->active_subscriptions[index] = *maybe_next; + should_continue = true; + } + } + if (should_deliver_error) { + state->MarkFinalError(maybe_next.status(), std::move(error_sink)); + } + if (should_mark_gen_complete) { + state->MarkFinishedAndPurge(); + } + if (should_continue) { + // There is a possibility that a large sequence of immediately available inner + // callbacks could lead to a stack overflow. To avoid this we need to + // synchronously loop through inner/outer callbacks until we either find an + // unfinished future or we find an actual item to deliver. + Future next_item = (*maybe_next)(); + if (!next_item.TryAddCallback([this] { return InnerCallback(state, index); })) { + // By setting recursive to true we signal to the inner callback that, if it is + // empty, instead of adding a new outer callback, it should just immediately + // return, flagging was_empty so that we know we need to check the next + // subscription. + InnerCallback immediate_inner(state, index, /*recursive=*/true); + immediate_inner(next_item.result()); + if (immediate_inner.was_empty) { + Future> next_source = state->PullSource(); + if (next_source.TryAddCallback([this] { + return OuterCallback{state, index}; + })) { + // We hit an unfinished future so we can stop looping + return; + } + // The current subscription was immediately and synchronously empty + // and we were able to synchronously pull the next subscription so we + // can keep looping. + maybe_next = next_source.result(); + continue; + } + } + } + return; + } + } + std::shared_ptr state; + std::size_t index; + }; + + std::shared_ptr state_; +}; + +/// \brief Create a generator that takes in a stream of generators and pulls from up to +/// max_subscriptions at a time +/// +/// Note: This may deliver items out of sequence. For example, items from the third +/// AsyncGenerator generated by the source may be emitted before some items from the first +/// AsyncGenerator generated by the source. +/// +/// This generator will pull from source async-reentrantly unless max_subscriptions is 1 +/// This generator will not pull from the individual subscriptions reentrantly. Add +/// readahead to the individual subscriptions if that is desired. +/// This generator is async-reentrant +/// +/// This generator may queue up to max_subscriptions instances of T +template +AsyncGenerator MakeMergedGenerator(AsyncGenerator> source, + int max_subscriptions) { + return MergedGenerator(std::move(source), max_subscriptions); +} + +template +Result> MakeSequencedMergedGenerator( + AsyncGenerator> source, int max_subscriptions) { + if (max_subscriptions < 0) { + return Status::Invalid("max_subscriptions must be a positive integer"); + } + if (max_subscriptions == 1) { + return Status::Invalid("Use MakeConcatenatedGenerator if max_subscriptions is 1"); + } + AsyncGenerator> autostarting_source = MakeMappedGenerator( + std::move(source), + [](const AsyncGenerator& sub) { return MakeAutoStartingGenerator(sub); }); + AsyncGenerator> sub_readahead = + MakeSerialReadaheadGenerator(std::move(autostarting_source), max_subscriptions - 1); + return MakeConcatenatedGenerator(std::move(sub_readahead)); +} + +/// \brief Create a generator that takes in a stream of generators and pulls from each +/// one in sequence. +/// +/// This generator is async-reentrant but will never pull from source reentrantly and +/// will never pull from any subscription reentrantly. +/// +/// This generator may queue 1 instance of T +/// +/// TODO: Could potentially make a bespoke implementation instead of MergedGenerator that +/// forwards async-reentrant requests instead of buffering them (which is what +/// MergedGenerator does) +template +AsyncGenerator MakeConcatenatedGenerator(AsyncGenerator> source) { + return MergedGenerator(std::move(source), 1); +} + +template +struct Enumerated { + T value; + int index; + bool last; +}; + +template +struct IterationTraits> { + static Enumerated End() { return Enumerated{IterationEnd(), -1, false}; } + static bool IsEnd(const Enumerated& val) { return val.index < 0; } +}; + +/// \see MakeEnumeratedGenerator +template +class EnumeratingGenerator { + public: + EnumeratingGenerator(AsyncGenerator source, T initial_value) + : state_(std::make_shared(std::move(source), std::move(initial_value))) {} + + Future> operator()() { + if (state_->finished) { + return AsyncGeneratorEnd>(); + } else { + auto state = state_; + return state->source().Then([state](const T& next) { + auto finished = IsIterationEnd(next); + auto prev = Enumerated{state->prev_value, state->prev_index, finished}; + state->prev_value = next; + state->prev_index++; + state->finished = finished; + return prev; + }); + } + } + + private: + struct State { + State(AsyncGenerator source, T initial_value) + : source(std::move(source)), prev_value(std::move(initial_value)), prev_index(0) { + finished = IsIterationEnd(prev_value); + } + + AsyncGenerator source; + T prev_value; + int prev_index; + bool finished; + }; + + std::shared_ptr state_; +}; + +/// Wrap items from a source generator with positional information +/// +/// When used with MakeMergedGenerator and MakeSequencingGenerator this allows items to be +/// processed in a "first-available" fashion and later resequenced which can reduce the +/// impact of sources with erratic performance (e.g. a filesystem where some items may +/// take longer to read than others). +/// +/// TODO(ARROW-12371) Would require this generator be async-reentrant +/// +/// \see MakeSequencingGenerator for an example of putting items back in order +/// +/// This generator is not async-reentrant +/// +/// This generator buffers one item (so it knows which item is the last item) +template +AsyncGenerator> MakeEnumeratedGenerator(AsyncGenerator source) { + return FutureFirstGenerator>( + source().Then([source](const T& initial_value) -> AsyncGenerator> { + return EnumeratingGenerator(std::move(source), initial_value); + })); +} + +/// \see MakeTransferredGenerator +template +class TransferringGenerator { + public: + explicit TransferringGenerator(AsyncGenerator source, internal::Executor* executor) + : source_(std::move(source)), executor_(executor) {} + + Future operator()() { return executor_->Transfer(source_()); } + + private: + AsyncGenerator source_; + internal::Executor* executor_; +}; + +/// \brief Transfer a future to an underlying executor. +/// +/// Continuations run on the returned future will be run on the given executor +/// if they cannot be run synchronously. +/// +/// This is often needed to move computation off I/O threads or other external +/// completion sources and back on to the CPU executor so the I/O thread can +/// stay busy and focused on I/O +/// +/// Keep in mind that continuations called on an already completed future will +/// always be run synchronously and so no transfer will happen in that case. +/// +/// This generator is async reentrant if the source is +/// +/// This generator will not queue +template +AsyncGenerator MakeTransferredGenerator(AsyncGenerator source, + internal::Executor* executor) { + return TransferringGenerator(std::move(source), executor); +} + +/// \see MakeBackgroundGenerator +template +class BackgroundGenerator { + public: + explicit BackgroundGenerator(Iterator it, internal::Executor* io_executor, int max_q, + int q_restart) + : state_(std::make_shared(io_executor, std::move(it), max_q, q_restart)), + cleanup_(std::make_shared(state_.get())) {} + + Future operator()() { + auto guard = state_->mutex.Lock(); + Future waiting_future; + if (state_->queue.empty()) { + if (state_->finished) { + return AsyncGeneratorEnd(); + } else { + waiting_future = Future::Make(); + state_->waiting_future = waiting_future; + } + } else { + auto next = Future::MakeFinished(std::move(state_->queue.front())); + state_->queue.pop(); + if (state_->NeedsRestart()) { + return state_->RestartTask(state_, std::move(guard), std::move(next)); + } + return next; + } + // This should only trigger the very first time this method is called + if (state_->NeedsRestart()) { + return state_->RestartTask(state_, std::move(guard), std::move(waiting_future)); + } + return waiting_future; + } + + protected: + static constexpr uint64_t kUnlikelyThreadId{std::numeric_limits::max()}; + + struct State { + State(internal::Executor* io_executor, Iterator it, int max_q, int q_restart) + : io_executor(io_executor), + max_q(max_q), + q_restart(q_restart), + it(std::move(it)), + reading(false), + finished(false), + should_shutdown(false) {} + + void ClearQueue() { + while (!queue.empty()) { + queue.pop(); + } + } + + bool TaskIsRunning() const { return task_finished.is_valid(); } + + bool NeedsRestart() const { + return !finished && !reading && static_cast(queue.size()) <= q_restart; + } + + void DoRestartTask(std::shared_ptr state, util::Mutex::Guard guard) { + // If we get here we are actually going to start a new task so let's create a + // task_finished future for it + state->task_finished = Future<>::Make(); + state->reading = true; + auto spawn_status = io_executor->Spawn( + [state]() { BackgroundGenerator::WorkerTask(std::move(state)); }); + if (!spawn_status.ok()) { + // If we can't spawn a new task then send an error to the consumer (either via a + // waiting future or the queue) and mark ourselves finished + state->finished = true; + state->task_finished = Future<>(); + if (waiting_future.has_value()) { + auto to_deliver = std::move(waiting_future.value()); + waiting_future.reset(); + guard.Unlock(); + to_deliver.MarkFinished(spawn_status); + } else { + ClearQueue(); + queue.push(spawn_status); + } + } + } + + Future RestartTask(std::shared_ptr state, util::Mutex::Guard guard, + Future next) { + if (TaskIsRunning()) { + // If the task is still cleaning up we need to wait for it to finish before + // restarting. We also want to block the consumer until we've restarted the + // reader to avoid multiple restarts + return task_finished.Then([state, next]() { + // This may appear dangerous (recursive mutex) but we should be guaranteed the + // outer guard has been released by this point. We know... + // * task_finished is not already finished (it would be invalid in that case) + // * task_finished will not be marked complete until we've given up the mutex + auto guard_ = state->mutex.Lock(); + state->DoRestartTask(state, std::move(guard_)); + return next; + }); + } + // Otherwise we can restart immediately + DoRestartTask(std::move(state), std::move(guard)); + return next; + } + + internal::Executor* io_executor; + const int max_q; + const int q_restart; + Iterator it; + std::atomic worker_thread_id{kUnlikelyThreadId}; + + // If true, the task is actively pumping items from the queue and does not need a + // restart + bool reading; + // Set to true when a terminal item arrives + bool finished; + // Signal to the background task to end early because consumers have given up on it + bool should_shutdown; + // If the queue is empty, the consumer will create a waiting future and wait for it + std::queue> queue; + std::optional> waiting_future; + // Every background task is given a future to complete when it is entirely finished + // processing and ready for the next task to start or for State to be destroyed + Future<> task_finished; + util::Mutex mutex; + }; + + // Cleanup task that will be run when all consumer references to the generator are lost + struct Cleanup { + explicit Cleanup(State* state) : state(state) {} + ~Cleanup() { + /// TODO: Once ARROW-13109 is available then we can be force consumers to spawn and + /// there is no need to perform this check. + /// + /// It's a deadlock if we enter cleanup from + /// the worker thread but it can happen if the consumer doesn't transfer away + assert(state->worker_thread_id.load() != ::arrow::internal::GetThreadId()); + Future<> finish_fut; + { + auto lock = state->mutex.Lock(); + if (!state->TaskIsRunning()) { + return; + } + // Signal the current task to stop and wait for it to finish + state->should_shutdown = true; + finish_fut = state->task_finished; + } + // Using future as a condition variable here + Status st = finish_fut.status(); + ARROW_UNUSED(st); + } + State* state; + }; + + static void WorkerTask(std::shared_ptr state) { + state->worker_thread_id.store(::arrow::internal::GetThreadId()); + // We need to capture the state to read while outside the mutex + bool reading = true; + while (reading) { + auto next = state->it.Next(); + // Need to capture state->waiting_future inside the mutex to mark finished outside + Future waiting_future; + { + auto guard = state->mutex.Lock(); + + if (state->should_shutdown) { + state->finished = true; + break; + } + + if (!next.ok() || IsIterationEnd(*next)) { + // Terminal item. Mark finished to true, send this last item, and quit + state->finished = true; + if (!next.ok()) { + state->ClearQueue(); + } + } + // At this point we are going to send an item. Either we will add it to the + // queue or deliver it to a waiting future. + if (state->waiting_future.has_value()) { + waiting_future = std::move(state->waiting_future.value()); + state->waiting_future.reset(); + } else { + state->queue.push(std::move(next)); + // We just filled up the queue so it is time to quit. We may need to notify + // a cleanup task so we transition to Quitting + if (static_cast(state->queue.size()) >= state->max_q) { + state->reading = false; + } + } + reading = state->reading && !state->finished; + } + // This should happen outside the mutex. Presumably there is a + // transferring generator on the other end that will quickly transfer any + // callbacks off of this thread so we can continue looping. Still, best not to + // rely on that + if (waiting_future.is_valid()) { + waiting_future.MarkFinished(next); + } + } + // Once we've sent our last item we can notify any waiters that we are done and so + // either state can be cleaned up or a new background task can be started + Future<> task_finished; + { + auto guard = state->mutex.Lock(); + // After we give up the mutex state can be safely deleted. We will no longer + // reference it. We can safely transition to idle now. + task_finished = state->task_finished; + state->task_finished = Future<>(); + state->worker_thread_id.store(kUnlikelyThreadId); + } + task_finished.MarkFinished(); + } + + std::shared_ptr state_; + // state_ is held by both the generator and the background thread so it won't be cleaned + // up when all consumer references are relinquished. cleanup_ is only held by the + // generator so it will be destructed when the last consumer reference is gone. We use + // this to cleanup / stop the background generator in case the consuming end stops + // listening (e.g. due to a downstream error) + std::shared_ptr cleanup_; +}; + +constexpr int kDefaultBackgroundMaxQ = 32; +constexpr int kDefaultBackgroundQRestart = 16; + +/// \brief Create an AsyncGenerator by iterating over an Iterator on a background +/// thread +/// +/// The parameter max_q and q_restart control queue size and background thread task +/// management. If the background task is fast you typically don't want it creating a +/// thread task for every item. Instead the background thread will run until it fills +/// up a readahead queue. +/// +/// Once the queue has filled up the background thread task will terminate (allowing other +/// I/O tasks to use the thread). Once the queue has been drained enough (specified by +/// q_restart) then the background thread task will be restarted. If q_restart is too low +/// then you may exhaust the queue waiting for the background thread task to start running +/// again. If it is too high then it will be constantly stopping and restarting the +/// background queue task +/// +/// The "background thread" is a logical thread and will run as tasks on the io_executor. +/// This thread may stop and start when the queue fills up but there will only be one +/// active background thread task at any given time. You MUST transfer away from this +/// background generator. Otherwise there could be a race condition if a callback on the +/// background thread deletes the last consumer reference to the background generator. You +/// can transfer onto the same executor as the background thread, it is only necessary to +/// create a new thread task, not to switch executors. +/// +/// This generator is not async-reentrant +/// +/// This generator will queue up to max_q blocks +template +static Result> MakeBackgroundGenerator( + Iterator iterator, internal::Executor* io_executor, + int max_q = kDefaultBackgroundMaxQ, int q_restart = kDefaultBackgroundQRestart) { + if (max_q < q_restart) { + return Status::Invalid("max_q must be >= q_restart"); + } + return BackgroundGenerator(std::move(iterator), io_executor, max_q, q_restart); +} + +/// \brief Create an AsyncGenerator by iterating over an Iterator synchronously +/// +/// This should only be used if you know the source iterator does not involve any +/// I/O (or other blocking calls). Otherwise a CPU thread will be blocked and, depending +/// on the complexity of the iterator, it may lead to deadlock. +/// +/// If you are not certain if there will be I/O then it is better to use +/// MakeBackgroundGenerator. If helpful you can think of this as the AsyncGenerator +/// equivalent of Future::MakeFinished +/// +/// It is impossible to call this in an async-reentrant manner since the returned +/// future will be completed by the time it is polled. +/// +/// This generator does not queue +template +static Result> MakeBlockingGenerator( + std::shared_ptr> iterator) { + return [it = std::move(iterator)]() mutable -> Future { + return Future::MakeFinished(it->Next()); + }; +} + +template +static Result> MakeBlockingGenerator(Iterator iterator) { + return MakeBlockingGenerator(std::make_shared>(std::move(iterator))); +} + +/// \see MakeGeneratorIterator +template +class GeneratorIterator { + public: + explicit GeneratorIterator(AsyncGenerator source) : source_(std::move(source)) {} + + Result Next() { return source_().result(); } + + private: + AsyncGenerator source_; +}; + +/// \brief Convert an AsyncGenerator to an Iterator which blocks until each future +/// is finished +template +Iterator MakeGeneratorIterator(AsyncGenerator source) { + return Iterator(GeneratorIterator(std::move(source))); +} + +/// \brief Add readahead to an iterator using a background thread. +/// +/// Under the hood this is converting the iterator to a generator using +/// MakeBackgroundGenerator, adding readahead to the converted generator with +/// MakeReadaheadGenerator, and then converting back to an iterator using +/// MakeGeneratorIterator. +template +Result> MakeReadaheadIterator(Iterator it, int readahead_queue_size) { + ARROW_ASSIGN_OR_RAISE(auto io_executor, internal::ThreadPool::Make(1)); + auto max_q = readahead_queue_size; + auto q_restart = std::max(1, max_q / 2); + ARROW_ASSIGN_OR_RAISE( + auto background_generator, + MakeBackgroundGenerator(std::move(it), io_executor.get(), max_q, q_restart)); + // Capture io_executor to keep it alive as long as owned_bg_generator is still + // referenced + AsyncGenerator owned_bg_generator = [io_executor, background_generator]() { + return background_generator(); + }; + return MakeGeneratorIterator(std::move(owned_bg_generator)); +} + +/// \brief Make a generator that returns a single pre-generated future +/// +/// This generator is async-reentrant. +template +std::function()> MakeSingleFutureGenerator(Future future) { + assert(future.is_valid()); + auto state = std::make_shared>(std::move(future)); + return [state]() -> Future { + auto fut = std::move(*state); + if (fut.is_valid()) { + return fut; + } else { + return AsyncGeneratorEnd(); + } + }; +} + +/// \brief Make a generator that immediately ends. +/// +/// This generator is async-reentrant. +template +std::function()> MakeEmptyGenerator() { + return []() -> Future { return AsyncGeneratorEnd(); }; +} + +/// \brief Make a generator that always fails with a given error +/// +/// This generator is async-reentrant. +template +AsyncGenerator MakeFailingGenerator(Status st) { + assert(!st.ok()); + auto state = std::make_shared(std::move(st)); + return [state]() -> Future { + auto st = std::move(*state); + if (!st.ok()) { + return std::move(st); + } else { + return AsyncGeneratorEnd(); + } + }; +} + +/// \brief Make a generator that always fails with a given error +/// +/// This overload allows inferring the return type from the argument. +template +AsyncGenerator MakeFailingGenerator(const Result& result) { + return MakeFailingGenerator(result.status()); +} + +/// \brief Prepend initial_values onto a generator +/// +/// This generator is async-reentrant but will buffer requests and will not +/// pull from following_values async-reentrantly. +template +AsyncGenerator MakeGeneratorStartsWith(std::vector initial_values, + AsyncGenerator following_values) { + auto initial_values_vec_gen = MakeVectorGenerator(std::move(initial_values)); + auto gen_gen = MakeVectorGenerator>( + {std::move(initial_values_vec_gen), std::move(following_values)}); + return MakeConcatenatedGenerator(std::move(gen_gen)); +} + +template +struct CancellableGenerator { + Future operator()() { + if (stop_token.IsStopRequested()) { + return stop_token.Poll(); + } + return source(); + } + + AsyncGenerator source; + StopToken stop_token; +}; + +/// \brief Allow an async generator to be cancelled +/// +/// This generator is async-reentrant +template +AsyncGenerator MakeCancellable(AsyncGenerator source, StopToken stop_token) { + return CancellableGenerator{std::move(source), std::move(stop_token)}; +} + +template +class DefaultIfEmptyGenerator { + public: + DefaultIfEmptyGenerator(AsyncGenerator source, T or_value) + : state_(std::make_shared(std::move(source), std::move(or_value))) {} + + Future operator()() { + if (state_->first) { + state_->first = false; + struct { + T or_value; + + Result operator()(const T& value) { + if (IterationTraits::IsEnd(value)) { + return std::move(or_value); + } + return value; + } + } Continuation; + Continuation.or_value = std::move(state_->or_value); + return state_->source().Then(std::move(Continuation)); + } + return state_->source(); + } + + private: + struct State { + AsyncGenerator source; + T or_value; + bool first; + State(AsyncGenerator source_, T or_value_) + : source(std::move(source_)), or_value(std::move(or_value_)), first(true) {} + }; + std::shared_ptr state_; +}; + +/// \brief If the generator is empty, return the given value, else +/// forward the values from the generator. +/// +/// This generator is async-reentrant. +template +AsyncGenerator MakeDefaultIfEmptyGenerator(AsyncGenerator source, T or_value) { + return DefaultIfEmptyGenerator(std::move(source), std::move(or_value)); +} +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7a675da59facd7712538fe038a20239208c105e4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_util.h @@ -0,0 +1,457 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/cancel.h" +#include "arrow/util/functional.h" +#include "arrow/util/future.h" +#include "arrow/util/iterator.h" +#include "arrow/util/mutex.h" +#include "arrow/util/thread_pool.h" +#include "arrow/util/tracing.h" + +namespace arrow { + +using internal::FnOnce; + +namespace util { + +/// A utility which keeps tracks of, and schedules, asynchronous tasks +/// +/// An asynchronous task has a synchronous component and an asynchronous component. +/// The synchronous component typically schedules some kind of work on an external +/// resource (e.g. the I/O thread pool or some kind of kernel-based asynchronous +/// resource like io_uring). The asynchronous part represents the work +/// done on that external resource. Executing the synchronous part will be referred +/// to as "submitting the task" since this usually includes submitting the asynchronous +/// portion to the external thread pool. +/// +/// By default the scheduler will submit the task (execute the synchronous part) as +/// soon as it is added, assuming the underlying thread pool hasn't terminated or the +/// scheduler hasn't aborted. In this mode, the scheduler is simply acting as +/// a simple task group. +/// +/// A task scheduler starts with an initial task. That task, and all subsequent tasks +/// are free to add subtasks. Once all submitted tasks finish the scheduler will +/// finish. Note, it is not an error to add additional tasks after a scheduler has +/// aborted. These tasks will be ignored and never submitted. The scheduler returns a +/// future which will complete when all submitted tasks have finished executing. Once all +/// tasks have been finished the scheduler is invalid and should no longer be used. +/// +/// Task failure (either the synchronous portion or the asynchronous portion) will cause +/// the scheduler to enter an aborted state. The first such failure will be reported in +/// the final task future. +class ARROW_EXPORT AsyncTaskScheduler { + public: + /// Destructor for AsyncTaskScheduler + /// + /// The lifetime of the task scheduled is managed automatically. The scheduler + /// will remain valid while any tasks are running (and can always be safely accessed) + /// within tasks) and will be destroyed as soon as all tasks have finished. + virtual ~AsyncTaskScheduler() = default; + /// An interface for a task + /// + /// Users may want to override this, for example, to add priority + /// information for use by a queue. + class Task { + public: + virtual ~Task() = default; + /// Submit the task + /// + /// This will be called by the scheduler at most once when there + /// is space to run the task. This is expected to be a fairly quick + /// function that simply submits the actual task work to an external + /// resource (e.g. I/O thread pool). + /// + /// If this call fails then the scheduler will enter an aborted state. + virtual Result> operator()() = 0; + /// The cost of the task + /// + /// A ThrottledAsyncTaskScheduler can be used to limit the number of concurrent tasks. + /// A custom cost may be used, for example, if you would like to limit the number of + /// tasks based on the total expected RAM usage of the tasks (this is done in the + /// scanner) + virtual int cost() const { return 1; } + /// The name of the task + /// + /// This is used for debugging and traceability. The returned view must remain + /// valid for the lifetime of the task. + virtual std::string_view name() const = 0; + + /// a span tied to the lifetime of the task, for internal use only + tracing::Span span; + }; + + /// Add a task to the scheduler + /// + /// If the scheduler is in an aborted state this call will return false and the task + /// will never be run. This is harmless and does not need to be guarded against. + /// + /// The return value for this call can usually be ignored. There is little harm in + /// attempting to add tasks to an aborted scheduler. It is only included for callers + /// that want to avoid future task generation to save effort. + /// + /// \param task the task to submit + /// + /// A task's name must remain valid for the duration of the task. It is used for + /// debugging (e.g. when debugging a deadlock to see which tasks still remain) and for + /// traceability (the name will be used for spans assigned to the task) + /// + /// \return true if the task was submitted or queued, false if the task was ignored + virtual bool AddTask(std::unique_ptr task) = 0; + + /// Adds an async generator to the scheduler + /// + /// The async generator will be visited, one item at a time. Submitting a task + /// will consist of polling the generator for the next future. The generator's future + /// will then represent the task itself. + /// + /// This visits the task serially without readahead. If readahead or parallelism + /// is desired then it should be added in the generator itself. + /// + /// The generator itself will be kept alive until all tasks have been completed. + /// However, if the scheduler is aborted, the generator will be destroyed as soon as the + /// next item would be requested. + /// + /// \param generator the generator to submit to the scheduler + /// \param visitor a function which visits each generator future as it completes + /// \param name a name which will be used for each submitted task + template + bool AddAsyncGenerator(std::function()> generator, + std::function visitor, std::string_view name); + + template + struct SimpleTask : public Task { + SimpleTask(Callable callable, std::string_view name) + : callable(std::move(callable)), name_(name) {} + SimpleTask(Callable callable, std::string name) + : callable(std::move(callable)), owned_name_(std::move(name)) { + name_ = *owned_name_; + } + Result> operator()() override { return callable(); } + std::string_view name() const override { return name_; } + Callable callable; + std::string_view name_; + std::optional owned_name_; + }; + + /// Add a task with cost 1 to the scheduler + /// + /// \param callable a "submit" function that should return a future + /// \param name a name for the task + /// + /// `name` must remain valid until the task has been submitted AND the returned + /// future completes. It is used for debugging and tracing. + /// + /// \see AddTask for more details + template + bool AddSimpleTask(Callable callable, std::string_view name) { + return AddTask(std::make_unique>(std::move(callable), name)); + } + + /// Add a task with cost 1 to the scheduler + /// + /// This is an overload of \see AddSimpleTask that keeps `name` alive + /// in the task. + template + bool AddSimpleTask(Callable callable, std::string name) { + return AddTask( + std::make_unique>(std::move(callable), std::move(name))); + } + + /// Construct a scheduler + /// + /// \param initial_task The initial task which is responsible for adding + /// the first subtasks to the scheduler. + /// \param abort_callback A callback that will be triggered immediately after a task + /// fails while other tasks may still be running. Nothing needs to be done here, + /// when a task fails the scheduler will stop accepting new tasks and eventually + /// return the error. However, this callback can be used to more quickly end + /// long running tasks that have already been submitted. Defaults to doing + /// nothing. + /// \param stop_token An optional stop token that will allow cancellation of the + /// scheduler. This will be checked before each task is submitted and, in the + /// event of a cancellation, the scheduler will enter an aborted state. This is + /// a graceful cancellation and submitted tasks will still complete. + /// \return A future that will be completed when the initial task and all subtasks have + /// finished. + static Future<> Make( + FnOnce initial_task, + FnOnce abort_callback = [](const Status&) {}, + StopToken stop_token = StopToken::Unstoppable()); + + /// A span tracking execution of the scheduler's tasks, for internal use only + virtual const tracing::Span& span() const = 0; +}; + +class ARROW_EXPORT ThrottledAsyncTaskScheduler : public AsyncTaskScheduler { + public: + /// An interface for a task queue + /// + /// A queue's methods will not be called concurrently + class Queue { + public: + virtual ~Queue() = default; + /// Push a task to the queue + /// + /// \param task the task to enqueue + virtual void Push(std::unique_ptr task) = 0; + /// Pop the next task from the queue + virtual std::unique_ptr Pop() = 0; + /// Peek the next task in the queue + virtual const Task& Peek() = 0; + /// Check if the queue is empty + virtual bool Empty() = 0; + /// Purge the queue of all items + virtual void Purge() = 0; + }; + + class Throttle { + public: + virtual ~Throttle() = default; + /// Acquire amt permits + /// + /// If nullopt is returned then the permits were immediately + /// acquired and the caller can proceed. If a future is returned then the caller + /// should wait for the future to complete first. When the returned future completes + /// the permits have NOT been acquired and the caller must call Acquire again + /// + /// \param amt the number of permits to acquire + virtual std::optional> TryAcquire(int amt) = 0; + /// Release amt permits + /// + /// This will possibly complete waiting futures and should probably not be + /// called while holding locks. + /// + /// \param amt the number of permits to release + virtual void Release(int amt) = 0; + + /// The size of the largest task that can run + /// + /// Incoming tasks will have their cost latched to this value to ensure + /// they can still run (although they will be the only thing allowed to + /// run at that time). + virtual int Capacity() = 0; + + /// Pause the throttle + /// + /// Any tasks that have been submitted already will continue. However, no new tasks + /// will be run until the throttle is resumed. + virtual void Pause() = 0; + /// Resume the throttle + /// + /// Allows task to be submitted again. If there is a max_concurrent_cost limit then + /// it will still apply. + virtual void Resume() = 0; + }; + + /// Pause the throttle + /// + /// Any tasks that have been submitted already will continue. However, no new tasks + /// will be run until the throttle is resumed. + virtual void Pause() = 0; + /// Resume the throttle + /// + /// Allows task to be submitted again. If there is a max_concurrent_cost limit then + /// it will still apply. + virtual void Resume() = 0; + + /// Create a throttled view of a scheduler + /// + /// Tasks added via this view will be subjected to the throttle and, if the tasks cannot + /// run immediately, will be placed into a queue. + /// + /// Although a shared_ptr is returned it should generally be assumed that the caller + /// is being given exclusive ownership. The shared_ptr is used to share the view with + /// queued and submitted tasks and the lifetime of those is unpredictable. It is + /// important the caller keep the returned pointer alive for as long as they plan to add + /// tasks to the view. + /// + /// \param scheduler a scheduler to submit tasks to after throttling + /// + /// This can be the root scheduler, another throttled scheduler, or a task group. These + /// are all composable. + /// + /// \param max_concurrent_cost the maximum amount of cost allowed to run at any one time + /// + /// If a task is added that has a cost greater than max_concurrent_cost then its cost + /// will be reduced to max_concurrent_cost so that it is still possible for the task to + /// run. + /// + /// \param queue the queue to use when tasks cannot be submitted + /// + /// By default a FIFO queue will be used. However, a custom queue can be provided if + /// some tasks have higher priority than other tasks. + static std::shared_ptr Make( + AsyncTaskScheduler* scheduler, int max_concurrent_cost, + std::unique_ptr queue = NULLPTR); + + /// @brief Create a ThrottledAsyncTaskScheduler using a custom throttle + /// + /// \see Make + static std::shared_ptr MakeWithCustomThrottle( + AsyncTaskScheduler* scheduler, std::unique_ptr throttle, + std::unique_ptr queue = NULLPTR); +}; + +/// A utility to keep track of a collection of tasks +/// +/// Often it is useful to keep track of some state that only needs to stay alive +/// for some small collection of tasks, or to perform some kind of final cleanup +/// when a collection of tasks is finished. +/// +/// For example, when scanning, we need to keep the file reader alive while all scan +/// tasks run for a given file, and then we can gracefully close it when we finish the +/// file. +class ARROW_EXPORT AsyncTaskGroup : public AsyncTaskScheduler { + public: + /// Destructor for the task group + /// + /// The destructor might trigger the finish callback. If the finish callback fails + /// then the error will be reported as a task on the scheduler. + /// + /// Failure to destroy the async task group will not prevent the scheduler from + /// finishing. If the scheduler finishes before the async task group is done then + /// the finish callback will be run immediately when the async task group finishes. + /// + /// If the scheduler has aborted then the finish callback will not run. + ~AsyncTaskGroup() = default; + /// Create an async task group + /// + /// The finish callback will not run until the task group is destroyed and all + /// tasks are finished so you will generally want to reset / destroy the returned + /// unique_ptr at some point. + /// + /// \param scheduler The underlying scheduler to submit tasks to + /// \param finish_callback A callback that will be run only after the task group has + /// been destroyed and all tasks added by the group have + /// finished. + /// + /// Note: in error scenarios the finish callback may not run. However, it will still, + /// of course, be destroyed. + static std::unique_ptr Make(AsyncTaskScheduler* scheduler, + FnOnce finish_callback); +}; + +/// Create a task group that is also throttled +/// +/// This is a utility factory that creates a throttled view of a scheduler and then +/// wraps that throttled view with a task group that destroys the throttle when finished. +/// +/// \see ThrottledAsyncTaskScheduler +/// \see AsyncTaskGroup +/// \param target the underlying scheduler to submit tasks to +/// \param max_concurrent_cost the maximum amount of cost allowed to run at any one time +/// \param queue the queue to use when tasks cannot be submitted +/// \param finish_callback A callback that will be run only after the task group has +/// been destroyed and all tasks added by the group have finished +ARROW_EXPORT std::unique_ptr MakeThrottledAsyncTaskGroup( + AsyncTaskScheduler* target, int max_concurrent_cost, + std::unique_ptr queue, + FnOnce finish_callback); + +// Defined down here to avoid circular dependency between AsyncTaskScheduler and +// AsyncTaskGroup +template +bool AsyncTaskScheduler::AddAsyncGenerator(std::function()> generator, + std::function visitor, + std::string_view name) { + struct State { + State(std::function()> generator, std::function visitor, + std::unique_ptr task_group, std::string_view name) + : generator(std::move(generator)), + visitor(std::move(visitor)), + task_group(std::move(task_group)), + name(name) {} + std::function()> generator; + std::function visitor; + std::unique_ptr task_group; + std::string_view name; + }; + struct SubmitTask : public Task { + explicit SubmitTask(std::unique_ptr state_holder) + : state_holder(std::move(state_holder)) {} + + struct SubmitTaskCallback { + SubmitTaskCallback(std::unique_ptr state_holder, Future<> task_completion) + : state_holder(std::move(state_holder)), + task_completion(std::move(task_completion)) {} + void operator()(const Result& maybe_item) { + if (!maybe_item.ok()) { + task_completion.MarkFinished(maybe_item.status()); + return; + } + const auto& item = *maybe_item; + if (IsIterationEnd(item)) { + task_completion.MarkFinished(); + return; + } + Status visit_st = state_holder->visitor(item); + if (!visit_st.ok()) { + task_completion.MarkFinished(std::move(visit_st)); + return; + } + state_holder->task_group->AddTask( + std::make_unique(std::move(state_holder))); + task_completion.MarkFinished(); + } + std::unique_ptr state_holder; + Future<> task_completion; + }; + + Result> operator()() { + Future<> task = Future<>::Make(); + // Consume as many items as we can (those that are already finished) + // synchronously to avoid recursion / stack overflow. + while (true) { + Future next = state_holder->generator(); + if (next.TryAddCallback( + [&] { return SubmitTaskCallback(std::move(state_holder), task); })) { + return task; + } + ARROW_ASSIGN_OR_RAISE(T item, next.result()); + if (IsIterationEnd(item)) { + task.MarkFinished(); + return task; + } + ARROW_RETURN_NOT_OK(state_holder->visitor(item)); + } + } + + std::string_view name() const { return state_holder->name; } + + std::unique_ptr state_holder; + }; + std::unique_ptr task_group = + AsyncTaskGroup::Make(this, [] { return Status::OK(); }); + AsyncTaskGroup* task_group_view = task_group.get(); + std::unique_ptr state_holder = std::make_unique( + std::move(generator), std::move(visitor), std::move(task_group), name); + task_group_view->AddTask(std::make_unique(std::move(state_holder))); + return true; +} + +} // namespace util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/basic_decimal.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/basic_decimal.h new file mode 100644 index 0000000000000000000000000000000000000000..d8a91ea76b3906ec8d8b55bdb282cdb8da874cfd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/basic_decimal.h @@ -0,0 +1,492 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/util/endian.h" +#include "arrow/util/macros.h" +#include "arrow/util/type_traits.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +enum class DecimalStatus { + kSuccess, + kDivideByZero, + kOverflow, + kRescaleDataLoss, +}; + +template +class ARROW_EXPORT GenericBasicDecimal { + protected: + struct LittleEndianArrayTag {}; + +#if ARROW_LITTLE_ENDIAN + static constexpr int kHighWordIndex = NWORDS - 1; + static constexpr int kLowWordIndex = 0; +#else + static constexpr int kHighWordIndex = 0; + static constexpr int kLowWordIndex = NWORDS - 1; +#endif + + public: + static constexpr int kBitWidth = BIT_WIDTH; + static constexpr int kByteWidth = kBitWidth / 8; + static constexpr int kNumWords = NWORDS; + + // A constructor tag to introduce a little-endian encoded array + static constexpr LittleEndianArrayTag LittleEndianArray{}; + + using WordArray = std::array; + + /// \brief Empty constructor creates a decimal with a value of 0. + constexpr GenericBasicDecimal() noexcept : array_({0}) {} + + /// \brief Create a decimal from the two's complement representation. + /// + /// Input array is assumed to be in native endianness. + explicit constexpr GenericBasicDecimal(const WordArray& array) noexcept + : array_(array) {} + + /// \brief Create a decimal from the two's complement representation. + /// + /// Input array is assumed to be in little endianness, with native endian elements. + GenericBasicDecimal(LittleEndianArrayTag, const WordArray& array) noexcept + : GenericBasicDecimal(bit_util::little_endian::ToNative(array)) {} + + /// \brief Create a decimal from any integer not wider than 64 bits. + template ::value && (sizeof(T) <= sizeof(uint64_t)), T>::type> + constexpr GenericBasicDecimal(T value) noexcept // NOLINT(runtime/explicit) + : array_(WordsFromLowBits(value)) {} + + /// \brief Create a decimal from an array of bytes. + /// + /// Bytes are assumed to be in native-endian byte order. + explicit GenericBasicDecimal(const uint8_t* bytes) { + memcpy(array_.data(), bytes, sizeof(array_)); + } + + /// \brief Get the bits of the two's complement representation of the number. + /// + /// The elements are in native endian order. The bits within each uint64_t element + /// are in native endian order. For example, on a little endian machine, + /// BasicDecimal128(123).native_endian_array() = {123, 0}; + /// but on a big endian machine, + /// BasicDecimal128(123).native_endian_array() = {0, 123}; + constexpr const WordArray& native_endian_array() const { return array_; } + + /// \brief Get the bits of the two's complement representation of the number. + /// + /// The elements are in little endian order. However, the bits within each + /// uint64_t element are in native endian order. + /// For example, BasicDecimal128(123).little_endian_array() = {123, 0}; + WordArray little_endian_array() const { + return bit_util::little_endian::FromNative(array_); + } + + const uint8_t* native_endian_bytes() const { + return reinterpret_cast(array_.data()); + } + + uint8_t* mutable_native_endian_bytes() { + return reinterpret_cast(array_.data()); + } + + /// \brief Return the raw bytes of the value in native-endian byte order. + std::array ToBytes() const { + std::array out{{0}}; + memcpy(out.data(), array_.data(), kByteWidth); + return out; + } + + /// \brief Copy the raw bytes of the value in native-endian byte order. + void ToBytes(uint8_t* out) const { memcpy(out, array_.data(), kByteWidth); } + + /// Return 1 if positive or zero, -1 if strictly negative. + int64_t Sign() const { + return 1 | (static_cast(array_[kHighWordIndex]) >> 63); + } + + bool IsNegative() const { return static_cast(array_[kHighWordIndex]) < 0; } + + explicit operator bool() const { return array_ != WordArray{}; } + + friend bool operator==(const GenericBasicDecimal& left, + const GenericBasicDecimal& right) { + return left.array_ == right.array_; + } + + friend bool operator!=(const GenericBasicDecimal& left, + const GenericBasicDecimal& right) { + return left.array_ != right.array_; + } + + protected: + WordArray array_; + + template + static constexpr uint64_t SignExtend(T low_bits) noexcept { + return low_bits >= T{} ? uint64_t{0} : ~uint64_t{0}; + } + + template + static constexpr WordArray WordsFromLowBits(T low_bits) { + WordArray words{}; + if (low_bits < T{}) { + for (auto& word : words) { + word = ~uint64_t{0}; + } + } + words[kLowWordIndex] = static_cast(low_bits); + return words; + } +}; + +/// Represents a signed 128-bit integer in two's complement. +/// +/// This class is also compiled into LLVM IR - so, it should not have cpp references like +/// streams and boost. +class ARROW_EXPORT BasicDecimal128 : public GenericBasicDecimal { + public: + static constexpr int kMaxPrecision = 38; + static constexpr int kMaxScale = 38; + + using GenericBasicDecimal::GenericBasicDecimal; + + constexpr BasicDecimal128() noexcept : GenericBasicDecimal() {} + + /// \brief Create a BasicDecimal128 from the two's complement representation. +#if ARROW_LITTLE_ENDIAN + constexpr BasicDecimal128(int64_t high, uint64_t low) noexcept + : BasicDecimal128(WordArray{low, static_cast(high)}) {} +#else + constexpr BasicDecimal128(int64_t high, uint64_t low) noexcept + : BasicDecimal128(WordArray{static_cast(high), low}) {} +#endif + + /// \brief Negate the current value (in-place) + BasicDecimal128& Negate(); + + /// \brief Absolute value (in-place) + BasicDecimal128& Abs(); + + /// \brief Absolute value + static BasicDecimal128 Abs(const BasicDecimal128& left); + + /// \brief Add a number to this one. The result is truncated to 128 bits. + BasicDecimal128& operator+=(const BasicDecimal128& right); + + /// \brief Subtract a number from this one. The result is truncated to 128 bits. + BasicDecimal128& operator-=(const BasicDecimal128& right); + + /// \brief Multiply this number by another number. The result is truncated to 128 bits. + BasicDecimal128& operator*=(const BasicDecimal128& right); + + /// Divide this number by right and return the result. + /// + /// This operation is not destructive. + /// The answer rounds to zero. Signs work like: + /// 21 / 5 -> 4, 1 + /// -21 / 5 -> -4, -1 + /// 21 / -5 -> -4, 1 + /// -21 / -5 -> 4, -1 + /// \param[in] divisor the number to divide by + /// \param[out] result the quotient + /// \param[out] remainder the remainder after the division + DecimalStatus Divide(const BasicDecimal128& divisor, BasicDecimal128* result, + BasicDecimal128* remainder) const; + + /// \brief In-place division. + BasicDecimal128& operator/=(const BasicDecimal128& right); + + /// \brief Bitwise "or" between two BasicDecimal128. + BasicDecimal128& operator|=(const BasicDecimal128& right); + + /// \brief Bitwise "and" between two BasicDecimal128. + BasicDecimal128& operator&=(const BasicDecimal128& right); + + /// \brief Shift left by the given number of bits. + BasicDecimal128& operator<<=(uint32_t bits); + + BasicDecimal128 operator<<(uint32_t bits) const { + auto res = *this; + res <<= bits; + return res; + } + + /// \brief Shift right by the given number of bits. + /// + /// Negative values will sign-extend. + BasicDecimal128& operator>>=(uint32_t bits); + + BasicDecimal128 operator>>(uint32_t bits) const { + auto res = *this; + res >>= bits; + return res; + } + + /// \brief Get the high bits of the two's complement representation of the number. + constexpr int64_t high_bits() const { +#if ARROW_LITTLE_ENDIAN + return static_cast(array_[1]); +#else + return static_cast(array_[0]); +#endif + } + + /// \brief Get the low bits of the two's complement representation of the number. + constexpr uint64_t low_bits() const { +#if ARROW_LITTLE_ENDIAN + return array_[0]; +#else + return array_[1]; +#endif + } + + /// \brief separate the integer and fractional parts for the given scale. + void GetWholeAndFraction(int32_t scale, BasicDecimal128* whole, + BasicDecimal128* fraction) const; + + /// \brief Scale multiplier for given scale value. + static const BasicDecimal128& GetScaleMultiplier(int32_t scale); + /// \brief Half-scale multiplier for given scale value. + static const BasicDecimal128& GetHalfScaleMultiplier(int32_t scale); + + /// \brief Convert BasicDecimal128 from one scale to another + DecimalStatus Rescale(int32_t original_scale, int32_t new_scale, + BasicDecimal128* out) const; + + /// \brief Scale up. + BasicDecimal128 IncreaseScaleBy(int32_t increase_by) const; + + /// \brief Scale down. + /// - If 'round' is true, the right-most digits are dropped and the result value is + /// rounded up (+1 for +ve, -1 for -ve) based on the value of the dropped digits + /// (>= 10^reduce_by / 2). + /// - If 'round' is false, the right-most digits are simply dropped. + BasicDecimal128 ReduceScaleBy(int32_t reduce_by, bool round = true) const; + + /// \brief Whether this number fits in the given precision + /// + /// Return true if the number of significant digits is less or equal to `precision`. + bool FitsInPrecision(int32_t precision) const; + + /// \brief count the number of leading binary zeroes. + int32_t CountLeadingBinaryZeros() const; + + /// \brief Get the maximum valid unscaled decimal value. + static const BasicDecimal128& GetMaxValue(); + + /// \brief Get the maximum valid unscaled decimal value for the given precision. + static BasicDecimal128 GetMaxValue(int32_t precision); + + /// \brief Get the maximum decimal value (is not a valid value). + static constexpr BasicDecimal128 GetMaxSentinel() { + return BasicDecimal128(/*high=*/std::numeric_limits::max(), + /*low=*/std::numeric_limits::max()); + } + /// \brief Get the minimum decimal value (is not a valid value). + static constexpr BasicDecimal128 GetMinSentinel() { + return BasicDecimal128(/*high=*/std::numeric_limits::min(), + /*low=*/std::numeric_limits::min()); + } +}; + +ARROW_EXPORT bool operator<(const BasicDecimal128& left, const BasicDecimal128& right); +ARROW_EXPORT bool operator<=(const BasicDecimal128& left, const BasicDecimal128& right); +ARROW_EXPORT bool operator>(const BasicDecimal128& left, const BasicDecimal128& right); +ARROW_EXPORT bool operator>=(const BasicDecimal128& left, const BasicDecimal128& right); + +ARROW_EXPORT BasicDecimal128 operator-(const BasicDecimal128& operand); +ARROW_EXPORT BasicDecimal128 operator~(const BasicDecimal128& operand); +ARROW_EXPORT BasicDecimal128 operator+(const BasicDecimal128& left, + const BasicDecimal128& right); +ARROW_EXPORT BasicDecimal128 operator-(const BasicDecimal128& left, + const BasicDecimal128& right); +ARROW_EXPORT BasicDecimal128 operator*(const BasicDecimal128& left, + const BasicDecimal128& right); +ARROW_EXPORT BasicDecimal128 operator/(const BasicDecimal128& left, + const BasicDecimal128& right); +ARROW_EXPORT BasicDecimal128 operator%(const BasicDecimal128& left, + const BasicDecimal128& right); + +class ARROW_EXPORT BasicDecimal256 : public GenericBasicDecimal { + public: + using GenericBasicDecimal::GenericBasicDecimal; + + static constexpr int kMaxPrecision = 76; + static constexpr int kMaxScale = 76; + + constexpr BasicDecimal256() noexcept : GenericBasicDecimal() {} + + explicit BasicDecimal256(const BasicDecimal128& value) noexcept + : BasicDecimal256(bit_util::little_endian::ToNative( + {value.low_bits(), static_cast(value.high_bits()), + SignExtend(value.high_bits()), SignExtend(value.high_bits())})) {} + + /// \brief Negate the current value (in-place) + BasicDecimal256& Negate(); + + /// \brief Absolute value (in-place) + BasicDecimal256& Abs(); + + /// \brief Absolute value + static BasicDecimal256 Abs(const BasicDecimal256& left); + + /// \brief Add a number to this one. The result is truncated to 256 bits. + BasicDecimal256& operator+=(const BasicDecimal256& right); + + /// \brief Subtract a number from this one. The result is truncated to 256 bits. + BasicDecimal256& operator-=(const BasicDecimal256& right); + + /// \brief Get the lowest bits of the two's complement representation of the number. + uint64_t low_bits() const { return bit_util::little_endian::Make(array_)[0]; } + + /// \brief separate the integer and fractional parts for the given scale. + void GetWholeAndFraction(int32_t scale, BasicDecimal256* whole, + BasicDecimal256* fraction) const; + + /// \brief Scale multiplier for given scale value. + static const BasicDecimal256& GetScaleMultiplier(int32_t scale); + /// \brief Half-scale multiplier for given scale value. + static const BasicDecimal256& GetHalfScaleMultiplier(int32_t scale); + + /// \brief Convert BasicDecimal256 from one scale to another + DecimalStatus Rescale(int32_t original_scale, int32_t new_scale, + BasicDecimal256* out) const; + + /// \brief Scale up. + BasicDecimal256 IncreaseScaleBy(int32_t increase_by) const; + + /// \brief Scale down. + /// - If 'round' is true, the right-most digits are dropped and the result value is + /// rounded up (+1 for positive, -1 for negative) based on the value of the + /// dropped digits (>= 10^reduce_by / 2). + /// - If 'round' is false, the right-most digits are simply dropped. + BasicDecimal256 ReduceScaleBy(int32_t reduce_by, bool round = true) const; + + /// \brief Whether this number fits in the given precision + /// + /// Return true if the number of significant digits is less or equal to `precision`. + bool FitsInPrecision(int32_t precision) const; + + /// \brief Multiply this number by another number. The result is truncated to 256 bits. + BasicDecimal256& operator*=(const BasicDecimal256& right); + + /// Divide this number by right and return the result. + /// + /// This operation is not destructive. + /// The answer rounds to zero. Signs work like: + /// 21 / 5 -> 4, 1 + /// -21 / 5 -> -4, -1 + /// 21 / -5 -> -4, 1 + /// -21 / -5 -> 4, -1 + /// \param[in] divisor the number to divide by + /// \param[out] result the quotient + /// \param[out] remainder the remainder after the division + DecimalStatus Divide(const BasicDecimal256& divisor, BasicDecimal256* result, + BasicDecimal256* remainder) const; + + /// \brief Shift left by the given number of bits. + BasicDecimal256& operator<<=(uint32_t bits); + + BasicDecimal256 operator<<(uint32_t bits) const { + auto res = *this; + res <<= bits; + return res; + } + + /// \brief Shift right by the given number of bits. + /// + /// Negative values will sign-extend. + BasicDecimal256& operator>>=(uint32_t bits); + + BasicDecimal256 operator>>(uint32_t bits) const { + auto res = *this; + res >>= bits; + return res; + } + + /// \brief In-place division. + BasicDecimal256& operator/=(const BasicDecimal256& right); + + /// \brief Get the maximum valid unscaled decimal value for the given precision. + static BasicDecimal256 GetMaxValue(int32_t precision); + + /// \brief Get the maximum decimal value (is not a valid value). + static constexpr BasicDecimal256 GetMaxSentinel() { +#if ARROW_LITTLE_ENDIAN + return BasicDecimal256({std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::max(), + static_cast(std::numeric_limits::max())}); +#else + return BasicDecimal256({static_cast(std::numeric_limits::max()), + std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::max()}); +#endif + } + /// \brief Get the minimum decimal value (is not a valid value). + static constexpr BasicDecimal256 GetMinSentinel() { +#if ARROW_LITTLE_ENDIAN + return BasicDecimal256( + {0, 0, 0, static_cast(std::numeric_limits::min())}); +#else + return BasicDecimal256( + {static_cast(std::numeric_limits::min()), 0, 0, 0}); +#endif + } +}; + +ARROW_EXPORT bool operator<(const BasicDecimal256& left, const BasicDecimal256& right); + +ARROW_EXPORT inline bool operator<=(const BasicDecimal256& left, + const BasicDecimal256& right) { + return !operator<(right, left); +} + +ARROW_EXPORT inline bool operator>(const BasicDecimal256& left, + const BasicDecimal256& right) { + return operator<(right, left); +} + +ARROW_EXPORT inline bool operator>=(const BasicDecimal256& left, + const BasicDecimal256& right) { + return !operator<(left, right); +} + +ARROW_EXPORT BasicDecimal256 operator-(const BasicDecimal256& operand); +ARROW_EXPORT BasicDecimal256 operator~(const BasicDecimal256& operand); +ARROW_EXPORT BasicDecimal256 operator+(const BasicDecimal256& left, + const BasicDecimal256& right); +ARROW_EXPORT BasicDecimal256 operator*(const BasicDecimal256& left, + const BasicDecimal256& right); +ARROW_EXPORT BasicDecimal256 operator/(const BasicDecimal256& left, + const BasicDecimal256& right); + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_block_counter.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_block_counter.h new file mode 100644 index 0000000000000000000000000000000000000000..73a1ee8600fb4e0be10f26e921083c3be5740490 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_block_counter.h @@ -0,0 +1,570 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/status.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/endian.h" +#include "arrow/util/macros.h" +#include "arrow/util/ubsan.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace internal { +namespace detail { + +inline uint64_t LoadWord(const uint8_t* bytes) { + return bit_util::ToLittleEndian(util::SafeLoadAs(bytes)); +} + +inline uint64_t ShiftWord(uint64_t current, uint64_t next, int64_t shift) { + if (shift == 0) { + return current; + } + return (current >> shift) | (next << (64 - shift)); +} + +// These templates are here to help with unit tests + +template +constexpr T BitNot(T x) { + return ~x; +} + +template <> +constexpr bool BitNot(bool x) { + return !x; +} + +struct BitBlockAnd { + template + static constexpr T Call(T left, T right) { + return left & right; + } +}; + +struct BitBlockAndNot { + template + static constexpr T Call(T left, T right) { + return left & BitNot(right); + } +}; + +struct BitBlockOr { + template + static constexpr T Call(T left, T right) { + return left | right; + } +}; + +struct BitBlockOrNot { + template + static constexpr T Call(T left, T right) { + return left | BitNot(right); + } +}; + +} // namespace detail + +/// \brief Return value from bit block counters: the total number of bits and +/// the number of set bits. +struct BitBlockCount { + int16_t length; + int16_t popcount; + + bool NoneSet() const { return this->popcount == 0; } + bool AllSet() const { return this->length == this->popcount; } +}; + +/// \brief A class that scans through a true/false bitmap to compute popcounts +/// 64 or 256 bits at a time. This is used to accelerate processing of +/// mostly-not-null array data. +class ARROW_EXPORT BitBlockCounter { + public: + BitBlockCounter(const uint8_t* bitmap, int64_t start_offset, int64_t length) + : bitmap_(util::MakeNonNull(bitmap) + start_offset / 8), + bits_remaining_(length), + offset_(start_offset % 8) {} + + /// \brief The bit size of each word run + static constexpr int64_t kWordBits = 64; + + /// \brief The bit size of four words run + static constexpr int64_t kFourWordsBits = kWordBits * 4; + + /// \brief Return the next run of available bits, usually 256. The returned + /// pair contains the size of run and the number of true values. The last + /// block will have a length less than 256 if the bitmap length is not a + /// multiple of 256, and will return 0-length blocks in subsequent + /// invocations. + BitBlockCount NextFourWords() { + using detail::LoadWord; + using detail::ShiftWord; + + if (!bits_remaining_) { + return {0, 0}; + } + int64_t total_popcount = 0; + if (offset_ == 0) { + if (bits_remaining_ < kFourWordsBits) { + return GetBlockSlow(kFourWordsBits); + } + total_popcount += bit_util::PopCount(LoadWord(bitmap_)); + total_popcount += bit_util::PopCount(LoadWord(bitmap_ + 8)); + total_popcount += bit_util::PopCount(LoadWord(bitmap_ + 16)); + total_popcount += bit_util::PopCount(LoadWord(bitmap_ + 24)); + } else { + // When the offset is > 0, we need there to be a word beyond the last + // aligned word in the bitmap for the bit shifting logic. + if (bits_remaining_ < 5 * kFourWordsBits - offset_) { + return GetBlockSlow(kFourWordsBits); + } + auto current = LoadWord(bitmap_); + auto next = LoadWord(bitmap_ + 8); + total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_)); + current = next; + next = LoadWord(bitmap_ + 16); + total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_)); + current = next; + next = LoadWord(bitmap_ + 24); + total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_)); + current = next; + next = LoadWord(bitmap_ + 32); + total_popcount += bit_util::PopCount(ShiftWord(current, next, offset_)); + } + bitmap_ += bit_util::BytesForBits(kFourWordsBits); + bits_remaining_ -= kFourWordsBits; + return {256, static_cast(total_popcount)}; + } + + /// \brief Return the next run of available bits, usually 64. The returned + /// pair contains the size of run and the number of true values. The last + /// block will have a length less than 64 if the bitmap length is not a + /// multiple of 64, and will return 0-length blocks in subsequent + /// invocations. + BitBlockCount NextWord() { + using detail::LoadWord; + using detail::ShiftWord; + + if (!bits_remaining_) { + return {0, 0}; + } + int64_t popcount = 0; + if (offset_ == 0) { + if (bits_remaining_ < kWordBits) { + return GetBlockSlow(kWordBits); + } + popcount = bit_util::PopCount(LoadWord(bitmap_)); + } else { + // When the offset is > 0, we need there to be a word beyond the last + // aligned word in the bitmap for the bit shifting logic. + if (bits_remaining_ < 2 * kWordBits - offset_) { + return GetBlockSlow(kWordBits); + } + popcount = bit_util::PopCount( + ShiftWord(LoadWord(bitmap_), LoadWord(bitmap_ + 8), offset_)); + } + bitmap_ += kWordBits / 8; + bits_remaining_ -= kWordBits; + return {64, static_cast(popcount)}; + } + + private: + /// \brief Return block with the requested size when doing word-wise + /// computation is not possible due to inadequate bits remaining. + BitBlockCount GetBlockSlow(int64_t block_size) noexcept; + + const uint8_t* bitmap_; + int64_t bits_remaining_; + int64_t offset_; +}; + +/// \brief A tool to iterate through a possibly nonexistent validity bitmap, +/// to allow us to write one code path for both the with-nulls and no-nulls +/// cases without giving up a lot of performance. +class ARROW_EXPORT OptionalBitBlockCounter { + public: + // validity_bitmap may be NULLPTR + OptionalBitBlockCounter(const uint8_t* validity_bitmap, int64_t offset, int64_t length); + + // validity_bitmap may be null + OptionalBitBlockCounter(const std::shared_ptr& validity_bitmap, int64_t offset, + int64_t length); + + /// Return block count for next word when the bitmap is available otherwise + /// return a block with length up to INT16_MAX when there is no validity + /// bitmap (so all the referenced values are not null). + BitBlockCount NextBlock() { + static constexpr int64_t kMaxBlockSize = std::numeric_limits::max(); + if (has_bitmap_) { + BitBlockCount block = counter_.NextWord(); + position_ += block.length; + return block; + } else { + int16_t block_size = + static_cast(std::min(kMaxBlockSize, length_ - position_)); + position_ += block_size; + // All values are non-null + return {block_size, block_size}; + } + } + + // Like NextBlock, but returns a word-sized block even when there is no + // validity bitmap + BitBlockCount NextWord() { + static constexpr int64_t kWordSize = 64; + if (has_bitmap_) { + BitBlockCount block = counter_.NextWord(); + position_ += block.length; + return block; + } else { + int16_t block_size = static_cast(std::min(kWordSize, length_ - position_)); + position_ += block_size; + // All values are non-null + return {block_size, block_size}; + } + } + + private: + const bool has_bitmap_; + int64_t position_; + int64_t length_; + BitBlockCounter counter_; +}; + +/// \brief A class that computes popcounts on the result of bitwise operations +/// between two bitmaps, 64 bits at a time. A 64-bit word is loaded from each +/// bitmap, then the popcount is computed on e.g. the bitwise-and of the two +/// words. +class ARROW_EXPORT BinaryBitBlockCounter { + public: + BinaryBitBlockCounter(const uint8_t* left_bitmap, int64_t left_offset, + const uint8_t* right_bitmap, int64_t right_offset, int64_t length) + : left_bitmap_(util::MakeNonNull(left_bitmap) + left_offset / 8), + left_offset_(left_offset % 8), + right_bitmap_(util::MakeNonNull(right_bitmap) + right_offset / 8), + right_offset_(right_offset % 8), + bits_remaining_(length) {} + + /// \brief Return the popcount of the bitwise-and of the next run of + /// available bits, up to 64. The returned pair contains the size of run and + /// the number of true values. The last block will have a length less than 64 + /// if the bitmap length is not a multiple of 64, and will return 0-length + /// blocks in subsequent invocations. + BitBlockCount NextAndWord() { return NextWord(); } + + /// \brief Computes "x & ~y" block for each available run of bits. + BitBlockCount NextAndNotWord() { return NextWord(); } + + /// \brief Computes "x | y" block for each available run of bits. + BitBlockCount NextOrWord() { return NextWord(); } + + /// \brief Computes "x | ~y" block for each available run of bits. + BitBlockCount NextOrNotWord() { return NextWord(); } + + private: + template + BitBlockCount NextWord() { + using detail::LoadWord; + using detail::ShiftWord; + + if (!bits_remaining_) { + return {0, 0}; + } + // When the offset is > 0, we need there to be a word beyond the last aligned + // word in the bitmap for the bit shifting logic. + constexpr int64_t kWordBits = BitBlockCounter::kWordBits; + const int64_t bits_required_to_use_words = + std::max(left_offset_ == 0 ? 64 : 64 + (64 - left_offset_), + right_offset_ == 0 ? 64 : 64 + (64 - right_offset_)); + if (bits_remaining_ < bits_required_to_use_words) { + const int16_t run_length = + static_cast(std::min(bits_remaining_, kWordBits)); + int16_t popcount = 0; + for (int64_t i = 0; i < run_length; ++i) { + if (Op::Call(bit_util::GetBit(left_bitmap_, left_offset_ + i), + bit_util::GetBit(right_bitmap_, right_offset_ + i))) { + ++popcount; + } + } + // This code path should trigger _at most_ 2 times. In the "two times" + // case, the first time the run length will be a multiple of 8. + left_bitmap_ += run_length / 8; + right_bitmap_ += run_length / 8; + bits_remaining_ -= run_length; + return {run_length, popcount}; + } + + int64_t popcount = 0; + if (left_offset_ == 0 && right_offset_ == 0) { + popcount = + bit_util::PopCount(Op::Call(LoadWord(left_bitmap_), LoadWord(right_bitmap_))); + } else { + auto left_word = + ShiftWord(LoadWord(left_bitmap_), LoadWord(left_bitmap_ + 8), left_offset_); + auto right_word = + ShiftWord(LoadWord(right_bitmap_), LoadWord(right_bitmap_ + 8), right_offset_); + popcount = bit_util::PopCount(Op::Call(left_word, right_word)); + } + left_bitmap_ += kWordBits / 8; + right_bitmap_ += kWordBits / 8; + bits_remaining_ -= kWordBits; + return {64, static_cast(popcount)}; + } + + const uint8_t* left_bitmap_; + int64_t left_offset_; + const uint8_t* right_bitmap_; + int64_t right_offset_; + int64_t bits_remaining_; +}; + +class ARROW_EXPORT OptionalBinaryBitBlockCounter { + public: + // Any bitmap may be NULLPTR + OptionalBinaryBitBlockCounter(const uint8_t* left_bitmap, int64_t left_offset, + const uint8_t* right_bitmap, int64_t right_offset, + int64_t length); + + // Any bitmap may be null + OptionalBinaryBitBlockCounter(const std::shared_ptr& left_bitmap, + int64_t left_offset, + const std::shared_ptr& right_bitmap, + int64_t right_offset, int64_t length); + + BitBlockCount NextAndBlock() { + static constexpr int64_t kMaxBlockSize = std::numeric_limits::max(); + switch (has_bitmap_) { + case HasBitmap::BOTH: { + BitBlockCount block = binary_counter_.NextAndWord(); + position_ += block.length; + return block; + } + case HasBitmap::ONE: { + BitBlockCount block = unary_counter_.NextWord(); + position_ += block.length; + return block; + } + case HasBitmap::NONE: + default: { + const int16_t block_size = + static_cast(std::min(kMaxBlockSize, length_ - position_)); + position_ += block_size; + // All values are non-null + return {block_size, block_size}; + } + } + } + + BitBlockCount NextOrNotBlock() { + static constexpr int64_t kMaxBlockSize = std::numeric_limits::max(); + switch (has_bitmap_) { + case HasBitmap::BOTH: { + BitBlockCount block = binary_counter_.NextOrNotWord(); + position_ += block.length; + return block; + } + case HasBitmap::ONE: { + BitBlockCount block = unary_counter_.NextWord(); + position_ += block.length; + return block; + } + case HasBitmap::NONE: + default: { + const int16_t block_size = + static_cast(std::min(kMaxBlockSize, length_ - position_)); + position_ += block_size; + // All values are non-null + return {block_size, block_size}; + } + } + } + + private: + enum class HasBitmap : int { BOTH, ONE, NONE }; + + const HasBitmap has_bitmap_; + int64_t position_; + int64_t length_; + BitBlockCounter unary_counter_; + BinaryBitBlockCounter binary_counter_; + + static HasBitmap HasBitmapFromBitmaps(bool has_left, bool has_right) { + switch (static_cast(has_left) + static_cast(has_right)) { + case 0: + return HasBitmap::NONE; + case 1: + return HasBitmap::ONE; + default: // 2 + return HasBitmap::BOTH; + } + } +}; + +// Functional-style bit block visitors. + +template +static Status VisitBitBlocks(const uint8_t* bitmap, int64_t offset, int64_t length, + VisitNotNull&& visit_not_null, VisitNull&& visit_null) { + internal::OptionalBitBlockCounter bit_counter(bitmap, offset, length); + int64_t position = 0; + while (position < length) { + internal::BitBlockCount block = bit_counter.NextBlock(); + if (block.AllSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + ARROW_RETURN_NOT_OK(visit_not_null(position)); + } + } else if (block.NoneSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + ARROW_RETURN_NOT_OK(visit_null()); + } + } else { + for (int64_t i = 0; i < block.length; ++i, ++position) { + if (bit_util::GetBit(bitmap, offset + position)) { + ARROW_RETURN_NOT_OK(visit_not_null(position)); + } else { + ARROW_RETURN_NOT_OK(visit_null()); + } + } + } + } + return Status::OK(); +} + +template +static void VisitBitBlocksVoid(const uint8_t* bitmap, int64_t offset, int64_t length, + VisitNotNull&& visit_not_null, VisitNull&& visit_null) { + internal::OptionalBitBlockCounter bit_counter(bitmap, offset, length); + int64_t position = 0; + while (position < length) { + internal::BitBlockCount block = bit_counter.NextBlock(); + if (block.AllSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + visit_not_null(position); + } + } else if (block.NoneSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + visit_null(); + } + } else { + for (int64_t i = 0; i < block.length; ++i, ++position) { + if (bit_util::GetBit(bitmap, offset + position)) { + visit_not_null(position); + } else { + visit_null(); + } + } + } + } +} + +template +static Status VisitTwoBitBlocks(const uint8_t* left_bitmap, int64_t left_offset, + const uint8_t* right_bitmap, int64_t right_offset, + int64_t length, VisitNotNull&& visit_not_null, + VisitNull&& visit_null) { + if (left_bitmap == NULLPTR || right_bitmap == NULLPTR) { + // At most one bitmap is present + if (left_bitmap == NULLPTR) { + return VisitBitBlocks(right_bitmap, right_offset, length, + std::forward(visit_not_null), + std::forward(visit_null)); + } else { + return VisitBitBlocks(left_bitmap, left_offset, length, + std::forward(visit_not_null), + std::forward(visit_null)); + } + } + BinaryBitBlockCounter bit_counter(left_bitmap, left_offset, right_bitmap, right_offset, + length); + int64_t position = 0; + while (position < length) { + BitBlockCount block = bit_counter.NextAndWord(); + if (block.AllSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + ARROW_RETURN_NOT_OK(visit_not_null(position)); + } + } else if (block.NoneSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + ARROW_RETURN_NOT_OK(visit_null()); + } + } else { + for (int64_t i = 0; i < block.length; ++i, ++position) { + if (bit_util::GetBit(left_bitmap, left_offset + position) && + bit_util::GetBit(right_bitmap, right_offset + position)) { + ARROW_RETURN_NOT_OK(visit_not_null(position)); + } else { + ARROW_RETURN_NOT_OK(visit_null()); + } + } + } + } + return Status::OK(); +} + +template +static void VisitTwoBitBlocksVoid(const uint8_t* left_bitmap, int64_t left_offset, + const uint8_t* right_bitmap, int64_t right_offset, + int64_t length, VisitNotNull&& visit_not_null, + VisitNull&& visit_null) { + if (left_bitmap == NULLPTR || right_bitmap == NULLPTR) { + // At most one bitmap is present + if (left_bitmap == NULLPTR) { + return VisitBitBlocksVoid(right_bitmap, right_offset, length, + std::forward(visit_not_null), + std::forward(visit_null)); + } else { + return VisitBitBlocksVoid(left_bitmap, left_offset, length, + std::forward(visit_not_null), + std::forward(visit_null)); + } + } + BinaryBitBlockCounter bit_counter(left_bitmap, left_offset, right_bitmap, right_offset, + length); + int64_t position = 0; + while (position < length) { + BitBlockCount block = bit_counter.NextAndWord(); + if (block.AllSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + visit_not_null(position); + } + } else if (block.NoneSet()) { + for (int64_t i = 0; i < block.length; ++i, ++position) { + visit_null(); + } + } else { + for (int64_t i = 0; i < block.length; ++i, ++position) { + if (bit_util::GetBit(left_bitmap, left_offset + position) && + bit_util::GetBit(right_bitmap, right_offset + position)) { + visit_not_null(position); + } else { + visit_null(); + } + } + } + } +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_stream_utils.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_stream_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..2afb2e5193697f5278427d1434afa620e1e018a8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bit_stream_utils.h @@ -0,0 +1,529 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// From Apache Impala (incubating) as of 2016-01-29 + +#pragma once + +#include +#include +#include + +#include "arrow/util/bit_util.h" +#include "arrow/util/bpacking.h" +#include "arrow/util/logging.h" +#include "arrow/util/macros.h" +#include "arrow/util/ubsan.h" + +namespace arrow { +namespace bit_util { + +/// Utility class to write bit/byte streams. This class can write data to either be +/// bit packed or byte aligned (and a single stream that has a mix of both). +/// This class does not allocate memory. +class BitWriter { + public: + /// buffer: buffer to write bits to. Buffer should be preallocated with + /// 'buffer_len' bytes. + BitWriter(uint8_t* buffer, int buffer_len) : buffer_(buffer), max_bytes_(buffer_len) { + Clear(); + } + + void Clear() { + buffered_values_ = 0; + byte_offset_ = 0; + bit_offset_ = 0; + } + + /// The number of current bytes written, including the current byte (i.e. may include a + /// fraction of a byte). Includes buffered values. + int bytes_written() const { + return byte_offset_ + static_cast(bit_util::BytesForBits(bit_offset_)); + } + uint8_t* buffer() const { return buffer_; } + int buffer_len() const { return max_bytes_; } + + /// Writes a value to buffered_values_, flushing to buffer_ if necessary. This is bit + /// packed. Returns false if there was not enough space. num_bits must be <= 32. + bool PutValue(uint64_t v, int num_bits); + + /// Writes v to the next aligned byte using num_bytes. If T is larger than + /// num_bytes, the extra high-order bytes will be ignored. Returns false if + /// there was not enough space. + /// Assume the v is stored in buffer_ as a little-endian format + template + bool PutAligned(T v, int num_bytes); + + /// Write a Vlq encoded int to the buffer. Returns false if there was not enough + /// room. The value is written byte aligned. + /// For more details on vlq: + /// en.wikipedia.org/wiki/Variable-length_quantity + bool PutVlqInt(uint32_t v); + + // Writes an int zigzag encoded. + bool PutZigZagVlqInt(int32_t v); + + /// Write a Vlq encoded int64 to the buffer. Returns false if there was not enough + /// room. The value is written byte aligned. + /// For more details on vlq: + /// en.wikipedia.org/wiki/Variable-length_quantity + bool PutVlqInt(uint64_t v); + + // Writes an int64 zigzag encoded. + bool PutZigZagVlqInt(int64_t v); + + /// Get a pointer to the next aligned byte and advance the underlying buffer + /// by num_bytes. + /// Returns NULL if there was not enough space. + uint8_t* GetNextBytePtr(int num_bytes = 1); + + /// Flushes all buffered values to the buffer. Call this when done writing to + /// the buffer. If 'align' is true, buffered_values_ is reset and any future + /// writes will be written to the next byte boundary. + void Flush(bool align = false); + + private: + uint8_t* buffer_; + int max_bytes_; + + /// Bit-packed values are initially written to this variable before being memcpy'd to + /// buffer_. This is faster than writing values byte by byte directly to buffer_. + uint64_t buffered_values_; + + int byte_offset_; // Offset in buffer_ + int bit_offset_; // Offset in buffered_values_ +}; + +namespace detail { + +inline uint64_t ReadLittleEndianWord(const uint8_t* buffer, int bytes_remaining) { + uint64_t le_value = 0; + if (ARROW_PREDICT_TRUE(bytes_remaining >= 8)) { + memcpy(&le_value, buffer, 8); + } else { + memcpy(&le_value, buffer, bytes_remaining); + } + return arrow::bit_util::FromLittleEndian(le_value); +} + +} // namespace detail + +/// Utility class to read bit/byte stream. This class can read bits or bytes +/// that are either byte aligned or not. It also has utilities to read multiple +/// bytes in one read (e.g. encoded int). +class BitReader { + public: + BitReader() = default; + + /// 'buffer' is the buffer to read from. The buffer's length is 'buffer_len'. + BitReader(const uint8_t* buffer, int buffer_len) : BitReader() { + Reset(buffer, buffer_len); + } + + void Reset(const uint8_t* buffer, int buffer_len) { + buffer_ = buffer; + max_bytes_ = buffer_len; + byte_offset_ = 0; + bit_offset_ = 0; + buffered_values_ = + detail::ReadLittleEndianWord(buffer_ + byte_offset_, max_bytes_ - byte_offset_); + } + + /// Gets the next value from the buffer. Returns true if 'v' could be read or false if + /// there are not enough bytes left. + template + bool GetValue(int num_bits, T* v); + + /// Get a number of values from the buffer. Return the number of values actually read. + template + int GetBatch(int num_bits, T* v, int batch_size); + + /// Reads a 'num_bytes'-sized value from the buffer and stores it in 'v'. T + /// needs to be a little-endian native type and big enough to store + /// 'num_bytes'. The value is assumed to be byte-aligned so the stream will + /// be advanced to the start of the next byte before 'v' is read. Returns + /// false if there are not enough bytes left. + /// Assume the v was stored in buffer_ as a little-endian format + template + bool GetAligned(int num_bytes, T* v); + + /// Advances the stream by a number of bits. Returns true if succeed or false if there + /// are not enough bits left. + bool Advance(int64_t num_bits); + + /// Reads a vlq encoded int from the stream. The encoded int must start at + /// the beginning of a byte. Return false if there were not enough bytes in + /// the buffer. + bool GetVlqInt(uint32_t* v); + + // Reads a zigzag encoded int `into` v. + bool GetZigZagVlqInt(int32_t* v); + + /// Reads a vlq encoded int64 from the stream. The encoded int must start at + /// the beginning of a byte. Return false if there were not enough bytes in + /// the buffer. + bool GetVlqInt(uint64_t* v); + + // Reads a zigzag encoded int64 `into` v. + bool GetZigZagVlqInt(int64_t* v); + + /// Returns the number of bytes left in the stream, not including the current + /// byte (i.e., there may be an additional fraction of a byte). + int bytes_left() { + return max_bytes_ - + (byte_offset_ + static_cast(bit_util::BytesForBits(bit_offset_))); + } + + /// Maximum byte length of a vlq encoded int + static constexpr int kMaxVlqByteLength = 5; + + /// Maximum byte length of a vlq encoded int64 + static constexpr int kMaxVlqByteLengthForInt64 = 10; + + private: + const uint8_t* buffer_; + int max_bytes_; + + /// Bytes are memcpy'd from buffer_ and values are read from this variable. This is + /// faster than reading values byte by byte directly from buffer_. + uint64_t buffered_values_; + + int byte_offset_; // Offset in buffer_ + int bit_offset_; // Offset in buffered_values_ +}; + +inline bool BitWriter::PutValue(uint64_t v, int num_bits) { + DCHECK_LE(num_bits, 64); + if (num_bits < 64) { + DCHECK_EQ(v >> num_bits, 0) << "v = " << v << ", num_bits = " << num_bits; + } + + if (ARROW_PREDICT_FALSE(byte_offset_ * 8 + bit_offset_ + num_bits > max_bytes_ * 8)) + return false; + + buffered_values_ |= v << bit_offset_; + bit_offset_ += num_bits; + + if (ARROW_PREDICT_FALSE(bit_offset_ >= 64)) { + // Flush buffered_values_ and write out bits of v that did not fit + buffered_values_ = arrow::bit_util::ToLittleEndian(buffered_values_); + memcpy(buffer_ + byte_offset_, &buffered_values_, 8); + buffered_values_ = 0; + byte_offset_ += 8; + bit_offset_ -= 64; + buffered_values_ = + (num_bits - bit_offset_ == 64) ? 0 : (v >> (num_bits - bit_offset_)); + } + DCHECK_LT(bit_offset_, 64); + return true; +} + +inline void BitWriter::Flush(bool align) { + int num_bytes = static_cast(bit_util::BytesForBits(bit_offset_)); + DCHECK_LE(byte_offset_ + num_bytes, max_bytes_); + auto buffered_values = arrow::bit_util::ToLittleEndian(buffered_values_); + memcpy(buffer_ + byte_offset_, &buffered_values, num_bytes); + + if (align) { + buffered_values_ = 0; + byte_offset_ += num_bytes; + bit_offset_ = 0; + } +} + +inline uint8_t* BitWriter::GetNextBytePtr(int num_bytes) { + Flush(/* align */ true); + DCHECK_LE(byte_offset_, max_bytes_); + if (byte_offset_ + num_bytes > max_bytes_) return NULL; + uint8_t* ptr = buffer_ + byte_offset_; + byte_offset_ += num_bytes; + return ptr; +} + +template +inline bool BitWriter::PutAligned(T val, int num_bytes) { + uint8_t* ptr = GetNextBytePtr(num_bytes); + if (ptr == NULL) return false; + val = arrow::bit_util::ToLittleEndian(val); + memcpy(ptr, &val, num_bytes); + return true; +} + +namespace detail { + +template +inline void GetValue_(int num_bits, T* v, int max_bytes, const uint8_t* buffer, + int* bit_offset, int* byte_offset, uint64_t* buffered_values) { +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4800) +#endif + *v = static_cast(bit_util::TrailingBits(*buffered_values, *bit_offset + num_bits) >> + *bit_offset); +#ifdef _MSC_VER +#pragma warning(pop) +#endif + *bit_offset += num_bits; + if (*bit_offset >= 64) { + *byte_offset += 8; + *bit_offset -= 64; + + *buffered_values = + detail::ReadLittleEndianWord(buffer + *byte_offset, max_bytes - *byte_offset); +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4800 4805) +#endif + // Read bits of v that crossed into new buffered_values_ + if (ARROW_PREDICT_TRUE(num_bits - *bit_offset < static_cast(8 * sizeof(T)))) { + // if shift exponent(num_bits - *bit_offset) is not less than sizeof(T), *v will not + // change and the following code may cause a runtime error that the shift exponent + // is too large + *v = *v | static_cast(bit_util::TrailingBits(*buffered_values, *bit_offset) + << (num_bits - *bit_offset)); + } +#ifdef _MSC_VER +#pragma warning(pop) +#endif + DCHECK_LE(*bit_offset, 64); + } +} + +} // namespace detail + +template +inline bool BitReader::GetValue(int num_bits, T* v) { + return GetBatch(num_bits, v, 1) == 1; +} + +template +inline int BitReader::GetBatch(int num_bits, T* v, int batch_size) { + DCHECK(buffer_ != NULL); + DCHECK_LE(num_bits, static_cast(sizeof(T) * 8)) << "num_bits: " << num_bits; + + int bit_offset = bit_offset_; + int byte_offset = byte_offset_; + uint64_t buffered_values = buffered_values_; + int max_bytes = max_bytes_; + const uint8_t* buffer = buffer_; + + const int64_t needed_bits = num_bits * static_cast(batch_size); + constexpr uint64_t kBitsPerByte = 8; + const int64_t remaining_bits = + static_cast(max_bytes - byte_offset) * kBitsPerByte - bit_offset; + if (remaining_bits < needed_bits) { + batch_size = static_cast(remaining_bits / num_bits); + } + + int i = 0; + if (ARROW_PREDICT_FALSE(bit_offset != 0)) { + for (; i < batch_size && bit_offset != 0; ++i) { + detail::GetValue_(num_bits, &v[i], max_bytes, buffer, &bit_offset, &byte_offset, + &buffered_values); + } + } + + if (sizeof(T) == 4) { + int num_unpacked = + internal::unpack32(reinterpret_cast(buffer + byte_offset), + reinterpret_cast(v + i), batch_size - i, num_bits); + i += num_unpacked; + byte_offset += num_unpacked * num_bits / 8; + } else if (sizeof(T) == 8 && num_bits > 32) { + // Use unpack64 only if num_bits is larger than 32 + // TODO (ARROW-13677): improve the performance of internal::unpack64 + // and remove the restriction of num_bits + int num_unpacked = + internal::unpack64(buffer + byte_offset, reinterpret_cast(v + i), + batch_size - i, num_bits); + i += num_unpacked; + byte_offset += num_unpacked * num_bits / 8; + } else { + // TODO: revisit this limit if necessary + DCHECK_LE(num_bits, 32); + const int buffer_size = 1024; + uint32_t unpack_buffer[buffer_size]; + while (i < batch_size) { + int unpack_size = std::min(buffer_size, batch_size - i); + int num_unpacked = + internal::unpack32(reinterpret_cast(buffer + byte_offset), + unpack_buffer, unpack_size, num_bits); + if (num_unpacked == 0) { + break; + } + for (int k = 0; k < num_unpacked; ++k) { +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4800) +#endif + v[i + k] = static_cast(unpack_buffer[k]); +#ifdef _MSC_VER +#pragma warning(pop) +#endif + } + i += num_unpacked; + byte_offset += num_unpacked * num_bits / 8; + } + } + + buffered_values = + detail::ReadLittleEndianWord(buffer + byte_offset, max_bytes - byte_offset); + + for (; i < batch_size; ++i) { + detail::GetValue_(num_bits, &v[i], max_bytes, buffer, &bit_offset, &byte_offset, + &buffered_values); + } + + bit_offset_ = bit_offset; + byte_offset_ = byte_offset; + buffered_values_ = buffered_values; + + return batch_size; +} + +template +inline bool BitReader::GetAligned(int num_bytes, T* v) { + if (ARROW_PREDICT_FALSE(num_bytes > static_cast(sizeof(T)))) { + return false; + } + + int bytes_read = static_cast(bit_util::BytesForBits(bit_offset_)); + if (ARROW_PREDICT_FALSE(byte_offset_ + bytes_read + num_bytes > max_bytes_)) { + return false; + } + + // Advance byte_offset to next unread byte and read num_bytes + byte_offset_ += bytes_read; + if constexpr (std::is_same_v) { + // ARROW-18031: if we're trying to get an aligned bool, just check + // the LSB of the next byte and move on. If we memcpy + FromLittleEndian + // as usual, we have potential undefined behavior for bools if the value + // isn't 0 or 1 + *v = *(buffer_ + byte_offset_) & 1; + } else { + memcpy(v, buffer_ + byte_offset_, num_bytes); + *v = arrow::bit_util::FromLittleEndian(*v); + } + byte_offset_ += num_bytes; + + bit_offset_ = 0; + buffered_values_ = + detail::ReadLittleEndianWord(buffer_ + byte_offset_, max_bytes_ - byte_offset_); + return true; +} + +inline bool BitReader::Advance(int64_t num_bits) { + int64_t bits_required = bit_offset_ + num_bits; + int64_t bytes_required = bit_util::BytesForBits(bits_required); + if (ARROW_PREDICT_FALSE(bytes_required > max_bytes_ - byte_offset_)) { + return false; + } + byte_offset_ += static_cast(bits_required >> 3); + bit_offset_ = static_cast(bits_required & 7); + buffered_values_ = + detail::ReadLittleEndianWord(buffer_ + byte_offset_, max_bytes_ - byte_offset_); + return true; +} + +inline bool BitWriter::PutVlqInt(uint32_t v) { + bool result = true; + while ((v & 0xFFFFFF80UL) != 0UL) { + result &= PutAligned(static_cast((v & 0x7F) | 0x80), 1); + v >>= 7; + } + result &= PutAligned(static_cast(v & 0x7F), 1); + return result; +} + +inline bool BitReader::GetVlqInt(uint32_t* v) { + uint32_t tmp = 0; + + for (int i = 0; i < kMaxVlqByteLength; i++) { + uint8_t byte = 0; + if (ARROW_PREDICT_FALSE(!GetAligned(1, &byte))) { + return false; + } + tmp |= static_cast(byte & 0x7F) << (7 * i); + + if ((byte & 0x80) == 0) { + *v = tmp; + return true; + } + } + + return false; +} + +inline bool BitWriter::PutZigZagVlqInt(int32_t v) { + uint32_t u_v = ::arrow::util::SafeCopy(v); + u_v = (u_v << 1) ^ static_cast(v >> 31); + return PutVlqInt(u_v); +} + +inline bool BitReader::GetZigZagVlqInt(int32_t* v) { + uint32_t u; + if (!GetVlqInt(&u)) return false; + u = (u >> 1) ^ (~(u & 1) + 1); + *v = ::arrow::util::SafeCopy(u); + return true; +} + +inline bool BitWriter::PutVlqInt(uint64_t v) { + bool result = true; + while ((v & 0xFFFFFFFFFFFFFF80ULL) != 0ULL) { + result &= PutAligned(static_cast((v & 0x7F) | 0x80), 1); + v >>= 7; + } + result &= PutAligned(static_cast(v & 0x7F), 1); + return result; +} + +inline bool BitReader::GetVlqInt(uint64_t* v) { + uint64_t tmp = 0; + + for (int i = 0; i < kMaxVlqByteLengthForInt64; i++) { + uint8_t byte = 0; + if (ARROW_PREDICT_FALSE(!GetAligned(1, &byte))) { + return false; + } + tmp |= static_cast(byte & 0x7F) << (7 * i); + + if ((byte & 0x80) == 0) { + *v = tmp; + return true; + } + } + + return false; +} + +inline bool BitWriter::PutZigZagVlqInt(int64_t v) { + uint64_t u_v = ::arrow::util::SafeCopy(v); + u_v = (u_v << 1) ^ static_cast(v >> 63); + return PutVlqInt(u_v); +} + +inline bool BitReader::GetZigZagVlqInt(int64_t* v) { + uint64_t u; + if (!GetVlqInt(&u)) return false; + u = (u >> 1) ^ (~(u & 1) + 1); + *v = ::arrow::util::SafeCopy(u); + return true; +} + +} // namespace bit_util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_reader.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_reader.h new file mode 100644 index 0000000000000000000000000000000000000000..5526c87dbcaf2d6fc69709d6853d7dbbb351f044 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_reader.h @@ -0,0 +1,273 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/endian.h" +#include "arrow/util/macros.h" + +namespace arrow { +namespace internal { + +class BitmapReader { + public: + BitmapReader(const uint8_t* bitmap, int64_t start_offset, int64_t length) + : bitmap_(bitmap), position_(0), length_(length) { + current_byte_ = 0; + byte_offset_ = start_offset / 8; + bit_offset_ = start_offset % 8; + if (length > 0) { + current_byte_ = bitmap[byte_offset_]; + } + } + + bool IsSet() const { return (current_byte_ & (1 << bit_offset_)) != 0; } + + bool IsNotSet() const { return (current_byte_ & (1 << bit_offset_)) == 0; } + + void Next() { + ++bit_offset_; + ++position_; + if (ARROW_PREDICT_FALSE(bit_offset_ == 8)) { + bit_offset_ = 0; + ++byte_offset_; + if (ARROW_PREDICT_TRUE(position_ < length_)) { + current_byte_ = bitmap_[byte_offset_]; + } + } + } + + int64_t position() const { return position_; } + + int64_t length() const { return length_; } + + private: + const uint8_t* bitmap_; + int64_t position_; + int64_t length_; + + uint8_t current_byte_; + int64_t byte_offset_; + int64_t bit_offset_; +}; + +// XXX Cannot name it BitmapWordReader because the name is already used +// in bitmap_ops.cc + +class BitmapUInt64Reader { + public: + BitmapUInt64Reader(const uint8_t* bitmap, int64_t start_offset, int64_t length) + : bitmap_(util::MakeNonNull(bitmap) + start_offset / 8), + num_carry_bits_(8 - start_offset % 8), + length_(length), + remaining_length_(length_), + carry_bits_(0) { + if (length_ > 0) { + // Load carry bits from the first byte's MSBs + if (length_ >= num_carry_bits_) { + carry_bits_ = + LoadPartialWord(static_cast(8 - num_carry_bits_), num_carry_bits_); + } else { + carry_bits_ = LoadPartialWord(static_cast(8 - num_carry_bits_), length_); + } + } + } + + uint64_t NextWord() { + if (ARROW_PREDICT_TRUE(remaining_length_ >= 64 + num_carry_bits_)) { + // We can load a full word + uint64_t next_word = LoadFullWord(); + // Carry bits come first, then the (64 - num_carry_bits_) LSBs from next_word + uint64_t word = carry_bits_ | (next_word << num_carry_bits_); + carry_bits_ = next_word >> (64 - num_carry_bits_); + remaining_length_ -= 64; + return word; + } else if (remaining_length_ > num_carry_bits_) { + // We can load a partial word + uint64_t next_word = + LoadPartialWord(/*bit_offset=*/0, remaining_length_ - num_carry_bits_); + uint64_t word = carry_bits_ | (next_word << num_carry_bits_); + carry_bits_ = next_word >> (64 - num_carry_bits_); + remaining_length_ = std::max(remaining_length_ - 64, 0); + return word; + } else { + remaining_length_ = 0; + return carry_bits_; + } + } + + int64_t position() const { return length_ - remaining_length_; } + + int64_t length() const { return length_; } + + private: + uint64_t LoadFullWord() { + uint64_t word; + memcpy(&word, bitmap_, 8); + bitmap_ += 8; + return bit_util::ToLittleEndian(word); + } + + uint64_t LoadPartialWord(int8_t bit_offset, int64_t num_bits) { + uint64_t word = 0; + const int64_t num_bytes = bit_util::BytesForBits(num_bits); + memcpy(&word, bitmap_, num_bytes); + bitmap_ += num_bytes; + return (bit_util::ToLittleEndian(word) >> bit_offset) & + bit_util::LeastSignificantBitMask(num_bits); + } + + const uint8_t* bitmap_; + const int64_t num_carry_bits_; // in [1, 8] + const int64_t length_; + int64_t remaining_length_; + uint64_t carry_bits_; +}; + +// BitmapWordReader here is faster than BitmapUInt64Reader (in bitmap_reader.h) +// on sufficiently large inputs. However, it has a larger prolog / epilog overhead +// and should probably not be used for small bitmaps. + +template +class BitmapWordReader { + public: + BitmapWordReader() = default; + BitmapWordReader(const uint8_t* bitmap, int64_t offset, int64_t length) + : offset_(static_cast(may_have_byte_offset) * (offset % 8)), + bitmap_(bitmap + offset / 8), + bitmap_end_(bitmap_ + bit_util::BytesForBits(offset_ + length)) { + // decrement word count by one as we may touch two adjacent words in one iteration + nwords_ = length / (sizeof(Word) * 8) - 1; + if (nwords_ < 0) { + nwords_ = 0; + } + trailing_bits_ = static_cast(length - nwords_ * sizeof(Word) * 8); + trailing_bytes_ = static_cast(bit_util::BytesForBits(trailing_bits_)); + + if (nwords_ > 0) { + current_data.word_ = load(bitmap_); + } else if (length > 0) { + current_data.epi.byte_ = load(bitmap_); + } + } + + Word NextWord() { + bitmap_ += sizeof(Word); + const Word next_word = load(bitmap_); + Word word = current_data.word_; + if (may_have_byte_offset && offset_) { + // combine two adjacent words into one word + // |<------ next ----->|<---- current ---->| + // +-------------+-----+-------------+-----+ + // | --- | A | B | --- | + // +-------------+-----+-------------+-----+ + // | | offset + // v v + // +-----+-------------+ + // | A | B | + // +-----+-------------+ + // |<------ word ----->| + word >>= offset_; + word |= next_word << (sizeof(Word) * 8 - offset_); + } + current_data.word_ = next_word; + return word; + } + + uint8_t NextTrailingByte(int& valid_bits) { + uint8_t byte; + assert(trailing_bits_ > 0); + + if (trailing_bits_ <= 8) { + // last byte + valid_bits = trailing_bits_; + trailing_bits_ = 0; + byte = 0; + internal::BitmapReader reader(bitmap_, offset_, valid_bits); + for (int i = 0; i < valid_bits; ++i) { + byte >>= 1; + if (reader.IsSet()) { + byte |= 0x80; + } + reader.Next(); + } + byte >>= (8 - valid_bits); + } else { + ++bitmap_; + const uint8_t next_byte = load(bitmap_); + byte = current_data.epi.byte_; + if (may_have_byte_offset && offset_) { + byte >>= offset_; + byte |= next_byte << (8 - offset_); + } + current_data.epi.byte_ = next_byte; + trailing_bits_ -= 8; + trailing_bytes_--; + valid_bits = 8; + } + return byte; + } + + int64_t words() const { return nwords_; } + int trailing_bytes() const { return trailing_bytes_; } + + private: + int64_t offset_; + const uint8_t* bitmap_; + + const uint8_t* bitmap_end_; + int64_t nwords_; + int trailing_bits_; + int trailing_bytes_; + union { + Word word_; + struct { +#if ARROW_LITTLE_ENDIAN == 0 + uint8_t padding_bytes_[sizeof(Word) - 1]; +#endif + uint8_t byte_; + } epi; + } current_data; + + template + DType load(const uint8_t* bitmap) { + assert(bitmap + sizeof(DType) <= bitmap_end_); + return bit_util::ToLittleEndian(util::SafeLoadAs(bitmap)); + } +}; + +/// \brief Index into a possibly nonexistent bitmap +struct OptionalBitIndexer { + const uint8_t* bitmap; + const int64_t offset; + + explicit OptionalBitIndexer(const uint8_t* buffer = NULLPTR, int64_t offset = 0) + : bitmap(buffer), offset(offset) {} + + bool operator[](int64_t i) const { + return bitmap == NULLPTR || bit_util::GetBit(bitmap, offset + i); + } +}; + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_visit.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_visit.h new file mode 100644 index 0000000000000000000000000000000000000000..c29589013e4b7863705e1de4cf8c69293451eb8b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_visit.h @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/util/bit_util.h" +#include "arrow/util/bitmap_reader.h" + +namespace arrow { +namespace internal { + +// A function that visits each bit in a bitmap and calls a visitor function with a +// boolean representation of that bit. This is intended to be analogous to +// GenerateBits. +template +void VisitBits(const uint8_t* bitmap, int64_t start_offset, int64_t length, + Visitor&& visit) { + BitmapReader reader(bitmap, start_offset, length); + for (int64_t index = 0; index < length; ++index) { + visit(reader.IsSet()); + reader.Next(); + } +} + +// Like VisitBits(), but unrolls its main loop for better performance. +template +void VisitBitsUnrolled(const uint8_t* bitmap, int64_t start_offset, int64_t length, + Visitor&& visit) { + if (length == 0) { + return; + } + + // Start by visiting any bits preceding the first full byte. + int64_t num_bits_before_full_bytes = + bit_util::RoundUpToMultipleOf8(start_offset) - start_offset; + // Truncate num_bits_before_full_bytes if it is greater than length. + if (num_bits_before_full_bytes > length) { + num_bits_before_full_bytes = length; + } + // Use the non loop-unrolled VisitBits since we don't want to add branches + VisitBits(bitmap, start_offset, num_bits_before_full_bytes, visit); + + // Shift the start pointer to the first full byte and compute the + // number of full bytes to be read. + const uint8_t* first_full_byte = bitmap + bit_util::CeilDiv(start_offset, 8); + const int64_t num_full_bytes = (length - num_bits_before_full_bytes) / 8; + + // Iterate over each full byte of the input bitmap and call the visitor in + // a loop-unrolled manner. + for (int64_t byte_index = 0; byte_index < num_full_bytes; ++byte_index) { + // Get the current bit-packed byte value from the bitmap. + const uint8_t byte = *(first_full_byte + byte_index); + + // Execute the visitor function on each bit of the current byte. + visit(bit_util::GetBitFromByte(byte, 0)); + visit(bit_util::GetBitFromByte(byte, 1)); + visit(bit_util::GetBitFromByte(byte, 2)); + visit(bit_util::GetBitFromByte(byte, 3)); + visit(bit_util::GetBitFromByte(byte, 4)); + visit(bit_util::GetBitFromByte(byte, 5)); + visit(bit_util::GetBitFromByte(byte, 6)); + visit(bit_util::GetBitFromByte(byte, 7)); + } + + // Write any leftover bits in the last byte. + const int64_t num_bits_after_full_bytes = (length - num_bits_before_full_bytes) % 8; + VisitBits(first_full_byte + num_full_bytes, 0, num_bits_after_full_bytes, + visit); +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitset_stack.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitset_stack.h new file mode 100644 index 0000000000000000000000000000000000000000..9b334b3605eeee020a2e717b64f530c5ba82bdcd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitset_stack.h @@ -0,0 +1,89 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/memory_pool.h" +#include "arrow/result.h" +#include "arrow/type_fwd.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/compare.h" +#include "arrow/util/functional.h" +#include "arrow/util/macros.h" +#include "arrow/util/string_builder.h" +#include "arrow/util/type_traits.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace internal { + +/// \brief Store a stack of bitsets efficiently. The top bitset may be +/// accessed and its bits may be modified, but it may not be resized. +class BitsetStack { + public: + using reference = typename std::vector::reference; + + /// \brief push a bitset onto the stack + /// \param size number of bits in the next bitset + /// \param value initial value for bits in the pushed bitset + void Push(int size, bool value) { + offsets_.push_back(bit_count()); + bits_.resize(bit_count() + size, value); + } + + /// \brief number of bits in the bitset at the top of the stack + int TopSize() const { + if (offsets_.size() == 0) return 0; + return bit_count() - offsets_.back(); + } + + /// \brief pop a bitset off the stack + void Pop() { + bits_.resize(offsets_.back()); + offsets_.pop_back(); + } + + /// \brief get the value of a bit in the top bitset + /// \param i index of the bit to access + bool operator[](int i) const { return bits_[offsets_.back() + i]; } + + /// \brief get a mutable reference to a bit in the top bitset + /// \param i index of the bit to access + reference operator[](int i) { return bits_[offsets_.back() + i]; } + + private: + int bit_count() const { return static_cast(bits_.size()); } + std::vector bits_; + std::vector offsets_; +}; + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx2.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx2.h new file mode 100644 index 0000000000000000000000000000000000000000..7a7d8bf8c44777f4c9e053c6ee1b086d7d954bd0 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx2.h @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +namespace arrow { +namespace internal { + +int unpack32_avx2(const uint32_t* in, uint32_t* out, int batch_size, int num_bits); + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx512.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx512.h new file mode 100644 index 0000000000000000000000000000000000000000..96723f803e0c1a64ef753ab6a51d8f2bd8c173d1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx512.h @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +namespace arrow { +namespace internal { + +int unpack32_avx512(const uint32_t* in, uint32_t* out, int batch_size, int num_bits); + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_default.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_default.h new file mode 100644 index 0000000000000000000000000000000000000000..4c661dcce3798c737c1d20bce525dcaa88c83078 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_default.h @@ -0,0 +1,4251 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This file was modified from its original version for inclusion in parquet-cpp. +// Original source: +// https://github.com/lemire/FrameOfReference/blob/6ccaf9e97160f9a3b299e23a8ef739e711ef0c71/src/bpacking.cpp +// The original copyright notice follows. + +// This code is released under the +// Apache License Version 2.0 http://www.apache.org/licenses/. +// (c) Daniel Lemire 2013 + +#pragma once + +#include "arrow/util/bit_util.h" +#include "arrow/util/ubsan.h" + +namespace arrow { +namespace internal { + +inline const uint32_t* unpack1_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) & 1; + out++; + *out = (inl >> 1) & 1; + out++; + *out = (inl >> 2) & 1; + out++; + *out = (inl >> 3) & 1; + out++; + *out = (inl >> 4) & 1; + out++; + *out = (inl >> 5) & 1; + out++; + *out = (inl >> 6) & 1; + out++; + *out = (inl >> 7) & 1; + out++; + *out = (inl >> 8) & 1; + out++; + *out = (inl >> 9) & 1; + out++; + *out = (inl >> 10) & 1; + out++; + *out = (inl >> 11) & 1; + out++; + *out = (inl >> 12) & 1; + out++; + *out = (inl >> 13) & 1; + out++; + *out = (inl >> 14) & 1; + out++; + *out = (inl >> 15) & 1; + out++; + *out = (inl >> 16) & 1; + out++; + *out = (inl >> 17) & 1; + out++; + *out = (inl >> 18) & 1; + out++; + *out = (inl >> 19) & 1; + out++; + *out = (inl >> 20) & 1; + out++; + *out = (inl >> 21) & 1; + out++; + *out = (inl >> 22) & 1; + out++; + *out = (inl >> 23) & 1; + out++; + *out = (inl >> 24) & 1; + out++; + *out = (inl >> 25) & 1; + out++; + *out = (inl >> 26) & 1; + out++; + *out = (inl >> 27) & 1; + out++; + *out = (inl >> 28) & 1; + out++; + *out = (inl >> 29) & 1; + out++; + *out = (inl >> 30) & 1; + out++; + *out = (inl >> 31); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack2_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 2); + out++; + *out = (inl >> 2) % (1U << 2); + out++; + *out = (inl >> 4) % (1U << 2); + out++; + *out = (inl >> 6) % (1U << 2); + out++; + *out = (inl >> 8) % (1U << 2); + out++; + *out = (inl >> 10) % (1U << 2); + out++; + *out = (inl >> 12) % (1U << 2); + out++; + *out = (inl >> 14) % (1U << 2); + out++; + *out = (inl >> 16) % (1U << 2); + out++; + *out = (inl >> 18) % (1U << 2); + out++; + *out = (inl >> 20) % (1U << 2); + out++; + *out = (inl >> 22) % (1U << 2); + out++; + *out = (inl >> 24) % (1U << 2); + out++; + *out = (inl >> 26) % (1U << 2); + out++; + *out = (inl >> 28) % (1U << 2); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 2); + out++; + *out = (inl >> 2) % (1U << 2); + out++; + *out = (inl >> 4) % (1U << 2); + out++; + *out = (inl >> 6) % (1U << 2); + out++; + *out = (inl >> 8) % (1U << 2); + out++; + *out = (inl >> 10) % (1U << 2); + out++; + *out = (inl >> 12) % (1U << 2); + out++; + *out = (inl >> 14) % (1U << 2); + out++; + *out = (inl >> 16) % (1U << 2); + out++; + *out = (inl >> 18) % (1U << 2); + out++; + *out = (inl >> 20) % (1U << 2); + out++; + *out = (inl >> 22) % (1U << 2); + out++; + *out = (inl >> 24) % (1U << 2); + out++; + *out = (inl >> 26) % (1U << 2); + out++; + *out = (inl >> 28) % (1U << 2); + out++; + *out = (inl >> 30); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack3_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 3); + out++; + *out = (inl >> 3) % (1U << 3); + out++; + *out = (inl >> 6) % (1U << 3); + out++; + *out = (inl >> 9) % (1U << 3); + out++; + *out = (inl >> 12) % (1U << 3); + out++; + *out = (inl >> 15) % (1U << 3); + out++; + *out = (inl >> 18) % (1U << 3); + out++; + *out = (inl >> 21) % (1U << 3); + out++; + *out = (inl >> 24) % (1U << 3); + out++; + *out = (inl >> 27) % (1U << 3); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (3 - 1); + out++; + *out = (inl >> 1) % (1U << 3); + out++; + *out = (inl >> 4) % (1U << 3); + out++; + *out = (inl >> 7) % (1U << 3); + out++; + *out = (inl >> 10) % (1U << 3); + out++; + *out = (inl >> 13) % (1U << 3); + out++; + *out = (inl >> 16) % (1U << 3); + out++; + *out = (inl >> 19) % (1U << 3); + out++; + *out = (inl >> 22) % (1U << 3); + out++; + *out = (inl >> 25) % (1U << 3); + out++; + *out = (inl >> 28) % (1U << 3); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (3 - 2); + out++; + *out = (inl >> 2) % (1U << 3); + out++; + *out = (inl >> 5) % (1U << 3); + out++; + *out = (inl >> 8) % (1U << 3); + out++; + *out = (inl >> 11) % (1U << 3); + out++; + *out = (inl >> 14) % (1U << 3); + out++; + *out = (inl >> 17) % (1U << 3); + out++; + *out = (inl >> 20) % (1U << 3); + out++; + *out = (inl >> 23) % (1U << 3); + out++; + *out = (inl >> 26) % (1U << 3); + out++; + *out = (inl >> 29); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack4_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 4); + out++; + *out = (inl >> 4) % (1U << 4); + out++; + *out = (inl >> 8) % (1U << 4); + out++; + *out = (inl >> 12) % (1U << 4); + out++; + *out = (inl >> 16) % (1U << 4); + out++; + *out = (inl >> 20) % (1U << 4); + out++; + *out = (inl >> 24) % (1U << 4); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 4); + out++; + *out = (inl >> 4) % (1U << 4); + out++; + *out = (inl >> 8) % (1U << 4); + out++; + *out = (inl >> 12) % (1U << 4); + out++; + *out = (inl >> 16) % (1U << 4); + out++; + *out = (inl >> 20) % (1U << 4); + out++; + *out = (inl >> 24) % (1U << 4); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 4); + out++; + *out = (inl >> 4) % (1U << 4); + out++; + *out = (inl >> 8) % (1U << 4); + out++; + *out = (inl >> 12) % (1U << 4); + out++; + *out = (inl >> 16) % (1U << 4); + out++; + *out = (inl >> 20) % (1U << 4); + out++; + *out = (inl >> 24) % (1U << 4); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 4); + out++; + *out = (inl >> 4) % (1U << 4); + out++; + *out = (inl >> 8) % (1U << 4); + out++; + *out = (inl >> 12) % (1U << 4); + out++; + *out = (inl >> 16) % (1U << 4); + out++; + *out = (inl >> 20) % (1U << 4); + out++; + *out = (inl >> 24) % (1U << 4); + out++; + *out = (inl >> 28); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack5_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 5); + out++; + *out = (inl >> 5) % (1U << 5); + out++; + *out = (inl >> 10) % (1U << 5); + out++; + *out = (inl >> 15) % (1U << 5); + out++; + *out = (inl >> 20) % (1U << 5); + out++; + *out = (inl >> 25) % (1U << 5); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (5 - 3); + out++; + *out = (inl >> 3) % (1U << 5); + out++; + *out = (inl >> 8) % (1U << 5); + out++; + *out = (inl >> 13) % (1U << 5); + out++; + *out = (inl >> 18) % (1U << 5); + out++; + *out = (inl >> 23) % (1U << 5); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (5 - 1); + out++; + *out = (inl >> 1) % (1U << 5); + out++; + *out = (inl >> 6) % (1U << 5); + out++; + *out = (inl >> 11) % (1U << 5); + out++; + *out = (inl >> 16) % (1U << 5); + out++; + *out = (inl >> 21) % (1U << 5); + out++; + *out = (inl >> 26) % (1U << 5); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (5 - 4); + out++; + *out = (inl >> 4) % (1U << 5); + out++; + *out = (inl >> 9) % (1U << 5); + out++; + *out = (inl >> 14) % (1U << 5); + out++; + *out = (inl >> 19) % (1U << 5); + out++; + *out = (inl >> 24) % (1U << 5); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (5 - 2); + out++; + *out = (inl >> 2) % (1U << 5); + out++; + *out = (inl >> 7) % (1U << 5); + out++; + *out = (inl >> 12) % (1U << 5); + out++; + *out = (inl >> 17) % (1U << 5); + out++; + *out = (inl >> 22) % (1U << 5); + out++; + *out = (inl >> 27); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack6_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 6); + out++; + *out = (inl >> 6) % (1U << 6); + out++; + *out = (inl >> 12) % (1U << 6); + out++; + *out = (inl >> 18) % (1U << 6); + out++; + *out = (inl >> 24) % (1U << 6); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (6 - 4); + out++; + *out = (inl >> 4) % (1U << 6); + out++; + *out = (inl >> 10) % (1U << 6); + out++; + *out = (inl >> 16) % (1U << 6); + out++; + *out = (inl >> 22) % (1U << 6); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (6 - 2); + out++; + *out = (inl >> 2) % (1U << 6); + out++; + *out = (inl >> 8) % (1U << 6); + out++; + *out = (inl >> 14) % (1U << 6); + out++; + *out = (inl >> 20) % (1U << 6); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 6); + out++; + *out = (inl >> 6) % (1U << 6); + out++; + *out = (inl >> 12) % (1U << 6); + out++; + *out = (inl >> 18) % (1U << 6); + out++; + *out = (inl >> 24) % (1U << 6); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (6 - 4); + out++; + *out = (inl >> 4) % (1U << 6); + out++; + *out = (inl >> 10) % (1U << 6); + out++; + *out = (inl >> 16) % (1U << 6); + out++; + *out = (inl >> 22) % (1U << 6); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (6 - 2); + out++; + *out = (inl >> 2) % (1U << 6); + out++; + *out = (inl >> 8) % (1U << 6); + out++; + *out = (inl >> 14) % (1U << 6); + out++; + *out = (inl >> 20) % (1U << 6); + out++; + *out = (inl >> 26); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack7_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 7); + out++; + *out = (inl >> 7) % (1U << 7); + out++; + *out = (inl >> 14) % (1U << 7); + out++; + *out = (inl >> 21) % (1U << 7); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (7 - 3); + out++; + *out = (inl >> 3) % (1U << 7); + out++; + *out = (inl >> 10) % (1U << 7); + out++; + *out = (inl >> 17) % (1U << 7); + out++; + *out = (inl >> 24) % (1U << 7); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (7 - 6); + out++; + *out = (inl >> 6) % (1U << 7); + out++; + *out = (inl >> 13) % (1U << 7); + out++; + *out = (inl >> 20) % (1U << 7); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (7 - 2); + out++; + *out = (inl >> 2) % (1U << 7); + out++; + *out = (inl >> 9) % (1U << 7); + out++; + *out = (inl >> 16) % (1U << 7); + out++; + *out = (inl >> 23) % (1U << 7); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (7 - 5); + out++; + *out = (inl >> 5) % (1U << 7); + out++; + *out = (inl >> 12) % (1U << 7); + out++; + *out = (inl >> 19) % (1U << 7); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (7 - 1); + out++; + *out = (inl >> 1) % (1U << 7); + out++; + *out = (inl >> 8) % (1U << 7); + out++; + *out = (inl >> 15) % (1U << 7); + out++; + *out = (inl >> 22) % (1U << 7); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (7 - 4); + out++; + *out = (inl >> 4) % (1U << 7); + out++; + *out = (inl >> 11) % (1U << 7); + out++; + *out = (inl >> 18) % (1U << 7); + out++; + *out = (inl >> 25); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack8_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 8); + out++; + *out = (inl >> 8) % (1U << 8); + out++; + *out = (inl >> 16) % (1U << 8); + out++; + *out = (inl >> 24); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack9_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 9); + out++; + *out = (inl >> 9) % (1U << 9); + out++; + *out = (inl >> 18) % (1U << 9); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (9 - 4); + out++; + *out = (inl >> 4) % (1U << 9); + out++; + *out = (inl >> 13) % (1U << 9); + out++; + *out = (inl >> 22) % (1U << 9); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (9 - 8); + out++; + *out = (inl >> 8) % (1U << 9); + out++; + *out = (inl >> 17) % (1U << 9); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (9 - 3); + out++; + *out = (inl >> 3) % (1U << 9); + out++; + *out = (inl >> 12) % (1U << 9); + out++; + *out = (inl >> 21) % (1U << 9); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (9 - 7); + out++; + *out = (inl >> 7) % (1U << 9); + out++; + *out = (inl >> 16) % (1U << 9); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (9 - 2); + out++; + *out = (inl >> 2) % (1U << 9); + out++; + *out = (inl >> 11) % (1U << 9); + out++; + *out = (inl >> 20) % (1U << 9); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (9 - 6); + out++; + *out = (inl >> 6) % (1U << 9); + out++; + *out = (inl >> 15) % (1U << 9); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (9 - 1); + out++; + *out = (inl >> 1) % (1U << 9); + out++; + *out = (inl >> 10) % (1U << 9); + out++; + *out = (inl >> 19) % (1U << 9); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (9 - 5); + out++; + *out = (inl >> 5) % (1U << 9); + out++; + *out = (inl >> 14) % (1U << 9); + out++; + *out = (inl >> 23); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack10_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 10); + out++; + *out = (inl >> 10) % (1U << 10); + out++; + *out = (inl >> 20) % (1U << 10); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (10 - 8); + out++; + *out = (inl >> 8) % (1U << 10); + out++; + *out = (inl >> 18) % (1U << 10); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (10 - 6); + out++; + *out = (inl >> 6) % (1U << 10); + out++; + *out = (inl >> 16) % (1U << 10); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (10 - 4); + out++; + *out = (inl >> 4) % (1U << 10); + out++; + *out = (inl >> 14) % (1U << 10); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (10 - 2); + out++; + *out = (inl >> 2) % (1U << 10); + out++; + *out = (inl >> 12) % (1U << 10); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 10); + out++; + *out = (inl >> 10) % (1U << 10); + out++; + *out = (inl >> 20) % (1U << 10); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (10 - 8); + out++; + *out = (inl >> 8) % (1U << 10); + out++; + *out = (inl >> 18) % (1U << 10); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (10 - 6); + out++; + *out = (inl >> 6) % (1U << 10); + out++; + *out = (inl >> 16) % (1U << 10); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (10 - 4); + out++; + *out = (inl >> 4) % (1U << 10); + out++; + *out = (inl >> 14) % (1U << 10); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (10 - 2); + out++; + *out = (inl >> 2) % (1U << 10); + out++; + *out = (inl >> 12) % (1U << 10); + out++; + *out = (inl >> 22); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack11_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 11); + out++; + *out = (inl >> 11) % (1U << 11); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (11 - 1); + out++; + *out = (inl >> 1) % (1U << 11); + out++; + *out = (inl >> 12) % (1U << 11); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (11 - 2); + out++; + *out = (inl >> 2) % (1U << 11); + out++; + *out = (inl >> 13) % (1U << 11); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (11 - 3); + out++; + *out = (inl >> 3) % (1U << 11); + out++; + *out = (inl >> 14) % (1U << 11); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (11 - 4); + out++; + *out = (inl >> 4) % (1U << 11); + out++; + *out = (inl >> 15) % (1U << 11); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (11 - 5); + out++; + *out = (inl >> 5) % (1U << 11); + out++; + *out = (inl >> 16) % (1U << 11); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (11 - 6); + out++; + *out = (inl >> 6) % (1U << 11); + out++; + *out = (inl >> 17) % (1U << 11); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (11 - 7); + out++; + *out = (inl >> 7) % (1U << 11); + out++; + *out = (inl >> 18) % (1U << 11); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (11 - 8); + out++; + *out = (inl >> 8) % (1U << 11); + out++; + *out = (inl >> 19) % (1U << 11); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (11 - 9); + out++; + *out = (inl >> 9) % (1U << 11); + out++; + *out = (inl >> 20) % (1U << 11); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (11 - 10); + out++; + *out = (inl >> 10) % (1U << 11); + out++; + *out = (inl >> 21); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack12_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 12); + out++; + *out = (inl >> 12) % (1U << 12); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (12 - 4); + out++; + *out = (inl >> 4) % (1U << 12); + out++; + *out = (inl >> 16) % (1U << 12); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (12 - 8); + out++; + *out = (inl >> 8) % (1U << 12); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 12); + out++; + *out = (inl >> 12) % (1U << 12); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (12 - 4); + out++; + *out = (inl >> 4) % (1U << 12); + out++; + *out = (inl >> 16) % (1U << 12); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (12 - 8); + out++; + *out = (inl >> 8) % (1U << 12); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 12); + out++; + *out = (inl >> 12) % (1U << 12); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (12 - 4); + out++; + *out = (inl >> 4) % (1U << 12); + out++; + *out = (inl >> 16) % (1U << 12); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (12 - 8); + out++; + *out = (inl >> 8) % (1U << 12); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 12); + out++; + *out = (inl >> 12) % (1U << 12); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (12 - 4); + out++; + *out = (inl >> 4) % (1U << 12); + out++; + *out = (inl >> 16) % (1U << 12); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (12 - 8); + out++; + *out = (inl >> 8) % (1U << 12); + out++; + *out = (inl >> 20); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack13_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 13); + out++; + *out = (inl >> 13) % (1U << 13); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (13 - 7); + out++; + *out = (inl >> 7) % (1U << 13); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (13 - 1); + out++; + *out = (inl >> 1) % (1U << 13); + out++; + *out = (inl >> 14) % (1U << 13); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (13 - 8); + out++; + *out = (inl >> 8) % (1U << 13); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (13 - 2); + out++; + *out = (inl >> 2) % (1U << 13); + out++; + *out = (inl >> 15) % (1U << 13); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (13 - 9); + out++; + *out = (inl >> 9) % (1U << 13); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (13 - 3); + out++; + *out = (inl >> 3) % (1U << 13); + out++; + *out = (inl >> 16) % (1U << 13); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (13 - 10); + out++; + *out = (inl >> 10) % (1U << 13); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (13 - 4); + out++; + *out = (inl >> 4) % (1U << 13); + out++; + *out = (inl >> 17) % (1U << 13); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (13 - 11); + out++; + *out = (inl >> 11) % (1U << 13); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (13 - 5); + out++; + *out = (inl >> 5) % (1U << 13); + out++; + *out = (inl >> 18) % (1U << 13); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (13 - 12); + out++; + *out = (inl >> 12) % (1U << 13); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (13 - 6); + out++; + *out = (inl >> 6) % (1U << 13); + out++; + *out = (inl >> 19); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack14_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 14); + out++; + *out = (inl >> 14) % (1U << 14); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (14 - 10); + out++; + *out = (inl >> 10) % (1U << 14); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (14 - 6); + out++; + *out = (inl >> 6) % (1U << 14); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (14 - 2); + out++; + *out = (inl >> 2) % (1U << 14); + out++; + *out = (inl >> 16) % (1U << 14); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (14 - 12); + out++; + *out = (inl >> 12) % (1U << 14); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (14 - 8); + out++; + *out = (inl >> 8) % (1U << 14); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (14 - 4); + out++; + *out = (inl >> 4) % (1U << 14); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 14); + out++; + *out = (inl >> 14) % (1U << 14); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (14 - 10); + out++; + *out = (inl >> 10) % (1U << 14); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (14 - 6); + out++; + *out = (inl >> 6) % (1U << 14); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (14 - 2); + out++; + *out = (inl >> 2) % (1U << 14); + out++; + *out = (inl >> 16) % (1U << 14); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (14 - 12); + out++; + *out = (inl >> 12) % (1U << 14); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (14 - 8); + out++; + *out = (inl >> 8) % (1U << 14); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (14 - 4); + out++; + *out = (inl >> 4) % (1U << 14); + out++; + *out = (inl >> 18); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack15_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 15); + out++; + *out = (inl >> 15) % (1U << 15); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (15 - 13); + out++; + *out = (inl >> 13) % (1U << 15); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (15 - 11); + out++; + *out = (inl >> 11) % (1U << 15); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (15 - 9); + out++; + *out = (inl >> 9) % (1U << 15); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (15 - 7); + out++; + *out = (inl >> 7) % (1U << 15); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (15 - 5); + out++; + *out = (inl >> 5) % (1U << 15); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (15 - 3); + out++; + *out = (inl >> 3) % (1U << 15); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (15 - 1); + out++; + *out = (inl >> 1) % (1U << 15); + out++; + *out = (inl >> 16) % (1U << 15); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (15 - 14); + out++; + *out = (inl >> 14) % (1U << 15); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (15 - 12); + out++; + *out = (inl >> 12) % (1U << 15); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (15 - 10); + out++; + *out = (inl >> 10) % (1U << 15); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (15 - 8); + out++; + *out = (inl >> 8) % (1U << 15); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (15 - 6); + out++; + *out = (inl >> 6) % (1U << 15); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (15 - 4); + out++; + *out = (inl >> 4) % (1U << 15); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (15 - 2); + out++; + *out = (inl >> 2) % (1U << 15); + out++; + *out = (inl >> 17); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack16_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 16); + out++; + *out = (inl >> 16); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack17_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (17 - 2); + out++; + *out = (inl >> 2) % (1U << 17); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (17 - 4); + out++; + *out = (inl >> 4) % (1U << 17); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (17 - 6); + out++; + *out = (inl >> 6) % (1U << 17); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (17 - 8); + out++; + *out = (inl >> 8) % (1U << 17); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (17 - 10); + out++; + *out = (inl >> 10) % (1U << 17); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (17 - 12); + out++; + *out = (inl >> 12) % (1U << 17); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (17 - 14); + out++; + *out = (inl >> 14) % (1U << 17); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (17 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (17 - 1); + out++; + *out = (inl >> 1) % (1U << 17); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (17 - 3); + out++; + *out = (inl >> 3) % (1U << 17); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (17 - 5); + out++; + *out = (inl >> 5) % (1U << 17); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (17 - 7); + out++; + *out = (inl >> 7) % (1U << 17); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (17 - 9); + out++; + *out = (inl >> 9) % (1U << 17); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (17 - 11); + out++; + *out = (inl >> 11) % (1U << 17); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (17 - 13); + out++; + *out = (inl >> 13) % (1U << 17); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (17 - 15); + out++; + *out = (inl >> 15); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack18_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (18 - 4); + out++; + *out = (inl >> 4) % (1U << 18); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (18 - 8); + out++; + *out = (inl >> 8) % (1U << 18); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (18 - 12); + out++; + *out = (inl >> 12) % (1U << 18); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (18 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (18 - 2); + out++; + *out = (inl >> 2) % (1U << 18); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (18 - 6); + out++; + *out = (inl >> 6) % (1U << 18); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (18 - 10); + out++; + *out = (inl >> 10) % (1U << 18); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (18 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (18 - 4); + out++; + *out = (inl >> 4) % (1U << 18); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (18 - 8); + out++; + *out = (inl >> 8) % (1U << 18); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (18 - 12); + out++; + *out = (inl >> 12) % (1U << 18); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (18 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (18 - 2); + out++; + *out = (inl >> 2) % (1U << 18); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (18 - 6); + out++; + *out = (inl >> 6) % (1U << 18); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (18 - 10); + out++; + *out = (inl >> 10) % (1U << 18); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (18 - 14); + out++; + *out = (inl >> 14); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack19_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 19); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (19 - 6); + out++; + *out = (inl >> 6) % (1U << 19); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (19 - 12); + out++; + *out = (inl >> 12) % (1U << 19); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (19 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (19 - 5); + out++; + *out = (inl >> 5) % (1U << 19); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (19 - 11); + out++; + *out = (inl >> 11) % (1U << 19); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 17)) << (19 - 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (19 - 4); + out++; + *out = (inl >> 4) % (1U << 19); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (19 - 10); + out++; + *out = (inl >> 10) % (1U << 19); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (19 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (19 - 3); + out++; + *out = (inl >> 3) % (1U << 19); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (19 - 9); + out++; + *out = (inl >> 9) % (1U << 19); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (19 - 15); + out++; + *out = (inl >> 15); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (19 - 2); + out++; + *out = (inl >> 2) % (1U << 19); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (19 - 8); + out++; + *out = (inl >> 8) % (1U << 19); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (19 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (19 - 1); + out++; + *out = (inl >> 1) % (1U << 19); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (19 - 7); + out++; + *out = (inl >> 7) % (1U << 19); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (19 - 13); + out++; + *out = (inl >> 13); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack20_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (20 - 8); + out++; + *out = (inl >> 8) % (1U << 20); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (20 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (20 - 4); + out++; + *out = (inl >> 4) % (1U << 20); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (20 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (20 - 8); + out++; + *out = (inl >> 8) % (1U << 20); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (20 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (20 - 4); + out++; + *out = (inl >> 4) % (1U << 20); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (20 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (20 - 8); + out++; + *out = (inl >> 8) % (1U << 20); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (20 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (20 - 4); + out++; + *out = (inl >> 4) % (1U << 20); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (20 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (20 - 8); + out++; + *out = (inl >> 8) % (1U << 20); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (20 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (20 - 4); + out++; + *out = (inl >> 4) % (1U << 20); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (20 - 12); + out++; + *out = (inl >> 12); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack21_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 21); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (21 - 10); + out++; + *out = (inl >> 10) % (1U << 21); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (21 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (21 - 9); + out++; + *out = (inl >> 9) % (1U << 21); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 19)) << (21 - 19); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (21 - 8); + out++; + *out = (inl >> 8) % (1U << 21); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (21 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (21 - 7); + out++; + *out = (inl >> 7) % (1U << 21); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 17)) << (21 - 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (21 - 6); + out++; + *out = (inl >> 6) % (1U << 21); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (21 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (21 - 5); + out++; + *out = (inl >> 5) % (1U << 21); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (21 - 15); + out++; + *out = (inl >> 15); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (21 - 4); + out++; + *out = (inl >> 4) % (1U << 21); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (21 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (21 - 3); + out++; + *out = (inl >> 3) % (1U << 21); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (21 - 13); + out++; + *out = (inl >> 13); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (21 - 2); + out++; + *out = (inl >> 2) % (1U << 21); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (21 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (21 - 1); + out++; + *out = (inl >> 1) % (1U << 21); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (21 - 11); + out++; + *out = (inl >> 11); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack22_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (22 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (22 - 2); + out++; + *out = (inl >> 2) % (1U << 22); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (22 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (22 - 4); + out++; + *out = (inl >> 4) % (1U << 22); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (22 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (22 - 6); + out++; + *out = (inl >> 6) % (1U << 22); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (22 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (22 - 8); + out++; + *out = (inl >> 8) % (1U << 22); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (22 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (22 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (22 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (22 - 2); + out++; + *out = (inl >> 2) % (1U << 22); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (22 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (22 - 4); + out++; + *out = (inl >> 4) % (1U << 22); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (22 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (22 - 6); + out++; + *out = (inl >> 6) % (1U << 22); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (22 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (22 - 8); + out++; + *out = (inl >> 8) % (1U << 22); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (22 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (22 - 10); + out++; + *out = (inl >> 10); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack23_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 23); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (23 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (23 - 5); + out++; + *out = (inl >> 5) % (1U << 23); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 19)) << (23 - 19); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (23 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (23 - 1); + out++; + *out = (inl >> 1) % (1U << 23); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (23 - 15); + out++; + *out = (inl >> 15); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (23 - 6); + out++; + *out = (inl >> 6) % (1U << 23); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (23 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (23 - 11); + out++; + *out = (inl >> 11); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (23 - 2); + out++; + *out = (inl >> 2) % (1U << 23); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (23 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (23 - 7); + out++; + *out = (inl >> 7) % (1U << 23); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 21)) << (23 - 21); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (23 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (23 - 3); + out++; + *out = (inl >> 3) % (1U << 23); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 17)) << (23 - 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (23 - 8); + out++; + *out = (inl >> 8) % (1U << 23); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (23 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (23 - 13); + out++; + *out = (inl >> 13); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (23 - 4); + out++; + *out = (inl >> 4) % (1U << 23); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (23 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (23 - 9); + out++; + *out = (inl >> 9); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack24_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (24 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (24 - 8); + out++; + *out = (inl >> 8); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack25_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 25); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (25 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (25 - 11); + out++; + *out = (inl >> 11); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (25 - 4); + out++; + *out = (inl >> 4) % (1U << 25); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (25 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (25 - 15); + out++; + *out = (inl >> 15); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (25 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (25 - 1); + out++; + *out = (inl >> 1) % (1U << 25); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 19)) << (25 - 19); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (25 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (25 - 5); + out++; + *out = (inl >> 5) % (1U << 25); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 23)) << (25 - 23); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (25 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (25 - 9); + out++; + *out = (inl >> 9); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (25 - 2); + out++; + *out = (inl >> 2) % (1U << 25); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (25 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (25 - 13); + out++; + *out = (inl >> 13); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (25 - 6); + out++; + *out = (inl >> 6) % (1U << 25); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (25 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 17)) << (25 - 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (25 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (25 - 3); + out++; + *out = (inl >> 3) % (1U << 25); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 21)) << (25 - 21); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (25 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (25 - 7); + out++; + *out = (inl >> 7); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack26_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 26); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (26 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (26 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (26 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (26 - 2); + out++; + *out = (inl >> 2) % (1U << 26); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (26 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (26 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (26 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (26 - 4); + out++; + *out = (inl >> 4) % (1U << 26); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (26 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (26 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (26 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (26 - 6); + out++; + *out = (inl >> 6); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 26); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (26 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (26 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (26 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (26 - 2); + out++; + *out = (inl >> 2) % (1U << 26); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (26 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (26 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (26 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (26 - 4); + out++; + *out = (inl >> 4) % (1U << 26); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (26 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (26 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (26 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (26 - 6); + out++; + *out = (inl >> 6); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack27_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 27); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (27 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 17)) << (27 - 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (27 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (27 - 7); + out++; + *out = (inl >> 7); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (27 - 2); + out++; + *out = (inl >> 2) % (1U << 27); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (27 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 19)) << (27 - 19); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (27 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (27 - 9); + out++; + *out = (inl >> 9); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (27 - 4); + out++; + *out = (inl >> 4) % (1U << 27); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 26)) << (27 - 26); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 21)) << (27 - 21); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (27 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (27 - 11); + out++; + *out = (inl >> 11); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (27 - 6); + out++; + *out = (inl >> 6); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (27 - 1); + out++; + *out = (inl >> 1) % (1U << 27); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 23)) << (27 - 23); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (27 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (27 - 13); + out++; + *out = (inl >> 13); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (27 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (27 - 3); + out++; + *out = (inl >> 3) % (1U << 27); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 25)) << (27 - 25); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (27 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (27 - 15); + out++; + *out = (inl >> 15); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (27 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (27 - 5); + out++; + *out = (inl >> 5); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack28_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (28 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (28 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (28 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (28 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (28 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (28 - 4); + out++; + *out = (inl >> 4); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (28 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (28 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (28 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (28 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (28 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (28 - 4); + out++; + *out = (inl >> 4); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (28 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (28 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (28 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (28 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (28 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (28 - 4); + out++; + *out = (inl >> 4); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (28 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (28 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (28 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (28 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (28 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (28 - 4); + out++; + *out = (inl >> 4); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack29_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 29); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 26)) << (29 - 26); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 23)) << (29 - 23); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (29 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 17)) << (29 - 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (29 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (29 - 11); + out++; + *out = (inl >> 11); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (29 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (29 - 5); + out++; + *out = (inl >> 5); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (29 - 2); + out++; + *out = (inl >> 2) % (1U << 29); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 28)) << (29 - 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 25)) << (29 - 25); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (29 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 19)) << (29 - 19); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (29 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (29 - 13); + out++; + *out = (inl >> 13); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (29 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (29 - 7); + out++; + *out = (inl >> 7); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (29 - 4); + out++; + *out = (inl >> 4); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (29 - 1); + out++; + *out = (inl >> 1) % (1U << 29); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 27)) << (29 - 27); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (29 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 21)) << (29 - 21); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (29 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (29 - 15); + out++; + *out = (inl >> 15); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (29 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (29 - 9); + out++; + *out = (inl >> 9); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (29 - 6); + out++; + *out = (inl >> 6); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (29 - 3); + out++; + *out = (inl >> 3); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack30_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 30); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 28)) << (30 - 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 26)) << (30 - 26); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (30 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (30 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (30 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (30 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (30 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (30 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (30 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (30 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (30 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (30 - 6); + out++; + *out = (inl >> 6); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (30 - 4); + out++; + *out = (inl >> 4); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (30 - 2); + out++; + *out = (inl >> 2); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0) % (1U << 30); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 28)) << (30 - 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 26)) << (30 - 26); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (30 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (30 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (30 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (30 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (30 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (30 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (30 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (30 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (30 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (30 - 6); + out++; + *out = (inl >> 6); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (30 - 4); + out++; + *out = (inl >> 4); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (30 - 2); + out++; + *out = (inl >> 2); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack31_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0) % (1U << 31); + out++; + *out = (inl >> 31); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 30)) << (31 - 30); + out++; + *out = (inl >> 30); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 29)) << (31 - 29); + out++; + *out = (inl >> 29); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 28)) << (31 - 28); + out++; + *out = (inl >> 28); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 27)) << (31 - 27); + out++; + *out = (inl >> 27); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 26)) << (31 - 26); + out++; + *out = (inl >> 26); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 25)) << (31 - 25); + out++; + *out = (inl >> 25); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 24)) << (31 - 24); + out++; + *out = (inl >> 24); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 23)) << (31 - 23); + out++; + *out = (inl >> 23); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 22)) << (31 - 22); + out++; + *out = (inl >> 22); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 21)) << (31 - 21); + out++; + *out = (inl >> 21); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 20)) << (31 - 20); + out++; + *out = (inl >> 20); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 19)) << (31 - 19); + out++; + *out = (inl >> 19); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 18)) << (31 - 18); + out++; + *out = (inl >> 18); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 17)) << (31 - 17); + out++; + *out = (inl >> 17); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 16)) << (31 - 16); + out++; + *out = (inl >> 16); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 15)) << (31 - 15); + out++; + *out = (inl >> 15); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 14)) << (31 - 14); + out++; + *out = (inl >> 14); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 13)) << (31 - 13); + out++; + *out = (inl >> 13); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 12)) << (31 - 12); + out++; + *out = (inl >> 12); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 11)) << (31 - 11); + out++; + *out = (inl >> 11); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 10)) << (31 - 10); + out++; + *out = (inl >> 10); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 9)) << (31 - 9); + out++; + *out = (inl >> 9); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 8)) << (31 - 8); + out++; + *out = (inl >> 8); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 7)) << (31 - 7); + out++; + *out = (inl >> 7); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 6)) << (31 - 6); + out++; + *out = (inl >> 6); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 5)) << (31 - 5); + out++; + *out = (inl >> 5); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 4)) << (31 - 4); + out++; + *out = (inl >> 4); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 3)) << (31 - 3); + out++; + *out = (inl >> 3); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 2)) << (31 - 2); + out++; + *out = (inl >> 2); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out |= (inl % (1U << 1)) << (31 - 1); + out++; + *out = (inl >> 1); + ++in; + out++; + + return in; +} + +inline const uint32_t* unpack32_32(const uint32_t* in, uint32_t* out) { + uint32_t inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + inl = util::SafeLoad(in); + inl = arrow::bit_util::FromLittleEndian(inl); + out++; + *out = (inl >> 0); + ++in; + out++; + + return in; +} + +inline const uint32_t* nullunpacker32(const uint32_t* in, uint32_t* out) { + for (int k = 0; k < 32; ++k) { + out[k] = 0; + } + return in; +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_neon.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_neon.h new file mode 100644 index 0000000000000000000000000000000000000000..9d02cd568acbc9661f763259e1d4ed134f609e4d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_neon.h @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +namespace arrow { +namespace internal { + +int unpack32_neon(const uint32_t* in, uint32_t* out, int batch_size, int num_bits); + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/byte_size.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/byte_size.h new file mode 100644 index 0000000000000000000000000000000000000000..214c7551b6c76bc95a7d71eb8b8c31bd96d4b838 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/byte_size.h @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/type_fwd.h" + +namespace arrow { + +namespace util { + +/// \brief The sum of bytes in each buffer referenced by the array +/// +/// Note: An array may only reference a portion of a buffer. +/// This method will overestimate in this case and return the +/// byte size of the entire buffer. +/// Note: If a buffer is referenced multiple times then it will +/// only be counted once. +ARROW_EXPORT int64_t TotalBufferSize(const ArrayData& array_data); +/// \brief The sum of bytes in each buffer referenced by the array +/// \see TotalBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT int64_t TotalBufferSize(const Array& array); +/// \brief The sum of bytes in each buffer referenced by the array +/// \see TotalBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT int64_t TotalBufferSize(const ChunkedArray& chunked_array); +/// \brief The sum of bytes in each buffer referenced by the batch +/// \see TotalBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT int64_t TotalBufferSize(const RecordBatch& record_batch); +/// \brief The sum of bytes in each buffer referenced by the table +/// \see TotalBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT int64_t TotalBufferSize(const Table& table); + +/// \brief Calculate the buffer ranges referenced by the array +/// +/// These ranges will take into account array offsets +/// +/// The ranges may contain duplicates +/// +/// Dictionary arrays will ignore the offset of their containing array +/// +/// The return value will be a struct array corresponding to the schema: +/// schema({field("start", uint64()), field("offset", uint64()), field("length", +/// uint64())) +ARROW_EXPORT Result> ReferencedRanges(const ArrayData& array_data); + +/// \brief Returns the sum of bytes from all buffer ranges referenced +/// +/// Unlike TotalBufferSize this method will account for array +/// offsets. +/// +/// If buffers are shared between arrays then the shared +/// portion will be counted multiple times. +/// +/// Dictionary arrays will always be counted in their entirety +/// even if the array only references a portion of the dictionary. +ARROW_EXPORT Result ReferencedBufferSize(const ArrayData& array_data); +/// \brief Returns the sum of bytes from all buffer ranges referenced +/// \see ReferencedBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT Result ReferencedBufferSize(const Array& array_data); +/// \brief Returns the sum of bytes from all buffer ranges referenced +/// \see ReferencedBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT Result ReferencedBufferSize(const ChunkedArray& array_data); +/// \brief Returns the sum of bytes from all buffer ranges referenced +/// \see ReferencedBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT Result ReferencedBufferSize(const RecordBatch& array_data); +/// \brief Returns the sum of bytes from all buffer ranges referenced +/// \see ReferencedBufferSize(const ArrayData& array_data) for details +ARROW_EXPORT Result ReferencedBufferSize(const Table& array_data); + +} // namespace util + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/cancel.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/cancel.h new file mode 100644 index 0000000000000000000000000000000000000000..f0d704b2ce08644064b627639ed536dac21bcd71 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/cancel.h @@ -0,0 +1,118 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class StopToken; + +struct StopSourceImpl; + +/// EXPERIMENTAL +class ARROW_EXPORT StopSource { + public: + StopSource(); + ~StopSource(); + + // Consumer API (the side that stops) + void RequestStop(); + void RequestStop(Status error); + // Async-signal-safe. TODO Deprecate this? + void RequestStopFromSignal(int signum); + + StopToken token(); + + // For internal use only + void Reset(); + + protected: + std::shared_ptr impl_; +}; + +/// EXPERIMENTAL +class ARROW_EXPORT StopToken { + public: + // Public for Cython + StopToken() {} + + explicit StopToken(std::shared_ptr impl) : impl_(std::move(impl)) {} + + // A trivial token that never propagates any stop request + static StopToken Unstoppable() { return StopToken(); } + + /// \brief Check if the stop source has been cancelled. + /// + /// Producers should call this method, whenever convenient, to check and + /// see if they should stop producing early (i.e. have been cancelled). + /// Failure to call this method often enough will lead to an unresponsive + /// cancellation. + /// + /// This is part of the producer API (the side that gets asked to stop) + /// This method is thread-safe + /// + /// \return An OK status if the stop source has not been cancelled or a + /// cancel error if the source has been cancelled. + Status Poll() const; + bool IsStopRequested() const; + + protected: + std::shared_ptr impl_; +}; + +/// EXPERIMENTAL: Set a global StopSource that can receive signals +/// +/// The only allowed order of calls is the following: +/// - SetSignalStopSource() +/// - any number of pairs of (RegisterCancellingSignalHandler, +/// UnregisterCancellingSignalHandler) calls +/// - ResetSignalStopSource() +/// +/// Beware that these settings are process-wide. Typically, only one +/// thread should call these APIs, even in a multithreaded setting. +ARROW_EXPORT +Result SetSignalStopSource(); + +/// EXPERIMENTAL: Reset the global signal-receiving StopSource +/// +/// This will invalidate the pointer returned by SetSignalStopSource. +ARROW_EXPORT +void ResetSignalStopSource(); + +/// EXPERIMENTAL: Register signal handler triggering the signal-receiving StopSource +/// +/// Note that those handlers are automatically un-registered in a fork()ed process, +/// therefore the child process will need to call RegisterCancellingSignalHandler() +/// if desired. +ARROW_EXPORT +Status RegisterCancellingSignalHandler(const std::vector& signals); + +/// EXPERIMENTAL: Unregister signal handler set up by RegisterCancellingSignalHandler +ARROW_EXPORT +void UnregisterCancellingSignalHandler(); + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/compare.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/compare.h new file mode 100644 index 0000000000000000000000000000000000000000..0594b6002ff573afcb420b260c921a78277c9daf --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/compare.h @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/util/macros.h" + +namespace arrow { +namespace util { + +/// CRTP helper for declaring equality comparison. Defines operator== and operator!= +template +class EqualityComparable { + public: + ~EqualityComparable() { + static_assert( + std::is_same().Equals(std::declval())), + bool>::value, + "EqualityComparable depends on the method T::Equals(const T&) const"); + } + + template + bool Equals(const std::shared_ptr& other, Extra&&... extra) const { + if (other == NULLPTR) { + return false; + } + return cast().Equals(*other, std::forward(extra)...); + } + + struct PtrsEqual { + bool operator()(const std::shared_ptr& l, const std::shared_ptr& r) const { + return l->Equals(*r); + } + }; + + friend bool operator==(T const& a, T const& b) { return a.Equals(b); } + friend bool operator!=(T const& a, T const& b) { return !(a == b); } + + private: + const T& cast() const { return static_cast(*this); } +}; + +} // namespace util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/concurrent_map.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/concurrent_map.h new file mode 100644 index 0000000000000000000000000000000000000000..ff1584552a8ffc77fa518002bd285795ec0d1408 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/concurrent_map.h @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/util/mutex.h" + +namespace arrow { +namespace util { + +template +class ConcurrentMap { + public: + void Insert(const K& key, const V& value) { + auto lock = mutex_.Lock(); + map_.insert({key, value}); + } + + template + V GetOrInsert(const K& key, ValueFunc&& compute_value_func) { + auto lock = mutex_.Lock(); + auto it = map_.find(key); + if (it == map_.end()) { + auto pair = map_.emplace(key, compute_value_func()); + it = pair.first; + } + return it->second; + } + + void Erase(const K& key) { + auto lock = mutex_.Lock(); + map_.erase(key); + } + + void Clear() { + auto lock = mutex_.Lock(); + map_.clear(); + } + + size_t size() const { + auto lock = mutex_.Lock(); + return map_.size(); + } + + private: + std::unordered_map map_; + mutable arrow::util::Mutex mutex_; +}; + +} // namespace util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/config.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/config.h new file mode 100644 index 0000000000000000000000000000000000000000..65ab89ab41a845b8e50558661e049913edd14590 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/config.h @@ -0,0 +1,61 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#define ARROW_VERSION_MAJOR 15 +#define ARROW_VERSION_MINOR 0 +#define ARROW_VERSION_PATCH 2 +#define ARROW_VERSION ((ARROW_VERSION_MAJOR * 1000) + ARROW_VERSION_MINOR) * 1000 + ARROW_VERSION_PATCH + +#define ARROW_VERSION_STRING "15.0.2" + +#define ARROW_SO_VERSION "1500" +#define ARROW_FULL_SO_VERSION "1500.2.0" + +#define ARROW_CXX_COMPILER_ID "GNU" +#define ARROW_CXX_COMPILER_VERSION "12.2.1" +#define ARROW_CXX_COMPILER_FLAGS " -fdiagnostics-color=always" + +#define ARROW_BUILD_TYPE "RELEASE" + +#define ARROW_GIT_ID "" +#define ARROW_GIT_DESCRIPTION "" + +#define ARROW_PACKAGE_KIND "python-wheel-manylinux228" + +#define ARROW_COMPUTE +#define ARROW_CSV +/* #undef ARROW_CUDA */ +#define ARROW_DATASET +#define ARROW_FILESYSTEM +#define ARROW_FLIGHT +/* #undef ARROW_FLIGHT_SQL */ +#define ARROW_IPC +#define ARROW_JEMALLOC +#define ARROW_JEMALLOC_VENDORED +#define ARROW_JSON +#define ARROW_ORC +#define ARROW_PARQUET +#define ARROW_SUBSTRAIT + +#define ARROW_ENABLE_THREADING +#define ARROW_GCS +#define ARROW_S3 +#define ARROW_USE_NATIVE_INT128 +/* #undef ARROW_WITH_MUSL */ +/* #undef ARROW_WITH_OPENTELEMETRY */ +/* #undef ARROW_WITH_UCX */ +#define PARQUET_REQUIRE_ENCRYPTION diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/counting_semaphore.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/counting_semaphore.h new file mode 100644 index 0000000000000000000000000000000000000000..a3c13cc3bea4d6be639b521051021f7cb1c07f14 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/counting_semaphore.h @@ -0,0 +1,60 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef ARROW_COUNTING_SEMAPHORE_H +#define ARROW_COUNTING_SEMAPHORE_H + +#include + +#include "arrow/status.h" + +namespace arrow { +namespace util { + +/// \brief Simple mutex-based counting semaphore with timeout +class ARROW_EXPORT CountingSemaphore { + public: + /// \brief Create an instance with initial_avail starting permits + /// + /// \param[in] initial_avail The semaphore will start with this many permits available + /// \param[in] timeout_seconds A timeout to be applied to all operations. Operations + /// will return Status::Invalid if this timeout elapses + explicit CountingSemaphore(uint32_t initial_avail = 0, double timeout_seconds = 10); + ~CountingSemaphore(); + /// \brief Block until num_permits permits are available + Status Acquire(uint32_t num_permits); + /// \brief Make num_permits permits available + Status Release(uint32_t num_permits); + /// \brief Wait until num_waiters are waiting on permits + /// + /// This method is non-standard but useful in unit tests to ensure sequencing + Status WaitForWaiters(uint32_t num_waiters); + /// \brief Immediately time out any waiters + /// + /// This method will return Status::OK only if there were no waiters to time out. + /// Once closed any operation on this instance will return an invalid status. + Status Close(); + + private: + class Impl; + std::unique_ptr impl_; +}; + +} // namespace util +} // namespace arrow + +#endif // ARROW_COUNTING_SEMAPHORE_H diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/cpu_info.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/cpu_info.h new file mode 100644 index 0000000000000000000000000000000000000000..949719b97ed84da6277139a70e22203706ed6055 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/cpu_info.h @@ -0,0 +1,114 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// From Apache Impala (incubating) as of 2016-01-29. Pared down to a minimal +// set of functions needed for Apache Arrow / Apache parquet-cpp + +#pragma once + +#include +#include +#include + +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace internal { + +/// CpuInfo is an interface to query for cpu information at runtime. The caller can +/// ask for the sizes of the caches and what hardware features are supported. +/// On Linux, this information is pulled from a couple of sys files (/proc/cpuinfo and +/// /sys/devices) +class ARROW_EXPORT CpuInfo { + public: + ~CpuInfo(); + + /// x86 features + static constexpr int64_t SSSE3 = (1LL << 0); + static constexpr int64_t SSE4_1 = (1LL << 1); + static constexpr int64_t SSE4_2 = (1LL << 2); + static constexpr int64_t POPCNT = (1LL << 3); + static constexpr int64_t AVX = (1LL << 4); + static constexpr int64_t AVX2 = (1LL << 5); + static constexpr int64_t AVX512F = (1LL << 6); + static constexpr int64_t AVX512CD = (1LL << 7); + static constexpr int64_t AVX512VL = (1LL << 8); + static constexpr int64_t AVX512DQ = (1LL << 9); + static constexpr int64_t AVX512BW = (1LL << 10); + static constexpr int64_t AVX512 = AVX512F | AVX512CD | AVX512VL | AVX512DQ | AVX512BW; + static constexpr int64_t BMI1 = (1LL << 11); + static constexpr int64_t BMI2 = (1LL << 12); + + /// Arm features + static constexpr int64_t ASIMD = (1LL << 32); + + /// Cache enums for L1 (data), L2 and L3 + enum class CacheLevel { L1 = 0, L2, L3, Last = L3 }; + + /// CPU vendors + enum class Vendor { Unknown, Intel, AMD }; + + static const CpuInfo* GetInstance(); + + /// Returns all the flags for this cpu + int64_t hardware_flags() const; + + /// Returns the number of cores (including hyper-threaded) on this machine. + int num_cores() const; + + /// Returns the vendor of the cpu. + Vendor vendor() const; + + /// Returns the model name of the cpu (e.g. Intel i7-2600) + const std::string& model_name() const; + + /// Returns the size of the cache in KB at this cache level + int64_t CacheSize(CacheLevel level) const; + + /// \brief Returns whether or not the given feature is enabled. + /// + /// IsSupported() is true iff IsDetected() is also true and the feature + /// wasn't disabled by the user (for example by setting the ARROW_USER_SIMD_LEVEL + /// environment variable). + bool IsSupported(int64_t flags) const; + + /// Returns whether or not the given feature is available on the CPU. + bool IsDetected(int64_t flags) const; + + /// Determine if the CPU meets the minimum CPU requirements and if not, issue an error + /// and terminate. + void VerifyCpuRequirements() const; + + /// Toggle a hardware feature on and off. It is not valid to turn on a feature + /// that the underlying hardware cannot support. This is useful for testing. + void EnableFeature(int64_t flag, bool enable); + + bool HasEfficientBmi2() const { + // BMI2 (pext, pdep) is only efficient on Intel X86 processors. + return vendor() == Vendor::Intel && IsSupported(BMI2); + } + + private: + CpuInfo(); + + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/decimal.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/decimal.h new file mode 100644 index 0000000000000000000000000000000000000000..345c74d95b1015474cbfc7c2dd932df45107d593 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/decimal.h @@ -0,0 +1,298 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/basic_decimal.h" + +namespace arrow { + +/// Represents a signed 128-bit integer in two's complement. +/// Calculations wrap around and overflow is ignored. +/// The max decimal precision that can be safely represented is +/// 38 significant digits. +/// +/// For a discussion of the algorithms, look at Knuth's volume 2, +/// Semi-numerical Algorithms section 4.3.1. +/// +/// Adapted from the Apache ORC C++ implementation +/// +/// The implementation is split into two parts : +/// +/// 1. BasicDecimal128 +/// - can be safely compiled to IR without references to libstdc++. +/// 2. Decimal128 +/// - has additional functionality on top of BasicDecimal128 to deal with +/// strings and streams. +class ARROW_EXPORT Decimal128 : public BasicDecimal128 { + public: + /// \cond FALSE + // (need to avoid a duplicate definition in Sphinx) + using BasicDecimal128::BasicDecimal128; + /// \endcond + + /// \brief constructor creates a Decimal128 from a BasicDecimal128. + constexpr Decimal128(const BasicDecimal128& value) noexcept // NOLINT runtime/explicit + : BasicDecimal128(value) {} + + /// \brief Parse the number from a base 10 string representation. + explicit Decimal128(const std::string& value); + + /// \brief Empty constructor creates a Decimal128 with a value of 0. + // This is required on some older compilers. + constexpr Decimal128() noexcept : BasicDecimal128() {} + + /// Divide this number by right and return the result. + /// + /// This operation is not destructive. + /// The answer rounds to zero. Signs work like: + /// 21 / 5 -> 4, 1 + /// -21 / 5 -> -4, -1 + /// 21 / -5 -> -4, 1 + /// -21 / -5 -> 4, -1 + /// \param[in] divisor the number to divide by + /// \return the pair of the quotient and the remainder + Result> Divide(const Decimal128& divisor) const { + std::pair result; + auto dstatus = BasicDecimal128::Divide(divisor, &result.first, &result.second); + ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus)); + return std::move(result); + } + + /// \brief Convert the Decimal128 value to a base 10 decimal string with the given + /// scale. + std::string ToString(int32_t scale) const; + + /// \brief Convert the value to an integer string + std::string ToIntegerString() const; + + /// \brief Cast this value to an int64_t. + explicit operator int64_t() const; + + /// \brief Convert a decimal string to a Decimal128 value, optionally including + /// precision and scale if they're passed in and not null. + static Status FromString(std::string_view s, Decimal128* out, int32_t* precision, + int32_t* scale = NULLPTR); + static Status FromString(const std::string& s, Decimal128* out, int32_t* precision, + int32_t* scale = NULLPTR); + static Status FromString(const char* s, Decimal128* out, int32_t* precision, + int32_t* scale = NULLPTR); + static Result FromString(std::string_view s); + static Result FromString(const std::string& s); + static Result FromString(const char* s); + + static Result FromReal(double real, int32_t precision, int32_t scale); + static Result FromReal(float real, int32_t precision, int32_t scale); + + /// \brief Convert from a big-endian byte representation. The length must be + /// between 1 and 16. + /// \return error status if the length is an invalid value + static Result FromBigEndian(const uint8_t* data, int32_t length); + + /// \brief Convert Decimal128 from one scale to another + Result Rescale(int32_t original_scale, int32_t new_scale) const { + Decimal128 out; + auto dstatus = BasicDecimal128::Rescale(original_scale, new_scale, &out); + ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus)); + return std::move(out); + } + + /// \brief Convert to a signed integer + template > + Result ToInteger() const { + constexpr auto min_value = std::numeric_limits::min(); + constexpr auto max_value = std::numeric_limits::max(); + const auto& self = *this; + if (self < min_value || self > max_value) { + return Status::Invalid("Invalid cast from Decimal128 to ", sizeof(T), + " byte integer"); + } + return static_cast(low_bits()); + } + + /// \brief Convert to a signed integer + template > + Status ToInteger(T* out) const { + return ToInteger().Value(out); + } + + /// \brief Convert to a floating-point number (scaled) + float ToFloat(int32_t scale) const; + /// \brief Convert to a floating-point number (scaled) + double ToDouble(int32_t scale) const; + + /// \brief Convert to a floating-point number (scaled) + template >> + T ToReal(int32_t scale) const { + static_assert(std::is_same_v || std::is_same_v, + "Unexpected floating-point type"); + if constexpr (std::is_same_v) { + return ToFloat(scale); + } else { + return ToDouble(scale); + } + } + + ARROW_FRIEND_EXPORT friend std::ostream& operator<<(std::ostream& os, + const Decimal128& decimal); + + private: + /// Converts internal error code to Status + Status ToArrowStatus(DecimalStatus dstatus) const; +}; + +/// Represents a signed 256-bit integer in two's complement. +/// The max decimal precision that can be safely represented is +/// 76 significant digits. +/// +/// The implementation is split into two parts : +/// +/// 1. BasicDecimal256 +/// - can be safely compiled to IR without references to libstdc++. +/// 2. Decimal256 +/// - (TODO) has additional functionality on top of BasicDecimal256 to deal with +/// strings and streams. +class ARROW_EXPORT Decimal256 : public BasicDecimal256 { + public: + /// \cond FALSE + // (need to avoid a duplicate definition in Sphinx) + using BasicDecimal256::BasicDecimal256; + /// \endcond + + /// \brief constructor creates a Decimal256 from a BasicDecimal256. + constexpr Decimal256(const BasicDecimal256& value) noexcept // NOLINT(runtime/explicit) + : BasicDecimal256(value) {} + + /// \brief Parse the number from a base 10 string representation. + explicit Decimal256(const std::string& value); + + /// \brief Empty constructor creates a Decimal256 with a value of 0. + // This is required on some older compilers. + constexpr Decimal256() noexcept : BasicDecimal256() {} + + /// \brief Convert the Decimal256 value to a base 10 decimal string with the given + /// scale. + std::string ToString(int32_t scale) const; + + /// \brief Convert the value to an integer string + std::string ToIntegerString() const; + + /// \brief Convert a decimal string to a Decimal256 value, optionally including + /// precision and scale if they're passed in and not null. + static Status FromString(std::string_view s, Decimal256* out, int32_t* precision, + int32_t* scale = NULLPTR); + static Status FromString(const std::string& s, Decimal256* out, int32_t* precision, + int32_t* scale = NULLPTR); + static Status FromString(const char* s, Decimal256* out, int32_t* precision, + int32_t* scale = NULLPTR); + static Result FromString(std::string_view s); + static Result FromString(const std::string& s); + static Result FromString(const char* s); + + /// \brief Convert Decimal256 from one scale to another + Result Rescale(int32_t original_scale, int32_t new_scale) const { + Decimal256 out; + auto dstatus = BasicDecimal256::Rescale(original_scale, new_scale, &out); + ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus)); + return std::move(out); + } + + /// Divide this number by right and return the result. + /// + /// This operation is not destructive. + /// The answer rounds to zero. Signs work like: + /// 21 / 5 -> 4, 1 + /// -21 / 5 -> -4, -1 + /// 21 / -5 -> -4, 1 + /// -21 / -5 -> 4, -1 + /// \param[in] divisor the number to divide by + /// \return the pair of the quotient and the remainder + Result> Divide(const Decimal256& divisor) const { + std::pair result; + auto dstatus = BasicDecimal256::Divide(divisor, &result.first, &result.second); + ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus)); + return std::move(result); + } + + /// \brief Convert from a big-endian byte representation. The length must be + /// between 1 and 32. + /// \return error status if the length is an invalid value + static Result FromBigEndian(const uint8_t* data, int32_t length); + + static Result FromReal(double real, int32_t precision, int32_t scale); + static Result FromReal(float real, int32_t precision, int32_t scale); + + /// \brief Convert to a floating-point number (scaled). + /// May return infinity in case of overflow. + float ToFloat(int32_t scale) const; + /// \brief Convert to a floating-point number (scaled) + double ToDouble(int32_t scale) const; + + /// \brief Convert to a floating-point number (scaled) + template >> + T ToReal(int32_t scale) const { + static_assert(std::is_same_v || std::is_same_v, + "Unexpected floating-point type"); + if constexpr (std::is_same_v) { + return ToFloat(scale); + } else { + return ToDouble(scale); + } + } + + ARROW_FRIEND_EXPORT friend std::ostream& operator<<(std::ostream& os, + const Decimal256& decimal); + + private: + /// Converts internal error code to Status + Status ToArrowStatus(DecimalStatus dstatus) const; +}; + +/// For an integer type, return the max number of decimal digits +/// (=minimal decimal precision) it can represent. +inline Result MaxDecimalDigitsForInteger(Type::type type_id) { + switch (type_id) { + case Type::INT8: + case Type::UINT8: + return 3; + case Type::INT16: + case Type::UINT16: + return 5; + case Type::INT32: + case Type::UINT32: + return 10; + case Type::INT64: + return 19; + case Type::UINT64: + return 20; + default: + break; + } + return Status::Invalid("Not an integer type: ", type_id); +} + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/dict_util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/dict_util.h new file mode 100644 index 0000000000000000000000000000000000000000..a92733ae0f63d589e8dbb381c020e009c453ab4e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/dict_util.h @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/array/data.h" + +namespace arrow { +namespace dict_util { + +int64_t LogicalNullCount(const ArraySpan& span); + +} // namespace dict_util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/double_conversion.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/double_conversion.h new file mode 100644 index 0000000000000000000000000000000000000000..0b07b1a2b9f295cbe01d02af5eb02775183f059d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/double_conversion.h @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/vendored/double-conversion/double-conversion.h" // IWYU pragma: export + +namespace arrow { +namespace util { +namespace double_conversion { + +using ::arrow_vendored::double_conversion::DoubleToStringConverter; +using ::arrow_vendored::double_conversion::StringBuilder; +using ::arrow_vendored::double_conversion::StringToDoubleConverter; + +} // namespace double_conversion +} // namespace util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/float16.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/float16.h new file mode 100644 index 0000000000000000000000000000000000000000..0a432fee2cd315d23bd35e0907e327efc7f419ca --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/float16.h @@ -0,0 +1,209 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/util/endian.h" +#include "arrow/util/macros.h" +#include "arrow/util/ubsan.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace util { + +/// \brief Class representing an IEEE half-precision float, encoded as a `uint16_t` +/// +/// The exact format is as follows (from LSB to MSB): +/// - bits 0-10: mantissa +/// - bits 10-15: exponent +/// - bit 15: sign +/// +class ARROW_EXPORT Float16 { + public: + Float16() = default; + explicit Float16(float f) : Float16(FromFloat(f)) {} + explicit Float16(double d) : Float16(FromDouble(d)) {} + template >* = NULLPTR> + explicit Float16(T v) : Float16(static_cast(v)) {} + + /// \brief Create a `Float16` from its exact binary representation + constexpr static Float16 FromBits(uint16_t bits) { return Float16{bits, bool{}}; } + /// \brief Create a `Float16` from a 32-bit float (may lose precision) + static Float16 FromFloat(float f); + /// \brief Create a `Float16` from a 64-bit float (may lose precision) + static Float16 FromDouble(double d); + + /// \brief Read a `Float16` from memory in native-endian byte order + static Float16 FromBytes(const uint8_t* src) { + return FromBits(SafeLoadAs(src)); + } + + /// \brief Read a `Float16` from memory in little-endian byte order + static Float16 FromLittleEndian(const uint8_t* src) { + return FromBits(::arrow::bit_util::FromLittleEndian(SafeLoadAs(src))); + } + + /// \brief Read a `Float16` from memory in big-endian byte order + static Float16 FromBigEndian(const uint8_t* src) { + return FromBits(::arrow::bit_util::FromBigEndian(SafeLoadAs(src))); + } + + /// \brief Return the value's binary representation as a `uint16_t` + constexpr uint16_t bits() const { return bits_; } + + /// \brief Return true if the value is negative (sign bit is set) + constexpr bool signbit() const { return (bits_ & 0x8000) != 0; } + + /// \brief Return true if the value is NaN + constexpr bool is_nan() const { return (bits_ & 0x7fff) > 0x7c00; } + /// \brief Return true if the value is positive/negative infinity + constexpr bool is_infinity() const { return (bits_ & 0x7fff) == 0x7c00; } + /// \brief Return true if the value is finite and not NaN + constexpr bool is_finite() const { return (bits_ & 0x7c00) != 0x7c00; } + /// \brief Return true if the value is positive/negative zero + constexpr bool is_zero() const { return (bits_ & 0x7fff) == 0; } + + /// \brief Convert to a 32-bit float + float ToFloat() const; + /// \brief Convert to a 64-bit float + double ToDouble() const; + + explicit operator float() const { return ToFloat(); } + explicit operator double() const { return ToDouble(); } + + /// \brief Copy the value's bytes in native-endian byte order + void ToBytes(uint8_t* dest) const { std::memcpy(dest, &bits_, sizeof(bits_)); } + /// \brief Return the value's bytes in native-endian byte order + constexpr std::array ToBytes() const { +#if ARROW_LITTLE_ENDIAN + return ToLittleEndian(); +#else + return ToBigEndian(); +#endif + } + + /// \brief Copy the value's bytes in little-endian byte order + void ToLittleEndian(uint8_t* dest) const { + const auto bytes = ToLittleEndian(); + std::memcpy(dest, bytes.data(), bytes.size()); + } + /// \brief Return the value's bytes in little-endian byte order + constexpr std::array ToLittleEndian() const { +#if ARROW_LITTLE_ENDIAN + return {uint8_t(bits_ & 0xff), uint8_t(bits_ >> 8)}; +#else + return {uint8_t(bits_ >> 8), uint8_t(bits_ & 0xff)}; +#endif + } + + /// \brief Copy the value's bytes in big-endian byte order + void ToBigEndian(uint8_t* dest) const { + const auto bytes = ToBigEndian(); + std::memcpy(dest, bytes.data(), bytes.size()); + } + /// \brief Return the value's bytes in big-endian byte order + constexpr std::array ToBigEndian() const { +#if ARROW_LITTLE_ENDIAN + return {uint8_t(bits_ >> 8), uint8_t(bits_ & 0xff)}; +#else + return {uint8_t(bits_ & 0xff), uint8_t(bits_ >> 8)}; +#endif + } + + constexpr Float16 operator-() const { return FromBits(bits_ ^ 0x8000); } + constexpr Float16 operator+() const { return FromBits(bits_); } + + friend constexpr bool operator==(Float16 lhs, Float16 rhs) { + if (lhs.is_nan() || rhs.is_nan()) return false; + return Float16::CompareEq(lhs, rhs); + } + friend constexpr bool operator!=(Float16 lhs, Float16 rhs) { return !(lhs == rhs); } + + friend constexpr bool operator<(Float16 lhs, Float16 rhs) { + if (lhs.is_nan() || rhs.is_nan()) return false; + return Float16::CompareLt(lhs, rhs); + } + friend constexpr bool operator>(Float16 lhs, Float16 rhs) { return rhs < lhs; } + + friend constexpr bool operator<=(Float16 lhs, Float16 rhs) { + if (lhs.is_nan() || rhs.is_nan()) return false; + return !Float16::CompareLt(rhs, lhs); + } + friend constexpr bool operator>=(Float16 lhs, Float16 rhs) { return rhs <= lhs; } + + ARROW_FRIEND_EXPORT friend std::ostream& operator<<(std::ostream& os, Float16 arg); + + protected: + uint16_t bits_; + + private: + constexpr Float16(uint16_t bits, bool) : bits_(bits) {} + + // Comparison helpers that assume neither operand is NaN + static constexpr bool CompareEq(Float16 lhs, Float16 rhs) { + return (lhs.bits() == rhs.bits()) || (lhs.is_zero() && rhs.is_zero()); + } + static constexpr bool CompareLt(Float16 lhs, Float16 rhs) { + if (lhs.signbit()) { + if (rhs.signbit()) { + // Both are negative + return lhs.bits() > rhs.bits(); + } else { + // Handle +/-0 + return !lhs.is_zero() || rhs.bits() != 0; + } + } else if (rhs.signbit()) { + return false; + } else { + // Both are positive + return lhs.bits() < rhs.bits(); + } + } +}; + +static_assert(std::is_trivial_v); + +} // namespace util +} // namespace arrow + +// TODO: Not complete +template <> +class std::numeric_limits { + using T = arrow::util::Float16; + + public: + static constexpr bool is_specialized = true; + static constexpr bool is_signed = true; + static constexpr bool has_infinity = true; + static constexpr bool has_quiet_NaN = true; + + static constexpr T min() { return T::FromBits(0b0000010000000000); } + static constexpr T max() { return T::FromBits(0b0111101111111111); } + static constexpr T lowest() { return -max(); } + + static constexpr T infinity() { return T::FromBits(0b0111110000000000); } + + static constexpr T quiet_NaN() { return T::FromBits(0b0111111111111111); } +}; diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/formatting.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/formatting.h new file mode 100644 index 0000000000000000000000000000000000000000..71bae74629e35eb76d30326e7ef15ac85287ddee --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/formatting.h @@ -0,0 +1,644 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This is a private header for number-to-string formatting utilities + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/double_conversion.h" +#include "arrow/util/macros.h" +#include "arrow/util/string.h" +#include "arrow/util/time.h" +#include "arrow/util/visibility.h" +#include "arrow/vendored/datetime.h" + +namespace arrow { +namespace internal { + +/// \brief The entry point for conversion to strings. +template +class StringFormatter; + +template +struct is_formattable { + template ::value_type> + static std::true_type Test(U*); + + template + static std::false_type Test(...); + + static constexpr bool value = decltype(Test(NULLPTR))::value; +}; + +template +using enable_if_formattable = enable_if_t::value, R>; + +template +using Return = decltype(std::declval()(std::string_view{})); + +///////////////////////////////////////////////////////////////////////// +// Boolean formatting + +template <> +class StringFormatter { + public: + explicit StringFormatter(const DataType* = NULLPTR) {} + + using value_type = bool; + + template + Return operator()(bool value, Appender&& append) { + if (value) { + const char string[] = "true"; + return append(std::string_view(string)); + } else { + const char string[] = "false"; + return append(std::string_view(string)); + } + } +}; + +///////////////////////////////////////////////////////////////////////// +// Decimals formatting + +template +class DecimalToStringFormatterMixin { + public: + explicit DecimalToStringFormatterMixin(const DataType* type) + : scale_(static_cast(type)->scale()) {} + + using value_type = typename TypeTraits::CType; + + template + Return operator()(const value_type& value, Appender&& append) { + return append(value.ToString(scale_)); + } + + private: + int32_t scale_; +}; + +template <> +class StringFormatter + : public DecimalToStringFormatterMixin { + using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin; +}; + +template <> +class StringFormatter + : public DecimalToStringFormatterMixin { + using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin; +}; + +///////////////////////////////////////////////////////////////////////// +// Integer formatting + +namespace detail { + +// A 2x100 direct table mapping integers in [0..99] to their decimal representations. +ARROW_EXPORT extern const char digit_pairs[]; + +// Based on fmtlib's format_int class: +// Write digits from right to left into a stack allocated buffer +inline void FormatOneChar(char c, char** cursor) { *--*cursor = c; } + +template +void FormatOneDigit(Int value, char** cursor) { + assert(value >= 0 && value <= 9); + FormatOneChar(static_cast('0' + value), cursor); +} + +// GH-35662: I don't know why but the following combination causes SEGV: +// * template implementation without inline +// * MinGW +// * Release build +template +inline void FormatTwoDigits(Int value, char** cursor) { + assert(value >= 0 && value <= 99); + auto digit_pair = &digit_pairs[value * 2]; + FormatOneChar(digit_pair[1], cursor); + FormatOneChar(digit_pair[0], cursor); +} + +template +void FormatAllDigits(Int value, char** cursor) { + assert(value >= 0); + while (value >= 100) { + FormatTwoDigits(value % 100, cursor); + value /= 100; + } + + if (value >= 10) { + FormatTwoDigits(value, cursor); + } else { + FormatOneDigit(value, cursor); + } +} + +template +void FormatAllDigitsLeftPadded(Int value, size_t pad, char pad_char, char** cursor) { + auto end = *cursor - pad; + FormatAllDigits(value, cursor); + while (*cursor > end) { + FormatOneChar(pad_char, cursor); + } +} + +template +std::string_view ViewDigitBuffer(const std::array& buffer, + char* cursor) { + auto buffer_end = buffer.data() + BUFFER_SIZE; + return {cursor, static_cast(buffer_end - cursor)}; +} + +template ::type> +constexpr UInt Abs(Int value) { + return value < 0 ? ~static_cast(value) + 1 : static_cast(value); +} + +template +constexpr size_t Digits10(Int value) { + return value <= 9 ? 1 : Digits10(value / 10) + 1; +} + +} // namespace detail + +template +class IntToStringFormatterMixin { + public: + explicit IntToStringFormatterMixin(const DataType* = NULLPTR) {} + + using value_type = typename ARROW_TYPE::c_type; + + template + Return operator()(value_type value, Appender&& append) { + constexpr size_t buffer_size = + detail::Digits10(std::numeric_limits::max()) + 1; + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + detail::FormatAllDigits(detail::Abs(value), &cursor); + if (value < 0) { + detail::FormatOneChar('-', &cursor); + } + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +///////////////////////////////////////////////////////////////////////// +// Floating-point formatting + +class ARROW_EXPORT FloatToStringFormatter { + public: + FloatToStringFormatter(); + FloatToStringFormatter(int flags, const char* inf_symbol, const char* nan_symbol, + char exp_character, int decimal_in_shortest_low, + int decimal_in_shortest_high, + int max_leading_padding_zeroes_in_precision_mode, + int max_trailing_padding_zeroes_in_precision_mode); + ~FloatToStringFormatter(); + + // Returns the number of characters written + int FormatFloat(float v, char* out_buffer, int out_size); + int FormatFloat(double v, char* out_buffer, int out_size); + + protected: + struct Impl; + std::unique_ptr impl_; +}; + +template +class FloatToStringFormatterMixin : public FloatToStringFormatter { + public: + using value_type = typename ARROW_TYPE::c_type; + + static constexpr int buffer_size = 50; + + explicit FloatToStringFormatterMixin(const DataType* = NULLPTR) {} + + FloatToStringFormatterMixin(int flags, const char* inf_symbol, const char* nan_symbol, + char exp_character, int decimal_in_shortest_low, + int decimal_in_shortest_high, + int max_leading_padding_zeroes_in_precision_mode, + int max_trailing_padding_zeroes_in_precision_mode) + : FloatToStringFormatter(flags, inf_symbol, nan_symbol, exp_character, + decimal_in_shortest_low, decimal_in_shortest_high, + max_leading_padding_zeroes_in_precision_mode, + max_trailing_padding_zeroes_in_precision_mode) {} + + template + Return operator()(value_type value, Appender&& append) { + char buffer[buffer_size]; + int size = FormatFloat(value, buffer, buffer_size); + return append(std::string_view(buffer, size)); + } +}; + +template <> +class StringFormatter : public FloatToStringFormatterMixin { + public: + using FloatToStringFormatterMixin::FloatToStringFormatterMixin; +}; + +template <> +class StringFormatter : public FloatToStringFormatterMixin { + public: + using FloatToStringFormatterMixin::FloatToStringFormatterMixin; +}; + +///////////////////////////////////////////////////////////////////////// +// Temporal formatting + +namespace detail { + +constexpr size_t BufferSizeYYYY_MM_DD() { + return 1 + detail::Digits10(99999) + 1 + detail::Digits10(12) + 1 + + detail::Digits10(31); +} + +inline void FormatYYYY_MM_DD(arrow_vendored::date::year_month_day ymd, char** cursor) { + FormatTwoDigits(static_cast(ymd.day()), cursor); + FormatOneChar('-', cursor); + FormatTwoDigits(static_cast(ymd.month()), cursor); + FormatOneChar('-', cursor); + auto year = static_cast(ymd.year()); + const auto is_neg_year = year < 0; + year = std::abs(year); + assert(year <= 99999); + FormatTwoDigits(year % 100, cursor); + year /= 100; + FormatTwoDigits(year % 100, cursor); + if (year >= 100) { + FormatOneDigit(year / 100, cursor); + } + if (is_neg_year) { + FormatOneChar('-', cursor); + } +} + +template +constexpr size_t BufferSizeHH_MM_SS() { + return detail::Digits10(23) + 1 + detail::Digits10(59) + 1 + detail::Digits10(59) + 1 + + detail::Digits10(Duration::period::den) - 1; +} + +template +void FormatHH_MM_SS(arrow_vendored::date::hh_mm_ss hms, char** cursor) { + constexpr size_t subsecond_digits = Digits10(Duration::period::den) - 1; + if (subsecond_digits != 0) { + FormatAllDigitsLeftPadded(hms.subseconds().count(), subsecond_digits, '0', cursor); + FormatOneChar('.', cursor); + } + FormatTwoDigits(hms.seconds().count(), cursor); + FormatOneChar(':', cursor); + FormatTwoDigits(hms.minutes().count(), cursor); + FormatOneChar(':', cursor); + FormatTwoDigits(hms.hours().count(), cursor); +} + +// Some out-of-bound datetime values would result in erroneous printing +// because of silent integer wraparound in the `arrow_vendored::date` library. +// +// To avoid such misprinting, we must therefore check the bounds explicitly. +// The bounds correspond to start of year -32767 and end of year 32767, +// respectively (-32768 is an invalid year value in `arrow_vendored::date`). +// +// Note these values are the same as documented for C++20: +// https://en.cppreference.com/w/cpp/chrono/year_month_day/operator_days +template +bool IsDateTimeInRange(Unit duration) { + constexpr Unit kMinIncl = + std::chrono::duration_cast(arrow_vendored::date::days{-12687428}); + constexpr Unit kMaxExcl = + std::chrono::duration_cast(arrow_vendored::date::days{11248738}); + return duration >= kMinIncl && duration < kMaxExcl; +} + +// IsDateTimeInRange() specialization for nanoseconds: a 64-bit number of +// nanoseconds cannot represent years outside of the [-32767, 32767] +// range, and the {kMinIncl, kMaxExcl} constants above would overflow. +constexpr bool IsDateTimeInRange(std::chrono::nanoseconds duration) { return true; } + +template +bool IsTimeInRange(Unit duration) { + constexpr Unit kMinIncl = std::chrono::duration_cast(std::chrono::seconds{0}); + constexpr Unit kMaxExcl = std::chrono::duration_cast(std::chrono::seconds{86400}); + return duration >= kMinIncl && duration < kMaxExcl; +} + +template +Return FormatOutOfRange(RawValue&& raw_value, Appender&& append) { + // XXX locale-sensitive but good enough for now + std::string formatted = ""; + return append(std::move(formatted)); +} + +const auto kEpoch = arrow_vendored::date::sys_days{arrow_vendored::date::jan / 1 / 1970}; + +} // namespace detail + +template <> +class StringFormatter : public IntToStringFormatterMixin { + using IntToStringFormatterMixin::IntToStringFormatterMixin; +}; + +class DateToStringFormatterMixin { + public: + explicit DateToStringFormatterMixin(const DataType* = NULLPTR) {} + + protected: + template + Return FormatDays(arrow_vendored::date::days since_epoch, Appender&& append) { + arrow_vendored::date::sys_days timepoint_days{since_epoch}; + + constexpr size_t buffer_size = detail::BufferSizeYYYY_MM_DD(); + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatYYYY_MM_DD(arrow_vendored::date::year_month_day{timepoint_days}, + &cursor); + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter : public DateToStringFormatterMixin { + public: + using value_type = typename Date32Type::c_type; + + using DateToStringFormatterMixin::DateToStringFormatterMixin; + + template + Return operator()(value_type value, Appender&& append) { + const auto since_epoch = arrow_vendored::date::days{value}; + if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) { + return detail::FormatOutOfRange(value, append); + } + return FormatDays(since_epoch, std::forward(append)); + } +}; + +template <> +class StringFormatter : public DateToStringFormatterMixin { + public: + using value_type = typename Date64Type::c_type; + + using DateToStringFormatterMixin::DateToStringFormatterMixin; + + template + Return operator()(value_type value, Appender&& append) { + const auto since_epoch = std::chrono::milliseconds{value}; + if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) { + return detail::FormatOutOfRange(value, append); + } + return FormatDays(std::chrono::duration_cast(since_epoch), + std::forward(append)); + } +}; + +template <> +class StringFormatter { + public: + using value_type = int64_t; + + explicit StringFormatter(const DataType* type) + : unit_(checked_cast(*type).unit()), + timezone_(checked_cast(*type).timezone()) {} + + template + Return operator()(Duration, value_type value, Appender&& append) { + using arrow_vendored::date::days; + + const Duration since_epoch{value}; + if (!ARROW_PREDICT_TRUE(detail::IsDateTimeInRange(since_epoch))) { + return detail::FormatOutOfRange(value, append); + } + + const auto timepoint = detail::kEpoch + since_epoch; + // Round days towards zero + // (the naive approach of using arrow_vendored::date::floor() would + // result in UB for very large negative timestamps, similarly as + // https://github.com/HowardHinnant/date/issues/696) + auto timepoint_days = std::chrono::time_point_cast(timepoint); + Duration since_midnight; + if (timepoint_days <= timepoint) { + // Year >= 1970 + since_midnight = timepoint - timepoint_days; + } else { + // Year < 1970 + since_midnight = days(1) - (timepoint_days - timepoint); + timepoint_days -= days(1); + } + + constexpr size_t buffer_size = + detail::BufferSizeYYYY_MM_DD() + 1 + detail::BufferSizeHH_MM_SS(); + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + if (timezone_.size() > 0) { + detail::FormatOneChar('Z', &cursor); + } + detail::FormatHH_MM_SS(arrow_vendored::date::make_time(since_midnight), &cursor); + detail::FormatOneChar(' ', &cursor); + detail::FormatYYYY_MM_DD(timepoint_days, &cursor); + return append(detail::ViewDigitBuffer(buffer, cursor)); + } + + template + Return operator()(value_type value, Appender&& append) { + return util::VisitDuration(unit_, *this, value, std::forward(append)); + } + + private: + TimeUnit::type unit_; + std::string timezone_; +}; + +template +class StringFormatter> { + public: + using value_type = typename T::c_type; + + explicit StringFormatter(const DataType* type) + : unit_(checked_cast(*type).unit()) {} + + template + Return operator()(Duration, value_type count, Appender&& append) { + const Duration since_midnight{count}; + if (!ARROW_PREDICT_TRUE(detail::IsTimeInRange(since_midnight))) { + return detail::FormatOutOfRange(count, append); + } + + constexpr size_t buffer_size = detail::BufferSizeHH_MM_SS(); + + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatHH_MM_SS(arrow_vendored::date::make_time(since_midnight), &cursor); + return append(detail::ViewDigitBuffer(buffer, cursor)); + } + + template + Return operator()(value_type value, Appender&& append) { + return util::VisitDuration(unit_, *this, value, std::forward(append)); + } + + private: + TimeUnit::type unit_; +}; + +template <> +class StringFormatter { + public: + using value_type = MonthIntervalType::c_type; + + explicit StringFormatter(const DataType*) {} + + template + Return operator()(value_type interval, Appender&& append) { + constexpr size_t buffer_size = + /*'m'*/ 3 + /*negative signs*/ 1 + + /*months*/ detail::Digits10(std::numeric_limits::max()); + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatOneChar('M', &cursor); + detail::FormatAllDigits(detail::Abs(interval), &cursor); + if (interval < 0) detail::FormatOneChar('-', &cursor); + + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter { + public: + using value_type = DayTimeIntervalType::DayMilliseconds; + + explicit StringFormatter(const DataType*) {} + + template + Return operator()(value_type interval, Appender&& append) { + constexpr size_t buffer_size = + /*d, ms*/ 3 + /*negative signs*/ 2 + + /*days/milliseconds*/ 2 * detail::Digits10(std::numeric_limits::max()); + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatOneChar('s', &cursor); + detail::FormatOneChar('m', &cursor); + detail::FormatAllDigits(detail::Abs(interval.milliseconds), &cursor); + if (interval.milliseconds < 0) detail::FormatOneChar('-', &cursor); + + detail::FormatOneChar('d', &cursor); + detail::FormatAllDigits(detail::Abs(interval.days), &cursor); + if (interval.days < 0) detail::FormatOneChar('-', &cursor); + + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +template <> +class StringFormatter { + public: + using value_type = MonthDayNanoIntervalType::MonthDayNanos; + + explicit StringFormatter(const DataType*) {} + + template + Return operator()(value_type interval, Appender&& append) { + constexpr size_t buffer_size = + /*m, d, ns*/ 4 + /*negative signs*/ 3 + + /*months/days*/ 2 * detail::Digits10(std::numeric_limits::max()) + + /*nanoseconds*/ detail::Digits10(std::numeric_limits::max()); + std::array buffer; + char* cursor = buffer.data() + buffer_size; + + detail::FormatOneChar('s', &cursor); + detail::FormatOneChar('n', &cursor); + detail::FormatAllDigits(detail::Abs(interval.nanoseconds), &cursor); + if (interval.nanoseconds < 0) detail::FormatOneChar('-', &cursor); + + detail::FormatOneChar('d', &cursor); + detail::FormatAllDigits(detail::Abs(interval.days), &cursor); + if (interval.days < 0) detail::FormatOneChar('-', &cursor); + + detail::FormatOneChar('M', &cursor); + detail::FormatAllDigits(detail::Abs(interval.months), &cursor); + if (interval.months < 0) detail::FormatOneChar('-', &cursor); + + return append(detail::ViewDigitBuffer(buffer, cursor)); + } +}; + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/future.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/future.h new file mode 100644 index 0000000000000000000000000000000000000000..283b581a5100aed9e92ae5019aab1a61c95aa745 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/future.h @@ -0,0 +1,882 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/type_traits.h" +#include "arrow/util/config.h" +#include "arrow/util/functional.h" +#include "arrow/util/macros.h" +#include "arrow/util/tracing.h" +#include "arrow/util/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +template +struct EnsureFuture; + +namespace detail { + +template +struct is_future : std::false_type {}; + +template +struct is_future> : std::true_type {}; + +template +struct result_of; + +template +struct result_of()(std::declval()...))>> { + using type = decltype(std::declval()(std::declval()...)); +}; + +template +using result_of_t = typename result_of::type; + +// Helper to find the synchronous counterpart for a Future +template +struct SyncType { + using type = Result; +}; + +template <> +struct SyncType { + using type = Status; +}; + +template +using first_arg_is_status = + std::is_same>::type, + Status>; + +template > +using if_has_no_args = typename std::conditional::type; + +/// Creates a callback that can be added to a future to mark a `dest` future finished +template +struct MarkNextFinished {}; + +/// If the source and dest are both empty we can pass on the status +template +struct MarkNextFinished { + void operator()(const Status& status) && { next.MarkFinished(status); } + Dest next; +}; + +/// If the source is not empty but the dest is then we can take the +/// status out of the result +template +struct MarkNextFinished { + void operator()(const Result& res) && { + next.MarkFinished(internal::Empty::ToResult(res.status())); + } + Dest next; +}; + +/// If neither are empty we pass on the result +template +struct MarkNextFinished { + void operator()(const Result& res) && { + next.MarkFinished(res); + } + Dest next; +}; + +/// Helper that contains information about how to apply a continuation +struct ContinueFuture { + template + struct ForReturnImpl; + + template + using ForReturn = typename ForReturnImpl::type; + + template + using ForSignature = ForReturn>; + + // If the callback returns void then we return Future<> that always finishes OK. + template , + typename NextFuture = ForReturn> + typename std::enable_if::value>::type operator()( + NextFuture next, ContinueFunc&& f, Args&&... a) const { + std::forward(f)(std::forward(a)...); + next.MarkFinished(); + } + + /// If the callback returns a non-future then we return Future + /// and mark the future finished with the callback result. It will get promoted + /// to Result as part of MarkFinished if it isn't already. + /// + /// If the callback returns Status and we return Future<> then also send the callback + /// result as-is to the destination future. + template , + typename NextFuture = ForReturn> + typename std::enable_if< + !std::is_void::value && !is_future::value && + (!NextFuture::is_empty || std::is_same::value)>::type + operator()(NextFuture next, ContinueFunc&& f, Args&&... a) const { + next.MarkFinished(std::forward(f)(std::forward(a)...)); + } + + /// If the callback returns a Result and the next future is Future<> then we mark + /// the future finished with the callback result. + /// + /// It may seem odd that the next future is Future<> when the callback returns a + /// result but this can occur if the OnFailure callback returns a result while the + /// OnSuccess callback is void/Status (e.g. you would get this calling the one-arg + /// version of Then with an OnSuccess callback that returns void) + template , + typename NextFuture = ForReturn> + typename std::enable_if::value && + !is_future::value && NextFuture::is_empty && + !std::is_same::value>::type + operator()(NextFuture next, ContinueFunc&& f, Args&&... a) const { + next.MarkFinished(std::forward(f)(std::forward(a)...).status()); + } + + /// If the callback returns a Future then we return Future. We create a new + /// future and add a callback to the future given to us by the user that forwards the + /// result to the future we just created + template , + typename NextFuture = ForReturn> + typename std::enable_if::value>::type operator()( + NextFuture next, ContinueFunc&& f, Args&&... a) const { + ContinueResult signal_to_complete_next = + std::forward(f)(std::forward(a)...); + MarkNextFinished callback{std::move(next)}; + signal_to_complete_next.AddCallback(std::move(callback)); + } + + /// Helpers to conditionally ignore arguments to ContinueFunc + template + void IgnoringArgsIf(std::true_type, NextFuture&& next, ContinueFunc&& f, + Args&&...) const { + operator()(std::forward(next), std::forward(f)); + } + template + void IgnoringArgsIf(std::false_type, NextFuture&& next, ContinueFunc&& f, + Args&&... a) const { + operator()(std::forward(next), std::forward(f), + std::forward(a)...); + } +}; + +/// Helper struct which tells us what kind of Future gets returned from `Then` based on +/// the return type of the OnSuccess callback +template <> +struct ContinueFuture::ForReturnImpl { + using type = Future<>; +}; + +template <> +struct ContinueFuture::ForReturnImpl { + using type = Future<>; +}; + +template +struct ContinueFuture::ForReturnImpl { + using type = Future; +}; + +template +struct ContinueFuture::ForReturnImpl> { + using type = Future; +}; + +template +struct ContinueFuture::ForReturnImpl> { + using type = Future; +}; + +} // namespace detail + +/// A Future's execution or completion status +enum class FutureState : int8_t { PENDING, SUCCESS, FAILURE }; + +inline bool IsFutureFinished(FutureState state) { return state != FutureState::PENDING; } + +/// \brief Describe whether the callback should be scheduled or run synchronously +enum class ShouldSchedule { + /// Always run the callback synchronously (the default) + Never = 0, + /// Schedule a new task only if the future is not finished when the + /// callback is added + IfUnfinished = 1, + /// Always schedule the callback as a new task + Always = 2, + /// Schedule a new task only if it would run on an executor other than + /// the specified executor. + IfDifferentExecutor = 3, +}; + +/// \brief Options that control how a continuation is run +struct CallbackOptions { + /// Describe whether the callback should be run synchronously or scheduled + ShouldSchedule should_schedule = ShouldSchedule::Never; + /// If the callback is scheduled then this is the executor it should be scheduled + /// on. If this is NULL then should_schedule must be Never + internal::Executor* executor = NULLPTR; + + static CallbackOptions Defaults() { return {}; } +}; + +// Untyped private implementation +class ARROW_EXPORT FutureImpl : public std::enable_shared_from_this { + public: + FutureImpl(); + virtual ~FutureImpl() = default; + + FutureState state() { return state_.load(); } + + static std::unique_ptr Make(); + static std::unique_ptr MakeFinished(FutureState state); + +#ifdef ARROW_WITH_OPENTELEMETRY + void SetSpan(util::tracing::Span* span) { span_ = span; } +#endif + + // Future API + void MarkFinished(); + void MarkFailed(); + void Wait(); + bool Wait(double seconds); + template + Result* CastResult() const { + return static_cast*>(result_.get()); + } + + using Callback = internal::FnOnce; + void AddCallback(Callback callback, CallbackOptions opts); + bool TryAddCallback(const std::function& callback_factory, + CallbackOptions opts); + + std::atomic state_{FutureState::PENDING}; + + // Type erased storage for arbitrary results + // XXX small objects could be stored inline instead of boxed in a pointer + using Storage = std::unique_ptr; + Storage result_{NULLPTR, NULLPTR}; + + struct CallbackRecord { + Callback callback; + CallbackOptions options; + }; + std::vector callbacks_; +#ifdef ARROW_WITH_OPENTELEMETRY + util::tracing::Span* span_ = NULLPTR; +#endif +}; + +// --------------------------------------------------------------------- +// Public API + +/// \brief EXPERIMENTAL A std::future-like class with more functionality. +/// +/// A Future represents the results of a past or future computation. +/// The Future API has two sides: a producer side and a consumer side. +/// +/// The producer API allows creating a Future and setting its result or +/// status, possibly after running a computation function. +/// +/// The consumer API allows querying a Future's current state, wait for it +/// to complete, and composing futures with callbacks. +template +class [[nodiscard]] Future { + public: + using ValueType = T; + using SyncType = typename detail::SyncType::type; + static constexpr bool is_empty = std::is_same::value; + // The default constructor creates an invalid Future. Use Future::Make() + // for a valid Future. This constructor is mostly for the convenience + // of being able to presize a vector of Futures. + Future() = default; + +#ifdef ARROW_WITH_OPENTELEMETRY + void SetSpan(util::tracing::Span* span) { impl_->SetSpan(span); } +#endif + + // Consumer API + + bool is_valid() const { return impl_ != NULLPTR; } + + /// \brief Return the Future's current state + /// + /// A return value of PENDING is only indicative, as the Future can complete + /// concurrently. A return value of FAILURE or SUCCESS is definitive, though. + FutureState state() const { + CheckValid(); + return impl_->state(); + } + + /// \brief Whether the Future is finished + /// + /// A false return value is only indicative, as the Future can complete + /// concurrently. A true return value is definitive, though. + bool is_finished() const { + CheckValid(); + return IsFutureFinished(impl_->state()); + } + + /// \brief Wait for the Future to complete and return its Result + const Result& result() const& { + Wait(); + return *GetResult(); + } + + /// \brief Returns an rvalue to the result. This method is potentially unsafe + /// + /// The future is not the unique owner of the result, copies of a future will + /// also point to the same result. You must make sure that no other copies + /// of the future exist. Attempts to add callbacks after you move the result + /// will result in undefined behavior. + Result&& MoveResult() { + Wait(); + return std::move(*GetResult()); + } + + /// \brief Wait for the Future to complete and return its Status + const Status& status() const { return result().status(); } + + /// \brief Future is convertible to Future<>, which views only the + /// Status of the original. Marking the returned Future Finished is not supported. + explicit operator Future<>() const { + Future<> status_future; + status_future.impl_ = impl_; + return status_future; + } + + /// \brief Wait for the Future to complete + void Wait() const { + CheckValid(); + impl_->Wait(); + } + + /// \brief Wait for the Future to complete, or for the timeout to expire + /// + /// `true` is returned if the Future completed, `false` if the timeout expired. + /// Note a `false` value is only indicative, as the Future can complete + /// concurrently. + bool Wait(double seconds) const { + CheckValid(); + return impl_->Wait(seconds); + } + + // Producer API + + /// \brief Producer API: mark Future finished + /// + /// The Future's result is set to `res`. + void MarkFinished(Result res) { DoMarkFinished(std::move(res)); } + + /// \brief Mark a Future<> completed with the provided Status. + template ::value>::type> + void MarkFinished(Status s = Status::OK()) { + return DoMarkFinished(E::ToResult(std::move(s))); + } + + /// \brief Producer API: instantiate a valid Future + /// + /// The Future's state is initialized with PENDING. If you are creating a future with + /// this method you must ensure that future is eventually completed (with success or + /// failure). Creating a future, returning it, and never completing the future can lead + /// to memory leaks (for example, see Loop). + static Future Make() { + Future fut; + fut.impl_ = FutureImpl::Make(); + return fut; + } + + /// \brief Producer API: instantiate a finished Future + static Future MakeFinished(Result res) { + Future fut; + fut.InitializeFromResult(std::move(res)); + return fut; + } + + /// \brief Make a finished Future<> with the provided Status. + template ::value>::type> + static Future<> MakeFinished(Status s = Status::OK()) { + return MakeFinished(E::ToResult(std::move(s))); + } + + struct WrapResultOnComplete { + template + struct Callback { + void operator()(const FutureImpl& impl) && { + std::move(on_complete)(*impl.CastResult()); + } + OnComplete on_complete; + }; + }; + + struct WrapStatusyOnComplete { + template + struct Callback { + static_assert(std::is_same::value, + "Only callbacks for Future<> should accept Status and not Result"); + + void operator()(const FutureImpl& impl) && { + std::move(on_complete)(impl.CastResult()->status()); + } + OnComplete on_complete; + }; + }; + + template + using WrapOnComplete = typename std::conditional< + detail::first_arg_is_status::value, WrapStatusyOnComplete, + WrapResultOnComplete>::type::template Callback; + + /// \brief Consumer API: Register a callback to run when this future completes + /// + /// The callback should receive the result of the future (const Result&) + /// For a void or statusy future this should be (const Status&) + /// + /// There is no guarantee to the order in which callbacks will run. In + /// particular, callbacks added while the future is being marked complete + /// may be executed immediately, ahead of, or even the same time as, other + /// callbacks that have been previously added. + /// + /// WARNING: callbacks may hold arbitrary references, including cyclic references. + /// Since callbacks will only be destroyed after they are invoked, this can lead to + /// memory leaks if a Future is never marked finished (abandoned): + /// + /// { + /// auto fut = Future<>::Make(); + /// fut.AddCallback([fut]() {}); + /// } + /// + /// In this example `fut` falls out of scope but is not destroyed because it holds a + /// cyclic reference to itself through the callback. + template > + void AddCallback(OnComplete on_complete, + CallbackOptions opts = CallbackOptions::Defaults()) const { + // We know impl_ will not be dangling when invoking callbacks because at least one + // thread will be waiting for MarkFinished to return. Thus it's safe to keep a + // weak reference to impl_ here + impl_->AddCallback(Callback{std::move(on_complete)}, opts); + } + + /// \brief Overload of AddCallback that will return false instead of running + /// synchronously + /// + /// This overload will guarantee the callback is never run synchronously. If the future + /// is already finished then it will simply return false. This can be useful to avoid + /// stack overflow in a situation where you have recursive Futures. For an example + /// see the Loop function + /// + /// Takes in a callback factory function to allow moving callbacks (the factory function + /// will only be called if the callback can successfully be added) + /// + /// Returns true if a callback was actually added and false if the callback failed + /// to add because the future was marked complete. + template , + typename Callback = WrapOnComplete> + bool TryAddCallback(CallbackFactory callback_factory, + CallbackOptions opts = CallbackOptions::Defaults()) const { + return impl_->TryAddCallback([&]() { return Callback{callback_factory()}; }, opts); + } + + template + struct ThenOnComplete { + static constexpr bool has_no_args = + internal::call_traits::argument_count::value == 0; + + using ContinuedFuture = detail::ContinueFuture::ForSignature< + detail::if_has_no_args>; + + static_assert( + std::is_same, + ContinuedFuture>::value, + "OnSuccess and OnFailure must continue with the same future type"); + + struct DummyOnSuccess { + void operator()(const T&); + }; + using OnSuccessArg = typename std::decay>>::type; + + static_assert( + !std::is_same::type>::value, + "OnSuccess' argument should not be a Result"); + + void operator()(const Result& result) && { + detail::ContinueFuture continue_future; + if (ARROW_PREDICT_TRUE(result.ok())) { + // move on_failure to a(n immediately destroyed) temporary to free its resources + ARROW_UNUSED(OnFailure(std::move(on_failure))); + continue_future.IgnoringArgsIf( + detail::if_has_no_args{}, + std::move(next), std::move(on_success), result.ValueOrDie()); + } else { + ARROW_UNUSED(OnSuccess(std::move(on_success))); + continue_future(std::move(next), std::move(on_failure), result.status()); + } + } + + OnSuccess on_success; + OnFailure on_failure; + ContinuedFuture next; + }; + + template + struct PassthruOnFailure { + using ContinuedFuture = detail::ContinueFuture::ForSignature< + detail::if_has_no_args>; + + Result operator()(const Status& s) { return s; } + }; + + /// \brief Consumer API: Register a continuation to run when this future completes + /// + /// The continuation will run in the same thread that called MarkFinished (whatever + /// callback is registered with this function will run before MarkFinished returns). + /// Avoid long-running callbacks in favor of submitting a task to an Executor and + /// returning the future. + /// + /// Two callbacks are supported: + /// - OnSuccess, called with the result (const ValueType&) on successful completion. + /// for an empty future this will be called with nothing () + /// - OnFailure, called with the error (const Status&) on failed completion. + /// This callback is optional and defaults to a passthru of any errors. + /// + /// Then() returns a Future whose ValueType is derived from the return type of the + /// callbacks. If a callback returns: + /// - void, a Future<> will be returned which will completes successfully as soon + /// as the callback runs. + /// - Status, a Future<> will be returned which will complete with the returned Status + /// as soon as the callback runs. + /// - V or Result, a Future will be returned which will complete with the result + /// of invoking the callback as soon as the callback runs. + /// - Future, a Future will be returned which will be marked complete when the + /// future returned by the callback completes (and will complete with the same + /// result). + /// + /// The continued Future type must be the same for both callbacks. + /// + /// Note that OnFailure can swallow errors, allowing continued Futures to successfully + /// complete even if this Future fails. + /// + /// If this future is already completed then the callback will be run immediately + /// and the returned future may already be marked complete. + /// + /// See AddCallback for general considerations when writing callbacks. + template , + typename OnComplete = ThenOnComplete, + typename ContinuedFuture = typename OnComplete::ContinuedFuture> + ContinuedFuture Then(OnSuccess on_success, OnFailure on_failure = {}, + CallbackOptions options = CallbackOptions::Defaults()) const { + auto next = ContinuedFuture::Make(); + AddCallback(OnComplete{std::forward(on_success), + std::forward(on_failure), next}, + options); + return next; + } + + /// \brief Implicit constructor to create a finished future from a value + Future(ValueType val) : Future() { // NOLINT runtime/explicit + impl_ = FutureImpl::MakeFinished(FutureState::SUCCESS); + SetResult(std::move(val)); + } + + /// \brief Implicit constructor to create a future from a Result, enabling use + /// of macros like ARROW_ASSIGN_OR_RAISE. + Future(Result res) : Future() { // NOLINT runtime/explicit + if (ARROW_PREDICT_TRUE(res.ok())) { + impl_ = FutureImpl::MakeFinished(FutureState::SUCCESS); + } else { + impl_ = FutureImpl::MakeFinished(FutureState::FAILURE); + } + SetResult(std::move(res)); + } + + /// \brief Implicit constructor to create a future from a Status, enabling use + /// of macros like ARROW_RETURN_NOT_OK. + Future(Status s) // NOLINT runtime/explicit + : Future(Result(std::move(s))) {} + + protected: + void InitializeFromResult(Result res) { + if (ARROW_PREDICT_TRUE(res.ok())) { + impl_ = FutureImpl::MakeFinished(FutureState::SUCCESS); + } else { + impl_ = FutureImpl::MakeFinished(FutureState::FAILURE); + } + SetResult(std::move(res)); + } + + void Initialize() { impl_ = FutureImpl::Make(); } + + Result* GetResult() const { return impl_->CastResult(); } + + void SetResult(Result res) { + impl_->result_ = {new Result(std::move(res)), + [](void* p) { delete static_cast*>(p); }}; + } + + void DoMarkFinished(Result res) { + SetResult(std::move(res)); + + if (ARROW_PREDICT_TRUE(GetResult()->ok())) { + impl_->MarkFinished(); + } else { + impl_->MarkFailed(); + } + } + + void CheckValid() const { +#ifndef NDEBUG + if (!is_valid()) { + Status::Invalid("Invalid Future (default-initialized?)").Abort(); + } +#endif + } + + explicit Future(std::shared_ptr impl) : impl_(std::move(impl)) {} + + std::shared_ptr impl_; + + friend struct detail::ContinueFuture; + + template + friend class Future; + friend class WeakFuture; + + FRIEND_TEST(FutureRefTest, ChainRemoved); + FRIEND_TEST(FutureRefTest, TailRemoved); + FRIEND_TEST(FutureRefTest, HeadRemoved); +}; + +template +typename Future::SyncType FutureToSync(const Future& fut) { + return fut.result(); +} + +template <> +inline typename Future::SyncType FutureToSync( + const Future& fut) { + return fut.status(); +} + +template <> +inline Future<>::Future(Status s) : Future(internal::Empty::ToResult(std::move(s))) {} + +template +class WeakFuture { + public: + explicit WeakFuture(const Future& future) : impl_(future.impl_) {} + + Future get() { return Future{impl_.lock()}; } + + private: + std::weak_ptr impl_; +}; + +/// \defgroup future-utilities Functions for working with Futures +/// @{ + +/// If a Result holds an error instead of a Future, construct a finished Future +/// holding that error. +template +static Future DeferNotOk(Result> maybe_future) { + if (ARROW_PREDICT_FALSE(!maybe_future.ok())) { + return Future::MakeFinished(std::move(maybe_future).status()); + } + return std::move(maybe_future).MoveValueUnsafe(); +} + +/// \brief Create a Future which completes when all of `futures` complete. +/// +/// The future's result is a vector of the results of `futures`. +/// Note that this future will never be marked "failed"; failed results +/// will be stored in the result vector alongside successful results. +template +Future>> All(std::vector> futures) { + struct State { + explicit State(std::vector> f) + : futures(std::move(f)), n_remaining(futures.size()) {} + + std::vector> futures; + std::atomic n_remaining; + }; + + if (futures.size() == 0) { + return {std::vector>{}}; + } + + auto state = std::make_shared(std::move(futures)); + + auto out = Future>>::Make(); + for (const Future& future : state->futures) { + future.AddCallback([state, out](const Result&) mutable { + if (state->n_remaining.fetch_sub(1) != 1) return; + + std::vector> results(state->futures.size()); + for (size_t i = 0; i < results.size(); ++i) { + results[i] = state->futures[i].result(); + } + out.MarkFinished(std::move(results)); + }); + } + return out; +} + +/// \brief Create a Future which completes when all of `futures` complete. +/// +/// The future will be marked complete if all `futures` complete +/// successfully. Otherwise, it will be marked failed with the status of +/// the first failing future. +ARROW_EXPORT +Future<> AllComplete(const std::vector>& futures); + +/// \brief Create a Future which completes when all of `futures` complete. +/// +/// The future will finish with an ok status if all `futures` finish with +/// an ok status. Otherwise, it will be marked failed with the status of +/// one of the failing futures. +/// +/// Unlike AllComplete this Future will not complete immediately when a +/// failure occurs. It will wait until all futures have finished. +ARROW_EXPORT +Future<> AllFinished(const std::vector>& futures); + +/// @} + +struct Continue { + template + operator std::optional() && { // NOLINT explicit + return {}; + } +}; + +template +std::optional Break(T break_value = {}) { + return std::optional{std::move(break_value)}; +} + +template +using ControlFlow = std::optional; + +/// \brief Loop through an asynchronous sequence +/// +/// \param[in] iterate A generator of Future>. On completion +/// of each yielded future the resulting ControlFlow will be examined. A Break will +/// terminate the loop, while a Continue will re-invoke `iterate`. +/// +/// \return A future which will complete when a Future returned by iterate completes with +/// a Break +template ::ValueType, + typename BreakValueType = typename Control::value_type> +Future Loop(Iterate iterate) { + struct Callback { + bool CheckForTermination(const Result& control_res) { + if (!control_res.ok()) { + break_fut.MarkFinished(control_res.status()); + return true; + } + if (control_res->has_value()) { + break_fut.MarkFinished(**control_res); + return true; + } + return false; + } + + void operator()(const Result& maybe_control) && { + if (CheckForTermination(maybe_control)) return; + + auto control_fut = iterate(); + while (true) { + if (control_fut.TryAddCallback([this]() { return *this; })) { + // Adding a callback succeeded; control_fut was not finished + // and we must wait to CheckForTermination. + return; + } + // Adding a callback failed; control_fut was finished and we + // can CheckForTermination immediately. This also avoids recursion and potential + // stack overflow. + if (CheckForTermination(control_fut.result())) return; + + control_fut = iterate(); + } + } + + Iterate iterate; + + // If the future returned by control_fut is never completed then we will be hanging on + // to break_fut forever even if the listener has given up listening on it. Instead we + // rely on the fact that a producer (the caller of Future<>::Make) is always + // responsible for completing the futures they create. + // TODO: Could avoid this kind of situation with "future abandonment" similar to mesos + Future break_fut; + }; + + auto break_fut = Future::Make(); + auto control_fut = iterate(); + control_fut.AddCallback(Callback{std::move(iterate), break_fut}); + + return break_fut; +} + +inline Future<> ToFuture(Status status) { + return Future<>::MakeFinished(std::move(status)); +} + +template +Future ToFuture(T value) { + return Future::MakeFinished(std::move(value)); +} + +template +Future ToFuture(Result maybe_value) { + return Future::MakeFinished(std::move(maybe_value)); +} + +template +Future ToFuture(Future fut) { + return std::move(fut); +} + +template +struct EnsureFuture { + using type = decltype(ToFuture(std::declval())); +}; + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/hash_util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/hash_util.h new file mode 100644 index 0000000000000000000000000000000000000000..dd1c38a78216e3f3d0d8c3f42c63a7d43f4bab44 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/hash_util.h @@ -0,0 +1,66 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +namespace arrow { +namespace internal { + +// ---------------------------------------------------------------------- +// BEGIN Hash utilities from Boost + +namespace detail { + +#if defined(_MSC_VER) +#define ARROW_HASH_ROTL32(x, r) _rotl(x, r) +#else +#define ARROW_HASH_ROTL32(x, r) (x << r) | (x >> (32 - r)) +#endif + +template +inline void hash_combine_impl(SizeT& seed, SizeT value) { + seed ^= value + 0x9e3779b9 + (seed << 6) + (seed >> 2); +} + +inline void hash_combine_impl(uint32_t& h1, uint32_t k1) { + const uint32_t c1 = 0xcc9e2d51; + const uint32_t c2 = 0x1b873593; + + k1 *= c1; + k1 = ARROW_HASH_ROTL32(k1, 15); + k1 *= c2; + + h1 ^= k1; + h1 = ARROW_HASH_ROTL32(h1, 13); + h1 = h1 * 5 + 0xe6546b64; +} + +#undef ARROW_HASH_ROTL32 + +} // namespace detail + +template +inline void hash_combine(std::size_t& seed, T const& v) { + std::hash hasher; + return ::arrow::internal::detail::hash_combine_impl(seed, hasher(v)); +} + +// END Hash utilities from Boost +// ---------------------------------------------------------------------- + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util_overflow.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util_overflow.h new file mode 100644 index 0000000000000000000000000000000000000000..ffe78be2470ddb846b5816be632e9921c041a23e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util_overflow.h @@ -0,0 +1,118 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +// "safe-math.h" includes from the Windows headers. +#include "arrow/util/windows_compatibility.h" +#include "arrow/vendored/portable-snippets/safe-math.h" +// clang-format off (avoid include reordering) +#include "arrow/util/windows_fixup.h" +// clang-format on + +namespace arrow { +namespace internal { + +// Define functions AddWithOverflow, SubtractWithOverflow, MultiplyWithOverflow +// with the signature `bool(T u, T v, T* out)` where T is an integer type. +// On overflow, these functions return true. Otherwise, false is returned +// and `out` is updated with the result of the operation. + +#define OP_WITH_OVERFLOW(_func_name, _psnip_op, _type, _psnip_type) \ + [[nodiscard]] static inline bool _func_name(_type u, _type v, _type* out) { \ + return !psnip_safe_##_psnip_type##_##_psnip_op(out, u, v); \ + } + +#define OPS_WITH_OVERFLOW(_func_name, _psnip_op) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, int8_t, int8) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, int16_t, int16) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, int32_t, int32) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, int64_t, int64) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, uint8_t, uint8) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, uint16_t, uint16) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, uint32_t, uint32) \ + OP_WITH_OVERFLOW(_func_name, _psnip_op, uint64_t, uint64) + +OPS_WITH_OVERFLOW(AddWithOverflow, add) +OPS_WITH_OVERFLOW(SubtractWithOverflow, sub) +OPS_WITH_OVERFLOW(MultiplyWithOverflow, mul) +OPS_WITH_OVERFLOW(DivideWithOverflow, div) + +#undef OP_WITH_OVERFLOW +#undef OPS_WITH_OVERFLOW + +// Define function NegateWithOverflow with the signature `bool(T u, T* out)` +// where T is a signed integer type. On overflow, these functions return true. +// Otherwise, false is returned and `out` is updated with the result of the +// operation. + +#define UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, _type, _psnip_type) \ + [[nodiscard]] static inline bool _func_name(_type u, _type* out) { \ + return !psnip_safe_##_psnip_type##_##_psnip_op(out, u); \ + } + +#define SIGNED_UNARY_OPS_WITH_OVERFLOW(_func_name, _psnip_op) \ + UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int8_t, int8) \ + UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int16_t, int16) \ + UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int32_t, int32) \ + UNARY_OP_WITH_OVERFLOW(_func_name, _psnip_op, int64_t, int64) + +SIGNED_UNARY_OPS_WITH_OVERFLOW(NegateWithOverflow, neg) + +#undef UNARY_OP_WITH_OVERFLOW +#undef SIGNED_UNARY_OPS_WITH_OVERFLOW + +/// Signed addition with well-defined behaviour on overflow (as unsigned) +template +SignedInt SafeSignedAdd(SignedInt u, SignedInt v) { + using UnsignedInt = typename std::make_unsigned::type; + return static_cast(static_cast(u) + + static_cast(v)); +} + +/// Signed subtraction with well-defined behaviour on overflow (as unsigned) +template +SignedInt SafeSignedSubtract(SignedInt u, SignedInt v) { + using UnsignedInt = typename std::make_unsigned::type; + return static_cast(static_cast(u) - + static_cast(v)); +} + +/// Signed negation with well-defined behaviour on overflow (as unsigned) +template +SignedInt SafeSignedNegate(SignedInt u) { + using UnsignedInt = typename std::make_unsigned::type; + return static_cast(~static_cast(u) + 1); +} + +/// Signed left shift with well-defined behaviour on negative numbers or overflow +template +SignedInt SafeLeftShift(SignedInt u, Shift shift) { + using UnsignedInt = typename std::make_unsigned::type; + return static_cast(static_cast(u) << shift); +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/iterator.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/iterator.h new file mode 100644 index 0000000000000000000000000000000000000000..5e716d0fd113d339a34b16e6f7353a169829e3e2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/iterator.h @@ -0,0 +1,568 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/compare.h" +#include "arrow/util/functional.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +template +class Iterator; + +template +struct IterationTraits { + /// \brief a reserved value which indicates the end of iteration. By + /// default this is NULLPTR since most iterators yield pointer types. + /// Specialize IterationTraits if different end semantics are required. + /// + /// Note: This should not be used to determine if a given value is a + /// terminal value. Use IsIterationEnd (which uses IsEnd) instead. This + /// is only for returning terminal values. + static T End() { return T(NULLPTR); } + + /// \brief Checks to see if the value is a terminal value. + /// A method is used here since T is not necessarily comparable in many + /// cases even though it has a distinct final value + static bool IsEnd(const T& val) { return val == End(); } +}; + +template +T IterationEnd() { + return IterationTraits::End(); +} + +template +bool IsIterationEnd(const T& val) { + return IterationTraits::IsEnd(val); +} + +template +struct IterationTraits> { + /// \brief by default when iterating through a sequence of optional, + /// nullopt indicates the end of iteration. + /// Specialize IterationTraits if different end semantics are required. + static std::optional End() { return std::nullopt; } + + /// \brief by default when iterating through a sequence of optional, + /// nullopt (!has_value()) indicates the end of iteration. + /// Specialize IterationTraits if different end semantics are required. + static bool IsEnd(const std::optional& val) { return !val.has_value(); } + + // TODO(bkietz) The range-for loop over Iterator> yields + // Result> which is unnecessary (since only the unyielded end optional + // is nullopt. Add IterationTraits::GetRangeElement() to handle this case +}; + +/// \brief A generic Iterator that can return errors +template +class Iterator : public util::EqualityComparable> { + public: + /// \brief Iterator may be constructed from any type which has a member function + /// with signature Result Next(); + /// End of iterator is signalled by returning IteratorTraits::End(); + /// + /// The argument is moved or copied to the heap and kept in a unique_ptr. Only + /// its destructor and its Next method (which are stored in function pointers) are + /// referenced after construction. + /// + /// This approach is used to dodge MSVC linkage hell (ARROW-6244, ARROW-6558) when using + /// an abstract template base class: instead of being inlined as usual for a template + /// function the base's virtual destructor will be exported, leading to multiple + /// definition errors when linking to any other TU where the base is instantiated. + template + explicit Iterator(Wrapped has_next) + : ptr_(new Wrapped(std::move(has_next)), Delete), next_(Next) {} + + Iterator() : ptr_(NULLPTR, [](void*) {}) {} + + /// \brief Return the next element of the sequence, IterationTraits::End() when the + /// iteration is completed. Calling this on a default constructed Iterator + /// will result in undefined behavior. + Result Next() { return next_(ptr_.get()); } + + /// Pass each element of the sequence to a visitor. Will return any error status + /// returned by the visitor, terminating iteration. + template + Status Visit(Visitor&& visitor) { + for (;;) { + ARROW_ASSIGN_OR_RAISE(auto value, Next()); + + if (IsIterationEnd(value)) break; + + ARROW_RETURN_NOT_OK(visitor(std::move(value))); + } + + return Status::OK(); + } + + /// Iterators will only compare equal if they are both null. + /// Equality comparability is required to make an Iterator of Iterators + /// (to check for the end condition). + bool Equals(const Iterator& other) const { return ptr_ == other.ptr_; } + + explicit operator bool() const { return ptr_ != NULLPTR; } + + class RangeIterator { + public: + RangeIterator() : value_(IterationTraits::End()) {} + + explicit RangeIterator(Iterator i) + : value_(IterationTraits::End()), + iterator_(std::make_shared(std::move(i))) { + Next(); + } + + bool operator!=(const RangeIterator& other) const { return value_ != other.value_; } + + RangeIterator& operator++() { + Next(); + return *this; + } + + Result operator*() { + ARROW_RETURN_NOT_OK(value_.status()); + + auto value = std::move(value_); + value_ = IterationTraits::End(); + return value; + } + + private: + void Next() { + if (!value_.ok()) { + value_ = IterationTraits::End(); + return; + } + value_ = iterator_->Next(); + } + + Result value_; + std::shared_ptr iterator_; + }; + + RangeIterator begin() { return RangeIterator(std::move(*this)); } + + RangeIterator end() { return RangeIterator(); } + + /// \brief Move every element of this iterator into a vector. + Result> ToVector() { + std::vector out; + for (auto maybe_element : *this) { + ARROW_ASSIGN_OR_RAISE(auto element, maybe_element); + out.push_back(std::move(element)); + } + // ARROW-8193: On gcc-4.8 without the explicit move it tries to use the + // copy constructor, which may be deleted on the elements of type T + return std::move(out); + } + + private: + /// Implementation of deleter for ptr_: Casts from void* to the wrapped type and + /// deletes that. + template + static void Delete(void* ptr) { + delete static_cast(ptr); + } + + /// Implementation of Next: Casts from void* to the wrapped type and invokes that + /// type's Next member function. + template + static Result Next(void* ptr) { + return static_cast(ptr)->Next(); + } + + /// ptr_ is a unique_ptr to void with a custom deleter: a function pointer which first + /// casts from void* to a pointer to the wrapped type then deletes that. + std::unique_ptr ptr_; + + /// next_ is a function pointer which first casts from void* to a pointer to the wrapped + /// type then invokes its Next member function. + Result (*next_)(void*) = NULLPTR; +}; + +template +struct TransformFlow { + using YieldValueType = T; + + TransformFlow(YieldValueType value, bool ready_for_next) + : finished_(false), + ready_for_next_(ready_for_next), + yield_value_(std::move(value)) {} + TransformFlow(bool finished, bool ready_for_next) + : finished_(finished), ready_for_next_(ready_for_next), yield_value_() {} + + bool HasValue() const { return yield_value_.has_value(); } + bool Finished() const { return finished_; } + bool ReadyForNext() const { return ready_for_next_; } + T Value() const { return *yield_value_; } + + bool finished_ = false; + bool ready_for_next_ = false; + std::optional yield_value_; +}; + +struct TransformFinish { + template + operator TransformFlow() && { // NOLINT explicit + return TransformFlow(true, true); + } +}; + +struct TransformSkip { + template + operator TransformFlow() && { // NOLINT explicit + return TransformFlow(false, true); + } +}; + +template +TransformFlow TransformYield(T value = {}, bool ready_for_next = true) { + return TransformFlow(std::move(value), ready_for_next); +} + +template +using Transformer = std::function>(T)>; + +template +class TransformIterator { + public: + explicit TransformIterator(Iterator it, Transformer transformer) + : it_(std::move(it)), + transformer_(std::move(transformer)), + last_value_(), + finished_() {} + + Result Next() { + while (!finished_) { + ARROW_ASSIGN_OR_RAISE(std::optional next, Pump()); + if (next.has_value()) { + return std::move(*next); + } + ARROW_ASSIGN_OR_RAISE(last_value_, it_.Next()); + } + return IterationTraits::End(); + } + + private: + // Calls the transform function on the current value. Can return in several ways + // * If the next value is requested (e.g. skip) it will return an empty optional + // * If an invalid status is encountered that will be returned + // * If finished it will return IterationTraits::End() + // * If a value is returned by the transformer that will be returned + Result> Pump() { + if (!finished_ && last_value_.has_value()) { + auto next_res = transformer_(*last_value_); + if (!next_res.ok()) { + finished_ = true; + return next_res.status(); + } + auto next = *next_res; + if (next.ReadyForNext()) { + if (IsIterationEnd(*last_value_)) { + finished_ = true; + } + last_value_.reset(); + } + if (next.Finished()) { + finished_ = true; + } + if (next.HasValue()) { + return next.Value(); + } + } + if (finished_) { + return IterationTraits::End(); + } + return std::nullopt; + } + + Iterator it_; + Transformer transformer_; + std::optional last_value_; + bool finished_ = false; +}; + +/// \brief Transforms an iterator according to a transformer, returning a new Iterator. +/// +/// The transformer will be called on each element of the source iterator and for each +/// call it can yield a value, skip, or finish the iteration. When yielding a value the +/// transformer can choose to consume the source item (the default, ready_for_next = true) +/// or to keep it and it will be called again on the same value. +/// +/// This is essentially a more generic form of the map operation that can return 0, 1, or +/// many values for each of the source items. +/// +/// The transformer will be exposed to the end of the source sequence +/// (IterationTraits::End) in case it needs to return some penultimate item(s). +/// +/// Any invalid status returned by the transformer will be returned immediately. +template +Iterator MakeTransformedIterator(Iterator it, Transformer op) { + return Iterator(TransformIterator(std::move(it), std::move(op))); +} + +template +struct IterationTraits> { + // The end condition for an Iterator of Iterators is a default constructed (null) + // Iterator. + static Iterator End() { return Iterator(); } + static bool IsEnd(const Iterator& val) { return !val; } +}; + +template +class FunctionIterator { + public: + explicit FunctionIterator(Fn fn) : fn_(std::move(fn)) {} + + Result Next() { return fn_(); } + + private: + Fn fn_; +}; + +/// \brief Construct an Iterator which invokes a callable on Next() +template ::ValueType> +Iterator MakeFunctionIterator(Fn fn) { + return Iterator(FunctionIterator(std::move(fn))); +} + +template +Iterator MakeEmptyIterator() { + return MakeFunctionIterator([]() -> Result { return IterationTraits::End(); }); +} + +template +Iterator MakeErrorIterator(Status s) { + return MakeFunctionIterator([s]() -> Result { + ARROW_RETURN_NOT_OK(s); + return IterationTraits::End(); + }); +} + +/// \brief Simple iterator which yields the elements of a std::vector +template +class VectorIterator { + public: + explicit VectorIterator(std::vector v) : elements_(std::move(v)) {} + + Result Next() { + if (i_ == elements_.size()) { + return IterationTraits::End(); + } + return std::move(elements_[i_++]); + } + + private: + std::vector elements_; + size_t i_ = 0; +}; + +template +Iterator MakeVectorIterator(std::vector v) { + return Iterator(VectorIterator(std::move(v))); +} + +/// \brief Simple iterator which yields *pointers* to the elements of a std::vector. +/// This is provided to support T where IterationTraits::End is not specialized +template +class VectorPointingIterator { + public: + explicit VectorPointingIterator(std::vector v) : elements_(std::move(v)) {} + + Result Next() { + if (i_ == elements_.size()) { + return NULLPTR; + } + return &elements_[i_++]; + } + + private: + std::vector elements_; + size_t i_ = 0; +}; + +template +Iterator MakeVectorPointingIterator(std::vector v) { + return Iterator(VectorPointingIterator(std::move(v))); +} + +/// \brief MapIterator takes ownership of an iterator and a function to apply +/// on every element. The mapped function is not allowed to fail. +template +class MapIterator { + public: + explicit MapIterator(Fn map, Iterator it) + : map_(std::move(map)), it_(std::move(it)) {} + + Result Next() { + ARROW_ASSIGN_OR_RAISE(I i, it_.Next()); + + if (IsIterationEnd(i)) { + return IterationTraits::End(); + } + + return map_(std::move(i)); + } + + private: + Fn map_; + Iterator it_; +}; + +/// \brief MapIterator takes ownership of an iterator and a function to apply +/// on every element. The mapped function is not allowed to fail. +template , + typename To = internal::call_traits::return_type> +Iterator MakeMapIterator(Fn map, Iterator it) { + return Iterator(MapIterator(std::move(map), std::move(it))); +} + +/// \brief Like MapIterator, but where the function can fail. +template , + typename To = typename internal::call_traits::return_type::ValueType> +Iterator MakeMaybeMapIterator(Fn map, Iterator it) { + return Iterator(MapIterator(std::move(map), std::move(it))); +} + +struct FilterIterator { + enum Action { ACCEPT, REJECT }; + + template + static Result> Reject() { + return std::make_pair(IterationTraits::End(), REJECT); + } + + template + static Result> Accept(To out) { + return std::make_pair(std::move(out), ACCEPT); + } + + template + static Result> MaybeAccept(Result maybe_out) { + return std::move(maybe_out).Map(Accept); + } + + template + static Result> Error(Status s) { + return s; + } + + template + class Impl { + public: + explicit Impl(Fn filter, Iterator it) : filter_(filter), it_(std::move(it)) {} + + Result Next() { + To out = IterationTraits::End(); + Action action; + + for (;;) { + ARROW_ASSIGN_OR_RAISE(From i, it_.Next()); + + if (IsIterationEnd(i)) { + return IterationTraits::End(); + } + + ARROW_ASSIGN_OR_RAISE(std::tie(out, action), filter_(std::move(i))); + + if (action == ACCEPT) return out; + } + } + + private: + Fn filter_; + Iterator it_; + }; +}; + +/// \brief Like MapIterator, but where the function can fail or reject elements. +template < + typename Fn, typename From = typename internal::call_traits::argument_type<0, Fn>, + typename Ret = typename internal::call_traits::return_type::ValueType, + typename To = typename std::tuple_element<0, Ret>::type, + typename Enable = typename std::enable_if::type, FilterIterator::Action>::value>::type> +Iterator MakeFilterIterator(Fn filter, Iterator it) { + return Iterator( + FilterIterator::Impl(std::move(filter), std::move(it))); +} + +/// \brief FlattenIterator takes an iterator generating iterators and yields a +/// unified iterator that flattens/concatenates in a single stream. +template +class FlattenIterator { + public: + explicit FlattenIterator(Iterator> it) : parent_(std::move(it)) {} + + Result Next() { + if (IsIterationEnd(child_)) { + // Pop from parent's iterator. + ARROW_ASSIGN_OR_RAISE(child_, parent_.Next()); + + // Check if final iteration reached. + if (IsIterationEnd(child_)) { + return IterationTraits::End(); + } + + return Next(); + } + + // Pop from child_ and check for depletion. + ARROW_ASSIGN_OR_RAISE(T out, child_.Next()); + if (IsIterationEnd(out)) { + // Reset state such that we pop from parent on the recursive call + child_ = IterationTraits>::End(); + + return Next(); + } + + return out; + } + + private: + Iterator> parent_; + Iterator child_ = IterationTraits>::End(); +}; + +template +Iterator MakeFlattenIterator(Iterator> it) { + return Iterator(FlattenIterator(std::move(it))); +} + +template +Iterator MakeIteratorFromReader( + const std::shared_ptr& reader) { + return MakeFunctionIterator([reader] { return reader->Next(); }); +} + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/list_util.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/list_util.h new file mode 100644 index 0000000000000000000000000000000000000000..58deb8019d94155e4488af7e3047e599abb7197b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/list_util.h @@ -0,0 +1,55 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/array/data.h" +#include "arrow/result.h" + +namespace arrow { +namespace list_util { +namespace internal { + +/// \brief Calculate the smallest continuous range of values used by the +/// var-length list-like input (list, map and list-view types). +/// +/// \param input The input array such that is_var_length_list_like(input.type) +/// is true +/// \return A pair of (offset, length) describing the range +ARROW_EXPORT Result> RangeOfValuesUsed( + const ArraySpan& input); + +/// \brief Calculate the sum of the sizes of all valid lists or list-views +/// +/// This is usually the same as the length of the RangeOfValuesUsed() range, but +/// it can be: +/// - Smaller: when the child array contains many values that are not +/// referenced by the lists or list-views in the parent array +/// - Greater: when the list-views share child array ranges +/// +/// \param input The input array such that is_var_length_list_like(input.type) +/// is true +/// \return The sum of all list or list-view sizes +ARROW_EXPORT Result SumOfLogicalListSizes(const ArraySpan& input); + +} // namespace internal + +} // namespace list_util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/memory.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/memory.h new file mode 100644 index 0000000000000000000000000000000000000000..4250d0694b7dd283aad6bbb159bd3e36328fe7ae --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/memory.h @@ -0,0 +1,43 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/util/macros.h" + +namespace arrow { +namespace internal { + +// A helper function for doing memcpy with multiple threads. This is required +// to saturate the memory bandwidth of modern cpus. +void parallel_memcopy(uint8_t* dst, const uint8_t* src, int64_t nbytes, + uintptr_t block_size, int num_threads); + +// A helper function for checking if two wrapped objects implementing `Equals` +// are equal. +template +bool SharedPtrEquals(const std::shared_ptr& left, const std::shared_ptr& right) { + if (left == right) return true; + if (left == NULLPTR || right == NULLPTR) return false; + return left->Equals(*right); +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/parallel.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/parallel.h new file mode 100644 index 0000000000000000000000000000000000000000..80f60fbdb3676a181f1d21b73f2e0d108eb58b78 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/parallel.h @@ -0,0 +1,102 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/status.h" +#include "arrow/util/functional.h" +#include "arrow/util/thread_pool.h" +#include "arrow/util/vector.h" + +namespace arrow { +namespace internal { + +// A parallelizer that takes a `Status(int)` function and calls it with +// arguments between 0 and `num_tasks - 1`, on an arbitrary number of threads. + +template +Status ParallelFor(int num_tasks, FUNCTION&& func, + Executor* executor = internal::GetCpuThreadPool()) { + std::vector> futures(num_tasks); + + for (int i = 0; i < num_tasks; ++i) { + ARROW_ASSIGN_OR_RAISE(futures[i], executor->Submit(func, i)); + } + auto st = Status::OK(); + for (auto& fut : futures) { + st &= fut.status(); + } + return st; +} + +template ::ValueType> +Future> ParallelForAsync( + std::vector inputs, FUNCTION&& func, + Executor* executor = internal::GetCpuThreadPool()) { + std::vector> futures(inputs.size()); + for (size_t i = 0; i < inputs.size(); ++i) { + ARROW_ASSIGN_OR_RAISE(futures[i], executor->Submit(func, i, std::move(inputs[i]))); + } + return All(std::move(futures)) + .Then([](const std::vector>& results) -> Result> { + return UnwrapOrRaise(results); + }); +} + +// A parallelizer that takes a `Status(int)` function and calls it with +// arguments between 0 and `num_tasks - 1`, in sequence or in parallel, +// depending on the input boolean. + +template +Status OptionalParallelFor(bool use_threads, int num_tasks, FUNCTION&& func, + Executor* executor = internal::GetCpuThreadPool()) { + if (use_threads) { + return ParallelFor(num_tasks, std::forward(func), executor); + } else { + for (int i = 0; i < num_tasks; ++i) { + RETURN_NOT_OK(func(i)); + } + return Status::OK(); + } +} + +// A parallelizer that takes a `Result(int index, T item)` function and +// calls it with each item from the input array, in sequence or in parallel, +// depending on the input boolean. + +template ::ValueType> +Future> OptionalParallelForAsync( + bool use_threads, std::vector inputs, FUNCTION&& func, + Executor* executor = internal::GetCpuThreadPool()) { + if (use_threads) { + return ParallelForAsync(std::move(inputs), std::forward(func), executor); + } else { + std::vector result(inputs.size()); + for (size_t i = 0; i < inputs.size(); ++i) { + ARROW_ASSIGN_OR_RAISE(result[i], func(i, inputs[i])); + } + return result; + } +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/pcg_random.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/pcg_random.h new file mode 100644 index 0000000000000000000000000000000000000000..768f2328200fb2635213358226cfdb3f9273c808 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/pcg_random.h @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/vendored/pcg/pcg_random.hpp" // IWYU pragma: export + +namespace arrow { +namespace random { + +using pcg32 = ::arrow_vendored::pcg32; +using pcg64 = ::arrow_vendored::pcg64; +using pcg32_fast = ::arrow_vendored::pcg32_fast; +using pcg64_fast = ::arrow_vendored::pcg64_fast; +using pcg32_oneseq = ::arrow_vendored::pcg32_oneseq; +using pcg64_oneseq = ::arrow_vendored::pcg64_oneseq; + +} // namespace random +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/queue.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/queue.h new file mode 100644 index 0000000000000000000000000000000000000000..6c71fa6e155e8818801db2ccb18127d75d6364a8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/queue.h @@ -0,0 +1,29 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/vendored/ProducerConsumerQueue.h" + +namespace arrow { +namespace util { + +template +using SpscQueue = arrow_vendored::folly::ProducerConsumerQueue; + +} +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/range.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/range.h new file mode 100644 index 0000000000000000000000000000000000000000..20553287985423970c228308742a7f85464a4a87 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/range.h @@ -0,0 +1,258 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace arrow::internal { + +/// Create a vector containing the values from start up to stop +template +std::vector Iota(T start, T stop) { + if (start > stop) { + return {}; + } + std::vector result(static_cast(stop - start)); + std::iota(result.begin(), result.end(), start); + return result; +} + +/// Create a vector containing the values from 0 up to length +template +std::vector Iota(T length) { + return Iota(static_cast(0), length); +} + +/// Create a range from a callable which takes a single index parameter +/// and returns the value of iterator on each call and a length. +/// Only iterators obtained from the same range should be compared, the +/// behaviour generally similar to other STL containers. +template +class LazyRange { + private: + // callable which generates the values + // has to be defined at the beginning of the class for type deduction + const Generator gen_; + // the length of the range + int64_t length_; +#ifdef _MSC_VER + // workaround to VS2010 not supporting decltype properly + // see https://stackoverflow.com/questions/21782846/decltype-for-class-member-function + static Generator gen_static_; +#endif + + public: +#ifdef _MSC_VER + using return_type = decltype(gen_static_(0)); +#else + using return_type = decltype(gen_(0)); +#endif + + /// Construct a new range from a callable and length + LazyRange(Generator gen, int64_t length) : gen_(gen), length_(length) {} + + // Class of the dependent iterator, created implicitly by begin and end + class RangeIter { + public: + using difference_type = int64_t; + using value_type = return_type; + using reference = const value_type&; + using pointer = const value_type*; + using iterator_category = std::forward_iterator_tag; + +#ifdef _MSC_VER + // msvc complains about unchecked iterators, + // see https://stackoverflow.com/questions/21655496/error-c4996-checked-iterators + using _Unchecked_type = typename LazyRange::RangeIter; +#endif + + RangeIter() = delete; + RangeIter(const RangeIter& other) = default; + RangeIter& operator=(const RangeIter& other) = default; + + RangeIter(const LazyRange& range, int64_t index) + : range_(&range), index_(index) {} + + const return_type operator*() const { return range_->gen_(index_); } + + RangeIter operator+(difference_type length) const { + return RangeIter(*range_, index_ + length); + } + + // pre-increment + RangeIter& operator++() { + ++index_; + return *this; + } + + // post-increment + RangeIter operator++(int) { + auto copy = RangeIter(*this); + ++index_; + return copy; + } + + bool operator==(const typename LazyRange::RangeIter& other) const { + return this->index_ == other.index_ && this->range_ == other.range_; + } + + bool operator!=(const typename LazyRange::RangeIter& other) const { + return this->index_ != other.index_ || this->range_ != other.range_; + } + + int64_t operator-(const typename LazyRange::RangeIter& other) const { + return this->index_ - other.index_; + } + + bool operator<(const typename LazyRange::RangeIter& other) const { + return this->index_ < other.index_; + } + + private: + // parent range reference + const LazyRange* range_; + // current index + int64_t index_; + }; + + friend class RangeIter; + + // Create a new begin const iterator + RangeIter begin() { return RangeIter(*this, 0); } + + // Create a new end const iterator + RangeIter end() { return RangeIter(*this, length_); } +}; + +/// Helper function to create a lazy range from a callable (e.g. lambda) and length +template +LazyRange MakeLazyRange(Generator&& gen, int64_t length) { + return LazyRange(std::forward(gen), length); +} + +/// \brief A helper for iterating multiple ranges simultaneously, similar to C++23's +/// zip() view adapter modelled after python's built-in zip() function. +/// +/// \code {.cpp} +/// const std::vector& tables = ... +/// std::function()> GetNames = ... +/// for (auto [table, name] : Zip(tables, GetNames())) { +/// static_assert(std::is_same_v); +/// static_assert(std::is_same_v); +/// // temporaries (like this vector of strings) are kept alive for the +/// // duration of a loop and are safely movable). +/// RegisterTableWithName(std::move(name), &table); +/// } +/// \endcode +/// +/// The zipped sequence ends as soon as any of its member ranges ends. +/// +/// Always use `auto` for the loop's declaration; it will always be a tuple +/// of references so for example using `const auto&` will compile but will +/// *look* like forcing const-ness even though the members of the tuple are +/// still mutable references. +/// +/// NOTE: we *could* make Zip a more full fledged range and enable things like +/// - gtest recognizing it as a container; it currently doesn't since Zip is +/// always mutable so this breaks: +/// EXPECT_THAT(Zip(std::vector{0}, std::vector{1}), +/// ElementsAre(std::tuple{0, 1})); +/// - letting it be random access when possible so we can do things like *sort* +/// parallel ranges +/// - ... +/// +/// However doing this will increase the compile time overhead of using Zip as +/// long as we're still using headers. Therefore until we can use c++20 modules: +/// *don't* extend Zip. +template +struct Zip; + +template +Zip(Ranges&&...) -> Zip, std::index_sequence_for>; + +template +struct Zip, std::index_sequence> { + explicit Zip(Ranges... ranges) : ranges_(std::forward(ranges)...) {} + + std::tuple ranges_; + + using sentinel = std::tuple(ranges_)))...>; + constexpr sentinel end() { return {std::end(std::get(ranges_))...}; } + + struct iterator : std::tuple(ranges_)))...> { + using std::tuple(ranges_)))...>::tuple; + + constexpr auto operator*() { + return std::tuple(*this))...>{*std::get(*this)...}; + } + + constexpr iterator& operator++() { + (++std::get(*this), ...); + return *this; + } + + constexpr bool operator!=(const sentinel& s) const { + bool all_iterators_valid = (... && (std::get(*this) != std::get(s))); + return all_iterators_valid; + } + }; + constexpr iterator begin() { return {std::begin(std::get(ranges_))...}; } +}; + +/// \brief A lazy sequence of integers which starts from 0 and never stops. +/// +/// This can be used in conjunction with Zip() to emulate python's built-in +/// enumerate() function: +/// +/// \code {.cpp} +/// const std::vector& tables = ... +/// for (auto [i, table] : Zip(Enumerate<>, tables)) { +/// std::cout << "#" << i << ": " << table.name() << std::endl; +/// } +/// \endcode +template +constexpr auto Enumerate = [] { + struct { + struct sentinel {}; + constexpr sentinel end() const { return {}; } + + struct iterator { + I value{0}; + + constexpr I operator*() { return value; } + + constexpr iterator& operator++() { + ++value; + return *this; + } + + constexpr std::true_type operator!=(sentinel) const { return {}; } + }; + constexpr iterator begin() const { return {}; } + } out; + + return out; +}(); + +} // namespace arrow::internal diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/rows_to_batches.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/rows_to_batches.h new file mode 100644 index 0000000000000000000000000000000000000000..8ad254df200efc08c5c9a4956e0e781b496b2b07 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/rows_to_batches.h @@ -0,0 +1,163 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/table_builder.h" +#include "arrow/util/iterator.h" + +#include + +namespace arrow::util { + +namespace detail { + +// Default identity function row accessor. Used to for the common case where the value +// of each row iterated over is it's self also directly iterable. +[[nodiscard]] constexpr inline auto MakeDefaultRowAccessor() { + return [](auto& x) -> Result { return std::ref(x); }; +} + +// Meta-function to check if a type `T` is a range (iterable using `std::begin()` / +// `std::end()`). `is_range::value` will be false if `T` is not a valid range. +template +struct is_range : std::false_type {}; + +template +struct is_range())), + decltype(std::end(std::declval()))>> : std::true_type { +}; + +} // namespace detail + +/// Delete overload for `const Range&& rows` because the data's lifetime must exceed +/// the lifetime of the function call. `data` will be read when client uses the +/// `RecordBatchReader` +template +[[nodiscard]] typename std::enable_if_t::value, + Result>> +/* Result>> */ RowsToBatches( + const std::shared_ptr& schema, const Range&& rows, + DataPointConvertor&& data_point_convertor, + RowAccessor&& row_accessor = detail::MakeDefaultRowAccessor(), + MemoryPool* pool = default_memory_pool(), + const std::size_t batch_size = 1024) = delete; + +/// \brief Utility function for converting any row-based structure into an +/// `arrow::RecordBatchReader` (this can be easily converted to an `arrow::Table` using +/// `arrow::RecordBatchReader::ToTable()`). +/// +/// Examples of supported types: +/// - `std::vector>>` +/// - `std::vector` + +/// If `rows` (client’s row-based structure) is not a valid C++ range, the client will +/// need to either make it iterable, or make an adapter/wrapper that is a valid C++ +/// range. + +/// The client must provide a `DataPointConvertor` callable type that will convert the +/// structure’s data points into the corresponding arrow types. + +/// Complex nested rows can be supported by providing a custom `row_accessor` instead +/// of the default. + +/// Example usage: +/// \code{.cpp} +/// auto IntConvertor = [](ArrayBuilder& array_builder, int value) { +/// return static_cast(array_builder).Append(value); +/// }; +/// std::vector> data = {{1, 2, 4}, {5, 6, 7}}; +/// auto batches = RowsToBatches(kTestSchema, data, IntConvertor); +/// \endcode + +/// \param[in] schema - The schema to be used in the `RecordBatchReader` + +/// \param[in] rows - Iterable row-based structure that will be converted to arrow +/// batches + +/// \param[in] data_point_convertor - Client provided callable type that will convert +/// the structure’s data points into the corresponding arrow types. The convertor must +/// return an error `Status` if an error happens during conversion. + +/// \param[in] row_accessor - In the common case where the value of each row iterated +/// over is it's self also directly iterable, the client can just use the default. +/// The provided callable must take the values of the `rows` range and return a +/// `std::reference_wrapper` to the data points in a given row. The data points +/// must be in order of their corresponding fields in the schema. +/// see: /ref `MakeDefaultRowAccessor` + +/// \param[in] pool - The MemoryPool to use for allocations. + +/// \param[in] batch_size - Number of rows to insert into each RecordBatch. + +/// \return `Result>>` result will be a +/// `std::shared_ptr>` if not errors occurred, else an error status. +template +[[nodiscard]] typename std::enable_if_t::value, + Result>> +/* Result>> */ RowsToBatches( + const std::shared_ptr& schema, const Range& rows, + DataPointConvertor&& data_point_convertor, + RowAccessor&& row_accessor = detail::MakeDefaultRowAccessor(), + MemoryPool* pool = default_memory_pool(), const std::size_t batch_size = 1024) { + auto make_next_batch = + [pool = pool, batch_size = batch_size, rows_ittr = std::begin(rows), + rows_ittr_end = std::end(rows), schema = schema, + row_accessor = std::forward(row_accessor), + data_point_convertor = std::forward( + data_point_convertor)]() mutable -> Result> { + if (rows_ittr == rows_ittr_end) return NULLPTR; + + ARROW_ASSIGN_OR_RAISE(auto record_batch_builder, + RecordBatchBuilder::Make(schema, pool, batch_size)); + + for (size_t i = 0; i < batch_size && (rows_ittr != rows_ittr_end); + i++, std::advance(rows_ittr, 1)) { + int col_index = 0; + ARROW_ASSIGN_OR_RAISE(const auto row, row_accessor(*rows_ittr)); + + // If the accessor returns a `std::reference_wrapper` unwrap if + const auto& row_unwrapped = [&]() { + if constexpr (detail::is_range::value) + return row; + else + return row.get(); + }(); + + for (auto& data_point : row_unwrapped) { + ArrayBuilder* array_builder = record_batch_builder->GetField(col_index); + ARROW_RETURN_IF(array_builder == NULLPTR, + Status::Invalid("array_builder == NULLPTR")); + + ARROW_RETURN_NOT_OK(data_point_convertor(*array_builder, data_point)); + col_index++; + } + } + + ARROW_ASSIGN_OR_RAISE(auto result, record_batch_builder->Flush()); + return result; + }; + return RecordBatchReader::MakeFromIterator(MakeFunctionIterator(make_next_batch), + schema); +} + +} // namespace arrow::util diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/spaced.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/spaced.h new file mode 100644 index 0000000000000000000000000000000000000000..8265e1d22ae0e78d7343b2fce6a0de4bc669ccc8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/spaced.h @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/util/bit_run_reader.h" + +namespace arrow { +namespace util { +namespace internal { + +/// \brief Compress the buffer to spaced, excluding the null entries. +/// +/// \param[in] src the source buffer +/// \param[in] num_values the size of source buffer +/// \param[in] valid_bits bitmap data indicating position of valid slots +/// \param[in] valid_bits_offset offset into valid_bits +/// \param[out] output the output buffer spaced +/// \return The size of spaced buffer. +template +inline int SpacedCompress(const T* src, int num_values, const uint8_t* valid_bits, + int64_t valid_bits_offset, T* output) { + int num_valid_values = 0; + + arrow::internal::SetBitRunReader reader(valid_bits, valid_bits_offset, num_values); + while (true) { + const auto run = reader.NextRun(); + if (run.length == 0) { + break; + } + std::memcpy(output + num_valid_values, src + run.position, run.length * sizeof(T)); + num_valid_values += static_cast(run.length); + } + + return num_valid_values; +} + +/// \brief Relocate values in buffer into positions of non-null values as indicated by +/// a validity bitmap. +/// +/// \param[in, out] buffer the in-place buffer +/// \param[in] num_values total size of buffer including null slots +/// \param[in] null_count number of null slots +/// \param[in] valid_bits bitmap data indicating position of valid slots +/// \param[in] valid_bits_offset offset into valid_bits +/// \return The number of values expanded, including nulls. +template +inline int SpacedExpand(T* buffer, int num_values, int null_count, + const uint8_t* valid_bits, int64_t valid_bits_offset) { + // Point to end as we add the spacing from the back. + int idx_decode = num_values - null_count; + + // Depending on the number of nulls, some of the value slots in buffer may + // be uninitialized, and this will cause valgrind warnings / potentially UB + std::memset(static_cast(buffer + idx_decode), 0, null_count * sizeof(T)); + if (idx_decode == 0) { + // All nulls, nothing more to do + return num_values; + } + + arrow::internal::ReverseSetBitRunReader reader(valid_bits, valid_bits_offset, + num_values); + while (true) { + const auto run = reader.NextRun(); + if (run.length == 0) { + break; + } + idx_decode -= static_cast(run.length); + assert(idx_decode >= 0); + std::memmove(buffer + run.position, buffer + idx_decode, run.length * sizeof(T)); + } + + // Otherwise caller gave an incorrect null_count + assert(idx_decode == 0); + return num_values; +} + +} // namespace internal +} // namespace util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/span.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/span.h new file mode 100644 index 0000000000000000000000000000000000000000..71cf9ed44890a78675e4187e03b4c01bff60ae54 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/span.h @@ -0,0 +1,156 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +namespace arrow::util { + +template +class span; + +// This trait is used to check if a type R can be used to construct a span. +// Specifically, it checks if std::data(R) and std::size(R) are valid expressions +// that may be passed to the span(T*, size_t) constructor. The reason this trait +// is needed rather than expressing this directly in the relevant span constructor +// is that this check requires instantiating span, which would violate the +// C++ standard if written directly in the constructor's enable_if clause +// because span is an incomplete type at that point. By defining this trait +// instead, we add an extra level of indirection that lets us delay the +// evaluation of the template until the first time the associated constructor +// is actually called, at which point span is a complete type. +// +// Note that most compilers do support the noncompliant construct, but nvcc +// does not. See https://github.com/apache/arrow/issues/40252 +template +struct ConstructibleFromDataAndSize : std::false_type {}; + +template +struct ConstructibleFromDataAndSize< + span, R, + std::void_t{std::data(std::declval()), + std::size(std::declval())})>> : std::true_type {}; + +/// std::span polyfill. +/// +/// Does not support static extents. +template +class span { + static_assert(sizeof(T), + R"( +std::span allows contiguous_iterators instead of just pointers, the enforcement +of which requires T to be a complete type. arrow::util::span does not support +contiguous_iterators, but T is still required to be a complete type to prevent +writing code which would break when it is replaced by std::span.)"); + + public: + using element_type = T; + using value_type = std::remove_cv_t; + using iterator = T*; + using const_iterator = T const*; + + span() = default; + span(const span&) = default; + span& operator=(const span&) = default; + + template >> + // NOLINTNEXTLINE runtime/explicit + constexpr span(span mut) : span{mut.data(), mut.size()} {} + + constexpr span(T* data, size_t count) : data_{data}, size_{count} {} + + constexpr span(T* begin, T* end) + : data_{begin}, size_{static_cast(end - begin)} {} + + template < + typename R, + std::enable_if_t, R>::value, bool> = true, + typename DisableUnlessSimilarTypes = std::enable_if_t()))>>, + std::decay_t>>> + // NOLINTNEXTLINE runtime/explicit, non-const reference + constexpr span(R&& range) : span{std::data(range), std::size(range)} {} + + constexpr T* begin() const { return data_; } + constexpr T* end() const { return data_ + size_; } + constexpr T* data() const { return data_; } + + constexpr size_t size() const { return size_; } + constexpr size_t size_bytes() const { return size_ * sizeof(T); } + constexpr bool empty() const { return size_ == 0; } + + constexpr T& operator[](size_t i) { return data_[i]; } + constexpr const T& operator[](size_t i) const { return data_[i]; } + + constexpr span subspan(size_t offset) const { + if (offset > size_) return {data_, data_}; + return {data_ + offset, size_ - offset}; + } + + constexpr span subspan(size_t offset, size_t count) const { + auto out = subspan(offset); + if (count < out.size_) { + out.size_ = count; + } + return out; + } + + constexpr bool operator==(span const& other) const { + if (size_ != other.size_) return false; + + if constexpr (std::is_integral_v) { + if (size_ == 0) { + return true; // memcmp does not handle null pointers, even if size_ == 0 + } + return std::memcmp(data_, other.data_, size_bytes()) == 0; + } else { + T* ptr = data_; + for (T const& e : other) { + if (*ptr++ != e) return false; + } + return true; + } + } + constexpr bool operator!=(span const& other) const { return !(*this == other); } + + private: + T* data_{}; + size_t size_{}; +}; + +template +span(R& range) -> span>; + +template +span(T*, size_t) -> span; + +template +constexpr span as_bytes(span s) { + return {reinterpret_cast(s.data()), s.size_bytes()}; +} + +template +constexpr span as_writable_bytes(span s) { + return {reinterpret_cast(s.data()), s.size_bytes()}; +} + +} // namespace arrow::util diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/string_builder.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/string_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..7c05ccd51f7fddaf3fbab65b0ba0fc1a8e5cf796 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/string_builder.h @@ -0,0 +1,84 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. template + +#pragma once + +#include +#include +#include +#include + +#include "arrow/util/visibility.h" + +namespace arrow { +namespace util { + +namespace detail { + +class ARROW_EXPORT StringStreamWrapper { + public: + StringStreamWrapper(); + ~StringStreamWrapper(); + + std::ostream& stream() { return ostream_; } + std::string str(); + + protected: + std::unique_ptr sstream_; + std::ostream& ostream_; +}; + +} // namespace detail + +template +void StringBuilderRecursive(std::ostream& stream, Head&& head) { + stream << head; +} + +template +void StringBuilderRecursive(std::ostream& stream, Head&& head, Tail&&... tail) { + StringBuilderRecursive(stream, std::forward(head)); + StringBuilderRecursive(stream, std::forward(tail)...); +} + +template +std::string StringBuilder(Args&&... args) { + detail::StringStreamWrapper ss; + StringBuilderRecursive(ss.stream(), std::forward(args)...); + return ss.str(); +} + +/// CRTP helper for declaring string representation. Defines operator<< +template +class ToStringOstreamable { + public: + ~ToStringOstreamable() { + static_assert( + std::is_same().ToString()), std::string>::value, + "ToStringOstreamable depends on the method T::ToString() const"); + } + + private: + const T& cast() const { return static_cast(*this); } + + friend inline std::ostream& operator<<(std::ostream& os, const ToStringOstreamable& t) { + return os << t.cast().ToString(); + } +}; + +} // namespace util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/tracing.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/tracing.h new file mode 100644 index 0000000000000000000000000000000000000000..d7808256418eef0faaf54a189d11c6896583d68b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/tracing.h @@ -0,0 +1,45 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/util/visibility.h" + +namespace arrow { +namespace util { +namespace tracing { + +class ARROW_EXPORT SpanDetails { + public: + virtual ~SpanDetails() {} +}; + +class ARROW_EXPORT Span { + public: + Span() noexcept; + /// True if this span has been started with START_SPAN + bool valid() const; + /// End the span early + void reset(); + std::unique_ptr details; +}; + +} // namespace tracing +} // namespace util +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/trie.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/trie.h new file mode 100644 index 0000000000000000000000000000000000000000..7815d4d1ecc1d66ba20c45eddb6c626833aa54e2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/trie.h @@ -0,0 +1,243 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace internal { + +// A non-zero-terminated small string class. +// std::string usually has a small string optimization +// (see review at https://shaharmike.com/cpp/std-string/) +// but this one allows tight control and optimization of memory layout. +template +class SmallString { + public: + SmallString() : length_(0) {} + + template + SmallString(const T& v) { // NOLINT implicit constructor + *this = std::string_view(v); + } + + SmallString& operator=(const std::string_view s) { +#ifndef NDEBUG + CheckSize(s.size()); +#endif + length_ = static_cast(s.size()); + std::memcpy(data_, s.data(), length_); + return *this; + } + + SmallString& operator=(const std::string& s) { + *this = std::string_view(s); + return *this; + } + + SmallString& operator=(const char* s) { + *this = std::string_view(s); + return *this; + } + + explicit operator std::string_view() const { return std::string_view(data_, length_); } + + const char* data() const { return data_; } + size_t length() const { return length_; } + bool empty() const { return length_ == 0; } + char operator[](size_t pos) const { +#ifdef NDEBUG + assert(pos <= length_); +#endif + return data_[pos]; + } + + SmallString substr(size_t pos) const { + return SmallString(std::string_view(*this).substr(pos)); + } + + SmallString substr(size_t pos, size_t count) const { + return SmallString(std::string_view(*this).substr(pos, count)); + } + + template + bool operator==(T&& other) const { + return std::string_view(*this) == std::string_view(std::forward(other)); + } + + template + bool operator!=(T&& other) const { + return std::string_view(*this) != std::string_view(std::forward(other)); + } + + protected: + uint8_t length_; + char data_[N]; + + void CheckSize(size_t n) { assert(n <= N); } +}; + +template +std::ostream& operator<<(std::ostream& os, const SmallString& str) { + return os << std::string_view(str); +} + +// A trie class for byte strings, optimized for small sets of short strings. +// This class is immutable by design, use a TrieBuilder to construct it. +class ARROW_EXPORT Trie { + using index_type = int16_t; + using fast_index_type = int_fast16_t; + static constexpr auto kMaxIndex = std::numeric_limits::max(); + + public: + Trie() : size_(0) {} + Trie(Trie&&) = default; + Trie& operator=(Trie&&) = default; + + int32_t Find(std::string_view s) const { + const Node* node = &nodes_[0]; + fast_index_type pos = 0; + if (s.length() > static_cast(kMaxIndex)) { + return -1; + } + fast_index_type remaining = static_cast(s.length()); + + while (remaining > 0) { + auto substring_length = node->substring_length(); + if (substring_length > 0) { + auto substring_data = node->substring_data(); + if (remaining < substring_length) { + // Input too short + return -1; + } + for (fast_index_type i = 0; i < substring_length; ++i) { + if (s[pos++] != substring_data[i]) { + // Mismatching substring + return -1; + } + --remaining; + } + if (remaining == 0) { + // Matched node exactly + return node->found_index_; + } + } + // Lookup child using next input character + if (node->child_lookup_ == -1) { + // Input too long + return -1; + } + auto c = static_cast(s[pos++]); + --remaining; + auto child_index = lookup_table_[node->child_lookup_ * 256 + c]; + if (child_index == -1) { + // Child not found + return -1; + } + node = &nodes_[child_index]; + } + + // Input exhausted + if (node->substring_.empty()) { + // Matched node exactly + return node->found_index_; + } else { + return -1; + } + } + + Status Validate() const; + + void Dump() const; + + protected: + static constexpr size_t kNodeSize = 16; + static constexpr auto kMaxSubstringLength = + kNodeSize - 2 * sizeof(index_type) - sizeof(int8_t); + + struct Node { + // If this node is a valid end of string, index of found string, otherwise -1 + index_type found_index_; + // Base index for child lookup in lookup_table_ (-1 if no child nodes) + index_type child_lookup_; + // The substring for this node. + SmallString substring_; + + fast_index_type substring_length() const { + return static_cast(substring_.length()); + } + const char* substring_data() const { return substring_.data(); } + }; + + static_assert(sizeof(Node) == kNodeSize, "Unexpected node size"); + + ARROW_DISALLOW_COPY_AND_ASSIGN(Trie); + + void Dump(const Node* node, const std::string& indent) const; + + // Node table: entry 0 is the root node + std::vector nodes_; + + // Indexed lookup structure: gives index in node table, or -1 if not found + std::vector lookup_table_; + + // Number of entries + index_type size_; + + friend class TrieBuilder; +}; + +class ARROW_EXPORT TrieBuilder { + using index_type = Trie::index_type; + using fast_index_type = Trie::fast_index_type; + + public: + TrieBuilder(); + Status Append(std::string_view s, bool allow_duplicate = false); + Trie Finish(); + + protected: + // Extend the lookup table by 256 entries, return the index of the new span + Status ExtendLookupTable(index_type* out_lookup_index); + // Split the node given by the index at the substring index `split_at` + Status SplitNode(fast_index_type node_index, fast_index_type split_at); + // Append an already constructed child node to the parent + Status AppendChildNode(Trie::Node* parent, uint8_t ch, Trie::Node&& node); + // Create a matching child node from this parent + Status CreateChildNode(Trie::Node* parent, uint8_t ch, std::string_view substring); + Status CreateChildNode(Trie::Node* parent, char ch, std::string_view substring); + + Trie trie_; + + static constexpr auto kMaxIndex = std::numeric_limits::max(); +}; + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/type_traits.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/type_traits.h new file mode 100644 index 0000000000000000000000000000000000000000..c1906152423c97e11ef9f577f46c7f4d4d124597 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/type_traits.h @@ -0,0 +1,46 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +namespace arrow { +namespace internal { + +/// \brief Metafunction to allow checking if a type matches any of another set of types +template +struct IsOneOf : std::false_type {}; /// Base case: nothing has matched + +template +struct IsOneOf { + /// Recursive case: T == U or T matches any other types provided (not including U). + static constexpr bool value = std::is_same::value || IsOneOf::value; +}; + +/// \brief Shorthand for using IsOneOf + std::enable_if +template +using EnableIfIsOneOf = typename std::enable_if::value, T>::type; + +/// \brief is_null_pointer from C++17 +template +struct is_null_pointer : std::is_same::type> { +}; + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/unreachable.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/unreachable.h new file mode 100644 index 0000000000000000000000000000000000000000..d2e383e714b3eb8e0a0b6a23b1086913093a5c29 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/unreachable.h @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/util/visibility.h" + +#include + +namespace arrow { + +[[noreturn]] ARROW_EXPORT void Unreachable(const char* message = "Unreachable"); + +[[noreturn]] ARROW_EXPORT void Unreachable(std::string_view message); + +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/value_parsing.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/value_parsing.h new file mode 100644 index 0000000000000000000000000000000000000000..b3c711840f3e2fd3d88d40f6ea71a4862866f7fb --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/value_parsing.h @@ -0,0 +1,928 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This is a private header for string-to-number parsing utilities + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/type.h" +#include "arrow/type_traits.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/config.h" +#include "arrow/util/macros.h" +#include "arrow/util/time.h" +#include "arrow/util/visibility.h" +#include "arrow/vendored/datetime.h" +#include "arrow/vendored/strptime.h" + +namespace arrow { + +/// \brief A virtual string to timestamp parser +class ARROW_EXPORT TimestampParser { + public: + virtual ~TimestampParser() = default; + + virtual bool operator()(const char* s, size_t length, TimeUnit::type out_unit, + int64_t* out, + bool* out_zone_offset_present = NULLPTR) const = 0; + + virtual const char* kind() const = 0; + + virtual const char* format() const; + + /// \brief Create a TimestampParser that recognizes strptime-like format strings + static std::shared_ptr MakeStrptime(std::string format); + + /// \brief Create a TimestampParser that recognizes (locale-agnostic) ISO8601 + /// timestamps + static std::shared_ptr MakeISO8601(); +}; + +namespace internal { + +/// \brief The entry point for conversion from strings. +/// +/// Specializations of StringConverter for `ARROW_TYPE` must define: +/// - A default constructible member type `value_type` which will be yielded on a +/// successful parse. +/// - The static member function `Convert`, callable with signature +/// `(const ARROW_TYPE& t, const char* s, size_t length, value_type* out)`. +/// `Convert` returns truthy for successful parses and assigns the parsed values to +/// `*out`. Parameters required for parsing (for example a timestamp's TimeUnit) +/// are acquired from the type parameter `t`. +template +struct StringConverter; + +template +struct is_parseable { + template ::value_type> + static std::true_type Test(U*); + + template + static std::false_type Test(...); + + static constexpr bool value = decltype(Test(NULLPTR))::value; +}; + +template +using enable_if_parseable = enable_if_t::value, R>; + +template <> +struct StringConverter { + using value_type = bool; + + bool Convert(const BooleanType&, const char* s, size_t length, value_type* out) { + if (length == 1) { + // "0" or "1"? + if (s[0] == '0') { + *out = false; + return true; + } + if (s[0] == '1') { + *out = true; + return true; + } + return false; + } + if (length == 4) { + // "true"? + *out = true; + return ((s[0] == 't' || s[0] == 'T') && (s[1] == 'r' || s[1] == 'R') && + (s[2] == 'u' || s[2] == 'U') && (s[3] == 'e' || s[3] == 'E')); + } + if (length == 5) { + // "false"? + *out = false; + return ((s[0] == 'f' || s[0] == 'F') && (s[1] == 'a' || s[1] == 'A') && + (s[2] == 'l' || s[2] == 'L') && (s[3] == 's' || s[3] == 'S') && + (s[4] == 'e' || s[4] == 'E')); + } + return false; + } +}; + +// Ideas for faster float parsing: +// - http://rapidjson.org/md_doc_internals.html#ParsingDouble +// - https://github.com/google/double-conversion [used here] +// - https://github.com/achan001/dtoa-fast + +ARROW_EXPORT +bool StringToFloat(const char* s, size_t length, char decimal_point, float* out); + +ARROW_EXPORT +bool StringToFloat(const char* s, size_t length, char decimal_point, double* out); + +template <> +struct StringConverter { + using value_type = float; + + explicit StringConverter(char decimal_point = '.') : decimal_point(decimal_point) {} + + bool Convert(const FloatType&, const char* s, size_t length, value_type* out) { + return ARROW_PREDICT_TRUE(StringToFloat(s, length, decimal_point, out)); + } + + private: + const char decimal_point; +}; + +template <> +struct StringConverter { + using value_type = double; + + explicit StringConverter(char decimal_point = '.') : decimal_point(decimal_point) {} + + bool Convert(const DoubleType&, const char* s, size_t length, value_type* out) { + return ARROW_PREDICT_TRUE(StringToFloat(s, length, decimal_point, out)); + } + + private: + const char decimal_point; +}; + +// NOTE: HalfFloatType would require a half<->float conversion library + +inline uint8_t ParseDecimalDigit(char c) { return static_cast(c - '0'); } + +#define PARSE_UNSIGNED_ITERATION(C_TYPE) \ + if (length > 0) { \ + uint8_t digit = ParseDecimalDigit(*s++); \ + result = static_cast(result * 10U); \ + length--; \ + if (ARROW_PREDICT_FALSE(digit > 9U)) { \ + /* Non-digit */ \ + return false; \ + } \ + result = static_cast(result + digit); \ + } else { \ + break; \ + } + +#define PARSE_UNSIGNED_ITERATION_LAST(C_TYPE) \ + if (length > 0) { \ + if (ARROW_PREDICT_FALSE(result > std::numeric_limits::max() / 10U)) { \ + /* Overflow */ \ + return false; \ + } \ + uint8_t digit = ParseDecimalDigit(*s++); \ + result = static_cast(result * 10U); \ + C_TYPE new_result = static_cast(result + digit); \ + if (ARROW_PREDICT_FALSE(--length > 0)) { \ + /* Too many digits */ \ + return false; \ + } \ + if (ARROW_PREDICT_FALSE(digit > 9U)) { \ + /* Non-digit */ \ + return false; \ + } \ + if (ARROW_PREDICT_FALSE(new_result < result)) { \ + /* Overflow */ \ + return false; \ + } \ + result = new_result; \ + } + +inline bool ParseUnsigned(const char* s, size_t length, uint8_t* out) { + uint8_t result = 0; + + do { + PARSE_UNSIGNED_ITERATION(uint8_t); + PARSE_UNSIGNED_ITERATION(uint8_t); + PARSE_UNSIGNED_ITERATION_LAST(uint8_t); + } while (false); + *out = result; + return true; +} + +inline bool ParseUnsigned(const char* s, size_t length, uint16_t* out) { + uint16_t result = 0; + do { + PARSE_UNSIGNED_ITERATION(uint16_t); + PARSE_UNSIGNED_ITERATION(uint16_t); + PARSE_UNSIGNED_ITERATION(uint16_t); + PARSE_UNSIGNED_ITERATION(uint16_t); + PARSE_UNSIGNED_ITERATION_LAST(uint16_t); + } while (false); + *out = result; + return true; +} + +inline bool ParseUnsigned(const char* s, size_t length, uint32_t* out) { + uint32_t result = 0; + do { + PARSE_UNSIGNED_ITERATION(uint32_t); + PARSE_UNSIGNED_ITERATION(uint32_t); + PARSE_UNSIGNED_ITERATION(uint32_t); + PARSE_UNSIGNED_ITERATION(uint32_t); + PARSE_UNSIGNED_ITERATION(uint32_t); + + PARSE_UNSIGNED_ITERATION(uint32_t); + PARSE_UNSIGNED_ITERATION(uint32_t); + PARSE_UNSIGNED_ITERATION(uint32_t); + PARSE_UNSIGNED_ITERATION(uint32_t); + + PARSE_UNSIGNED_ITERATION_LAST(uint32_t); + } while (false); + *out = result; + return true; +} + +inline bool ParseUnsigned(const char* s, size_t length, uint64_t* out) { + uint64_t result = 0; + do { + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + PARSE_UNSIGNED_ITERATION(uint64_t); + + PARSE_UNSIGNED_ITERATION_LAST(uint64_t); + } while (false); + *out = result; + return true; +} + +#undef PARSE_UNSIGNED_ITERATION +#undef PARSE_UNSIGNED_ITERATION_LAST + +template +bool ParseHex(const char* s, size_t length, T* out) { + // lets make sure that the length of the string is not too big + if (!ARROW_PREDICT_TRUE(sizeof(T) * 2 >= length && length > 0)) { + return false; + } + T result = 0; + for (size_t i = 0; i < length; i++) { + result = static_cast(result << 4); + if (s[i] >= '0' && s[i] <= '9') { + result = static_cast(result | (s[i] - '0')); + } else if (s[i] >= 'A' && s[i] <= 'F') { + result = static_cast(result | (s[i] - 'A' + 10)); + } else if (s[i] >= 'a' && s[i] <= 'f') { + result = static_cast(result | (s[i] - 'a' + 10)); + } else { + /* Non-digit */ + return false; + } + } + *out = result; + return true; +} + +template +struct StringToUnsignedIntConverterMixin { + using value_type = typename ARROW_TYPE::c_type; + + bool Convert(const ARROW_TYPE&, const char* s, size_t length, value_type* out) { + if (ARROW_PREDICT_FALSE(length == 0)) { + return false; + } + // If it starts with 0x then its hex + if (length > 2 && s[0] == '0' && ((s[1] == 'x') || (s[1] == 'X'))) { + length -= 2; + s += 2; + + return ARROW_PREDICT_TRUE(ParseHex(s, length, out)); + } + // Skip leading zeros + while (length > 0 && *s == '0') { + length--; + s++; + } + return ParseUnsigned(s, length, out); + } +}; + +template <> +struct StringConverter : public StringToUnsignedIntConverterMixin { + using StringToUnsignedIntConverterMixin::StringToUnsignedIntConverterMixin; +}; + +template <> +struct StringConverter + : public StringToUnsignedIntConverterMixin { + using StringToUnsignedIntConverterMixin::StringToUnsignedIntConverterMixin; +}; + +template <> +struct StringConverter + : public StringToUnsignedIntConverterMixin { + using StringToUnsignedIntConverterMixin::StringToUnsignedIntConverterMixin; +}; + +template <> +struct StringConverter + : public StringToUnsignedIntConverterMixin { + using StringToUnsignedIntConverterMixin::StringToUnsignedIntConverterMixin; +}; + +template +struct StringToSignedIntConverterMixin { + using value_type = typename ARROW_TYPE::c_type; + using unsigned_type = typename std::make_unsigned::type; + + bool Convert(const ARROW_TYPE&, const char* s, size_t length, value_type* out) { + static constexpr auto max_positive = + static_cast(std::numeric_limits::max()); + // Assuming two's complement + static constexpr unsigned_type max_negative = max_positive + 1; + bool negative = false; + unsigned_type unsigned_value = 0; + + if (ARROW_PREDICT_FALSE(length == 0)) { + return false; + } + // If it starts with 0x then its hex + if (length > 2 && s[0] == '0' && ((s[1] == 'x') || (s[1] == 'X'))) { + length -= 2; + s += 2; + + if (!ARROW_PREDICT_TRUE(ParseHex(s, length, &unsigned_value))) { + return false; + } + *out = static_cast(unsigned_value); + return true; + } + + if (*s == '-') { + negative = true; + s++; + if (--length == 0) { + return false; + } + } + // Skip leading zeros + while (length > 0 && *s == '0') { + length--; + s++; + } + if (!ARROW_PREDICT_TRUE(ParseUnsigned(s, length, &unsigned_value))) { + return false; + } + if (negative) { + if (ARROW_PREDICT_FALSE(unsigned_value > max_negative)) { + return false; + } + // To avoid both compiler warnings (with unsigned negation) + // and undefined behaviour (with signed negation overflow), + // use the expanded formula for 2's complement negation. + *out = static_cast(~unsigned_value + 1); + } else { + if (ARROW_PREDICT_FALSE(unsigned_value > max_positive)) { + return false; + } + *out = static_cast(unsigned_value); + } + return true; + } +}; + +template <> +struct StringConverter : public StringToSignedIntConverterMixin { + using StringToSignedIntConverterMixin::StringToSignedIntConverterMixin; +}; + +template <> +struct StringConverter : public StringToSignedIntConverterMixin { + using StringToSignedIntConverterMixin::StringToSignedIntConverterMixin; +}; + +template <> +struct StringConverter : public StringToSignedIntConverterMixin { + using StringToSignedIntConverterMixin::StringToSignedIntConverterMixin; +}; + +template <> +struct StringConverter : public StringToSignedIntConverterMixin { + using StringToSignedIntConverterMixin::StringToSignedIntConverterMixin; +}; + +namespace detail { + +// Inline-able ISO-8601 parser + +using ts_type = TimestampType::c_type; + +template +static inline bool ParseHH(const char* s, Duration* out) { + uint8_t hours = 0; + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 0, 2, &hours))) { + return false; + } + if (ARROW_PREDICT_FALSE(hours >= 24)) { + return false; + } + *out = std::chrono::duration_cast(std::chrono::hours(hours)); + return true; +} + +template +static inline bool ParseHH_MM(const char* s, Duration* out) { + uint8_t hours = 0; + uint8_t minutes = 0; + if (ARROW_PREDICT_FALSE(s[2] != ':')) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 0, 2, &hours))) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 3, 2, &minutes))) { + return false; + } + if (ARROW_PREDICT_FALSE(hours >= 24)) { + return false; + } + if (ARROW_PREDICT_FALSE(minutes >= 60)) { + return false; + } + *out = std::chrono::duration_cast(std::chrono::hours(hours) + + std::chrono::minutes(minutes)); + return true; +} + +template +static inline bool ParseHHMM(const char* s, Duration* out) { + uint8_t hours = 0; + uint8_t minutes = 0; + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 0, 2, &hours))) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 2, 2, &minutes))) { + return false; + } + if (ARROW_PREDICT_FALSE(hours >= 24)) { + return false; + } + if (ARROW_PREDICT_FALSE(minutes >= 60)) { + return false; + } + *out = std::chrono::duration_cast(std::chrono::hours(hours) + + std::chrono::minutes(minutes)); + return true; +} + +template +static inline bool ParseHH_MM_SS(const char* s, Duration* out) { + uint8_t hours = 0; + uint8_t minutes = 0; + uint8_t seconds = 0; + if (ARROW_PREDICT_FALSE(s[2] != ':') || ARROW_PREDICT_FALSE(s[5] != ':')) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 0, 2, &hours))) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 3, 2, &minutes))) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 6, 2, &seconds))) { + return false; + } + if (ARROW_PREDICT_FALSE(hours >= 24)) { + return false; + } + if (ARROW_PREDICT_FALSE(minutes >= 60)) { + return false; + } + if (ARROW_PREDICT_FALSE(seconds >= 60)) { + return false; + } + *out = std::chrono::duration_cast(std::chrono::hours(hours) + + std::chrono::minutes(minutes) + + std::chrono::seconds(seconds)); + return true; +} + +static inline bool ParseSubSeconds(const char* s, size_t length, TimeUnit::type unit, + uint32_t* out) { + // The decimal point has been peeled off at this point + + // Fail if number of decimal places provided exceeds what the unit can hold. + // Calculate how many trailing decimal places are omitted for the unit + // e.g. if 4 decimal places are provided and unit is MICRO, 2 are missing + size_t omitted = 0; + switch (unit) { + case TimeUnit::MILLI: + if (ARROW_PREDICT_FALSE(length > 3)) { + return false; + } + if (length < 3) { + omitted = 3 - length; + } + break; + case TimeUnit::MICRO: + if (ARROW_PREDICT_FALSE(length > 6)) { + return false; + } + if (length < 6) { + omitted = 6 - length; + } + break; + case TimeUnit::NANO: + if (ARROW_PREDICT_FALSE(length > 9)) { + return false; + } + if (length < 9) { + omitted = 9 - length; + } + break; + default: + return false; + } + + if (ARROW_PREDICT_TRUE(omitted == 0)) { + return ParseUnsigned(s, length, out); + } else { + uint32_t subseconds = 0; + bool success = ParseUnsigned(s, length, &subseconds); + if (ARROW_PREDICT_TRUE(success)) { + switch (omitted) { + case 1: + *out = subseconds * 10; + break; + case 2: + *out = subseconds * 100; + break; + case 3: + *out = subseconds * 1000; + break; + case 4: + *out = subseconds * 10000; + break; + case 5: + *out = subseconds * 100000; + break; + case 6: + *out = subseconds * 1000000; + break; + case 7: + *out = subseconds * 10000000; + break; + case 8: + *out = subseconds * 100000000; + break; + default: + // Impossible case + break; + } + return true; + } else { + return false; + } + } +} + +} // namespace detail + +template +static inline bool ParseYYYY_MM_DD(const char* s, Duration* since_epoch) { + uint16_t year = 0; + uint8_t month = 0; + uint8_t day = 0; + if (ARROW_PREDICT_FALSE(s[4] != '-') || ARROW_PREDICT_FALSE(s[7] != '-')) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 0, 4, &year))) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 5, 2, &month))) { + return false; + } + if (ARROW_PREDICT_FALSE(!ParseUnsigned(s + 8, 2, &day))) { + return false; + } + arrow_vendored::date::year_month_day ymd{arrow_vendored::date::year{year}, + arrow_vendored::date::month{month}, + arrow_vendored::date::day{day}}; + if (ARROW_PREDICT_FALSE(!ymd.ok())) return false; + + *since_epoch = std::chrono::duration_cast( + arrow_vendored::date::sys_days{ymd}.time_since_epoch()); + return true; +} + +static inline bool ParseTimestampISO8601(const char* s, size_t length, + TimeUnit::type unit, TimestampType::c_type* out, + bool* out_zone_offset_present = NULLPTR) { + using seconds_type = std::chrono::duration; + + // We allow the following zone offset formats: + // - (none) + // - Z + // - [+-]HH(:?MM)? + // + // We allow the following formats for all units: + // - "YYYY-MM-DD" + // - "YYYY-MM-DD[ T]hhZ?" + // - "YYYY-MM-DD[ T]hh:mmZ?" + // - "YYYY-MM-DD[ T]hh:mm:ssZ?" + // + // We allow the following formats for unit == MILLI, MICRO, or NANO: + // - "YYYY-MM-DD[ T]hh:mm:ss.s{1,3}Z?" + // + // We allow the following formats for unit == MICRO, or NANO: + // - "YYYY-MM-DD[ T]hh:mm:ss.s{4,6}Z?" + // + // We allow the following formats for unit == NANO: + // - "YYYY-MM-DD[ T]hh:mm:ss.s{7,9}Z?" + // + // UTC is always assumed, and the DataType's timezone is ignored. + // + + if (ARROW_PREDICT_FALSE(length < 10)) return false; + + seconds_type seconds_since_epoch; + if (ARROW_PREDICT_FALSE(!ParseYYYY_MM_DD(s, &seconds_since_epoch))) { + return false; + } + + if (length == 10) { + *out = util::CastSecondsToUnit(unit, seconds_since_epoch.count()); + return true; + } + + if (ARROW_PREDICT_FALSE(s[10] != ' ') && ARROW_PREDICT_FALSE(s[10] != 'T')) { + return false; + } + + if (out_zone_offset_present) { + *out_zone_offset_present = false; + } + + seconds_type zone_offset(0); + if (s[length - 1] == 'Z') { + --length; + if (out_zone_offset_present) *out_zone_offset_present = true; + } else if (s[length - 3] == '+' || s[length - 3] == '-') { + // [+-]HH + length -= 3; + if (ARROW_PREDICT_FALSE(!detail::ParseHH(s + length + 1, &zone_offset))) { + return false; + } + if (s[length] == '+') zone_offset *= -1; + if (out_zone_offset_present) *out_zone_offset_present = true; + } else if (s[length - 5] == '+' || s[length - 5] == '-') { + // [+-]HHMM + length -= 5; + if (ARROW_PREDICT_FALSE(!detail::ParseHHMM(s + length + 1, &zone_offset))) { + return false; + } + if (s[length] == '+') zone_offset *= -1; + if (out_zone_offset_present) *out_zone_offset_present = true; + } else if ((s[length - 6] == '+' || s[length - 6] == '-') && (s[length - 3] == ':')) { + // [+-]HH:MM + length -= 6; + if (ARROW_PREDICT_FALSE(!detail::ParseHH_MM(s + length + 1, &zone_offset))) { + return false; + } + if (s[length] == '+') zone_offset *= -1; + if (out_zone_offset_present) *out_zone_offset_present = true; + } + + seconds_type seconds_since_midnight; + switch (length) { + case 13: // YYYY-MM-DD[ T]hh + if (ARROW_PREDICT_FALSE(!detail::ParseHH(s + 11, &seconds_since_midnight))) { + return false; + } + break; + case 16: // YYYY-MM-DD[ T]hh:mm + if (ARROW_PREDICT_FALSE(!detail::ParseHH_MM(s + 11, &seconds_since_midnight))) { + return false; + } + break; + case 19: // YYYY-MM-DD[ T]hh:mm:ss + case 21: // YYYY-MM-DD[ T]hh:mm:ss.s + case 22: // YYYY-MM-DD[ T]hh:mm:ss.ss + case 23: // YYYY-MM-DD[ T]hh:mm:ss.sss + case 24: // YYYY-MM-DD[ T]hh:mm:ss.ssss + case 25: // YYYY-MM-DD[ T]hh:mm:ss.sssss + case 26: // YYYY-MM-DD[ T]hh:mm:ss.ssssss + case 27: // YYYY-MM-DD[ T]hh:mm:ss.sssssss + case 28: // YYYY-MM-DD[ T]hh:mm:ss.ssssssss + case 29: // YYYY-MM-DD[ T]hh:mm:ss.sssssssss + if (ARROW_PREDICT_FALSE(!detail::ParseHH_MM_SS(s + 11, &seconds_since_midnight))) { + return false; + } + break; + default: + return false; + } + + seconds_since_epoch += seconds_since_midnight; + seconds_since_epoch += zone_offset; + + if (length <= 19) { + *out = util::CastSecondsToUnit(unit, seconds_since_epoch.count()); + return true; + } + + if (ARROW_PREDICT_FALSE(s[19] != '.')) { + return false; + } + + uint32_t subseconds = 0; + if (ARROW_PREDICT_FALSE( + !detail::ParseSubSeconds(s + 20, length - 20, unit, &subseconds))) { + return false; + } + + *out = util::CastSecondsToUnit(unit, seconds_since_epoch.count()) + subseconds; + return true; +} + +#if defined(_WIN32) || defined(ARROW_WITH_MUSL) +static constexpr bool kStrptimeSupportsZone = false; +#else +static constexpr bool kStrptimeSupportsZone = true; +#endif + +/// \brief Returns time since the UNIX epoch in the requested unit +static inline bool ParseTimestampStrptime(const char* buf, size_t length, + const char* format, bool ignore_time_in_day, + bool allow_trailing_chars, TimeUnit::type unit, + int64_t* out) { + // NOTE: strptime() is more than 10x faster than arrow_vendored::date::parse(). + // The buffer may not be nul-terminated + std::string clean_copy(buf, length); + struct tm result; + memset(&result, 0, sizeof(struct tm)); +#ifdef _WIN32 + char* ret = arrow_strptime(clean_copy.c_str(), format, &result); +#else + char* ret = strptime(clean_copy.c_str(), format, &result); +#endif + if (ret == NULLPTR) { + return false; + } + if (!allow_trailing_chars && static_cast(ret - clean_copy.c_str()) != length) { + return false; + } + // ignore the time part + arrow_vendored::date::sys_seconds secs = + arrow_vendored::date::sys_days(arrow_vendored::date::year(result.tm_year + 1900) / + (result.tm_mon + 1) / std::max(result.tm_mday, 1)); + if (!ignore_time_in_day) { + secs += (std::chrono::hours(result.tm_hour) + std::chrono::minutes(result.tm_min) + + std::chrono::seconds(result.tm_sec)); +#ifndef _WIN32 + secs -= std::chrono::seconds(result.tm_gmtoff); +#endif + } + *out = util::CastSecondsToUnit(unit, secs.time_since_epoch().count()); + return true; +} + +template <> +struct StringConverter { + using value_type = int64_t; + + bool Convert(const TimestampType& type, const char* s, size_t length, value_type* out) { + return ParseTimestampISO8601(s, length, type.unit(), out); + } +}; + +template <> +struct StringConverter + : public StringToSignedIntConverterMixin { + using StringToSignedIntConverterMixin::StringToSignedIntConverterMixin; +}; + +template +struct StringConverter> { + using value_type = typename DATE_TYPE::c_type; + + using duration_type = + typename std::conditional::value, + arrow_vendored::date::days, + std::chrono::milliseconds>::type; + + bool Convert(const DATE_TYPE& type, const char* s, size_t length, value_type* out) { + if (ARROW_PREDICT_FALSE(length != 10)) { + return false; + } + + duration_type since_epoch; + if (ARROW_PREDICT_FALSE(!ParseYYYY_MM_DD(s, &since_epoch))) { + return false; + } + + *out = static_cast(since_epoch.count()); + return true; + } +}; + +template +struct StringConverter> { + using value_type = typename TIME_TYPE::c_type; + + // We allow the following formats for all units: + // - "hh:mm" + // - "hh:mm:ss" + // + // We allow the following formats for unit == MILLI, MICRO, or NANO: + // - "hh:mm:ss.s{1,3}" + // + // We allow the following formats for unit == MICRO, or NANO: + // - "hh:mm:ss.s{4,6}" + // + // We allow the following formats for unit == NANO: + // - "hh:mm:ss.s{7,9}" + + bool Convert(const TIME_TYPE& type, const char* s, size_t length, value_type* out) { + const auto unit = type.unit(); + std::chrono::seconds since_midnight; + + if (length == 5) { + if (ARROW_PREDICT_FALSE(!detail::ParseHH_MM(s, &since_midnight))) { + return false; + } + *out = + static_cast(util::CastSecondsToUnit(unit, since_midnight.count())); + return true; + } + + if (ARROW_PREDICT_FALSE(length < 8)) { + return false; + } + if (ARROW_PREDICT_FALSE(!detail::ParseHH_MM_SS(s, &since_midnight))) { + return false; + } + + *out = static_cast(util::CastSecondsToUnit(unit, since_midnight.count())); + + if (length == 8) { + return true; + } + + if (ARROW_PREDICT_FALSE(s[8] != '.')) { + return false; + } + + uint32_t subseconds_count = 0; + if (ARROW_PREDICT_FALSE( + !detail::ParseSubSeconds(s + 9, length - 9, unit, &subseconds_count))) { + return false; + } + + *out += subseconds_count; + return true; + } +}; + +/// \brief Convenience wrappers around internal::StringConverter. +template +bool ParseValue(const T& type, const char* s, size_t length, + typename StringConverter::value_type* out) { + return StringConverter{}.Convert(type, s, length, out); +} + +template +enable_if_parameter_free ParseValue( + const char* s, size_t length, typename StringConverter::value_type* out) { + static T type; + return StringConverter{}.Convert(type, s, length, out); +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/vector.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/vector.h new file mode 100644 index 0000000000000000000000000000000000000000..e3c0a67cf46c4ef403e87b5df08686ea4f2d1ba7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/vector.h @@ -0,0 +1,172 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/util/algorithm.h" +#include "arrow/util/functional.h" +#include "arrow/util/logging.h" + +namespace arrow { +namespace internal { + +template +std::vector DeleteVectorElement(const std::vector& values, size_t index) { + DCHECK(!values.empty()); + DCHECK_LT(index, values.size()); + std::vector out; + out.reserve(values.size() - 1); + for (size_t i = 0; i < index; ++i) { + out.push_back(values[i]); + } + for (size_t i = index + 1; i < values.size(); ++i) { + out.push_back(values[i]); + } + return out; +} + +template +std::vector AddVectorElement(const std::vector& values, size_t index, + T new_element) { + DCHECK_LE(index, values.size()); + std::vector out; + out.reserve(values.size() + 1); + for (size_t i = 0; i < index; ++i) { + out.push_back(values[i]); + } + out.emplace_back(std::move(new_element)); + for (size_t i = index; i < values.size(); ++i) { + out.push_back(values[i]); + } + return out; +} + +template +std::vector ReplaceVectorElement(const std::vector& values, size_t index, + T new_element) { + DCHECK_LE(index, values.size()); + std::vector out; + out.reserve(values.size()); + for (size_t i = 0; i < index; ++i) { + out.push_back(values[i]); + } + out.emplace_back(std::move(new_element)); + for (size_t i = index + 1; i < values.size(); ++i) { + out.push_back(values[i]); + } + return out; +} + +template +std::vector FilterVector(std::vector values, Predicate&& predicate) { + auto new_end = std::remove_if(values.begin(), values.end(), + [&](const T& value) { return !predicate(value); }); + values.erase(new_end, values.end()); + return values; +} + +template ()(std::declval()))> +std::vector MapVector(Fn&& map, const std::vector& source) { + std::vector out; + out.reserve(source.size()); + std::transform(source.begin(), source.end(), std::back_inserter(out), + std::forward(map)); + return out; +} + +template ()(std::declval()))> +std::vector MapVector(Fn&& map, std::vector&& source) { + std::vector out; + out.reserve(source.size()); + std::transform(std::make_move_iterator(source.begin()), + std::make_move_iterator(source.end()), std::back_inserter(out), + std::forward(map)); + return out; +} + +/// \brief Like MapVector, but where the function can fail. +template , + typename To = typename internal::call_traits::return_type::ValueType> +Result> MaybeMapVector(Fn&& map, const std::vector& source) { + std::vector out; + out.reserve(source.size()); + ARROW_RETURN_NOT_OK(MaybeTransform(source.begin(), source.end(), + std::back_inserter(out), std::forward(map))); + return std::move(out); +} + +template , + typename To = typename internal::call_traits::return_type::ValueType> +Result> MaybeMapVector(Fn&& map, std::vector&& source) { + std::vector out; + out.reserve(source.size()); + ARROW_RETURN_NOT_OK(MaybeTransform(std::make_move_iterator(source.begin()), + std::make_move_iterator(source.end()), + std::back_inserter(out), std::forward(map))); + return std::move(out); +} + +template +std::vector FlattenVectors(const std::vector>& vecs) { + std::size_t sum = 0; + for (const auto& vec : vecs) { + sum += vec.size(); + } + std::vector out; + out.reserve(sum); + for (const auto& vec : vecs) { + out.insert(out.end(), vec.begin(), vec.end()); + } + return out; +} + +template +Result> UnwrapOrRaise(std::vector>&& results) { + std::vector out; + out.reserve(results.size()); + auto end = std::make_move_iterator(results.end()); + for (auto it = std::make_move_iterator(results.begin()); it != end; it++) { + if (!it->ok()) { + return it->status(); + } + out.push_back(it->MoveValueUnsafe()); + } + return std::move(out); +} + +template +Result> UnwrapOrRaise(const std::vector>& results) { + std::vector out; + out.reserve(results.size()); + for (const auto& result : results) { + if (!result.ok()) { + return result.status(); + } + out.push_back(result.ValueUnsafe()); + } + return std::move(out); +} + +} // namespace internal +} // namespace arrow diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/visibility.h b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/visibility.h new file mode 100644 index 0000000000000000000000000000000000000000..b0fd790295b021745438794636c05200bad1c814 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/include/arrow/util/visibility.h @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) +// Windows + +#if defined(_MSC_VER) +#pragma warning(disable : 4251) +#else +#pragma GCC diagnostic ignored "-Wattributes" +#endif + +#if defined(__cplusplus) && defined(__GNUC__) && !defined(__clang__) +// Use C++ attribute syntax where possible to avoid GCC parser bug +// (https://stackoverflow.com/questions/57993818/gcc-how-to-combine-attribute-dllexport-and-nodiscard-in-a-struct-de) +#define ARROW_DLLEXPORT [[gnu::dllexport]] +#define ARROW_DLLIMPORT [[gnu::dllimport]] +#else +#define ARROW_DLLEXPORT __declspec(dllexport) +#define ARROW_DLLIMPORT __declspec(dllimport) +#endif + +#ifdef ARROW_STATIC +#define ARROW_EXPORT +#define ARROW_FRIEND_EXPORT +#define ARROW_TEMPLATE_EXPORT +#elif defined(ARROW_EXPORTING) +#define ARROW_EXPORT ARROW_DLLEXPORT +// For some reason [[gnu::dllexport]] doesn't work well with friend declarations +#define ARROW_FRIEND_EXPORT __declspec(dllexport) +#define ARROW_TEMPLATE_EXPORT ARROW_DLLEXPORT +#else +#define ARROW_EXPORT ARROW_DLLIMPORT +#define ARROW_FRIEND_EXPORT __declspec(dllimport) +#define ARROW_TEMPLATE_EXPORT ARROW_DLLIMPORT +#endif + +#define ARROW_NO_EXPORT +#define ARROW_FORCE_INLINE __forceinline + +#else + +// Non-Windows + +#define ARROW_FORCE_INLINE + +#if defined(__cplusplus) && (defined(__GNUC__) || defined(__clang__)) +#ifndef ARROW_EXPORT +#define ARROW_EXPORT [[gnu::visibility("default")]] +#endif +#ifndef ARROW_NO_EXPORT +#define ARROW_NO_EXPORT [[gnu::visibility("hidden")]] +#endif +#else +// Not C++, or not gcc/clang +#ifndef ARROW_EXPORT +#define ARROW_EXPORT +#endif +#ifndef ARROW_NO_EXPORT +#define ARROW_NO_EXPORT +#endif +#endif + +#define ARROW_FRIEND_EXPORT +#define ARROW_TEMPLATE_EXPORT + +#endif // Non-Windows diff --git a/env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1500 b/env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1500 new file mode 100644 index 0000000000000000000000000000000000000000..827eeb45ddde49e8201985cddca2592a55d14613 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1500 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25779d55da43c3836e9b96df49a47cea4d2d28544552e291adab5a6822b4ff95 +size 2064824