Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/arrow_to_pandas.hAdded+146
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/benchmark.hAdded+36
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/csv.hAdded+42
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/deserialize.hAdded+106
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/gdb.hAdded+29
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/helpers.hAdded+162
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/inference.hAdded+64
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/init.hAdded+26
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/lib_api.hAdded+201
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/numpy_interop.hAdded+103
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/numpy_to_arrow.hAdded+72
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/parquet_encryption.hAdded+132
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/pch.hAdded+24
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/platform.hAdded+41
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/pyarrow.hAdded+89
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/pyarrow_lib.hAdded+19
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/python_test.hAdded+42
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/python_to_arrow.hAdded+80
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/udf.hAdded+81
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/visibility.hAdded+39
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/algorithm.hAdded+33
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/align_util.hAdded+221
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator.hAdded+2058
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator_fwd.hAdded+71
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/base64.hAdded+35
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/binary_view_util.hAdded+95
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap.hAdded+466
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_builders.hAdded+43
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_generate.hAdded+112
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_visit.hAdded+88
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_writer.hAdded+286
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitset_stack.hAdded+89
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking.hAdded+34
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx512.hAdded+28
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_neon.hAdded+28
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/checked_cast.hAdded+61
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/compression.hAdded+241
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/converter.hAdded+411
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/counting_semaphore.hAdded+60
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/cpu_info.hAdded+114
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/decimal.hAdded+298
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/delimiting.hAdded+181
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/dict_util.hAdded+28
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/dispatch.hAdded+115
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/formatting.hAdded+656
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/future.hAdded+882
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/hashing.hAdded+944
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util.hAdded+137
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util_overflow.hAdded+118
- valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/io_util.hAdded+452
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146// 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.
// Functions for converting between pandas's NumPy-based data representation// and Arrow data structures
#pragma once
#include "arrow/python/platform.h"
#include <memory>#include <string>#include <unordered_set>
#include "arrow/memory_pool.h"#include "arrow/python/visibility.h"
namespace arrow {
class Array;class ChunkedArray;class Column;class DataType;class MemoryPool;class Status;class Table;
namespace py {
enum class MapConversionType { DEFAULT, // convert arrow maps to assoc lists (list of kev-value tuples) in Pandas LOSSY, // report warnings when lossiness is encountered due to duplicate keys STRICT_, // raise a Python exception when lossiness is encountered due to duplicate // keys};
struct PandasOptions { /// arrow::MemoryPool to use for memory allocations MemoryPool* pool = default_memory_pool();
/// If true, we will convert all string columns to categoricals bool strings_to_categorical = false; bool zero_copy_only = false; bool integer_object_nulls = false; bool date_as_object = false; bool timestamp_as_object = false; bool use_threads = false;
/// Coerce all date and timestamp to datetime64[ns] bool coerce_temporal_nanoseconds = false;
/// Used to maintain backwards compatibility for /// timezone bugs (see ARROW-9528). Should be removed /// after Arrow 2.0 release. bool ignore_timezone = false;
/// \brief If true, do not create duplicate PyObject versions of equal /// objects. This only applies to immutable objects like strings or datetime /// objects bool deduplicate_objects = false;
/// \brief For certain data types, a cast is needed in order to store the /// data in a pandas DataFrame or Series (e.g. timestamps are always stored /// as nanoseconds in pandas). This option controls whether it is a safe /// cast or not. bool safe_cast = true;
/// \brief If true, create one block per column rather than consolidated /// blocks (1 per data type). Do zero-copy wrapping when there are no /// nulls. pandas currently will consolidate the blocks on its own, causing /// increased memory use, so keep this in mind if you are working on a /// memory-constrained situation. bool split_blocks = false;
/// \brief If true, allow non-writable zero-copy views to be created for /// single column blocks. This option is also used to provide zero copy for /// Series data bool allow_zero_copy_blocks = false;
/// \brief If true, attempt to deallocate buffers in passed Arrow object if /// it is the only remaining shared_ptr copy of it. See ARROW-3789 for /// original context for this feature. Only currently implemented for Table /// conversions bool self_destruct = false;
/// \brief The default behavior (DEFAULT), is to convert Arrow Map arrays to /// Python association lists (list-of-tuples) in the same order as the Arrow /// Map, as in [(key1, value1), (key2, value2), ...] /// If LOSSY or STRICT, convert Arrow Map arrays to native Python dicts. /// This can change the ordering of (key, value) pairs, and will deduplicate /// multiple keys, resulting in a possible loss of data. /// If 'lossy', this key deduplication results in a warning printed /// when detected. If 'strict', this instead results in an exception /// being raised when detected. MapConversionType maps_as_pydicts = MapConversionType::DEFAULT;
// Used internally for nested arrays. bool decode_dictionaries = false;
// Columns that should be casted to categorical std::unordered_set<std::string> categorical_columns;
// Columns that should be passed through to be converted to // ExtensionArray/Block std::unordered_set<std::string> extension_columns;
// Used internally to decipher between to_numpy() and to_pandas() when // the expected output differs bool to_numpy = false;};
ARROW_PYTHON_EXPORTStatus ConvertArrayToPandas(const PandasOptions& options, std::shared_ptr<Array> arr, PyObject* py_ref, PyObject** out);
ARROW_PYTHON_EXPORTStatus ConvertChunkedArrayToPandas(const PandasOptions& options, std::shared_ptr<ChunkedArray> col, PyObject* py_ref, PyObject** out);
// Convert a whole table as efficiently as possible to a pandas.DataFrame.//// The returned Python object is a list of tuples consisting of the exact 2D// BlockManager structure of the pandas.DataFrame used as of pandas 0.19.x.//// tuple item: (indices: ndarray[int32], block: ndarray[TYPE, ndim=2])ARROW_PYTHON_EXPORTStatus ConvertTableToPandas(const PandasOptions& options, std::shared_ptr<Table> table, PyObject** out);
} // namespace py} // namespace arrow123456789101112131415161718192021222324252627282930313233343536// 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/python/platform.h"
#include "arrow/python/visibility.h"
namespace arrow {namespace py {namespace benchmark {
// Micro-benchmark routines for use from ASV
// Run PandasObjectIsNull() once over every object in *list*ARROW_PYTHON_EXPORTvoid Benchmark_PandasObjectIsNull(PyObject* list);
} // namespace benchmark} // namespace py} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142// 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 <functional>#include <memory>#include <string>#include <vector>
#include "arrow/csv/options.h"#include "arrow/python/common.h"#include "arrow/util/macros.h"
namespace arrow {namespace py {namespace csv {
using PyInvalidRowCallback = std::function<::arrow::csv::InvalidRowResult( PyObject*, const ::arrow::csv::InvalidRow&)>;
ARROW_PYTHON_EXPORT::arrow::csv::InvalidRowHandler MakeInvalidRowHandler(PyInvalidRowCallback, PyObject* handler);
} // namespace csv} // namespace py} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106// 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 <cstdint>#include <memory>#include <vector>
#include "arrow/python/serialize.h"#include "arrow/python/visibility.h"#include "arrow/status.h"
namespace arrow {
class RecordBatch;class Tensor;
namespace io {
class RandomAccessFile;
} // namespace io
namespace py {
struct ARROW_PYTHON_EXPORT SparseTensorCounts { int coo; int csr; int csc; int csf; int ndim_csf;
int num_total_tensors() const { return coo + csr + csc + csf; } int num_total_buffers() const { return coo * 3 + csr * 4 + csc * 4 + 2 * ndim_csf + csf; }};
/// \brief Read serialized Python sequence from file interface using Arrow IPC/// \param[in] src a RandomAccessFile/// \param[out] out the reconstructed data/// \return StatusARROW_PYTHON_EXPORTStatus ReadSerializedObject(io::RandomAccessFile* src, SerializedPyObject* out);
/// \brief Reconstruct SerializedPyObject from representation produced by/// SerializedPyObject::GetComponents.////// \param[in] num_tensors number of tensors in the object/// \param[in] num_sparse_tensors number of sparse tensors in the object/// \param[in] num_ndarrays number of numpy Ndarrays in the object/// \param[in] num_buffers number of buffers in the object/// \param[in] data a list containing pyarrow.Buffer instances. It must be 1 +/// num_tensors * 2 + num_coo_tensors * 3 + num_csr_tensors * 4 + num_csc_tensors * 4 +/// num_csf_tensors * (2 * ndim_csf + 3) + num_buffers in length/// \param[out] out the reconstructed object/// \return StatusARROW_PYTHON_EXPORTStatus GetSerializedFromComponents(int num_tensors, const SparseTensorCounts& num_sparse_tensors, int num_ndarrays, int num_buffers, PyObject* data, SerializedPyObject* out);
/// \brief Reconstruct Python object from Arrow-serialized representation/// \param[in] context Serialization context which contains custom serialization/// and deserialization callbacks. Can be any Python object with a/// _serialize_callback method for serialization and a _deserialize_callback/// method for deserialization. If context is None, no custom serialization/// will be attempted./// \param[in] object Object to deserialize/// \param[in] base a Python object holding the underlying data that any NumPy/// arrays will reference, to avoid premature deallocation/// \param[out] out The returned object/// \return Status/// This acquires the GILARROW_PYTHON_EXPORTStatus DeserializeObject(PyObject* context, const SerializedPyObject& object, PyObject* base, PyObject** out);
/// \brief Reconstruct Ndarray from Arrow-serialized representation/// \param[in] object Object to deserialize/// \param[out] out The deserialized tensor/// \return StatusARROW_PYTHON_EXPORTStatus DeserializeNdarray(const SerializedPyObject& object, std::shared_ptr<Tensor>* out);
ARROW_PYTHON_EXPORTStatus NdarrayFromBuffer(std::shared_ptr<Buffer> src, std::shared_ptr<Tensor>* out);
} // namespace py} // namespace arrow1234567891011121314151617181920212223242526272829// 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/python/visibility.h"
namespace arrow {namespace gdb {
ARROW_PYTHON_EXPORTvoid TestSession();
} // namespace gdb} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162// 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/python/platform.h"
#include <limits>#include <memory>#include <string>#include <utility>
#include "arrow/python/numpy_interop.h"
#include <numpy/halffloat.h>
#include "arrow/python/visibility.h"#include "arrow/type.h"#include "arrow/util/macros.h"
namespace arrow {
namespace py {
class OwnedRef;
// \brief Get an arrow DataType instance from Arrow's Type::type enum// \param[in] type One of the values of Arrow's Type::type enum// \return A shared pointer to DataTypeARROW_PYTHON_EXPORT std::shared_ptr<DataType> GetPrimitiveType(Type::type type);
// \brief Construct a np.float16 object from a npy_half value.ARROW_PYTHON_EXPORT PyObject* PyHalf_FromHalf(npy_half value);
// \brief Convert a Python object to a npy_half value.ARROW_PYTHON_EXPORT Status PyFloat_AsHalf(PyObject* obj, npy_half* out);
namespace internal {
// \brief Check that a Python module has been already imported// \param[in] module_name The name of the moduleResult<bool> IsModuleImported(const std::string& module_name);
// \brief Import a Python module// \param[in] module_name The name of the module// \param[out] ref The OwnedRef containing the module PyObject*ARROW_PYTHON_EXPORTStatus ImportModule(const std::string& module_name, OwnedRef* ref);
// \brief Import an object from a Python module// \param[in] module A Python module// \param[in] name The name of the object to import// \param[out] ref The OwnedRef containing the \c name attribute of the Python module \c// moduleARROW_PYTHON_EXPORTStatus ImportFromModule(PyObject* module, const std::string& name, OwnedRef* ref);
// \brief Check whether obj is an integer, independent of Python versions.inline bool IsPyInteger(PyObject* obj) { return PyLong_Check(obj); }
// \brief Import symbols from pandas that we need for various type-checking,// like pandas.NaT or pandas.NAvoid InitPandasStaticData();
// \brief Use pandas missing value semantics to check if a value is nullARROW_PYTHON_EXPORTbool PandasObjectIsNull(PyObject* obj);
// \brief Check that obj is a pandas.Timedelta instanceARROW_PYTHON_EXPORTbool IsPandasTimedelta(PyObject* obj);
// \brief Check that obj is a pandas.Timestamp instancebool IsPandasTimestamp(PyObject* obj);
// \brief Returned a borrowed reference to the pandas.tseries.offsets.DateOffsetPyObject* BorrowPandasDataOffsetType();
// \brief Check whether obj is a floating-point NaNARROW_PYTHON_EXPORTbool PyFloat_IsNaN(PyObject* obj);
inline bool IsPyBinary(PyObject* obj) { return PyBytes_Check(obj) || PyByteArray_Check(obj) || PyMemoryView_Check(obj);}
// \brief Convert a Python integer into a C integer// \param[in] obj A Python integer// \param[out] out A pointer to a C integer to hold the result of the conversion// \return The status of the operationtemplate <typename Int>Status CIntFromPython(PyObject* obj, Int* out, const std::string& overflow_message = "");
// \brief Convert a Python unicode string to a std::stringARROW_PYTHON_EXPORTStatus PyUnicode_AsStdString(PyObject* obj, std::string* out);
// \brief Convert a Python bytes object to a std::stringARROW_PYTHON_EXPORTstd::string PyBytes_AsStdString(PyObject* obj);
// \brief Call str() on the given object and return the result as a std::stringARROW_PYTHON_EXPORTStatus PyObject_StdStringStr(PyObject* obj, std::string* out);
// \brief Return the repr() of the given object (always succeeds)ARROW_PYTHON_EXPORTstd::string PyObject_StdStringRepr(PyObject* obj);
// \brief Cast the given size to int32_t, with error checkinginline Status CastSize(Py_ssize_t size, int32_t* out, const char* error_msg = "Maximum size exceeded (2GB)") { // size is assumed to be positive if (size > std::numeric_limits<int32_t>::max()) { return Status::Invalid(error_msg); } *out = static_cast<int32_t>(size); return Status::OK();}
inline Status CastSize(Py_ssize_t size, int64_t* out, const char* error_msg = NULLPTR) { // size is assumed to be positive *out = static_cast<int64_t>(size); return Status::OK();}
// \brief Print the Python object's __str__ form along with the passed error// messageARROW_PYTHON_EXPORTStatus InvalidValue(PyObject* obj, const std::string& why);
ARROW_PYTHON_EXPORTStatus InvalidType(PyObject* obj, const std::string& why);
ARROW_PYTHON_EXPORTStatus IntegerScalarToDoubleSafe(PyObject* obj, double* result);ARROW_PYTHON_EXPORTStatus IntegerScalarToFloat32Safe(PyObject* obj, float* result);
// \brief Print Python object __repr__void DebugPrint(PyObject* obj);
ARROW_PYTHON_EXPORTbool IsThreadingEnabled();
} // namespace internal} // namespace py} // namespace arrow12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364// 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.
// Functions for converting between CPython built-in data structures and Arrow// data structures
#pragma once
#include "arrow/python/platform.h"
#include <memory>
#include "arrow/python/visibility.h"#include "arrow/type.h"#include "arrow/util/macros.h"
#include "common.h"
namespace arrow {
class Array;class Status;
namespace py {
// These functions take a sequence input, not arbitrary iterables
/// \brief Infer Arrow type from a Python sequence/// \param[in] obj the sequence of values/// \param[in] mask an optional mask where True values are null. May/// be nullptr/// \param[in] pandas_null_sentinels use pandas's null value markersARROW_PYTHON_EXPORTResult<std::shared_ptr<arrow::DataType>> InferArrowType(PyObject* obj, PyObject* mask, bool pandas_null_sentinels);
/// Checks whether the passed Python object is a boolean scalarARROW_PYTHON_EXPORTbool IsPyBool(PyObject* obj);
/// Checks whether the passed Python object is an integer scalarARROW_PYTHON_EXPORTbool IsPyInt(PyObject* obj);
/// Checks whether the passed Python object is a float scalarARROW_PYTHON_EXPORTbool IsPyFloat(PyObject* obj);
} // namespace py} // namespace arrow1234567891011121314151617181920212223242526// 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/python/platform.h"#include "arrow/python/visibility.h"
extern "C" {ARROW_PYTHON_EXPORTint arrow_init_numpy();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201/* Generated by Cython 3.0.10 */
#ifndef __PYX_HAVE_API__pyarrow__lib#define __PYX_HAVE_API__pyarrow__lib#ifdef __MINGW64__#define MS_WIN64#endif#include "Python.h"#include "lib.h"
static PyObject *(*__pyx_api_f_7pyarrow_3lib_box_memory_pool)( arrow::MemoryPool *) = 0;#define box_memory_pool __pyx_api_f_7pyarrow_3lib_box_memory_poolstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_buffer)(std::shared_ptr< arrow::Buffer> const &) = 0;#define pyarrow_wrap_buffer __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_bufferstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_resizable_buffer)(std::shared_ptr< arrow::ResizableBuffer> const &) = 0;#define pyarrow_wrap_resizable_buffer __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_resizable_bufferstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_data_type)(std::shared_ptr< arrow::DataType> const &) = 0;#define pyarrow_wrap_data_type __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_data_typestatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_field)(std::shared_ptr< arrow::Field> const &) = 0;#define pyarrow_wrap_field __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_fieldstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_schema)(std::shared_ptr< arrow::Schema> const &) = 0;#define pyarrow_wrap_schema __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_schemastatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_scalar)(std::shared_ptr< arrow::Scalar> const &) = 0;#define pyarrow_wrap_scalar __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_scalarstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_array)(std::shared_ptr< arrow::Array> const &) = 0;#define pyarrow_wrap_array __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_arraystatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_chunked_array)(std::shared_ptr< arrow::ChunkedArray> const &) = 0;#define pyarrow_wrap_chunked_array __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_chunked_arraystatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_coo_tensor)(std::shared_ptr< arrow::SparseCOOTensor> const &) = 0;#define pyarrow_wrap_sparse_coo_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_coo_tensorstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csc_matrix)(std::shared_ptr< arrow::SparseCSCMatrix> const &) = 0;#define pyarrow_wrap_sparse_csc_matrix __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csc_matrixstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csf_tensor)(std::shared_ptr< arrow::SparseCSFTensor> const &) = 0;#define pyarrow_wrap_sparse_csf_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csf_tensorstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csr_matrix)(std::shared_ptr< arrow::SparseCSRMatrix> const &) = 0;#define pyarrow_wrap_sparse_csr_matrix __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csr_matrixstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_tensor)(std::shared_ptr< arrow::Tensor> const &) = 0;#define pyarrow_wrap_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_tensorstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_batch)(std::shared_ptr< arrow::RecordBatch> const &) = 0;#define pyarrow_wrap_batch __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_batchstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_table)(std::shared_ptr< arrow::Table> const &) = 0;#define pyarrow_wrap_table __pyx_api_f_7pyarrow_3lib_pyarrow_wrap_tablestatic std::shared_ptr< arrow::Buffer> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_buffer)(PyObject *) = 0;#define pyarrow_unwrap_buffer __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_bufferstatic std::shared_ptr< arrow::DataType> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_data_type)(PyObject *) = 0;#define pyarrow_unwrap_data_type __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_data_typestatic std::shared_ptr< arrow::Field> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_field)(PyObject *) = 0;#define pyarrow_unwrap_field __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_fieldstatic std::shared_ptr< arrow::Schema> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_schema)(PyObject *) = 0;#define pyarrow_unwrap_schema __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_schemastatic std::shared_ptr< arrow::Scalar> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_scalar)(PyObject *) = 0;#define pyarrow_unwrap_scalar __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_scalarstatic std::shared_ptr< arrow::Array> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_array)(PyObject *) = 0;#define pyarrow_unwrap_array __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_arraystatic std::shared_ptr< arrow::ChunkedArray> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_chunked_array)(PyObject *) = 0;#define pyarrow_unwrap_chunked_array __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_chunked_arraystatic std::shared_ptr< arrow::SparseCOOTensor> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_coo_tensor)(PyObject *) = 0;#define pyarrow_unwrap_sparse_coo_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_coo_tensorstatic std::shared_ptr< arrow::SparseCSCMatrix> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csc_matrix)(PyObject *) = 0;#define pyarrow_unwrap_sparse_csc_matrix __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csc_matrixstatic std::shared_ptr< arrow::SparseCSFTensor> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csf_tensor)(PyObject *) = 0;#define pyarrow_unwrap_sparse_csf_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csf_tensorstatic std::shared_ptr< arrow::SparseCSRMatrix> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csr_matrix)(PyObject *) = 0;#define pyarrow_unwrap_sparse_csr_matrix __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csr_matrixstatic std::shared_ptr< arrow::Tensor> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_tensor)(PyObject *) = 0;#define pyarrow_unwrap_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_tensorstatic std::shared_ptr< arrow::RecordBatch> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_batch)(PyObject *) = 0;#define pyarrow_unwrap_batch __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_batchstatic std::shared_ptr< arrow::Table> (*__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_table)(PyObject *) = 0;#define pyarrow_unwrap_table __pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_tablestatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_internal_check_status)(arrow::Status const &) = 0;#define pyarrow_internal_check_status __pyx_api_f_7pyarrow_3lib_pyarrow_internal_check_statusstatic PyObject *(*__pyx_api_f_7pyarrow_3lib_pyarrow_internal_convert_status)(arrow::Status const &) = 0;#define pyarrow_internal_convert_status __pyx_api_f_7pyarrow_3lib_pyarrow_internal_convert_statusstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_buffer)(PyObject *) = 0;#define pyarrow_is_buffer __pyx_api_f_7pyarrow_3lib_pyarrow_is_bufferstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_data_type)(PyObject *) = 0;#define pyarrow_is_data_type __pyx_api_f_7pyarrow_3lib_pyarrow_is_data_typestatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_metadata)(PyObject *) = 0;#define pyarrow_is_metadata __pyx_api_f_7pyarrow_3lib_pyarrow_is_metadatastatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_field)(PyObject *) = 0;#define pyarrow_is_field __pyx_api_f_7pyarrow_3lib_pyarrow_is_fieldstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_schema)(PyObject *) = 0;#define pyarrow_is_schema __pyx_api_f_7pyarrow_3lib_pyarrow_is_schemastatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_array)(PyObject *) = 0;#define pyarrow_is_array __pyx_api_f_7pyarrow_3lib_pyarrow_is_arraystatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_chunked_array)(PyObject *) = 0;#define pyarrow_is_chunked_array __pyx_api_f_7pyarrow_3lib_pyarrow_is_chunked_arraystatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_scalar)(PyObject *) = 0;#define pyarrow_is_scalar __pyx_api_f_7pyarrow_3lib_pyarrow_is_scalarstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_tensor)(PyObject *) = 0;#define pyarrow_is_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_is_tensorstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_coo_tensor)(PyObject *) = 0;#define pyarrow_is_sparse_coo_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_coo_tensorstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csr_matrix)(PyObject *) = 0;#define pyarrow_is_sparse_csr_matrix __pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csr_matrixstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csc_matrix)(PyObject *) = 0;#define pyarrow_is_sparse_csc_matrix __pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csc_matrixstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csf_tensor)(PyObject *) = 0;#define pyarrow_is_sparse_csf_tensor __pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csf_tensorstatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_table)(PyObject *) = 0;#define pyarrow_is_table __pyx_api_f_7pyarrow_3lib_pyarrow_is_tablestatic int (*__pyx_api_f_7pyarrow_3lib_pyarrow_is_batch)(PyObject *) = 0;#define pyarrow_is_batch __pyx_api_f_7pyarrow_3lib_pyarrow_is_batch#ifndef __PYX_HAVE_RT_ImportFunction_3_0_10#define __PYX_HAVE_RT_ImportFunction_3_0_10static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { PyObject *d = 0; PyObject *cobj = 0; union { void (*fp)(void); void *p; } tmp; d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); if (!d) goto bad; cobj = PyDict_GetItemString(d, funcname); if (!cobj) { PyErr_Format(PyExc_ImportError, "%.200s does not export expected C function %.200s", PyModule_GetName(module), funcname); goto bad; } if (!PyCapsule_IsValid(cobj, sig)) { PyErr_Format(PyExc_TypeError, "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); goto bad; } tmp.p = PyCapsule_GetPointer(cobj, sig); *f = tmp.fp; if (!(*f)) goto bad; Py_DECREF(d); return 0;bad: Py_XDECREF(d); return -1;}#endif
static int import_pyarrow__lib(void) { PyObject *module = 0; module = PyImport_ImportModule("pyarrow.lib"); if (!module) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "box_memory_pool", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_box_memory_pool, "PyObject *( arrow::MemoryPool *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_buffer", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_buffer, "PyObject *(std::shared_ptr< arrow::Buffer> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_resizable_buffer", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_resizable_buffer, "PyObject *(std::shared_ptr< arrow::ResizableBuffer> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_data_type", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_data_type, "PyObject *(std::shared_ptr< arrow::DataType> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_field", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_field, "PyObject *(std::shared_ptr< arrow::Field> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_schema", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_schema, "PyObject *(std::shared_ptr< arrow::Schema> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_scalar", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_scalar, "PyObject *(std::shared_ptr< arrow::Scalar> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_array", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_array, "PyObject *(std::shared_ptr< arrow::Array> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_chunked_array", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_chunked_array, "PyObject *(std::shared_ptr< arrow::ChunkedArray> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_sparse_coo_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_coo_tensor, "PyObject *(std::shared_ptr< arrow::SparseCOOTensor> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_sparse_csc_matrix", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csc_matrix, "PyObject *(std::shared_ptr< arrow::SparseCSCMatrix> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_sparse_csf_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csf_tensor, "PyObject *(std::shared_ptr< arrow::SparseCSFTensor> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_sparse_csr_matrix", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_sparse_csr_matrix, "PyObject *(std::shared_ptr< arrow::SparseCSRMatrix> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_tensor, "PyObject *(std::shared_ptr< arrow::Tensor> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_batch", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_batch, "PyObject *(std::shared_ptr< arrow::RecordBatch> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_wrap_table", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_wrap_table, "PyObject *(std::shared_ptr< arrow::Table> const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_buffer", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_buffer, "std::shared_ptr< arrow::Buffer> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_data_type", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_data_type, "std::shared_ptr< arrow::DataType> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_field", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_field, "std::shared_ptr< arrow::Field> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_schema", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_schema, "std::shared_ptr< arrow::Schema> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_scalar", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_scalar, "std::shared_ptr< arrow::Scalar> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_array", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_array, "std::shared_ptr< arrow::Array> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_chunked_array", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_chunked_array, "std::shared_ptr< arrow::ChunkedArray> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_sparse_coo_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_coo_tensor, "std::shared_ptr< arrow::SparseCOOTensor> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_sparse_csc_matrix", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csc_matrix, "std::shared_ptr< arrow::SparseCSCMatrix> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_sparse_csf_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csf_tensor, "std::shared_ptr< arrow::SparseCSFTensor> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_sparse_csr_matrix", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_sparse_csr_matrix, "std::shared_ptr< arrow::SparseCSRMatrix> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_tensor, "std::shared_ptr< arrow::Tensor> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_batch", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_batch, "std::shared_ptr< arrow::RecordBatch> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_unwrap_table", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_unwrap_table, "std::shared_ptr< arrow::Table> (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_internal_check_status", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_internal_check_status, "int (arrow::Status const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_internal_convert_status", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_internal_convert_status, "PyObject *(arrow::Status const &)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_buffer", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_buffer, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_data_type", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_data_type, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_metadata", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_metadata, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_field", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_field, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_schema", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_schema, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_array", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_array, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_chunked_array", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_chunked_array, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_scalar", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_scalar, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_tensor, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_sparse_coo_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_coo_tensor, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_sparse_csr_matrix", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csr_matrix, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_sparse_csc_matrix", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csc_matrix, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_sparse_csf_tensor", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_sparse_csf_tensor, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_table", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_table, "int (PyObject *)") < 0) goto bad; if (__Pyx_ImportFunction_3_0_10(module, "pyarrow_is_batch", (void (**)(void))&__pyx_api_f_7pyarrow_3lib_pyarrow_is_batch, "int (PyObject *)") < 0) goto bad; Py_DECREF(module); module = 0; return 0; bad: Py_XDECREF(module); return -1;}
#endif /* !__PYX_HAVE_API__pyarrow__lib */123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103// 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/python/platform.h" // IWYU pragma: export
#include <numpy/numpyconfig.h> // IWYU pragma: export
// Don't use the deprecated Numpy functions#ifdef NPY_1_7_API_VERSION#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION#else#define NPY_ARRAY_NOTSWAPPED NPY_NOTSWAPPED#define NPY_ARRAY_ALIGNED NPY_ALIGNED#define NPY_ARRAY_WRITEABLE NPY_WRITEABLE#define NPY_ARRAY_UPDATEIFCOPY NPY_UPDATEIFCOPY#endif
// This is required to be able to access the NumPy C API properly in C++ files// other than init.cc.#define PY_ARRAY_UNIQUE_SYMBOL arrow_ARRAY_API#ifndef NUMPY_IMPORT_ARRAY#define NO_IMPORT_ARRAY#endif
#include <numpy/arrayobject.h> // IWYU pragma: export#include <numpy/arrayscalars.h> // IWYU pragma: export#include <numpy/ufuncobject.h> // IWYU pragma: export
// A bit subtle. Numpy has 5 canonical integer types:// (or, rather, type pairs: signed and unsigned)// NPY_BYTE, NPY_SHORT, NPY_INT, NPY_LONG, NPY_LONGLONG// It also has 4 fixed-width integer aliases.// When mapping Arrow integer types to these 4 fixed-width aliases,// we always miss one of the canonical types (even though it may// have the same width as one of the aliases).// Which one depends on the platform...// On a LP64 system, NPY_INT64 maps to NPY_LONG and// NPY_LONGLONG needs to be handled separately.// On a LLP64 system, NPY_INT32 maps to NPY_LONG and// NPY_INT needs to be handled separately.
#if NPY_BITSOF_LONG == 32 && NPY_BITSOF_LONGLONG == 64#define NPY_INT64_IS_LONG_LONG 1#else#define NPY_INT64_IS_LONG_LONG 0#endif
#if NPY_BITSOF_INT == 32 && NPY_BITSOF_LONG == 64#define NPY_INT32_IS_INT 1#else#define NPY_INT32_IS_INT 0#endif
// Backported NumPy 2 API (can be removed if numpy 2 is required)#if NPY_ABI_VERSION < 0x02000000#define PyDataType_ELSIZE(descr) ((descr)->elsize)#define PyDataType_C_METADATA(descr) ((descr)->c_metadata)#define PyDataType_FIELDS(descr) ((descr)->fields)#endif
namespace arrow {namespace py {
inline int import_numpy() {#ifdef NUMPY_IMPORT_ARRAY import_array1(-1); import_umath1(-1);#endif
return 0;}
// See above about the missing Numpy integer type numbersinline int fix_numpy_type_num(int type_num) {#if !NPY_INT32_IS_INT && NPY_BITSOF_INT == 32 if (type_num == NPY_INT) return NPY_INT32; if (type_num == NPY_UINT) return NPY_UINT32;#endif#if !NPY_INT64_IS_LONG_LONG && NPY_BITSOF_LONGLONG == 64 if (type_num == NPY_LONGLONG) return NPY_INT64; if (type_num == NPY_ULONGLONG) return NPY_UINT64;#endif return type_num;}
} // namespace py} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172// 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.
// Converting from pandas memory representation to Arrow data structures
#pragma once
#include "arrow/python/platform.h"
#include <memory>
#include "arrow/compute/api.h"#include "arrow/python/visibility.h"
namespace arrow {
class Array;class ChunkedArray;class DataType;class MemoryPool;class Status;
namespace py {
/// Convert NumPy arrays to Arrow. If target data type is not known, pass a/// type with null////// \param[in] pool Memory pool for any memory allocations/// \param[in] ao an ndarray with the array data/// \param[in] mo an ndarray with a null mask (True is null), optional/// \param[in] from_pandas If true, use pandas's null sentinels to determine/// whether values are null/// \param[in] type a specific type to cast to, may be null/// \param[in] cast_options casting options/// \param[out] out a ChunkedArray, to accommodate chunked outputARROW_PYTHON_EXPORTStatus NdarrayToArrow(MemoryPool* pool, PyObject* ao, PyObject* mo, bool from_pandas, const std::shared_ptr<DataType>& type, const compute::CastOptions& cast_options, std::shared_ptr<ChunkedArray>* out);
/// Safely convert NumPy arrays to Arrow. If target data type is not known,/// pass a type with null.////// \param[in] pool Memory pool for any memory allocations/// \param[in] ao an ndarray with the array data/// \param[in] mo an ndarray with a null mask (True is null), optional/// \param[in] from_pandas If true, use pandas's null sentinels to determine/// whether values are null/// \param[in] type a specific type to cast to, may be null/// \param[out] out a ChunkedArray, to accommodate chunked outputARROW_PYTHON_EXPORTStatus NdarrayToArrow(MemoryPool* pool, PyObject* ao, PyObject* mo, bool from_pandas, const std::shared_ptr<DataType>& type, std::shared_ptr<ChunkedArray>* out);
} // namespace py} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132// 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 <string>
#include "arrow/python/common.h"#include "arrow/python/visibility.h"#include "arrow/util/macros.h"#include "parquet/encryption/crypto_factory.h"#include "parquet/encryption/kms_client.h"#include "parquet/encryption/kms_client_factory.h"
#if defined(_WIN32) || defined(__CYGWIN__) // Windows#if defined(_MSC_VER)#pragma warning(disable : 4251)#else#pragma GCC diagnostic ignored "-Wattributes"#endif
#ifdef ARROW_PYTHON_STATIC#define ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT#elif defined(ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORTING)#define ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT __declspec(dllexport)#else#define ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT __declspec(dllimport)#endif
#else // Not Windows#ifndef ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT#define ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT __attribute__((visibility("default")))#endif#endif // Non-Windows
namespace arrow {namespace py {namespace parquet {namespace encryption {
/// \brief A table of function pointers for calling from C++ into/// Python.class ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT PyKmsClientVtable { public: std::function<void(PyObject*, const std::string& key_bytes, const std::string& master_key_identifier, std::string* out)> wrap_key; std::function<void(PyObject*, const std::string& wrapped_key, const std::string& master_key_identifier, std::string* out)> unwrap_key;};
/// \brief A helper for KmsClient implementation in Python.class ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT PyKmsClient : public ::parquet::encryption::KmsClient { public: PyKmsClient(PyObject* handler, PyKmsClientVtable vtable); ~PyKmsClient() override;
std::string WrapKey(const std::string& key_bytes, const std::string& master_key_identifier) override;
std::string UnwrapKey(const std::string& wrapped_key, const std::string& master_key_identifier) override;
private: OwnedRefNoGIL handler_; PyKmsClientVtable vtable_;};
/// \brief A table of function pointers for calling from C++ into/// Python.class ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT PyKmsClientFactoryVtable { public: std::function<void( PyObject*, const ::parquet::encryption::KmsConnectionConfig& kms_connection_config, std::shared_ptr<::parquet::encryption::KmsClient>* out)> create_kms_client;};
/// \brief A helper for KmsClientFactory implementation in Python.class ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT PyKmsClientFactory : public ::parquet::encryption::KmsClientFactory { public: PyKmsClientFactory(PyObject* handler, PyKmsClientFactoryVtable vtable); ~PyKmsClientFactory() override;
std::shared_ptr<::parquet::encryption::KmsClient> CreateKmsClient( const ::parquet::encryption::KmsConnectionConfig& kms_connection_config) override;
private: OwnedRefNoGIL handler_; PyKmsClientFactoryVtable vtable_;};
/// \brief A CryptoFactory that returns Results instead of throwing exceptions.class ARROW_PYTHON_PARQUET_ENCRYPTION_EXPORT PyCryptoFactory : public ::parquet::encryption::CryptoFactory { public: arrow::Result<std::shared_ptr<::parquet::FileEncryptionProperties>> SafeGetFileEncryptionProperties( const ::parquet::encryption::KmsConnectionConfig& kms_connection_config, const ::parquet::encryption::EncryptionConfiguration& encryption_config);
/// The returned FileDecryptionProperties object will use the cache inside this /// CryptoFactory object, so please keep this /// CryptoFactory object alive along with the returned /// FileDecryptionProperties object. arrow::Result<std::shared_ptr<::parquet::FileDecryptionProperties>> SafeGetFileDecryptionProperties( const ::parquet::encryption::KmsConnectionConfig& kms_connection_config, const ::parquet::encryption::DecryptionConfiguration& decryption_config);};
} // namespace encryption} // namespace parquet} // namespace py} // namespace arrow123456789101112131415161718192021222324// 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/python/platform.h"1234567891011121314151617181920212223242526272829303132333435363738394041// 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.
// Functions for converting between pandas's NumPy-based data representation// and Arrow data structures
#pragma once
// If PY_SSIZE_T_CLEAN is defined, argument parsing functions treat #-specifier// to mean Py_ssize_t (defining this to suppress deprecation warning)#define PY_SSIZE_T_CLEAN
#include <Python.h> // IWYU pragma: export#include <datetime.h>
// Work around C2528 error#ifdef _MSC_VER#if _MSC_VER >= 1900#undef timezone#endif
// https://bugs.python.org/issue36020// TODO(wjones127): Can remove once we drop support for CPython 3.9#ifdef snprintf#undef snprintf#endif#endif1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889// 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/python/platform.h"
#include <memory>
#include "arrow/python/visibility.h"
#include "arrow/sparse_tensor.h"
// Work around ARROW-2317 (C linkage warning from Cython)extern "C++" {
namespace arrow {
class Array;class Buffer;class DataType;class Field;class RecordBatch;class Schema;class Status;class Table;class Tensor;
namespace py {
// Returns 0 on success, -1 on error.ARROW_PYTHON_EXPORT int import_pyarrow();
#define DECLARE_WRAP_FUNCTIONS(FUNC_SUFFIX, TYPE_NAME) \ ARROW_PYTHON_EXPORT bool is_##FUNC_SUFFIX(PyObject*); \ ARROW_PYTHON_EXPORT Result<std::shared_ptr<TYPE_NAME>> unwrap_##FUNC_SUFFIX( \ PyObject*); \ ARROW_PYTHON_EXPORT PyObject* wrap_##FUNC_SUFFIX(const std::shared_ptr<TYPE_NAME>&);
DECLARE_WRAP_FUNCTIONS(buffer, Buffer)
DECLARE_WRAP_FUNCTIONS(data_type, DataType)DECLARE_WRAP_FUNCTIONS(field, Field)DECLARE_WRAP_FUNCTIONS(schema, Schema)
DECLARE_WRAP_FUNCTIONS(scalar, Scalar)
DECLARE_WRAP_FUNCTIONS(array, Array)DECLARE_WRAP_FUNCTIONS(chunked_array, ChunkedArray)
DECLARE_WRAP_FUNCTIONS(sparse_coo_tensor, SparseCOOTensor)DECLARE_WRAP_FUNCTIONS(sparse_csc_matrix, SparseCSCMatrix)DECLARE_WRAP_FUNCTIONS(sparse_csf_tensor, SparseCSFTensor)DECLARE_WRAP_FUNCTIONS(sparse_csr_matrix, SparseCSRMatrix)DECLARE_WRAP_FUNCTIONS(tensor, Tensor)
DECLARE_WRAP_FUNCTIONS(batch, RecordBatch)DECLARE_WRAP_FUNCTIONS(table, Table)
#undef DECLARE_WRAP_FUNCTIONS
namespace internal {
// If status is ok, return 0.// If status is not ok, set Python error indicator and return -1.ARROW_PYTHON_EXPORT int check_status(const Status& status);
// Convert status to a Python exception object. Status must not be ok.ARROW_PYTHON_EXPORT PyObject* convert_status(const Status& status);
} // namespace internal} // namespace py} // namespace arrow
} // extern "C++"12345678910111213141516171819// 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.
// For backward compatibility.#include "arrow/python/lib.h"123456789101112131415161718192021222324252627282930313233343536373839404142// 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 <functional>#include <string>#include <vector>
#include "arrow/status.h"
#include "arrow/python/visibility.h"
namespace arrow {namespace py {namespace testing {
struct TestCase { std::string name; std::function<Status()> func;};
ARROW_PYTHON_EXPORTstd::vector<TestCase> GetCppTestCases();
} // namespace testing} // namespace py} // namespace arrow1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980// 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.
// Functions for converting between CPython built-in data structures and Arrow// data structures
#pragma once
#include "arrow/python/platform.h"
#include <cstdint>#include <memory>
#include "arrow/python/visibility.h"#include "arrow/type.h"#include "arrow/util/macros.h"
#include "arrow/python/common.h"
namespace arrow {
class Array;class Status;
namespace py {
struct PyConversionOptions { PyConversionOptions() = default;
PyConversionOptions(const std::shared_ptr<DataType>& type, int64_t size, MemoryPool* pool, bool from_pandas) : type(type), size(size), from_pandas(from_pandas) {}
// Set to null if to be inferred std::shared_ptr<DataType> type;
// Default is -1, which indicates the size should the same as the input sequence int64_t size = -1;
bool from_pandas = false;
/// Used to maintain backwards compatibility for /// timezone bugs (see ARROW-9528). Should be removed /// after Arrow 2.0 release. bool ignore_timezone = false;
bool strict = false;};
/// \brief Convert sequence (list, generator, NumPy array with dtype object) of/// Python objects./// \param[in] obj the sequence to convert/// \param[in] mask a NumPy array of true/false values to indicate whether/// values in the sequence are null (true) or not null (false). This parameter/// may be null/// \param[in] options various conversion options/// \param[in] pool MemoryPool to use for allocations/// \return Result ChunkedArrayARROW_PYTHON_EXPORTResult<std::shared_ptr<ChunkedArray>> ConvertPySequence( PyObject* obj, PyObject* mask, PyConversionOptions options, MemoryPool* pool = default_memory_pool());
} // namespace py
} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081// 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/compute/exec.h"#include "arrow/compute/function.h"#include "arrow/compute/registry.h"#include "arrow/python/platform.h"#include "arrow/record_batch.h"#include "arrow/util/iterator.h"
#include "arrow/python/common.h"#include "arrow/python/pyarrow.h"#include "arrow/python/visibility.h"
namespace arrow {
namespace py {
// TODO: TODO(ARROW-16041): UDF Options are not exposed to the Python// users. This feature will be included when extending to provide advanced// options for the users.struct ARROW_PYTHON_EXPORT UdfOptions { std::string func_name; compute::Arity arity; compute::FunctionDoc func_doc; std::vector<std::shared_ptr<DataType>> input_types; std::shared_ptr<DataType> output_type;};
/// \brief A context passed as the first argument of UDF functions.struct ARROW_PYTHON_EXPORT UdfContext { MemoryPool* pool; int64_t batch_length;};
using UdfWrapperCallback = std::function<PyObject*( PyObject* user_function, const UdfContext& context, PyObject* inputs)>;
/// \brief register a Scalar user-defined-function from PythonStatus ARROW_PYTHON_EXPORT RegisterScalarFunction( PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, compute::FunctionRegistry* registry = NULLPTR);
/// \brief register a Table user-defined-function from PythonStatus ARROW_PYTHON_EXPORT RegisterTabularFunction( PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, compute::FunctionRegistry* registry = NULLPTR);
/// \brief register a Aggregate user-defined-function from PythonStatus ARROW_PYTHON_EXPORT RegisterAggregateFunction( PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, compute::FunctionRegistry* registry = NULLPTR);
/// \brief register a Vector user-defined-function from PythonStatus ARROW_PYTHON_EXPORT RegisterVectorFunction( PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, compute::FunctionRegistry* registry = NULLPTR);
Result<std::shared_ptr<RecordBatchReader>> ARROW_PYTHON_EXPORTCallTabularFunction(const std::string& func_name, const std::vector<Datum>& args, compute::FunctionRegistry* registry = NULLPTR);
} // namespace py
} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839// 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
#ifdef ARROW_PYTHON_STATIC#define ARROW_PYTHON_EXPORT#elif defined(ARROW_PYTHON_EXPORTING)#define ARROW_PYTHON_EXPORT __declspec(dllexport)#else#define ARROW_PYTHON_EXPORT __declspec(dllimport)#endif
#else // Not Windows#ifndef ARROW_PYTHON_EXPORT#define ARROW_PYTHON_EXPORT __attribute__((visibility("default")))#endif#endif // Non-Windows123456789101112131415161718192021222324252627282930313233// 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/result.h"
namespace arrow {
template <typename InputIterator, typename OutputIterator, typename UnaryOperation>Status MaybeTransform(InputIterator first, InputIterator last, OutputIterator out, UnaryOperation unary_op) { for (; first != last; ++first, (void)++out) { ARROW_ASSIGN_OR_RAISE(*out, unary_op(*first)); } return Status::OK();}
} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221// 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 <algorithm>
#include "arrow/memory_pool.h"#include "arrow/type_fwd.h"#include "arrow/util/bit_util.h"
namespace arrow {namespace internal {
struct BitmapWordAlignParams { int64_t leading_bits; int64_t trailing_bits; int64_t trailing_bit_offset; const uint8_t* aligned_start; int64_t aligned_bits; int64_t aligned_words;};
// Compute parameters for accessing a bitmap using aligned word instructions.// The returned parameters describe:// - a leading area of size `leading_bits` before the aligned words// - a word-aligned area of size `aligned_bits`// - a trailing area of size `trailing_bits` after the aligned wordstemplate <uint64_t ALIGN_IN_BYTES>inline BitmapWordAlignParams BitmapWordAlign(const uint8_t* data, int64_t bit_offset, int64_t length) { static_assert(bit_util::IsPowerOf2(ALIGN_IN_BYTES), "ALIGN_IN_BYTES should be a positive power of two"); constexpr uint64_t ALIGN_IN_BITS = ALIGN_IN_BYTES * 8;
BitmapWordAlignParams p;
// Compute a "bit address" that we can align up to ALIGN_IN_BITS. // We don't care about losing the upper bits since we are only interested in the // difference between both addresses. const uint64_t bit_addr = reinterpret_cast<size_t>(data) * 8 + static_cast<uint64_t>(bit_offset); const uint64_t aligned_bit_addr = bit_util::RoundUpToPowerOf2(bit_addr, ALIGN_IN_BITS);
p.leading_bits = std::min<int64_t>(length, aligned_bit_addr - bit_addr); p.aligned_words = (length - p.leading_bits) / ALIGN_IN_BITS; p.aligned_bits = p.aligned_words * ALIGN_IN_BITS; p.trailing_bits = length - p.leading_bits - p.aligned_bits; p.trailing_bit_offset = bit_offset + p.leading_bits + p.aligned_bits;
p.aligned_start = data + (bit_offset + p.leading_bits) / 8; return p;}} // namespace internal
namespace util {
// Functions to check if the provided Arrow object is aligned by the specified alignment
/// \brief Special alignment value to use data type-specific alignment////// If this is passed as the `alignment` in one of the CheckAlignment or EnsureAlignment/// functions, then the function will ensure each buffer is suitably aligned/// for the data type of the array. For example, given an int32 buffer the values/// buffer's address must be a multiple of 4. Given a large_string buffer the offsets/// buffer's address must be a multiple of 8.constexpr int64_t kValueAlignment = -3;
/// \brief Calculate if the buffer's address is a multiple of `alignment`////// If `alignment` is less than or equal to 0 then this method will always return true/// \param buffer the buffer to check/// \param alignment the alignment (in bytes) to check forARROW_EXPORT bool CheckAlignment(const Buffer& buffer, int64_t alignment);/// \brief Calculate if all buffers in the array data are aligned////// This will also check the buffers in the dictionary and any children/// \param array the array data to check/// \param alignment the alignment (in bytes) to check forARROW_EXPORT bool CheckAlignment(const ArrayData& array, int64_t alignment);/// \brief Calculate if all buffers in the array are aligned////// This will also check the buffers in the dictionary and any children/// \param array the array to check/// \param alignment the alignment (in bytes) to check forARROW_EXPORT bool CheckAlignment(const Array& array, int64_t alignment);
// Following functions require an additional boolean vector which stores the// alignment check bits of the constituent objects.// For example, needs_alignment vector for a ChunkedArray will contain the// check bits of the constituent Arrays.// The boolean vector check was introduced to minimize the repetitive checks// of the constituent objects during the EnsureAlignment function where certain// objects can be ignored for further checking if we already know that they are// completely aligned.
/// \brief Calculate which (if any) chunks in a chunked array are unaligned/// \param array the array to check/// \param alignment the alignment (in bytes) to check for/// \param needs_alignment an output vector that will store the results of the check/// it must be set to a valid vector. Extra elements will be added to the end/// of the vector for each chunk that is checked. `true` will be stored if/// the chunk is unaligned./// \param offset the index of the chunk to start checking/// \return true if all chunks (starting at `offset`) are aligned, false otherwiseARROW_EXPORT bool CheckAlignment(const ChunkedArray& array, int64_t alignment, std::vector<bool>* needs_alignment, int offset = 0);
/// \brief calculate which (if any) columns in a record batch are unaligned/// \param batch the batch to check/// \param alignment the alignment (in bytes) to check for/// \param needs_alignment an output vector that will store the results of the/// check. It must be set to a valid vector. Extra elements will be added/// to the end of the vector for each column that is checked. `true` will be/// stored if the column is unaligned.ARROW_EXPORT bool CheckAlignment(const RecordBatch& batch, int64_t alignment, std::vector<bool>* needs_alignment);
/// \brief calculate which (if any) columns in a table are unaligned/// \param table the table to check/// \param alignment the alignment (in bytes) to check for/// \param needs_alignment an output vector that will store the results of the/// check. It must be set to a valid vector. Extra elements will be added/// to the end of the vector for each column that is checked. `true` will be/// stored if the column is unaligned.ARROW_EXPORT bool CheckAlignment(const Table& table, int64_t alignment, std::vector<bool>* needs_alignment);
/// \brief return a buffer that has the given alignment and the same data as the input/// buffer////// If the input buffer is already aligned then this method will return the input buffer/// If the input buffer is not already aligned then this method will allocate a new/// buffer. The alignment of the new buffer will have at least/// max(kDefaultBufferAlignment, alignment) bytes of alignment.////// \param buffer the buffer to check/// \param alignment the alignment (in bytes) to check for/// \param memory_pool a memory pool that will be used to allocate a new buffer if the/// input buffer is not sufficiently alignedARROW_EXPORT Result<std::shared_ptr<Buffer>> EnsureAlignment( std::shared_ptr<Buffer> buffer, int64_t alignment, MemoryPool* memory_pool);
/// \brief return an array data where all buffers are aligned by the given alignment////// If any input buffer is already aligned then this method will reuse that same input/// buffer.////// \param array_data the array data to check/// \param alignment the alignment (in bytes) to check for/// \param memory_pool a memory pool that will be used to allocate new buffers if any/// input buffer is not sufficiently alignedARROW_EXPORT Result<std::shared_ptr<ArrayData>> EnsureAlignment( std::shared_ptr<ArrayData> array_data, int64_t alignment, MemoryPool* memory_pool);
/// \brief return an array where all buffers are aligned by the given alignment////// If any input buffer is already aligned then this method will reuse that same input/// buffer.////// \param array the array to check/// \param alignment the alignment (in bytes) to check for/// \param memory_pool a memory pool that will be used to allocate new buffers if any/// input buffer is not sufficiently alignedARROW_EXPORT Result<std::shared_ptr<Array>> EnsureAlignment(std::shared_ptr<Array> array, int64_t alignment, MemoryPool* memory_pool);
/// \brief return a chunked array where all buffers are aligned by the given alignment////// If any input buffer is already aligned then this method will reuse that same input/// buffer.////// \param array the chunked array to check/// \param alignment the alignment (in bytes) to check for/// \param memory_pool a memory pool that will be used to allocate new buffers if any/// input buffer is not sufficiently alignedARROW_EXPORT Result<std::shared_ptr<ChunkedArray>> EnsureAlignment( std::shared_ptr<ChunkedArray> array, int64_t alignment, MemoryPool* memory_pool);
/// \brief return a record batch where all buffers are aligned by the given alignment////// If any input buffer is already aligned then this method will reuse that same input/// buffer.////// \param batch the batch to check/// \param alignment the alignment (in bytes) to check for/// \param memory_pool a memory pool that will be used to allocate new buffers if any/// input buffer is not sufficiently alignedARROW_EXPORT Result<std::shared_ptr<RecordBatch>> EnsureAlignment( std::shared_ptr<RecordBatch> batch, int64_t alignment, MemoryPool* memory_pool);
/// \brief return a table where all buffers are aligned by the given alignment////// If any input buffer is already aligned then this method will reuse that same input/// buffer.////// \param table the table to check/// \param alignment the alignment (in bytes) to check for/// \param memory_pool a memory pool that will be used to allocate new buffers if any/// input buffer is not sufficiently alignedARROW_EXPORT Result<std::shared_ptr<Table>> EnsureAlignment(std::shared_ptr<Table> table, int64_t alignment, MemoryPool* memory_pool);
} // namespace util} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058// 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 <atomic>#include <cassert>#include <cstring>#include <deque>#include <limits>#include <optional>#include <queue>
#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 <typename T>struct IterationTraits<AsyncGenerator<T>> { /// \brief by default when iterating through a sequence of AsyncGenerator<T>, /// an empty function indicates the end of iteration. static AsyncGenerator<T> End() { return AsyncGenerator<T>(); }
static bool IsEnd(const AsyncGenerator<T>& val) { return !val; }};
template <typename T>Future<T> AsyncGeneratorEnd() { return Future<T>::MakeFinished(IterationTraits<T>::End());}
/// returning a future that completes when all have been visitedtemplate <typename T, typename Visitor>Future<> VisitAsyncGenerator(AsyncGenerator<T> generator, Visitor visitor) { struct LoopBody { struct Callback { Result<ControlFlow<>> 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<ControlFlow<>> operator()() { Callback callback{visitor}; auto next = generator(); return next.Then(std::move(callback)); }
AsyncGenerator<T> generator; Visitor visitor; };
return Loop(LoopBody{std::move(generator), std::move(visitor)});}
/// \brief Wait for an async generator to complete, discarding results.template <typename T>Future<> DiscardAllFromAsyncGenerator(AsyncGenerator<T> generator) { std::function<Status(T)> visitor = [](const T&) { return Status::OK(); }; return VisitAsyncGenerator(generator, visitor);}
/// \brief Collect the results of an async generator into a vectortemplate <typename T>Future<std::vector<T>> CollectAsyncGenerator(AsyncGenerator<T> generator) { auto vec = std::make_shared<std::vector<T>>(); auto loop_body = [generator = std::move(generator), vec = std::move(vec)]() -> Future<ControlFlow<std::vector<T>>> { auto next = generator(); return next.Then([vec](const T& result) -> Result<ControlFlow<std::vector<T>>> { if (IsIterationEnd(result)) { return Break(*vec); } else { vec->push_back(result); return Continue(); } }); }; return Loop(std::move(loop_body));}
/// \see MakeMappedGeneratortemplate <typename T, typename V>class MappingGenerator { public: MappingGenerator(AsyncGenerator<T> source, std::function<Future<V>(const T&)> map) : state_(std::make_shared<State>(std::move(source), std::move(map))) {}
Future<V> operator()() { auto future = Future<V>::Make(); bool should_trigger; { auto guard = state_->mutex.Lock(); if (state_->finished) { return AsyncGeneratorEnd<V>(); } 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<T> source, std::function<Future<V>(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<V>::End()); waiting_jobs.pop_front(); } }
AsyncGenerator<T> source; std::function<Future<V>(const T&)> map; std::deque<Future<V>> waiting_jobs; util::Mutex mutex; bool finished; };
struct Callback;
struct MappedCallback { void operator()(const Result<V>& 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> state; Future<V> sink; };
struct Callback { void operator()(const Result<T>& maybe_next) { Future<V> 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<V>::End()); } else { Future<V> 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> state; };
std::shared_ptr<State> 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 alsotemplate <typename T, typename MapFn, typename Mapped = detail::result_of_t<MapFn(const T&)>, typename V = typename EnsureFuture<Mapped>::type::ValueType>AsyncGenerator<V> MakeMappedGenerator(AsyncGenerator<T> source_generator, MapFn map) { auto map_callback = [map = std::move(map)](const T& val) mutable -> Future<V> { return ToFuture(map(val)); }; return MappingGenerator<T, V>(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 alsotemplate <typename T, typename MapFn, typename Mapped = detail::result_of_t<MapFn(const T&)>, typename V = typename EnsureFuture<Mapped>::type::ValueType>AsyncGenerator<T> MakeFlatMappedGenerator(AsyncGenerator<T> source_generator, MapFn map) { return MakeConcatenatedGenerator( MakeMappedGenerator(std::move(source_generator), std::move(map)));}
/// \see MakeSequencingGeneratortemplate <typename T, typename ComesAfter, typename IsNext>class SequencingGenerator { public: SequencingGenerator(AsyncGenerator<T> source, ComesAfter compare, IsNext is_next, T initial_value) : state_(std::make_shared<State>(std::move(source), std::move(compare), std::move(is_next), std::move(initial_value))) {}
Future<T> 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<T>::MakeFinished(result); } if (state_->finished) { return AsyncGeneratorEnd<T>(); } // The next item is not in the queue so we will need to wait auto new_waiting_fut = Future<T>::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<T>& left, const Result<T>& right) { if (!left.ok() || !right.ok()) { // Should never happen return false; } return compare(*left, *right); } ComesAfter compare; };
struct State { State(AsyncGenerator<T> 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<T> source; IsNext is_next; T previous_value; Future<T> waiting_future; std::priority_queue<Result<T>, std::vector<Result<T>>, WrappedComesAfter> queue; bool finished; util::Mutex mutex; };
class Callback { public: explicit Callback(std::shared_ptr<State> state) : state_(std::move(state)) {}
void operator()(const Result<T> result) { Future<T> 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<T>(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> state_; };
const std::shared_ptr<State> 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 <typename T, typename ComesAfter, typename IsNext>AsyncGenerator<T> MakeSequencingGenerator(AsyncGenerator<T> source_generator, ComesAfter compare, IsNext is_next, T initial_value) { return SequencingGenerator<T, ComesAfter, IsNext>( std::move(source_generator), std::move(compare), std::move(is_next), std::move(initial_value));}
/// \see MakeTransformedGeneratortemplate <typename T, typename V>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> { TransformingGeneratorState(AsyncGenerator<T> generator, Transformer<T, V> transformer) : generator_(std::move(generator)), transformer_(std::move(transformer)), last_value_(), finished_() {}
Future<V> operator()() { while (true) { auto maybe_next_result = Pump(); if (!maybe_next_result.ok()) { return Future<V>::MakeFinished(maybe_next_result.status()); } auto maybe_next = std::move(maybe_next_result).ValueUnsafe(); if (maybe_next.has_value()) { return Future<V>::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<V>::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<std::optional<V>> Pump() { if (!finished_ && last_value_.has_value()) { ARROW_ASSIGN_OR_RAISE(TransformFlow<V> 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<V>::End(); } return std::nullopt; }
AsyncGenerator<T> generator_; Transformer<T, V> transformer_; std::optional<T> last_value_; bool finished_; };
public: explicit TransformingGenerator(AsyncGenerator<T> generator, Transformer<T, V> transformer) : state_(std::make_shared<TransformingGeneratorState>(std::move(generator), std::move(transformer))) {}
Future<V> operator()() { return (*state_)(); }
protected: std::shared_ptr<TransformingGeneratorState> 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 delaytemplate <typename T, typename V>AsyncGenerator<V> MakeTransformedGenerator(AsyncGenerator<T> generator, Transformer<T, V> transformer) { return TransformingGenerator<T, V>(generator, transformer);}
/// \see MakeSerialReadaheadGeneratortemplate <typename T>class SerialReadaheadGenerator { public: SerialReadaheadGenerator(AsyncGenerator<T> source_generator, int max_readahead) : state_(std::make_shared<State>(std::move(source_generator), max_readahead)) {}
Future<T> 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<T>(); }
std::shared_ptr<Future<T>> 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<T> 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<State>& 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<Future<T>>(); 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<T> source_; std::atomic<bool> 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<uint32_t> 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<std::shared_ptr<Future<T>>> readahead_queue_; };
struct Callback { Result<T> 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> state_; };
struct ErrCallback { Result<T> operator()(const Status& st) { state_->finished_.store(true); return st; }
std::shared_ptr<State> state_; };
std::shared_ptr<State> state_;};
/// \see MakeFromFuturetemplate <typename T>class FutureFirstGenerator { public: explicit FutureFirstGenerator(Future<AsyncGenerator<T>> future) : state_(std::make_shared<State>(std::move(future))) {}
Future<T> operator()() { if (state_->source_) { return state_->source_(); } else { auto state = state_; return state_->future_.Then([state](const AsyncGenerator<T>& source) { state->source_ = source; return state->source_(); }); } }
private: struct State { explicit State(Future<AsyncGenerator<T>> future) : future_(future), source_() {}
Future<AsyncGenerator<T>> future_; AsyncGenerator<T> source_; };
std::shared_ptr<State> state_;};
/// \brief Transform a Future<AsyncGenerator<T>> into an AsyncGenerator<T>/// 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 queuetemplate <typename T>AsyncGenerator<T> MakeFromFuture(Future<AsyncGenerator<T>> future) { return FutureFirstGenerator<T>(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 Ttemplate <typename T>AsyncGenerator<T> MakeSerialReadaheadGenerator(AsyncGenerator<T> source_generator, int max_readahead) { return SerialReadaheadGenerator<T>(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 <typename T>AsyncGenerator<T> MakeAutoStartingGenerator(AsyncGenerator<T> generator) { struct AutostartGenerator { Future<T> operator()() { if (first_future->is_valid()) { Future<T> result = *first_future; *first_future = Future<T>(); return result; } return source(); }
std::shared_ptr<Future<T>> first_future; AsyncGenerator<T> source; };
std::shared_ptr<Future<T>> first_future = std::make_shared<Future<T>>(generator()); return AutostartGenerator{std::move(first_future), std::move(generator)};}
/// \see MakeReadaheadGeneratortemplate <typename T>class ReadaheadGenerator { public: ReadaheadGenerator(AsyncGenerator<T> source_generator, int max_readahead) : state_(std::make_shared<State>(std::move(source_generator), max_readahead)) {}
Future<T> AddMarkFinishedContinuation(Future<T> fut) { auto state = state_; return fut.Then( [state](const T& result) -> Future<T> { 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<T> { // 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<T> { return err; }); }); }
Future<T> 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<T>()); } 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<T> 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<T> source_generator; int max_readahead; Future<> final_future = Future<>::Make(); std::atomic<int> num_running{0}; std::atomic<bool> finished{false}; std::queue<Future<T>> readahead_queue; };
std::shared_ptr<State> 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 <typename T>class PushGenerator { struct State { State() {}
util::Mutex mutex; std::deque<Result<T>> result_q; std::optional<Future<T>> consumer_fut; bool finished = false; };
public: /// Producer API for PushGenerator class Producer { public: explicit Producer(const std::shared_ptr<State>& 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<T> 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<T>::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<State> weak_state_; };
PushGenerator() : state_(std::make_shared<State>()) {}
/// Read an item from the queue Future<T> operator()() const { auto lock = state_->mutex.Lock(); assert(!state_->consumer_fut.has_value()); // Non-reentrant if (!state_->result_q.empty()) { auto fut = Future<T>::MakeFinished(std::move(state_->result_q.front())); state_->result_q.pop_front(); return fut; } if (state_->finished) { return AsyncGeneratorEnd<T>(); } auto fut = Future<T>::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> 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 Ttemplate <typename T>AsyncGenerator<T> MakeReadaheadGenerator(AsyncGenerator<T> source_generator, int max_readahead) { return ReadaheadGenerator<T>(std::move(source_generator), max_readahead);}
/// \brief Creates a generator that will yield finished futures from a vector////// This generator is async-reentranttemplate <typename T>AsyncGenerator<T> MakeVectorGenerator(std::vector<T> vec) { struct State { explicit State(std::vector<T> vec_) : vec(std::move(vec_)), vec_idx(0) {}
std::vector<T> vec; std::atomic<std::size_t> vec_idx; };
auto state = std::make_shared<State>(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<T>(); } return Future<T>::MakeFinished(state->vec[idx]); };}
/// \see MakeMergedGeneratortemplate <typename T>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<AsyncGenerator<T>> source, int max_subscriptions) : state_(std::make_shared<State>(std::move(source), max_subscriptions)) {}
Future<T> operator()() { // A caller has requested a future Future<T> waiting_future; std::shared_ptr<DeliveredJob> 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<T> end_res = IterationEnd<T>(); if (!state_->final_error.ok()) { end_res = state_->final_error; state_->final_error = Status::OK(); } return state_->all_finished.Then([end_res]() -> Result<T> { 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<T>::Make(); state_->waiting_jobs.push_back(std::make_shared<Future<T>>(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<int>(state_->active_subscriptions.size()); state_->num_running_subscriptions += static_cast<int>(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<int>(state_->active_subscriptions.size()); i++) { state_->PullSource().AddCallback( OuterCallback{state_, static_cast<std::size_t>(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<int>(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<T> deliverer_, Result<T> 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<T> deliverer; // The result we received from the generator Result<T> 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<AsyncGenerator<T>> 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<AsyncGenerator<T>> 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<T>()); 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<T> 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<AsyncGenerator<T>> source; // active_subscriptions and delivered_jobs will be bounded by max_subscriptions std::vector<AsyncGenerator<T>> active_subscriptions; // Results delivered by the inner subscriptions that weren't yet asked for by the // caller std::deque<std::shared_ptr<DeliveredJob>> delivered_jobs; // waiting_jobs is unbounded, reentrant pulls (e.g. AddReadahead) will provide the // backpressure std::deque<std::shared_ptr<Future<T>>> 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> state, std::size_t index, bool recursive = false) : state(std::move(state)), index(index), recursive(recursive) {}
void operator()(const Result<T>& maybe_next_ref) { // An item has been delivered by one of the inner subscriptions Future<T> next_fut; const Result<T>* 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<T> 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<DeliveredJob>( 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> state; std::size_t index; bool recursive; bool was_empty = false; };
struct OuterCallback { void operator()(const Result<AsyncGenerator<T>>& initial_maybe_next) { Result<AsyncGenerator<T>> 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<T> 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<T> 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<AsyncGenerator<T>> 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> state; std::size_t index; };
std::shared_ptr<State> 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 Ttemplate <typename T>AsyncGenerator<T> MakeMergedGenerator(AsyncGenerator<AsyncGenerator<T>> source, int max_subscriptions) { return MergedGenerator<T>(std::move(source), max_subscriptions);}
template <typename T>Result<AsyncGenerator<T>> MakeSequencedMergedGenerator( AsyncGenerator<AsyncGenerator<T>> 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<AsyncGenerator<T>> autostarting_source = MakeMappedGenerator( std::move(source), [](const AsyncGenerator<T>& sub) { return MakeAutoStartingGenerator(sub); }); AsyncGenerator<AsyncGenerator<T>> 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 <typename T>AsyncGenerator<T> MakeConcatenatedGenerator(AsyncGenerator<AsyncGenerator<T>> source) { return MergedGenerator<T>(std::move(source), 1);}
template <typename T>struct Enumerated { T value; int index; bool last;};
template <typename T>struct IterationTraits<Enumerated<T>> { static Enumerated<T> End() { return Enumerated<T>{IterationEnd<T>(), -1, false}; } static bool IsEnd(const Enumerated<T>& val) { return val.index < 0; }};
/// \see MakeEnumeratedGeneratortemplate <typename T>class EnumeratingGenerator { public: EnumeratingGenerator(AsyncGenerator<T> source, T initial_value) : state_(std::make_shared<State>(std::move(source), std::move(initial_value))) {}
Future<Enumerated<T>> operator()() { if (state_->finished) { return AsyncGeneratorEnd<Enumerated<T>>(); } else { auto state = state_; return state->source().Then([state](const T& next) { auto finished = IsIterationEnd<T>(next); auto prev = Enumerated<T>{state->prev_value, state->prev_index, finished}; state->prev_value = next; state->prev_index++; state->finished = finished; return prev; }); } }
private: struct State { State(AsyncGenerator<T> source, T initial_value) : source(std::move(source)), prev_value(std::move(initial_value)), prev_index(0) { finished = IsIterationEnd<T>(prev_value); }
AsyncGenerator<T> source; T prev_value; int prev_index; bool finished; };
std::shared_ptr<State> 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 <typename T>AsyncGenerator<Enumerated<T>> MakeEnumeratedGenerator(AsyncGenerator<T> source) { return FutureFirstGenerator<Enumerated<T>>( source().Then([source](const T& initial_value) -> AsyncGenerator<Enumerated<T>> { return EnumeratingGenerator<T>(std::move(source), initial_value); }));}
/// \see MakeTransferredGeneratortemplate <typename T>class TransferringGenerator { public: explicit TransferringGenerator(AsyncGenerator<T> source, internal::Executor* executor) : source_(std::move(source)), executor_(executor) {}
Future<T> operator()() { return executor_->Transfer(source_()); }
private: AsyncGenerator<T> 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 queuetemplate <typename T>AsyncGenerator<T> MakeTransferredGenerator(AsyncGenerator<T> source, internal::Executor* executor) { return TransferringGenerator<T>(std::move(source), executor);}
/// \see MakeBackgroundGeneratortemplate <typename T>class BackgroundGenerator { public: explicit BackgroundGenerator(Iterator<T> it, internal::Executor* io_executor, int max_q, int q_restart) : state_(std::make_shared<State>(io_executor, std::move(it), max_q, q_restart)), cleanup_(std::make_shared<Cleanup>(state_.get())) {}
Future<T> operator()() { auto guard = state_->mutex.Lock(); Future<T> waiting_future; if (state_->queue.empty()) { if (state_->finished) { return AsyncGeneratorEnd<T>(); } else { waiting_future = Future<T>::Make(); state_->waiting_future = waiting_future; } } else { auto next = Future<T>::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<uint64_t>::max()};
struct State { State(internal::Executor* io_executor, Iterator<T> 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<int>(queue.size()) <= q_restart; }
void DoRestartTask(std::shared_ptr<State> 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<T> RestartTask(std::shared_ptr<State> state, util::Mutex::Guard guard, Future<T> 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<T> it; std::atomic<uint64_t> 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<Result<T>> queue; std::optional<Future<T>> 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) { 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<T> waiting_future; { auto guard = state->mutex.Lock();
if (state->should_shutdown) { state->finished = true; break; }
if (!next.ok() || IsIterationEnd<T>(*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<int>(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_; // 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> cleanup_;};
constexpr int kDefaultBackgroundMaxQ = 32;constexpr int kDefaultBackgroundQRestart = 16;
/// \brief Create an AsyncGenerator<T> by iterating over an Iterator<T> 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 blockstemplate <typename T>static Result<AsyncGenerator<T>> MakeBackgroundGenerator( Iterator<T> 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<T>(std::move(iterator), io_executor, max_q, q_restart);}
/// \brief Create an AsyncGenerator<T> by iterating over an Iterator<T> 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 queuetemplate <typename T>static Result<AsyncGenerator<T>> MakeBlockingGenerator( std::shared_ptr<Iterator<T>> iterator) { return [it = std::move(iterator)]() mutable -> Future<T> { return Future<T>::MakeFinished(it->Next()); };}
template <typename T>static Result<AsyncGenerator<T>> MakeBlockingGenerator(Iterator<T> iterator) { return MakeBlockingGenerator(std::make_shared<Iterator<T>>(std::move(iterator)));}
/// \see MakeGeneratorIteratortemplate <typename T>class GeneratorIterator { public: explicit GeneratorIterator(AsyncGenerator<T> source) : source_(std::move(source)) {}
Result<T> Next() { return source_().result(); }
private: AsyncGenerator<T> source_;};
/// \brief Convert an AsyncGenerator<T> to an Iterator<T> which blocks until each future/// is finishedtemplate <typename T>Iterator<T> MakeGeneratorIterator(AsyncGenerator<T> source) { return Iterator<T>(GeneratorIterator<T>(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 <typename T>Result<Iterator<T>> MakeReadaheadIterator(Iterator<T> 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<T> 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 <typename T>std::function<Future<T>()> MakeSingleFutureGenerator(Future<T> future) { assert(future.is_valid()); auto state = std::make_shared<Future<T>>(std::move(future)); return [state]() -> Future<T> { auto fut = std::move(*state); if (fut.is_valid()) { return fut; } else { return AsyncGeneratorEnd<T>(); } };}
/// \brief Make a generator that immediately ends.////// This generator is async-reentrant.template <typename T>std::function<Future<T>()> MakeEmptyGenerator() { return []() -> Future<T> { return AsyncGeneratorEnd<T>(); };}
/// \brief Make a generator that always fails with a given error////// This generator is async-reentrant.template <typename T>AsyncGenerator<T> MakeFailingGenerator(Status st) { assert(!st.ok()); auto state = std::make_shared<Status>(std::move(st)); return [state]() -> Future<T> { auto st = std::move(*state); if (!st.ok()) { return st; } else { return AsyncGeneratorEnd<T>(); } };}
/// \brief Make a generator that always fails with a given error////// This overload allows inferring the return type from the argument.template <typename T>AsyncGenerator<T> MakeFailingGenerator(const Result<T>& result) { return MakeFailingGenerator<T>(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 <typename T>AsyncGenerator<T> MakeGeneratorStartsWith(std::vector<T> initial_values, AsyncGenerator<T> following_values) { auto initial_values_vec_gen = MakeVectorGenerator(std::move(initial_values)); auto gen_gen = MakeVectorGenerator<AsyncGenerator<T>>( {std::move(initial_values_vec_gen), std::move(following_values)}); return MakeConcatenatedGenerator(std::move(gen_gen));}
template <typename T>struct CancellableGenerator { Future<T> operator()() { if (stop_token.IsStopRequested()) { return stop_token.Poll(); } return source(); }
AsyncGenerator<T> source; StopToken stop_token;};
/// \brief Allow an async generator to be cancelled////// This generator is async-reentranttemplate <typename T>AsyncGenerator<T> MakeCancellable(AsyncGenerator<T> source, StopToken stop_token) { return CancellableGenerator<T>{std::move(source), std::move(stop_token)};}
template <typename T>class DefaultIfEmptyGenerator { public: DefaultIfEmptyGenerator(AsyncGenerator<T> source, T or_value) : state_(std::make_shared<State>(std::move(source), std::move(or_value))) {}
Future<T> operator()() { if (state_->first) { state_->first = false; struct { T or_value;
Result<T> operator()(const T& value) { if (IterationTraits<T>::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<T> source; T or_value; bool first; State(AsyncGenerator<T> source_, T or_value_) : source(std::move(source_)), or_value(std::move(or_value_)), first(true) {} }; std::shared_ptr<State> state_;};
/// \brief If the generator is empty, return the given value, else/// forward the values from the generator.////// This generator is async-reentrant.template <typename T>AsyncGenerator<T> MakeDefaultIfEmptyGenerator(AsyncGenerator<T> source, T or_value) { return DefaultIfEmptyGenerator<T>(std::move(source), std::move(or_value));}} // namespace arrow1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071// 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 <functional>
#include "arrow/type_fwd.h"
namespace arrow {
template <typename T>using AsyncGenerator = std::function<Future<T>()>;
template <typename T, typename V>class MappingGenerator;
template <typename T, typename ComesAfter, typename IsNext>class SequencingGenerator;
template <typename T, typename V>class TransformingGenerator;
template <typename T>class SerialReadaheadGenerator;
template <typename T>class ReadaheadGenerator;
template <typename T>class PushGenerator;
template <typename T>class MergedGenerator;
template <typename T>struct Enumerated;
template <typename T>class EnumeratingGenerator;
template <typename T>class TransferringGenerator;
template <typename T>class BackgroundGenerator;
template <typename T>class GeneratorIterator;
template <typename T>struct CancellableGenerator;
template <typename T>class DefaultIfEmptyGenerator;
} // namespace arrow1234567891011121314151617181920212223242526272829303132333435// 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 <string>#include <string_view>
#include "arrow/util/visibility.h"
namespace arrow {namespace util {
ARROW_EXPORTstd::string base64_encode(std::string_view s);
ARROW_EXPORTstd::string base64_decode(std::string_view s);
} // namespace util} // namespace arrow1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495// 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 <string_view>#include <utility>
#include "arrow/type.h"#include "arrow/util/span.h"
namespace arrow::util {
inline BinaryViewType::c_type ToInlineBinaryView(const void* data, int32_t size) { // Small string: inlined. Bytes beyond size are zeroed BinaryViewType::c_type out; out.inlined = {size, {}}; memcpy(&out.inlined.data, data, size); return out;}
inline BinaryViewType::c_type ToInlineBinaryView(std::string_view v) { return ToInlineBinaryView(v.data(), static_cast<int32_t>(v.size()));}
inline BinaryViewType::c_type ToBinaryView(const void* data, int32_t size, int32_t buffer_index, int32_t offset) { if (size <= BinaryViewType::kInlineSize) { return ToInlineBinaryView(data, size); }
// Large string: store index/offset. BinaryViewType::c_type out; out.ref = {size, {}, buffer_index, offset}; memcpy(&out.ref.prefix, data, sizeof(out.ref.prefix)); return out;}
inline BinaryViewType::c_type ToBinaryView(std::string_view v, int32_t buffer_index, int32_t offset) { return ToBinaryView(v.data(), static_cast<int32_t>(v.size()), buffer_index, offset);}
template <typename BufferPtr>std::string_view FromBinaryView(const BinaryViewType::c_type& v, const BufferPtr* data_buffers) { auto* data = v.is_inline() ? v.inlined.data.data() : data_buffers[v.ref.buffer_index]->data() + v.ref.offset; return {reinterpret_cast<const char*>(data), static_cast<size_t>(v.size())};}template <typename BufferPtr>std::string_view FromBinaryView(BinaryViewType::c_type&&, const BufferPtr*) = delete;
template <typename BufferPtr>bool EqualBinaryView(BinaryViewType::c_type l, BinaryViewType::c_type r, const BufferPtr* l_buffers, const BufferPtr* r_buffers) { int64_t l_size_and_prefix, r_size_and_prefix; memcpy(&l_size_and_prefix, &l, sizeof(l_size_and_prefix)); memcpy(&r_size_and_prefix, &r, sizeof(r_size_and_prefix));
if (l_size_and_prefix != r_size_and_prefix) return false;
if (l.is_inline()) { // The columnar spec mandates that the inlined part be zero-padded, so we can compare // a word at a time regardless of the exact size. int64_t l_inlined, r_inlined; memcpy(&l_inlined, l.inline_data() + BinaryViewType::kPrefixSize, sizeof(l_inlined)); memcpy(&r_inlined, r.inline_data() + BinaryViewType::kPrefixSize, sizeof(r_inlined)); return l_inlined == r_inlined; }
// Sizes are equal and this is not inline, therefore both are out // of line and have kPrefixSize first in common. const uint8_t* l_data = l_buffers[l.ref.buffer_index]->data() + l.ref.offset; const uint8_t* r_data = r_buffers[r.ref.buffer_index]->data() + r.ref.offset; return memcmp(l_data + BinaryViewType::kPrefixSize, r_data + BinaryViewType::kPrefixSize, l.size() - BinaryViewType::kPrefixSize) == 0;}
} // namespace arrow::util123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466// 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 <algorithm>#include <array>#include <bitset>#include <cassert>#include <cstdint>#include <cstring>#include <memory>#include <string>#include <string_view>#include <utility>
#include "arrow/buffer.h"#include "arrow/util/bit_util.h"#include "arrow/util/bitmap_ops.h"#include "arrow/util/bitmap_reader.h"#include "arrow/util/bitmap_writer.h"#include "arrow/util/compare.h"#include "arrow/util/endian.h"#include "arrow/util/functional.h"#include "arrow/util/span.h"#include "arrow/util/string_builder.h"#include "arrow/util/visibility.h"
namespace arrow {
class BooleanArray;
namespace internal {
class ARROW_EXPORT Bitmap : public util::ToStringOstreamable<Bitmap>, public util::EqualityComparable<Bitmap> { public: Bitmap() = default;
Bitmap(const std::shared_ptr<Buffer>& buffer, int64_t offset, int64_t length) : data_(buffer->data()), offset_(offset), length_(length) { if (buffer->is_mutable()) { mutable_data_ = buffer->mutable_data(); } }
Bitmap(const void* data, int64_t offset, int64_t length) : data_(reinterpret_cast<const uint8_t*>(data)), offset_(offset), length_(length) {}
Bitmap(void* data, int64_t offset, int64_t length) : data_(reinterpret_cast<const uint8_t*>(data)), mutable_data_(reinterpret_cast<uint8_t*>(data)), offset_(offset), length_(length) {}
Bitmap Slice(int64_t offset) const { if (mutable_data_ != NULLPTR) { return {mutable_data_, offset_ + offset, length_ - offset}; } else { return {data_, offset_ + offset, length_ - offset}; } }
Bitmap Slice(int64_t offset, int64_t length) const { if (mutable_data_ != NULLPTR) { return {mutable_data_, offset_ + offset, length}; } else { return {data_, offset_ + offset, length}; } }
std::string ToString() const;
bool Equals(const Bitmap& other) const;
std::string Diff(const Bitmap& other) const;
bool GetBit(int64_t i) const { return bit_util::GetBit(data_, i + offset_); }
bool operator[](int64_t i) const { return GetBit(i); }
void SetBitTo(int64_t i, bool v) const { bit_util::SetBitTo(mutable_data_, i + offset_, v); }
void SetBitsTo(bool v) { bit_util::SetBitsTo(mutable_data_, offset_, length_, v); }
void CopyFrom(const Bitmap& other); void CopyFromInverted(const Bitmap& other);
/// \brief Visit bits from each bitmap as bitset<N> /// /// All bitmaps must have identical length. template <size_t N, typename Visitor> static void VisitBits(const Bitmap (&bitmaps)[N], Visitor&& visitor) { int64_t bit_length = BitLength(bitmaps, N); std::bitset<N> bits; for (int64_t bit_i = 0; bit_i < bit_length; ++bit_i) { for (size_t i = 0; i < N; ++i) { bits[i] = bitmaps[i].GetBit(bit_i); } visitor(bits); } }
/// \brief Visit bits from each bitmap as bitset<N> /// /// All bitmaps must have identical length. template <size_t N, typename Visitor> static void VisitBits(const std::array<Bitmap, N>& bitmaps, Visitor&& visitor) { int64_t bit_length = BitLength(bitmaps); std::bitset<N> bits; for (int64_t bit_i = 0; bit_i < bit_length; ++bit_i) { for (size_t i = 0; i < N; ++i) { bits[i] = bitmaps[i].GetBit(bit_i); } visitor(bits); } }
/// \brief Visit words of bits from each bitmap as array<Word, N> /// /// All bitmaps must have identical length. The first bit in a visited bitmap /// may be offset within the first visited word, but words will otherwise contain /// densely packed bits loaded from the bitmap. That offset within the first word is /// returned. /// /// TODO(bkietz) allow for early termination // NOTE: this function is efficient on 3+ sufficiently large bitmaps. // It also has a large prolog / epilog overhead and should be used // carefully in other cases. // For 2 bitmaps or less, and/or smaller bitmaps, see also VisitTwoBitBlocksVoid // and BitmapUInt64Reader. template <size_t N, typename Visitor, typename Word = typename std::decay< internal::call_traits::argument_type<0, Visitor&&>>::type::value_type> static int64_t VisitWords(const Bitmap (&bitmaps_arg)[N], Visitor&& visitor) { constexpr int64_t kBitWidth = sizeof(Word) * 8;
// local, mutable variables which will be sliced/decremented to represent consumption: Bitmap bitmaps[N]; int64_t offsets[N]; int64_t bit_length = BitLength(bitmaps_arg, N); util::span<const Word> words[N]; for (size_t i = 0; i < N; ++i) { bitmaps[i] = bitmaps_arg[i]; offsets[i] = bitmaps[i].template word_offset<Word>(); assert(offsets[i] >= 0 && offsets[i] < kBitWidth); words[i] = bitmaps[i].template words<Word>(); }
auto consume = [&](int64_t consumed_bits) { for (size_t i = 0; i < N; ++i) { bitmaps[i] = bitmaps[i].Slice(consumed_bits, bit_length - consumed_bits); offsets[i] = bitmaps[i].template word_offset<Word>(); assert(offsets[i] >= 0 && offsets[i] < kBitWidth); words[i] = bitmaps[i].template words<Word>(); } bit_length -= consumed_bits; };
std::array<Word, N> visited_words; visited_words.fill(0);
if (bit_length <= kBitWidth * 2) { // bitmaps fit into one or two words so don't bother with optimization while (bit_length > 0) { auto leading_bits = std::min(bit_length, kBitWidth); SafeLoadWords(bitmaps, 0, leading_bits, false, &visited_words); visitor(visited_words); consume(leading_bits); } return 0; }
int64_t max_offset = *std::max_element(offsets, offsets + N); int64_t min_offset = *std::min_element(offsets, offsets + N); if (max_offset > 0) { // consume leading bits auto leading_bits = kBitWidth - min_offset; SafeLoadWords(bitmaps, 0, leading_bits, true, &visited_words); visitor(visited_words); consume(leading_bits); } assert(*std::min_element(offsets, offsets + N) == 0);
int64_t whole_word_count = bit_length / kBitWidth; assert(whole_word_count >= 1);
if (min_offset == max_offset) { // all offsets were identical, all leading bits have been consumed assert( std::all_of(offsets, offsets + N, [](int64_t offset) { return offset == 0; }));
for (int64_t word_i = 0; word_i < whole_word_count; ++word_i) { for (size_t i = 0; i < N; ++i) { visited_words[i] = words[i][word_i]; } visitor(visited_words); } consume(whole_word_count * kBitWidth); } else { // leading bits from potentially incomplete words have been consumed
// word_i such that words[i][word_i] and words[i][word_i + 1] are lie entirely // within the bitmap for all i for (int64_t word_i = 0; word_i < whole_word_count - 1; ++word_i) { for (size_t i = 0; i < N; ++i) { if (offsets[i] == 0) { visited_words[i] = words[i][word_i]; } else { auto words0 = bit_util::ToLittleEndian(words[i][word_i]); auto words1 = bit_util::ToLittleEndian(words[i][word_i + 1]); visited_words[i] = bit_util::FromLittleEndian( (words0 >> offsets[i]) | (words1 << (kBitWidth - offsets[i]))); } } visitor(visited_words); } consume((whole_word_count - 1) * kBitWidth);
SafeLoadWords(bitmaps, 0, kBitWidth, false, &visited_words);
visitor(visited_words); consume(kBitWidth); }
// load remaining bits if (bit_length > 0) { SafeLoadWords(bitmaps, 0, bit_length, false, &visited_words); visitor(visited_words); }
return min_offset; }
template <size_t N, size_t M, typename ReaderT, typename WriterT, typename Visitor, typename Word = typename std::decay< internal::call_traits::argument_type<0, Visitor&&>>::type::value_type> static void RunVisitWordsAndWriteLoop(int64_t bit_length, std::array<ReaderT, N>& readers, std::array<WriterT, M>& writers, Visitor&& visitor) { constexpr int64_t kBitWidth = sizeof(Word) * 8;
std::array<Word, N> visited_words; std::array<Word, M> output_words;
// every reader will have same number of words, since they are same length'ed // TODO($JIRA) this will be inefficient in some cases. When there are offsets beyond // Word boundary, every Word would have to be created from 2 adjoining Words auto n_words = readers[0].words(); bit_length -= n_words * kBitWidth; while (n_words--) { // first collect all words to visited_words array for (size_t i = 0; i < N; i++) { visited_words[i] = readers[i].NextWord(); } visitor(visited_words, &output_words); for (size_t i = 0; i < M; i++) { writers[i].PutNextWord(output_words[i]); } }
// every reader will have same number of trailing bytes, because of the above reason // tailing portion could be more than one word! (ref: BitmapWordReader constructor) // remaining full/ partial words to write
if (bit_length) { // convert the word visitor lambda to a byte_visitor auto byte_visitor = [&](const std::array<uint8_t, N>& in, std::array<uint8_t, M>* out) { std::array<Word, N> in_words; std::array<Word, M> out_words; std::copy(in.begin(), in.end(), in_words.begin()); visitor(in_words, &out_words); for (size_t i = 0; i < M; i++) { out->at(i) = static_cast<uint8_t>(out_words[i]); } };
std::array<uint8_t, N> visited_bytes; std::array<uint8_t, M> output_bytes; int n_bytes = readers[0].trailing_bytes(); while (n_bytes--) { visited_bytes.fill(0); output_bytes.fill(0); int valid_bits; for (size_t i = 0; i < N; i++) { visited_bytes[i] = readers[i].NextTrailingByte(valid_bits); } byte_visitor(visited_bytes, &output_bytes); for (size_t i = 0; i < M; i++) { writers[i].PutNextTrailingByte(output_bytes[i], valid_bits); } } } }
/// \brief Visit words of bits from each input bitmap as array<Word, N> and collects /// outputs to an array<Word, M>, to be written into the output bitmaps accordingly. /// /// All bitmaps must have identical length. The first bit in a visited bitmap /// may be offset within the first visited word, but words will otherwise contain /// densely packed bits loaded from the bitmap. That offset within the first word is /// returned. /// Visitor is expected to have the following signature /// [](const std::array<Word, N>& in_words, std::array<Word, M>* out_words){...} /// // NOTE: this function is efficient on 3+ sufficiently large bitmaps. // It also has a large prolog / epilog overhead and should be used // carefully in other cases. // For 2 bitmaps or less, and/or smaller bitmaps, see also VisitTwoBitBlocksVoid // and BitmapUInt64Reader. template <size_t N, size_t M, typename Visitor, typename Word = typename std::decay< internal::call_traits::argument_type<0, Visitor&&>>::type::value_type> static void VisitWordsAndWrite(const std::array<Bitmap, N>& bitmaps_arg, std::array<Bitmap, M>* out_bitmaps_arg, Visitor&& visitor) { int64_t bit_length = BitLength(bitmaps_arg); assert(bit_length == BitLength(*out_bitmaps_arg));
// if both input and output bitmaps have no byte offset, then use special template if (std::all_of(bitmaps_arg.begin(), bitmaps_arg.end(), [](const Bitmap& b) { return b.offset_ % 8 == 0; }) && std::all_of(out_bitmaps_arg->begin(), out_bitmaps_arg->end(), [](const Bitmap& b) { return b.offset_ % 8 == 0; })) { std::array<BitmapWordReader<Word, /*may_have_byte_offset=*/false>, N> readers; for (size_t i = 0; i < N; ++i) { const Bitmap& in_bitmap = bitmaps_arg[i]; readers[i] = BitmapWordReader<Word, /*may_have_byte_offset=*/false>( in_bitmap.data_, in_bitmap.offset_, in_bitmap.length_); }
std::array<BitmapWordWriter<Word, /*may_have_byte_offset=*/false>, M> writers; for (size_t i = 0; i < M; ++i) { const Bitmap& out_bitmap = out_bitmaps_arg->at(i); writers[i] = BitmapWordWriter<Word, /*may_have_byte_offset=*/false>( out_bitmap.mutable_data_, out_bitmap.offset_, out_bitmap.length_); }
RunVisitWordsAndWriteLoop(bit_length, readers, writers, visitor); } else { std::array<BitmapWordReader<Word>, N> readers; for (size_t i = 0; i < N; ++i) { const Bitmap& in_bitmap = bitmaps_arg[i]; readers[i] = BitmapWordReader<Word>(in_bitmap.data_, in_bitmap.offset_, in_bitmap.length_); }
std::array<BitmapWordWriter<Word>, M> writers; for (size_t i = 0; i < M; ++i) { const Bitmap& out_bitmap = out_bitmaps_arg->at(i); writers[i] = BitmapWordWriter<Word>(out_bitmap.mutable_data_, out_bitmap.offset_, out_bitmap.length_); }
RunVisitWordsAndWriteLoop(bit_length, readers, writers, visitor); } }
const uint8_t* data() const { return data_; } uint8_t* mutable_data() { return mutable_data_; }
/// offset of first bit relative to buffer().data() int64_t offset() const { return offset_; }
/// number of bits in this Bitmap int64_t length() const { return length_; }
/// span of all bytes which contain any bit in this Bitmap util::span<const uint8_t> bytes() const { auto byte_offset = offset_ / 8; auto byte_count = bit_util::CeilDiv(offset_ + length_, 8) - byte_offset; return {data_ + byte_offset, static_cast<size_t>(byte_count)}; }
private: /// span of all Words which contain any bit in this Bitmap /// /// For example, given Word=uint16_t and a bitmap spanning bits [20, 36) /// words() would span bits [16, 48). /// /// 0 16 32 48 64 /// |-------|-------|------|------| (buffer) /// [ ] (bitmap) /// |-------|------| (returned words) /// /// \warning The words may contain bytes which lie outside the buffer or are /// uninitialized. template <typename Word> util::span<const Word> words() const { auto bytes_addr = reinterpret_cast<intptr_t>(bytes().data()); auto words_addr = bytes_addr - bytes_addr % sizeof(Word); auto word_byte_count = bit_util::RoundUpToPowerOf2(static_cast<int64_t>(bytes_addr + bytes().size()), static_cast<int64_t>(sizeof(Word))) - words_addr; return {reinterpret_cast<const Word*>(words_addr), static_cast<size_t>(word_byte_count / sizeof(Word))}; }
/// offset of first bit relative to words<Word>().data() template <typename Word> int64_t word_offset() const { return offset_ + 8 * (reinterpret_cast<intptr_t>(data_) - reinterpret_cast<intptr_t>(words<Word>().data())); }
/// load words from bitmaps bitwise template <size_t N, typename Word> static void SafeLoadWords(const Bitmap (&bitmaps)[N], int64_t offset, int64_t out_length, bool set_trailing_bits, std::array<Word, N>* out) { out->fill(0);
int64_t out_offset = set_trailing_bits ? sizeof(Word) * 8 - out_length : 0;
Bitmap slices[N], out_bitmaps[N]; for (size_t i = 0; i < N; ++i) { slices[i] = bitmaps[i].Slice(offset, out_length); out_bitmaps[i] = Bitmap(&out->at(i), out_offset, out_length); }
int64_t bit_i = 0; Bitmap::VisitBits(slices, [&](std::bitset<N> bits) { for (size_t i = 0; i < N; ++i) { out_bitmaps[i].SetBitTo(bit_i, bits[i]); } ++bit_i; }); }
/// assert bitmaps have identical length and return that length static int64_t BitLength(const Bitmap* bitmaps, size_t N);
template <size_t N> static int64_t BitLength(const std::array<Bitmap, N>& bitmaps) { for (size_t i = 1; i < N; ++i) { assert(bitmaps[i].length() == bitmaps[0].length()); } return bitmaps[0].length(); }
const uint8_t* data_ = NULLPTR; uint8_t* mutable_data_ = NULLPTR; int64_t offset_ = 0, length_ = 0;};
} // namespace internal} // namespace arrow12345678910111213141516171819202122232425262728293031323334353637383940414243// 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 <cstdint>#include <memory>#include <vector>
#include "arrow/result.h"#include "arrow/type_fwd.h"#include "arrow/util/visibility.h"
namespace arrow {namespace internal {
/// \brief Generate Bitmap with all position to `value` except for one found/// at `straggler_pos`.ARROW_EXPORTResult<std::shared_ptr<Buffer>> BitmapAllButOne(MemoryPool* pool, int64_t length, int64_t straggler_pos, bool value = true);
/// \brief Convert vector of bytes to bitmap bufferARROW_EXPORTResult<std::shared_ptr<Buffer>> BytesToBits(const std::vector<uint8_t>&, MemoryPool* pool = default_memory_pool());
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112// 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 <cstdint>#include <memory>
#include "arrow/buffer.h"#include "arrow/memory_pool.h"#include "arrow/result.h"#include "arrow/util/bit_util.h"#include "arrow/util/visibility.h"
namespace arrow {namespace internal {
// A std::generate() like function to write sequential bits into a bitmap area.// Bits preceding the bitmap area are preserved, bits following the bitmap// area may be clobbered.
template <class Generator>void GenerateBits(uint8_t* bitmap, int64_t start_offset, int64_t length, Generator&& g) { if (length == 0) { return; } uint8_t* cur = bitmap + start_offset / 8; uint8_t bit_mask = bit_util::kBitmask[start_offset % 8]; uint8_t current_byte = *cur & bit_util::kPrecedingBitmask[start_offset % 8];
for (int64_t index = 0; index < length; ++index) { const bool bit = g(); current_byte = bit ? (current_byte | bit_mask) : current_byte; bit_mask = static_cast<uint8_t>(bit_mask << 1); if (bit_mask == 0) { bit_mask = 1; *cur++ = current_byte; current_byte = 0; } } if (bit_mask != 1) { *cur++ = current_byte; }}
// Like GenerateBits(), but unrolls its main loop for higher performance.
template <class Generator>void GenerateBitsUnrolled(uint8_t* bitmap, int64_t start_offset, int64_t length, Generator&& g) { static_assert(std::is_same<decltype(std::declval<Generator>()()), bool>::value, "Functor passed to GenerateBitsUnrolled must return bool");
if (length == 0) { return; } uint8_t current_byte; uint8_t* cur = bitmap + start_offset / 8; const uint64_t start_bit_offset = start_offset % 8; uint8_t bit_mask = bit_util::kBitmask[start_bit_offset]; int64_t remaining = length;
if (bit_mask != 0x01) { current_byte = *cur & bit_util::kPrecedingBitmask[start_bit_offset]; while (bit_mask != 0 && remaining > 0) { current_byte |= g() * bit_mask; bit_mask = static_cast<uint8_t>(bit_mask << 1); --remaining; } *cur++ = current_byte; }
int64_t remaining_bytes = remaining / 8; uint8_t out_results[8]; while (remaining_bytes-- > 0) { for (int i = 0; i < 8; ++i) { out_results[i] = g(); } *cur++ = static_cast<uint8_t>(out_results[0] | out_results[1] << 1 | out_results[2] << 2 | out_results[3] << 3 | out_results[4] << 4 | out_results[5] << 5 | out_results[6] << 6 | out_results[7] << 7); }
int64_t remaining_bits = remaining % 8; if (remaining_bits) { current_byte = 0; bit_mask = 0x01; while (remaining_bits-- > 0) { current_byte |= g() * bit_mask; bit_mask = static_cast<uint8_t>(bit_mask << 1); } *cur++ = current_byte; }}
} // namespace internal} // namespace arrow12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788// 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 <cstdint>
#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 <class Visitor>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 <class Visitor>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<Visitor>(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<Visitor>(first_full_byte + num_full_bytes, 0, num_bits_after_full_bytes, visit);}
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286// 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 <cstdint>#include <cstring>
#include "arrow/util/bit_util.h"#include "arrow/util/endian.h"#include "arrow/util/macros.h"
namespace arrow {namespace internal {
class BitmapWriter { // A sequential bitwise writer that preserves surrounding bit values.
public: BitmapWriter(uint8_t* bitmap, int64_t start_offset, int64_t length) : bitmap_(bitmap), position_(0), length_(length) { byte_offset_ = start_offset / 8; bit_mask_ = bit_util::kBitmask[start_offset % 8]; if (length > 0) { current_byte_ = bitmap[byte_offset_]; } else { current_byte_ = 0; } }
void Set() { current_byte_ |= bit_mask_; }
void Clear() { current_byte_ &= bit_mask_ ^ 0xFF; }
void Next() { bit_mask_ = static_cast<uint8_t>(bit_mask_ << 1); ++position_; if (bit_mask_ == 0) { // Finished this byte, need advancing bit_mask_ = 0x01; bitmap_[byte_offset_++] = current_byte_; if (ARROW_PREDICT_TRUE(position_ < length_)) { current_byte_ = bitmap_[byte_offset_]; } } }
void Finish() { // Store current byte if we didn't went past bitmap storage if (length_ > 0 && (bit_mask_ != 0x01 || position_ < length_)) { bitmap_[byte_offset_] = current_byte_; } }
int64_t position() const { return position_; }
private: uint8_t* bitmap_; int64_t position_; int64_t length_;
uint8_t current_byte_; uint8_t bit_mask_; int64_t byte_offset_;};
class FirstTimeBitmapWriter { // Like BitmapWriter, but any bit values *following* the bits written // might be clobbered. It is hence faster than BitmapWriter, and can // also avoid false positives with Valgrind.
public: FirstTimeBitmapWriter(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_mask_ = bit_util::kBitmask[start_offset % 8]; if (length > 0) { current_byte_ = bitmap[byte_offset_] & bit_util::kPrecedingBitmask[start_offset % 8]; } else { current_byte_ = 0; } }
/// Appends number_of_bits from word to valid_bits and valid_bits_offset. /// /// \param[in] word The LSB bitmap to append. Any bits past number_of_bits are assumed /// to be unset (i.e. 0). /// \param[in] number_of_bits The number of bits to append from word. void AppendWord(uint64_t word, int64_t number_of_bits) { if (ARROW_PREDICT_FALSE(number_of_bits == 0)) { return; }
// Location that the first byte needs to be written to. uint8_t* append_position = bitmap_ + byte_offset_;
// Update state variables except for current_byte_ here. position_ += number_of_bits; int64_t bit_offset = bit_util::CountTrailingZeros(static_cast<uint32_t>(bit_mask_)); bit_mask_ = bit_util::kBitmask[(bit_offset + number_of_bits) % 8]; byte_offset_ += (bit_offset + number_of_bits) / 8;
if (bit_offset != 0) { // We are in the middle of the byte. This code updates the byte and shifts // bits appropriately within word so it can be memcpy'd below. int64_t bits_to_carry = 8 - bit_offset; // Carry over bits from word to current_byte_. We assume any extra bits in word // unset so no additional accounting is needed for when number_of_bits < // bits_to_carry. current_byte_ |= (word & bit_util::kPrecedingBitmask[bits_to_carry]) << bit_offset; // Check if everything is transferred into current_byte_. if (ARROW_PREDICT_FALSE(number_of_bits < bits_to_carry)) { return; } *append_position = current_byte_; append_position++; // Move the carry bits off of word. word = word >> bits_to_carry; number_of_bits -= bits_to_carry; } word = bit_util::ToLittleEndian(word); int64_t bytes_for_word = ::arrow::bit_util::BytesForBits(number_of_bits); std::memcpy(append_position, &word, bytes_for_word); // At this point, the previous current_byte_ has been written to bitmap_. // The new current_byte_ is either the last relevant byte in 'word' // or cleared if the new position is byte aligned (i.e. a fresh byte). if (bit_mask_ == 0x1) { current_byte_ = 0; } else { current_byte_ = *(append_position + bytes_for_word - 1); } }
void Set() { current_byte_ |= bit_mask_; }
void Clear() {}
void Next() { bit_mask_ = static_cast<uint8_t>(bit_mask_ << 1); ++position_; if (bit_mask_ == 0) { // Finished this byte, need advancing bit_mask_ = 0x01; bitmap_[byte_offset_++] = current_byte_; current_byte_ = 0; } }
void Finish() { // Store current byte if we didn't went go bitmap storage if (length_ > 0 && (bit_mask_ != 0x01 || position_ < length_)) { bitmap_[byte_offset_] = current_byte_; } }
int64_t position() const { return position_; }
private: uint8_t* bitmap_; int64_t position_; int64_t length_;
uint8_t current_byte_; uint8_t bit_mask_; int64_t byte_offset_;};
template <typename Word, bool may_have_byte_offset = true>class BitmapWordWriter { public: BitmapWordWriter() = default; BitmapWordWriter(uint8_t* bitmap, int64_t offset, int64_t length) : offset_(static_cast<int64_t>(may_have_byte_offset) * (offset % 8)), bitmap_(bitmap + offset / 8), bitmap_end_(bitmap_ + bit_util::BytesForBits(offset_ + length)), mask_((1U << offset_) - 1) { if (offset_) { if (length >= static_cast<int>(sizeof(Word) * 8)) { current_data.word_ = load<Word>(bitmap_); } else if (length > 0) { current_data.epi.byte_ = load<uint8_t>(bitmap_); } } }
void PutNextWord(Word word) { if (may_have_byte_offset && offset_) { // split one word into two adjacent words, don't touch unused bits // |<------ word ----->| // +-----+-------------+ // | A | B | // +-----+-------------+ // | | // v v offset // +-------------+-----+-------------+-----+ // | --- | A | B | --- | // +-------------+-----+-------------+-----+ // |<------ next ----->|<---- current ---->| word = (word << offset_) | (word >> (sizeof(Word) * 8 - offset_)); Word next_word = load<Word>(bitmap_ + sizeof(Word)); current_data.word_ = (current_data.word_ & mask_) | (word & ~mask_); next_word = (next_word & ~mask_) | (word & mask_); store<Word>(bitmap_, current_data.word_); store<Word>(bitmap_ + sizeof(Word), next_word); current_data.word_ = next_word; } else { store<Word>(bitmap_, word); } bitmap_ += sizeof(Word); }
void PutNextTrailingByte(uint8_t byte, int valid_bits) { if (valid_bits == 8) { if (may_have_byte_offset && offset_) { byte = (byte << offset_) | (byte >> (8 - offset_)); uint8_t next_byte = load<uint8_t>(bitmap_ + 1); current_data.epi.byte_ = (current_data.epi.byte_ & mask_) | (byte & ~mask_); next_byte = (next_byte & ~mask_) | (byte & mask_); store<uint8_t>(bitmap_, current_data.epi.byte_); store<uint8_t>(bitmap_ + 1, next_byte); current_data.epi.byte_ = next_byte; } else { store<uint8_t>(bitmap_, byte); } ++bitmap_; } else { assert(valid_bits > 0); assert(valid_bits < 8); assert(bitmap_ + bit_util::BytesForBits(offset_ + valid_bits) <= bitmap_end_); internal::BitmapWriter writer(bitmap_, offset_, valid_bits); for (int i = 0; i < valid_bits; ++i) { (byte & 0x01) ? writer.Set() : writer.Clear(); writer.Next(); byte >>= 1; } writer.Finish(); } }
private: int64_t offset_; uint8_t* bitmap_;
const uint8_t* bitmap_end_; uint64_t mask_; union { Word word_; struct {#if ARROW_LITTLE_ENDIAN == 0 uint8_t padding_bytes_[sizeof(Word) - 1];#endif uint8_t byte_; } epi; } current_data;
template <typename DType> DType load(const uint8_t* bitmap) { assert(bitmap + sizeof(DType) <= bitmap_end_); return bit_util::ToLittleEndian(util::SafeLoadAs<DType>(bitmap)); }
template <typename DType> void store(uint8_t* bitmap, DType data) { assert(bitmap + sizeof(DType) <= bitmap_end_); util::SafeStore(bitmap, bit_util::FromLittleEndian(data)); }};
} // namespace internal} // namespace arrow1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889// 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 <algorithm>#include <array>#include <bitset>#include <cassert>#include <cstdint>#include <cstring>#include <memory>#include <string>#include <string_view>#include <type_traits>#include <utility>#include <vector>
#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<bool>::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<int>(bits_.size()); } std::vector<bool> bits_; std::vector<int> offsets_;};
} // namespace internal} // namespace arrow12345678910111213141516171819202122232425262728293031323334// 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/endian.h"#include "arrow/util/visibility.h"
#include <stdint.h>
namespace arrow {namespace internal {
ARROW_EXPORTint unpack32(const uint32_t* in, uint32_t* out, int batch_size, int num_bits);ARROW_EXPORTint unpack64(const uint8_t* in, uint64_t* out, int batch_size, int num_bits);
} // namespace internal} // namespace arrow12345678910111213141516171819202122232425262728// 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 <stdint.h>
namespace arrow {namespace internal {
int unpack32_avx512(const uint32_t* in, uint32_t* out, int batch_size, int num_bits);
} // namespace internal} // namespace arrow12345678910111213141516171819202122232425262728// 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 <stdint.h>
namespace arrow {namespace internal {
int unpack32_neon(const uint32_t* in, uint32_t* out, int batch_size, int num_bits);
} // namespace internal} // namespace arrow12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061// 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 <memory>#include <type_traits>#include <utility>
namespace arrow {namespace internal {
template <typename OutputType, typename InputType>inline OutputType checked_cast(InputType&& value) { static_assert(std::is_class<typename std::remove_pointer< typename std::remove_reference<InputType>::type>::type>::value, "checked_cast input type must be a class"); static_assert(std::is_class<typename std::remove_pointer< typename std::remove_reference<OutputType>::type>::type>::value, "checked_cast output type must be a class");#ifdef NDEBUG return static_cast<OutputType>(value);#else return dynamic_cast<OutputType>(value);#endif}
template <class T, class U>std::shared_ptr<T> checked_pointer_cast(std::shared_ptr<U> r) noexcept {#ifdef NDEBUG return std::static_pointer_cast<T>(std::move(r));#else return std::dynamic_pointer_cast<T>(std::move(r));#endif}
template <class T, class U>std::unique_ptr<T> checked_pointer_cast(std::unique_ptr<U> r) noexcept {#ifdef NDEBUG return std::unique_ptr<T>(static_cast<T*>(r.release()));#else return std::unique_ptr<T>(dynamic_cast<T*>(r.release()));#endif}
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241// 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 <cstdint>#include <limits>#include <memory>#include <optional>#include <string>
#include "arrow/result.h"#include "arrow/status.h"#include "arrow/util/type_fwd.h"#include "arrow/util/visibility.h"
namespace arrow {namespace util {
constexpr int kUseDefaultCompressionLevel = std::numeric_limits<int>::min();
/// \brief Streaming compressor interface///class ARROW_EXPORT Compressor { public: virtual ~Compressor() = default;
struct CompressResult { int64_t bytes_read; int64_t bytes_written; }; struct FlushResult { int64_t bytes_written; bool should_retry; }; struct EndResult { int64_t bytes_written; bool should_retry; };
/// \brief Compress some input. /// /// If bytes_read is 0 on return, then a larger output buffer should be supplied. virtual Result<CompressResult> Compress(int64_t input_len, const uint8_t* input, int64_t output_len, uint8_t* output) = 0;
/// \brief Flush part of the compressed output. /// /// If should_retry is true on return, Flush() should be called again /// with a larger buffer. virtual Result<FlushResult> Flush(int64_t output_len, uint8_t* output) = 0;
/// \brief End compressing, doing whatever is necessary to end the stream. /// /// If should_retry is true on return, End() should be called again /// with a larger buffer. Otherwise, the Compressor should not be used anymore. /// /// End() implies Flush(). virtual Result<EndResult> End(int64_t output_len, uint8_t* output) = 0;
// XXX add methods for buffer size heuristics?};
/// \brief Streaming decompressor interface///class ARROW_EXPORT Decompressor { public: virtual ~Decompressor() = default;
struct DecompressResult { // XXX is need_more_output necessary? (Brotli?) int64_t bytes_read; int64_t bytes_written; bool need_more_output; };
/// \brief Decompress some input. /// /// If need_more_output is true on return, a larger output buffer needs /// to be supplied. virtual Result<DecompressResult> Decompress(int64_t input_len, const uint8_t* input, int64_t output_len, uint8_t* output) = 0;
/// \brief Return whether the compressed stream is finished. /// /// This is a heuristic. If true is returned, then it is guaranteed /// that the stream is finished. If false is returned, however, it may /// simply be that the underlying library isn't able to provide the information. virtual bool IsFinished() = 0;
/// \brief Reinitialize decompressor, making it ready for a new compressed stream. virtual Status Reset() = 0;
// XXX add methods for buffer size heuristics?};
/// \brief Compression codec optionsclass ARROW_EXPORT CodecOptions { public: explicit CodecOptions(int compression_level = kUseDefaultCompressionLevel) : compression_level(compression_level) {}
virtual ~CodecOptions() = default;
int compression_level;};
// ----------------------------------------------------------------------// GZip codec options implementation
enum class GZipFormat { ZLIB, DEFLATE, GZIP,};
class ARROW_EXPORT GZipCodecOptions : public CodecOptions { public: GZipFormat gzip_format = GZipFormat::GZIP; std::optional<int> window_bits;};
// ----------------------------------------------------------------------// brotli codec options implementation
class ARROW_EXPORT BrotliCodecOptions : public CodecOptions { public: std::optional<int> window_bits;};
/// \brief Compression codecclass ARROW_EXPORT Codec { public: virtual ~Codec() = default;
/// \brief Return special value to indicate that a codec implementation /// should use its default compression level static int UseDefaultCompressionLevel();
/// \brief Return a string name for compression type static const std::string& GetCodecAsString(Compression::type t);
/// \brief Return compression type for name (all lower case) static Result<Compression::type> GetCompressionType(const std::string& name);
/// \brief Create a codec for the given compression algorithm with CodecOptions static Result<std::unique_ptr<Codec>> Create( Compression::type codec, const CodecOptions& codec_options = CodecOptions{});
/// \brief Create a codec for the given compression algorithm static Result<std::unique_ptr<Codec>> Create(Compression::type codec, int compression_level);
/// \brief Return true if support for indicated codec has been enabled static bool IsAvailable(Compression::type codec);
/// \brief Return true if indicated codec supports setting a compression level static bool SupportsCompressionLevel(Compression::type codec);
/// \brief Return the smallest supported compression level for the codec /// Note: This function creates a temporary Codec instance static Result<int> MinimumCompressionLevel(Compression::type codec);
/// \brief Return the largest supported compression level for the codec /// Note: This function creates a temporary Codec instance static Result<int> MaximumCompressionLevel(Compression::type codec);
/// \brief Return the default compression level /// Note: This function creates a temporary Codec instance static Result<int> DefaultCompressionLevel(Compression::type codec);
/// \brief Return the smallest supported compression level virtual int minimum_compression_level() const = 0;
/// \brief Return the largest supported compression level virtual int maximum_compression_level() const = 0;
/// \brief Return the default compression level virtual int default_compression_level() const = 0;
/// \brief One-shot decompression function /// /// output_buffer_len must be correct and therefore be obtained in advance. /// The actual decompressed length is returned. /// /// \note One-shot decompression is not always compatible with streaming /// compression. Depending on the codec (e.g. LZ4), different formats may /// be used. virtual Result<int64_t> Decompress(int64_t input_len, const uint8_t* input, int64_t output_buffer_len, uint8_t* output_buffer) = 0;
/// \brief One-shot compression function /// /// output_buffer_len must first have been computed using MaxCompressedLen(). /// The actual compressed length is returned. /// /// \note One-shot compression is not always compatible with streaming /// decompression. Depending on the codec (e.g. LZ4), different formats may /// be used. virtual Result<int64_t> Compress(int64_t input_len, const uint8_t* input, int64_t output_buffer_len, uint8_t* output_buffer) = 0;
virtual int64_t MaxCompressedLen(int64_t input_len, const uint8_t* input) = 0;
/// \brief Create a streaming compressor instance virtual Result<std::shared_ptr<Compressor>> MakeCompressor() = 0;
/// \brief Create a streaming compressor instance virtual Result<std::shared_ptr<Decompressor>> MakeDecompressor() = 0;
/// \brief This Codec's compression type virtual Compression::type compression_type() const = 0;
/// \brief The name of this Codec's compression type const std::string& name() const { return GetCodecAsString(compression_type()); }
/// \brief This Codec's compression level, if applicable virtual int compression_level() const { return UseDefaultCompressionLevel(); }
private: /// \brief Initializes the codec's resources. virtual Status Init();};
} // namespace util} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411// Licensed to the Apache Software Foundation (ASF) under one// or more contributor license agreements. See the NOTICE file// distributed with this work for additional information// regarding copyright ownership. The ASF licenses this file// to you under the Apache License, Version 2.0 (the// "License"); you may not use this file except in compliance// with the License. You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing,// software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.
#include <memory>#include <string>#include <utility>#include <vector>
#include "arrow/array.h"#include "arrow/chunked_array.h"#include "arrow/status.h"#include "arrow/type.h"#include "arrow/type_traits.h"#include "arrow/util/checked_cast.h"#include "arrow/visit_type_inline.h"
namespace arrow {namespace internal {
template <typename BaseConverter, template <typename...> class ConverterTrait>static Result<std::unique_ptr<BaseConverter>> MakeConverter( std::shared_ptr<DataType> type, typename BaseConverter::OptionsType options, MemoryPool* pool);
template <typename Input, typename Options>class Converter { public: using Self = Converter<Input, Options>; using InputType = Input; using OptionsType = Options;
virtual ~Converter() = default;
Status Construct(std::shared_ptr<DataType> type, OptionsType options, MemoryPool* pool) { type_ = std::move(type); options_ = std::move(options); return Init(pool); }
virtual Status Append(InputType value) { return Status::NotImplemented("Append"); }
virtual Status Extend(InputType values, int64_t size, int64_t offset = 0) { return Status::NotImplemented("Extend"); }
virtual Status ExtendMasked(InputType values, InputType mask, int64_t size, int64_t offset = 0) { return Status::NotImplemented("ExtendMasked"); }
const std::shared_ptr<ArrayBuilder>& builder() const { return builder_; }
const std::shared_ptr<DataType>& type() const { return type_; }
OptionsType options() const { return options_; }
bool may_overflow() const { return may_overflow_; }
bool rewind_on_overflow() const { return rewind_on_overflow_; }
virtual Status Reserve(int64_t additional_capacity) { return builder_->Reserve(additional_capacity); }
Status AppendNull() { return builder_->AppendNull(); }
virtual Result<std::shared_ptr<Array>> ToArray() { return builder_->Finish(); }
virtual Result<std::shared_ptr<Array>> ToArray(int64_t length) { ARROW_ASSIGN_OR_RAISE(auto arr, this->ToArray()); return arr->Slice(0, length); }
virtual Result<std::shared_ptr<ChunkedArray>> ToChunkedArray() { ARROW_ASSIGN_OR_RAISE(auto array, ToArray()); std::vector<std::shared_ptr<Array>> chunks = {std::move(array)}; return std::make_shared<ChunkedArray>(chunks); }
protected: virtual Status Init(MemoryPool* pool) { return Status::OK(); }
std::shared_ptr<DataType> type_; std::shared_ptr<ArrayBuilder> builder_; OptionsType options_; bool may_overflow_ = false; bool rewind_on_overflow_ = false;};
template <typename ArrowType, typename BaseConverter>class PrimitiveConverter : public BaseConverter { public: using BuilderType = typename TypeTraits<ArrowType>::BuilderType;
protected: Status Init(MemoryPool* pool) override { this->builder_ = std::make_shared<BuilderType>(this->type_, pool); // Narrow variable-sized binary types may overflow this->may_overflow_ = is_binary_like(this->type_->id()); primitive_type_ = checked_cast<const ArrowType*>(this->type_.get()); primitive_builder_ = checked_cast<BuilderType*>(this->builder_.get()); return Status::OK(); }
const ArrowType* primitive_type_; BuilderType* primitive_builder_;};
template <typename ArrowType, typename BaseConverter, template <typename...> class ConverterTrait>class ListConverter : public BaseConverter { public: using BuilderType = typename TypeTraits<ArrowType>::BuilderType; using ConverterType = typename ConverterTrait<ArrowType>::type;
protected: Status Init(MemoryPool* pool) override { list_type_ = checked_cast<const ArrowType*>(this->type_.get()); ARROW_ASSIGN_OR_RAISE(value_converter_, (MakeConverter<BaseConverter, ConverterTrait>( list_type_->value_type(), this->options_, pool))); this->builder_ = std::make_shared<BuilderType>(pool, value_converter_->builder(), this->type_); list_builder_ = checked_cast<BuilderType*>(this->builder_.get()); // Narrow list types may overflow this->may_overflow_ = this->rewind_on_overflow_ = sizeof(typename ArrowType::offset_type) < sizeof(int64_t); return Status::OK(); }
const ArrowType* list_type_; BuilderType* list_builder_; std::unique_ptr<BaseConverter> value_converter_;};
template <typename BaseConverter, template <typename...> class ConverterTrait>class StructConverter : public BaseConverter { public: using ConverterType = typename ConverterTrait<StructType>::type;
Status Reserve(int64_t additional_capacity) override { ARROW_RETURN_NOT_OK(this->builder_->Reserve(additional_capacity)); for (const auto& child : children_) { ARROW_RETURN_NOT_OK(child->Reserve(additional_capacity)); } return Status::OK(); }
protected: Status Init(MemoryPool* pool) override { std::unique_ptr<BaseConverter> child_converter; std::vector<std::shared_ptr<ArrayBuilder>> child_builders;
struct_type_ = checked_cast<const StructType*>(this->type_.get()); for (const auto& field : struct_type_->fields()) { ARROW_ASSIGN_OR_RAISE(child_converter, (MakeConverter<BaseConverter, ConverterTrait>( field->type(), this->options_, pool))); this->may_overflow_ |= child_converter->may_overflow(); this->rewind_on_overflow_ = this->may_overflow_; child_builders.push_back(child_converter->builder()); children_.push_back(std::move(child_converter)); }
this->builder_ = std::make_shared<StructBuilder>(this->type_, pool, std::move(child_builders)); struct_builder_ = checked_cast<StructBuilder*>(this->builder_.get());
return Status::OK(); }
const StructType* struct_type_; StructBuilder* struct_builder_; std::vector<std::unique_ptr<BaseConverter>> children_;};
template <typename ValueType, typename BaseConverter>class DictionaryConverter : public BaseConverter { public: using BuilderType = DictionaryBuilder<ValueType>;
protected: Status Init(MemoryPool* pool) override { std::unique_ptr<ArrayBuilder> builder; ARROW_RETURN_NOT_OK(MakeDictionaryBuilder(pool, this->type_, NULLPTR, &builder)); this->builder_ = std::move(builder); this->may_overflow_ = false; dict_type_ = checked_cast<const DictionaryType*>(this->type_.get()); value_type_ = checked_cast<const ValueType*>(dict_type_->value_type().get()); value_builder_ = checked_cast<BuilderType*>(this->builder_.get()); return Status::OK(); }
const DictionaryType* dict_type_; const ValueType* value_type_; BuilderType* value_builder_;};
template <typename BaseConverter, template <typename...> class ConverterTrait>struct MakeConverterImpl { template <typename T, typename ConverterType = typename ConverterTrait<T>::type> Status Visit(const T&) { out.reset(new ConverterType()); return out->Construct(std::move(type), std::move(options), pool); }
Status Visit(const DictionaryType& t) { switch (t.value_type()->id()) {#define DICTIONARY_CASE(TYPE) \ case TYPE::type_id: \ out = std::make_unique< \ typename ConverterTrait<DictionaryType>::template dictionary_type<TYPE>>(); \ break; DICTIONARY_CASE(BooleanType); DICTIONARY_CASE(Int8Type); DICTIONARY_CASE(Int16Type); DICTIONARY_CASE(Int32Type); DICTIONARY_CASE(Int64Type); DICTIONARY_CASE(UInt8Type); DICTIONARY_CASE(UInt16Type); DICTIONARY_CASE(UInt32Type); DICTIONARY_CASE(UInt64Type); DICTIONARY_CASE(FloatType); DICTIONARY_CASE(DoubleType); DICTIONARY_CASE(BinaryType); DICTIONARY_CASE(StringType); DICTIONARY_CASE(FixedSizeBinaryType);#undef DICTIONARY_CASE default: return Status::NotImplemented("DictionaryArray converter for type ", t.ToString(), " not implemented"); } return out->Construct(std::move(type), std::move(options), pool); }
Status Visit(const DataType& t) { return Status::NotImplemented(t.name()); }
std::shared_ptr<DataType> type; typename BaseConverter::OptionsType options; MemoryPool* pool; std::unique_ptr<BaseConverter> out;};
template <typename BaseConverter, template <typename...> class ConverterTrait>static Result<std::unique_ptr<BaseConverter>> MakeConverter( std::shared_ptr<DataType> type, typename BaseConverter::OptionsType options, MemoryPool* pool) { MakeConverterImpl<BaseConverter, ConverterTrait> visitor{ std::move(type), std::move(options), pool, NULLPTR}; ARROW_RETURN_NOT_OK(VisitTypeInline(*visitor.type, &visitor)); return std::move(visitor.out);}
template <typename Converter>class Chunker { public: using InputType = typename Converter::InputType;
explicit Chunker(std::unique_ptr<Converter> converter) : converter_(std::move(converter)) {}
Status Reserve(int64_t additional_capacity) { ARROW_RETURN_NOT_OK(converter_->Reserve(additional_capacity)); reserved_ += additional_capacity; return Status::OK(); }
Status AppendNull() { auto status = converter_->AppendNull(); if (ARROW_PREDICT_FALSE(status.IsCapacityError())) { if (converter_->builder()->length() == 0) { // Builder length == 0 means the individual element is too large to append. // In this case, no need to try again. return status; } ARROW_RETURN_NOT_OK(FinishChunk()); return converter_->AppendNull(); } ++length_; return status; }
Status Append(InputType value) { auto status = converter_->Append(value); if (ARROW_PREDICT_FALSE(status.IsCapacityError())) { if (converter_->builder()->length() == 0) { return status; } ARROW_RETURN_NOT_OK(FinishChunk()); return Append(value); } ++length_; return status; }
Status Extend(InputType values, int64_t size, int64_t offset = 0) { while (offset < size) { auto length_before = converter_->builder()->length(); auto status = converter_->Extend(values, size, offset); auto length_after = converter_->builder()->length(); auto num_converted = length_after - length_before;
offset += num_converted; length_ += num_converted;
if (status.IsCapacityError()) { if (converter_->builder()->length() == 0) { // Builder length == 0 means the individual element is too large to append. // In this case, no need to try again. return status; } else if (converter_->rewind_on_overflow()) { // The list-like and binary-like conversion paths may raise a capacity error, // we need to handle them differently. While the binary-like converters check // the capacity before append/extend the list-like converters just check after // append/extend. Thus depending on the implementation semantics we may need // to rewind (slice) the output chunk by one. length_ -= 1; offset -= 1; } ARROW_RETURN_NOT_OK(FinishChunk()); } else if (!status.ok()) { return status; } } return Status::OK(); }
Status ExtendMasked(InputType values, InputType mask, int64_t size, int64_t offset = 0) { while (offset < size) { auto length_before = converter_->builder()->length(); auto status = converter_->ExtendMasked(values, mask, size, offset); auto length_after = converter_->builder()->length(); auto num_converted = length_after - length_before;
offset += num_converted; length_ += num_converted;
if (status.IsCapacityError()) { if (converter_->builder()->length() == 0) { // Builder length == 0 means the individual element is too large to append. // In this case, no need to try again. return status; } else if (converter_->rewind_on_overflow()) { // The list-like and binary-like conversion paths may raise a capacity error, // we need to handle them differently. While the binary-like converters check // the capacity before append/extend the list-like converters just check after // append/extend. Thus depending on the implementation semantics we may need // to rewind (slice) the output chunk by one. length_ -= 1; offset -= 1; } ARROW_RETURN_NOT_OK(FinishChunk()); } else if (!status.ok()) { return status; } } return Status::OK(); }
Status FinishChunk() { ARROW_ASSIGN_OR_RAISE(auto chunk, converter_->ToArray(length_)); chunks_.push_back(chunk); // Reserve space for the remaining items. // Besides being an optimization, it is also required if the converter's // implementation relies on unsafe builder methods in converter->Append(). auto remaining = reserved_ - length_; Reset(); return Reserve(remaining); }
Result<std::shared_ptr<ChunkedArray>> ToChunkedArray() { ARROW_RETURN_NOT_OK(FinishChunk()); return std::make_shared<ChunkedArray>(chunks_); }
protected: void Reset() { converter_->builder()->Reset(); length_ = 0; reserved_ = 0; }
int64_t length_ = 0; int64_t reserved_ = 0; std::unique_ptr<Converter> converter_; std::vector<std::shared_ptr<Array>> chunks_;};
template <typename T>static Result<std::unique_ptr<Chunker<T>>> MakeChunker(std::unique_ptr<T> converter) { return std::make_unique<Chunker<T>>(std::move(converter));}
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960// 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 <memory>
#include "arrow/status.h"
namespace arrow {namespace util {
/// \brief Simple mutex-based counting semaphore with timeoutclass 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> impl_;};
} // namespace util} // namespace arrow
#endif // ARROW_COUNTING_SEMAPHORE_H123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114// 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 <cstdint>#include <memory>#include <string>
#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> impl_;};
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298// 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 <cstdint>#include <iosfwd>#include <limits>#include <string>#include <string_view>#include <utility>
#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<std::pair<Decimal128, Decimal128>> Divide(const Decimal128& divisor) const { std::pair<Decimal128, Decimal128> result; auto dstatus = BasicDecimal128::Divide(divisor, &result.first, &result.second); ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus)); return 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<Decimal128> FromString(std::string_view s); static Result<Decimal128> FromString(const std::string& s); static Result<Decimal128> FromString(const char* s);
static Result<Decimal128> FromReal(double real, int32_t precision, int32_t scale); static Result<Decimal128> 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<Decimal128> FromBigEndian(const uint8_t* data, int32_t length);
/// \brief Convert Decimal128 from one scale to another Result<Decimal128> 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 out; }
/// \brief Convert to a signed integer template <typename T, typename = internal::EnableIfIsOneOf<T, int32_t, int64_t>> Result<T> ToInteger() const { constexpr auto min_value = std::numeric_limits<T>::min(); constexpr auto max_value = std::numeric_limits<T>::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<T>(low_bits()); }
/// \brief Convert to a signed integer template <typename T, typename = internal::EnableIfIsOneOf<T, int32_t, int64_t>> Status ToInteger(T* out) const { return ToInteger<T>().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 <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>> T ToReal(int32_t scale) const { static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>, "Unexpected floating-point type"); if constexpr (std::is_same_v<T, float>) { 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<Decimal256> FromString(std::string_view s); static Result<Decimal256> FromString(const std::string& s); static Result<Decimal256> FromString(const char* s);
/// \brief Convert Decimal256 from one scale to another Result<Decimal256> 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 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<std::pair<Decimal256, Decimal256>> Divide(const Decimal256& divisor) const { std::pair<Decimal256, Decimal256> result; auto dstatus = BasicDecimal256::Divide(divisor, &result.first, &result.second); ARROW_RETURN_NOT_OK(ToArrowStatus(dstatus)); return 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<Decimal256> FromBigEndian(const uint8_t* data, int32_t length);
static Result<Decimal256> FromReal(double real, int32_t precision, int32_t scale); static Result<Decimal256> 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 <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>> T ToReal(int32_t scale) const { static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>, "Unexpected floating-point type"); if constexpr (std::is_same_v<T, float>) { 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<int32_t> 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 arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181// 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 <cstdint>#include <memory>#include <string_view>
#include "arrow/status.h"#include "arrow/util/macros.h"#include "arrow/util/visibility.h"
namespace arrow {
class Buffer;
class ARROW_EXPORT BoundaryFinder { public: BoundaryFinder() = default;
virtual ~BoundaryFinder();
/// \brief Find the position of the first delimiter inside block /// /// `partial` is taken to be the beginning of the block, and `block` /// its continuation. Also, `partial` doesn't contain a delimiter. /// /// The returned `out_pos` is relative to `block`'s start and should point /// to the first character after the first delimiter. /// `out_pos` will be -1 if no delimiter is found. virtual Status FindFirst(std::string_view partial, std::string_view block, int64_t* out_pos) = 0;
/// \brief Find the position of the last delimiter inside block /// /// The returned `out_pos` is relative to `block`'s start and should point /// to the first character after the last delimiter. /// `out_pos` will be -1 if no delimiter is found. virtual Status FindLast(std::string_view block, int64_t* out_pos) = 0;
/// \brief Find the position of the Nth delimiter inside the block /// /// `partial` is taken to be the beginning of the block, and `block` /// its continuation. Also, `partial` doesn't contain a delimiter. /// /// The returned `out_pos` is relative to `block`'s start and should point /// to the first character after the first delimiter. /// `out_pos` will be -1 if no delimiter is found. /// /// The returned `num_found` is the number of delimiters actually found virtual Status FindNth(std::string_view partial, std::string_view block, int64_t count, int64_t* out_pos, int64_t* num_found) = 0;
static constexpr int64_t kNoDelimiterFound = -1;
protected: ARROW_DISALLOW_COPY_AND_ASSIGN(BoundaryFinder);};
ARROW_EXPORTstd::shared_ptr<BoundaryFinder> MakeNewlineBoundaryFinder();
/// \brief A reusable block-based chunker for delimited data////// The chunker takes a block of delimited data and helps carve a sub-block/// which begins and ends on delimiters (suitable for consumption by parsers/// which can only parse whole objects).class ARROW_EXPORT Chunker { public: explicit Chunker(std::shared_ptr<BoundaryFinder> delimiter); ~Chunker();
/// \brief Carve up a chunk in a block of data to contain only whole objects /// /// Pre-conditions: /// - `block` is the start of a valid block of delimited data /// (i.e. starts just after a delimiter) /// /// Post-conditions: /// - block == whole + partial /// - `whole` is a valid block of delimited data /// (i.e. starts just after a delimiter and ends with a delimiter) /// - `partial` doesn't contain an entire delimited object /// (IOW: `partial` is generally small) /// /// This method will look for the last delimiter in `block` and may /// therefore be costly. /// /// \param[in] block data to be chunked /// \param[out] whole subrange of block containing whole delimited objects /// \param[out] partial subrange of block starting with a partial delimited object Status Process(std::shared_ptr<Buffer> block, std::shared_ptr<Buffer>* whole, std::shared_ptr<Buffer>* partial);
/// \brief Carve the completion of a partial object out of a block /// /// Pre-conditions: /// - `partial` is the start of a valid block of delimited data /// (i.e. starts just after a delimiter) /// - `block` follows `partial` in file order /// /// Post-conditions: /// - block == completion + rest /// - `partial + completion` is a valid block of delimited data /// (i.e. starts just after a delimiter and ends with a delimiter) /// - `completion` doesn't contain an entire delimited object /// (IOW: `completion` is generally small) /// /// This method will look for the first delimiter in `block` and should /// therefore be reasonably cheap. /// /// \param[in] partial incomplete delimited data /// \param[in] block delimited data following partial /// \param[out] completion subrange of block containing the completion of partial /// \param[out] rest subrange of block containing what completion does not cover Status ProcessWithPartial(std::shared_ptr<Buffer> partial, std::shared_ptr<Buffer> block, std::shared_ptr<Buffer>* completion, std::shared_ptr<Buffer>* rest);
/// \brief Like ProcessWithPartial, but for the last block of a file /// /// This method allows for a final delimited object without a trailing delimiter /// (ProcessWithPartial would return an error in that case). /// /// Pre-conditions: /// - `partial` is the start of a valid block of delimited data /// - `block` follows `partial` in file order and is the last data block /// /// Post-conditions: /// - block == completion + rest /// - `partial + completion` is a valid block of delimited data /// - `completion` doesn't contain an entire delimited object /// (IOW: `completion` is generally small) /// Status ProcessFinal(std::shared_ptr<Buffer> partial, std::shared_ptr<Buffer> block, std::shared_ptr<Buffer>* completion, std::shared_ptr<Buffer>* rest);
/// \brief Skip count number of rows /// Pre-conditions: /// - `partial` is the start of a valid block of delimited data /// (i.e. starts just after a delimiter) /// - `block` follows `partial` in file order /// /// Post-conditions: /// - `count` is updated to indicate the number of rows that still need to be skipped /// - If `count` is > 0 then `rest` is an incomplete block that should be a future /// `partial` /// - Else `rest` could be one or more valid blocks of delimited data which need to be /// parsed /// /// \param[in] partial incomplete delimited data /// \param[in] block delimited data following partial /// \param[in] final whether this is the final chunk /// \param[in,out] count number of rows that need to be skipped /// \param[out] rest subrange of block containing what was not skipped Status ProcessSkip(std::shared_ptr<Buffer> partial, std::shared_ptr<Buffer> block, bool final, int64_t* count, std::shared_ptr<Buffer>* rest);
protected: ARROW_DISALLOW_COPY_AND_ASSIGN(Chunker);
std::shared_ptr<BoundaryFinder> boundary_finder_;};
} // namespace arrow12345678910111213141516171819202122232425262728// 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 arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115// 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 <utility>#include <vector>
#include "arrow/status.h"#include "arrow/util/cpu_info.h"
namespace arrow {namespace internal {
enum class DispatchLevel : int { // These dispatch levels, corresponding to instruction set features, // are sorted in increasing order of preference. NONE = 0, SSE4_2, AVX2, AVX512, NEON, MAX};
/* A facility for dynamic dispatch according to available DispatchLevel.
Typical use:
static void my_function_default(...); static void my_function_avx2(...);
struct MyDynamicFunction { using FunctionType = decltype(&my_function_default);
static std::vector<std::pair<DispatchLevel, FunctionType>> implementations() { return { { DispatchLevel::NONE, my_function_default } #if defined(ARROW_HAVE_RUNTIME_AVX2) , { DispatchLevel::AVX2, my_function_avx2 } #endif }; } };
void my_function(...) { static DynamicDispatch<MyDynamicFunction> dispatch; return dispatch.func(...); }*/template <typename DynamicFunction>class DynamicDispatch { protected: using FunctionType = typename DynamicFunction::FunctionType; using Implementation = std::pair<DispatchLevel, FunctionType>;
public: DynamicDispatch() { Resolve(DynamicFunction::implementations()); }
FunctionType func = {};
protected: // Use the Implementation with the highest DispatchLevel void Resolve(const std::vector<Implementation>& implementations) { Implementation cur{DispatchLevel::NONE, {}};
for (const auto& impl : implementations) { if (impl.first >= cur.first && IsSupported(impl.first)) { // Higher (or same) level than current cur = impl; } }
if (!cur.second) { Status::Invalid("No appropriate implementation found").Abort(); } func = cur.second; }
private: bool IsSupported(DispatchLevel level) const { static const auto cpu_info = arrow::internal::CpuInfo::GetInstance();
switch (level) { case DispatchLevel::NONE: return true; case DispatchLevel::SSE4_2: return cpu_info->IsSupported(CpuInfo::SSE4_2); case DispatchLevel::AVX2: return cpu_info->IsSupported(CpuInfo::AVX2); case DispatchLevel::AVX512: return cpu_info->IsSupported(CpuInfo::AVX512); default: return false; } }};
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656// 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 <array>#include <cassert>#include <chrono>#include <limits>#include <memory>#include <string>#include <string_view>#include <type_traits>#include <utility>
#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 <typename ARROW_TYPE, typename Enable = void>class StringFormatter;
template <typename T>struct is_formattable { template <typename U, typename = typename StringFormatter<U>::value_type> static std::true_type Test(U*);
template <typename U> static std::false_type Test(...);
static constexpr bool value = decltype(Test<T>(NULLPTR))::value;};
template <typename T, typename R = void>using enable_if_formattable = enable_if_t<is_formattable<T>::value, R>;
template <typename Appender>using Return = decltype(std::declval<Appender>()(std::string_view{}));
/////////////////////////////////////////////////////////////////////////// Boolean formatting
template <>class StringFormatter<BooleanType> { public: explicit StringFormatter(const DataType* = NULLPTR) {}
using value_type = bool;
template <typename Appender> Return<Appender> 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 <typename ARROW_TYPE>class DecimalToStringFormatterMixin { public: explicit DecimalToStringFormatterMixin(const DataType* type) : scale_(static_cast<const ARROW_TYPE*>(type)->scale()) {}
using value_type = typename TypeTraits<ARROW_TYPE>::CType;
template <typename Appender> Return<Appender> operator()(const value_type& value, Appender&& append) { return append(value.ToString(scale_)); }
private: int32_t scale_;};
template <>class StringFormatter<Decimal128Type> : public DecimalToStringFormatterMixin<Decimal128Type> { using DecimalToStringFormatterMixin::DecimalToStringFormatterMixin;};
template <>class StringFormatter<Decimal256Type> : public DecimalToStringFormatterMixin<Decimal256Type> { 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.// \pre *cursor points to the byte after the one that will be written.// \post *cursor points to the byte that was written.inline void FormatOneChar(char c, char** cursor) { *(--(*cursor)) = c; }
template <typename Int>void FormatOneDigit(Int value, char** cursor) { assert(value >= 0 && value <= 9); FormatOneChar(static_cast<char>('0' + value), cursor);}
// GH-35662: I don't know why but the following combination causes SEGV:// * template implementation without inline// * MinGW// * Release buildtemplate <typename Int>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 <typename Int>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 <typename Int>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 <size_t BUFFER_SIZE>std::string_view ViewDigitBuffer(const std::array<char, BUFFER_SIZE>& buffer, char* cursor) { auto buffer_end = buffer.data() + BUFFER_SIZE; return {cursor, static_cast<size_t>(buffer_end - cursor)};}
template <typename Int, typename UInt = typename std::make_unsigned<Int>::type>constexpr UInt Abs(Int value) { return value < 0 ? ~static_cast<UInt>(value) + 1 : static_cast<UInt>(value);}
template <typename Int>constexpr size_t Digits10(Int value) { return value <= 9 ? 1 : Digits10(value / 10) + 1;}
} // namespace detail
template <typename ARROW_TYPE>class IntToStringFormatterMixin { public: explicit IntToStringFormatterMixin(const DataType* = NULLPTR) {}
using value_type = typename ARROW_TYPE::c_type;
template <typename Appender> Return<Appender> operator()(value_type value, Appender&& append) { constexpr size_t buffer_size = detail::Digits10(std::numeric_limits<value_type>::max()) + 1;
std::array<char, buffer_size> 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<Int8Type> : public IntToStringFormatterMixin<Int8Type> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
template <>class StringFormatter<Int16Type> : public IntToStringFormatterMixin<Int16Type> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
template <>class StringFormatter<Int32Type> : public IntToStringFormatterMixin<Int32Type> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
template <>class StringFormatter<Int64Type> : public IntToStringFormatterMixin<Int64Type> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
template <>class StringFormatter<UInt8Type> : public IntToStringFormatterMixin<UInt8Type> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
template <>class StringFormatter<UInt16Type> : public IntToStringFormatterMixin<UInt16Type> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
template <>class StringFormatter<UInt32Type> : public IntToStringFormatterMixin<UInt32Type> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
template <>class StringFormatter<UInt64Type> : public IntToStringFormatterMixin<UInt64Type> { 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); int FormatFloat(uint16_t v, char* out_buffer, int out_size);
protected: struct Impl; std::unique_ptr<Impl> impl_;};
template <typename ARROW_TYPE>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 <typename Appender> Return<Appender> 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<HalfFloatType> : public FloatToStringFormatterMixin<HalfFloatType> { public: using FloatToStringFormatterMixin::FloatToStringFormatterMixin;};
template <>class StringFormatter<FloatType> : public FloatToStringFormatterMixin<FloatType> { public: using FloatToStringFormatterMixin::FloatToStringFormatterMixin;};
template <>class StringFormatter<DoubleType> : public FloatToStringFormatterMixin<DoubleType> { public: using FloatToStringFormatterMixin::FloatToStringFormatterMixin;};
/////////////////////////////////////////////////////////////////////////// Temporal formatting
namespace detail {
constexpr size_t BufferSizeYYYY_MM_DD() { // "-"? "99999-12-31" 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<unsigned>(ymd.day()), cursor); FormatOneChar('-', cursor); FormatTwoDigits(static_cast<unsigned>(ymd.month()), cursor); FormatOneChar('-', cursor); auto year = static_cast<int>(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 <typename Duration>constexpr size_t BufferSizeHH_MM_SS() { // "23:59:59" ("." "9"+)? return detail::Digits10(23) + 1 + detail::Digits10(59) + 1 + detail::Digits10(59) + 1 + detail::Digits10(Duration::period::den) - 1;}
template <typename Duration>void FormatHH_MM_SS(arrow_vendored::date::hh_mm_ss<Duration> 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_daystemplate <typename Unit>bool IsDateTimeInRange(Unit duration) { constexpr Unit kMinIncl = std::chrono::duration_cast<Unit>(arrow_vendored::date::days{-12687428}); constexpr Unit kMaxExcl = std::chrono::duration_cast<Unit>(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 <typename Unit>bool IsTimeInRange(Unit duration) { constexpr Unit kMinIncl = std::chrono::duration_cast<Unit>(std::chrono::seconds{0}); constexpr Unit kMaxExcl = std::chrono::duration_cast<Unit>(std::chrono::seconds{86400}); return duration >= kMinIncl && duration < kMaxExcl;}
template <typename RawValue, typename Appender>Return<Appender> FormatOutOfRange(RawValue&& raw_value, Appender&& append) { // XXX locale-sensitive but good enough for now std::string formatted = "<value out of range: " + ToChars(raw_value) + ">"; return append(std::move(formatted));}
const auto kEpoch = arrow_vendored::date::sys_days{arrow_vendored::date::jan / 1 / 1970};
} // namespace detail
template <>class StringFormatter<DurationType> : public IntToStringFormatterMixin<DurationType> { using IntToStringFormatterMixin::IntToStringFormatterMixin;};
class DateToStringFormatterMixin { public: explicit DateToStringFormatterMixin(const DataType* = NULLPTR) {}
protected: template <typename Appender> Return<Appender> 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<char, buffer_size> 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<Date32Type> : public DateToStringFormatterMixin { public: using value_type = typename Date32Type::c_type;
using DateToStringFormatterMixin::DateToStringFormatterMixin;
template <typename Appender> Return<Appender> 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<Appender>(append)); }};
template <>class StringFormatter<Date64Type> : public DateToStringFormatterMixin { public: using value_type = typename Date64Type::c_type;
using DateToStringFormatterMixin::DateToStringFormatterMixin;
template <typename Appender> Return<Appender> 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<arrow_vendored::date::days>(since_epoch), std::forward<Appender>(append)); }};
template <>class StringFormatter<TimestampType> { public: using value_type = int64_t;
explicit StringFormatter(const DataType* type) : unit_(checked_cast<const TimestampType&>(*type).unit()), timezone_(checked_cast<const TimestampType&>(*type).timezone()) {}
template <typename Duration, typename Appender> Return<Appender> 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<days>(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); }
// YYYY_MM_DD " " HH_MM_SS "Z"? constexpr size_t buffer_size = detail::BufferSizeYYYY_MM_DD() + 1 + detail::BufferSizeHH_MM_SS<Duration>() + 1;
std::array<char, buffer_size> 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 <typename Appender> Return<Appender> operator()(value_type value, Appender&& append) { return util::VisitDuration(unit_, *this, value, std::forward<Appender>(append)); }
private: TimeUnit::type unit_; std::string timezone_;};
template <typename T>class StringFormatter<T, enable_if_time<T>> { public: using value_type = typename T::c_type;
explicit StringFormatter(const DataType* type) : unit_(checked_cast<const T&>(*type).unit()) {}
template <typename Duration, typename Appender> Return<Appender> 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<Duration>();
std::array<char, buffer_size> 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 <typename Appender> Return<Appender> operator()(value_type value, Appender&& append) { return util::VisitDuration(unit_, *this, value, std::forward<Appender>(append)); }
private: TimeUnit::type unit_;};
template <>class StringFormatter<MonthIntervalType> { public: using value_type = MonthIntervalType::c_type;
explicit StringFormatter(const DataType*) {}
template <typename Appender> Return<Appender> operator()(value_type interval, Appender&& append) { constexpr size_t buffer_size = /*'m'*/ 3 + /*negative signs*/ 1 + /*months*/ detail::Digits10(std::numeric_limits<value_type>::max()); std::array<char, buffer_size> 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<DayTimeIntervalType> { public: using value_type = DayTimeIntervalType::DayMilliseconds;
explicit StringFormatter(const DataType*) {}
template <typename Appender> Return<Appender> 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<int32_t>::max()); std::array<char, buffer_size> 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<MonthDayNanoIntervalType> { public: using value_type = MonthDayNanoIntervalType::MonthDayNanos;
explicit StringFormatter(const DataType*) {}
template <typename Appender> Return<Appender> 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<int32_t>::max()) + /*nanoseconds*/ detail::Digits10(std::numeric_limits<int64_t>::max()); std::array<char, buffer_size> 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 arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882// 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 <atomic>#include <cmath>#include <functional>#include <memory>#include <optional>#include <type_traits>#include <utility>#include <vector>
#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 <typename>struct EnsureFuture;
namespace detail {
template <typename>struct is_future : std::false_type {};
template <typename T>struct is_future<Future<T>> : std::true_type {};
template <typename Signature, typename Enable = void>struct result_of;
template <typename Fn, typename... A>struct result_of<Fn(A...), internal::void_t<decltype(std::declval<Fn>()(std::declval<A>()...))>> { using type = decltype(std::declval<Fn>()(std::declval<A>()...));};
template <typename Signature>using result_of_t = typename result_of<Signature>::type;
// Helper to find the synchronous counterpart for a Futuretemplate <typename T>struct SyncType { using type = Result<T>;};
template <>struct SyncType<internal::Empty> { using type = Status;};
template <typename Fn>using first_arg_is_status = std::is_same<typename std::decay<internal::call_traits::argument_type<0, Fn>>::type, Status>;
template <typename Fn, typename Then, typename Else, typename Count = internal::call_traits::argument_count<Fn>>using if_has_no_args = typename std::conditional<Count::value == 0, Then, Else>::type;
/// Creates a callback that can be added to a future to mark a `dest` future finishedtemplate <typename Source, typename Dest, bool SourceEmpty = Source::is_empty, bool DestEmpty = Dest::is_empty>struct MarkNextFinished {};
/// If the source and dest are both empty we can pass on the statustemplate <typename Source, typename Dest>struct MarkNextFinished<Source, Dest, true, true> { 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 resulttemplate <typename Source, typename Dest>struct MarkNextFinished<Source, Dest, false, true> { void operator()(const Result<typename Source::ValueType>& res) && { next.MarkFinished(internal::Empty::ToResult(res.status())); } Dest next;};
/// If neither are empty we pass on the resulttemplate <typename Source, typename Dest>struct MarkNextFinished<Source, Dest, false, false> { void operator()(const Result<typename Source::ValueType>& res) && { next.MarkFinished(res); } Dest next;};
/// Helper that contains information about how to apply a continuationstruct ContinueFuture { template <typename Return> struct ForReturnImpl;
template <typename Return> using ForReturn = typename ForReturnImpl<Return>::type;
template <typename Signature> using ForSignature = ForReturn<result_of_t<Signature>>;
// If the callback returns void then we return Future<> that always finishes OK. template <typename ContinueFunc, typename... Args, typename ContinueResult = result_of_t<ContinueFunc && (Args && ...)>, typename NextFuture = ForReturn<ContinueResult>> typename std::enable_if<std::is_void<ContinueResult>::value>::type operator()( NextFuture next, ContinueFunc&& f, Args&&... a) const { std::forward<ContinueFunc>(f)(std::forward<Args>(a)...); next.MarkFinished(); }
/// If the callback returns a non-future then we return Future<T> /// and mark the future finished with the callback result. It will get promoted /// to Result<T> 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 ContinueFunc, typename... Args, typename ContinueResult = result_of_t<ContinueFunc && (Args && ...)>, typename NextFuture = ForReturn<ContinueResult>> typename std::enable_if< !std::is_void<ContinueResult>::value && !is_future<ContinueResult>::value && (!NextFuture::is_empty || std::is_same<ContinueResult, Status>::value)>::type operator()(NextFuture next, ContinueFunc&& f, Args&&... a) const { next.MarkFinished(std::forward<ContinueFunc>(f)(std::forward<Args>(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 ContinueFunc, typename... Args, typename ContinueResult = result_of_t<ContinueFunc && (Args && ...)>, typename NextFuture = ForReturn<ContinueResult>> typename std::enable_if<!std::is_void<ContinueResult>::value && !is_future<ContinueResult>::value && NextFuture::is_empty && !std::is_same<ContinueResult, Status>::value>::type operator()(NextFuture next, ContinueFunc&& f, Args&&... a) const { next.MarkFinished(std::forward<ContinueFunc>(f)(std::forward<Args>(a)...).status()); }
/// If the callback returns a Future<T> then we return Future<T>. 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 ContinueFunc, typename... Args, typename ContinueResult = result_of_t<ContinueFunc && (Args && ...)>, typename NextFuture = ForReturn<ContinueResult>> typename std::enable_if<is_future<ContinueResult>::value>::type operator()( NextFuture next, ContinueFunc&& f, Args&&... a) const { ContinueResult signal_to_complete_next = std::forward<ContinueFunc>(f)(std::forward<Args>(a)...); MarkNextFinished<ContinueResult, NextFuture> callback{std::move(next)}; signal_to_complete_next.AddCallback(std::move(callback)); }
/// Helpers to conditionally ignore arguments to ContinueFunc template <typename ContinueFunc, typename NextFuture, typename... Args> void IgnoringArgsIf(std::true_type, NextFuture&& next, ContinueFunc&& f, Args&&...) const { operator()(std::forward<NextFuture>(next), std::forward<ContinueFunc>(f)); } template <typename ContinueFunc, typename NextFuture, typename... Args> void IgnoringArgsIf(std::false_type, NextFuture&& next, ContinueFunc&& f, Args&&... a) const { operator()(std::forward<NextFuture>(next), std::forward<ContinueFunc>(f), std::forward<Args>(a)...); }};
/// Helper struct which tells us what kind of Future gets returned from `Then` based on/// the return type of the OnSuccess callbacktemplate <>struct ContinueFuture::ForReturnImpl<void> { using type = Future<>;};
template <>struct ContinueFuture::ForReturnImpl<Status> { using type = Future<>;};
template <typename R>struct ContinueFuture::ForReturnImpl { using type = Future<R>;};
template <typename T>struct ContinueFuture::ForReturnImpl<Result<T>> { using type = Future<T>;};
template <typename T>struct ContinueFuture::ForReturnImpl<Future<T>> { using type = Future<T>;};
} // namespace detail
/// A Future's execution or completion statusenum 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 synchronouslyenum 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 runstruct 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 implementationclass ARROW_EXPORT FutureImpl : public std::enable_shared_from_this<FutureImpl> { public: FutureImpl(); virtual ~FutureImpl() = default;
FutureState state() { return state_.load(); }
static std::unique_ptr<FutureImpl> Make(); static std::unique_ptr<FutureImpl> 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 <typename ValueType> Result<ValueType>* CastResult() const { return static_cast<Result<ValueType>*>(result_.get()); }
using Callback = internal::FnOnce<void(const FutureImpl& impl)>; void AddCallback(Callback callback, CallbackOptions opts); bool TryAddCallback(const std::function<Callback()>& callback_factory, CallbackOptions opts);
std::atomic<FutureState> 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<void, void (*)(void*)>; Storage result_{NULLPTR, NULLPTR};
struct CallbackRecord { Callback callback; CallbackOptions options; }; std::vector<CallbackRecord> 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 <typename T>class [[nodiscard]] Future { public: using ValueType = T; using SyncType = typename detail::SyncType<T>::type; static constexpr bool is_empty = std::is_same<T, internal::Empty>::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<ValueType>& 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<ValueType>&& 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<T> 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<ValueType> res) { DoMarkFinished(std::move(res)); }
/// \brief Mark a Future<> completed with the provided Status. template <typename E = ValueType, typename = typename std::enable_if< std::is_same<E, internal::Empty>::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<ValueType> MakeFinished(Result<ValueType> res) { Future<ValueType> fut; fut.InitializeFromResult(std::move(res)); return fut; }
/// \brief Make a finished Future<> with the provided Status. template <typename E = ValueType, typename = typename std::enable_if< std::is_same<E, internal::Empty>::value>::type> static Future<> MakeFinished(Status s = Status::OK()) { return MakeFinished(E::ToResult(std::move(s))); }
struct WrapResultOnComplete { template <typename OnComplete> struct Callback { void operator()(const FutureImpl& impl) && { std::move(on_complete)(*impl.CastResult<ValueType>()); } OnComplete on_complete; }; };
struct WrapStatusyOnComplete { template <typename OnComplete> struct Callback { static_assert(std::is_same<internal::Empty, ValueType>::value, "Only callbacks for Future<> should accept Status and not Result");
void operator()(const FutureImpl& impl) && { std::move(on_complete)(impl.CastResult<ValueType>()->status()); } OnComplete on_complete; }; };
template <typename OnComplete> using WrapOnComplete = typename std::conditional< detail::first_arg_is_status<OnComplete>::value, WrapStatusyOnComplete, WrapResultOnComplete>::type::template Callback<OnComplete>;
/// \brief Consumer API: Register a callback to run when this future completes /// /// The callback should receive the result of the future (const Result<T>&) /// 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 <typename OnComplete, typename Callback = WrapOnComplete<OnComplete>> 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 CallbackFactory, typename OnComplete = detail::result_of_t<CallbackFactory()>, typename Callback = WrapOnComplete<OnComplete>> bool TryAddCallback(CallbackFactory callback_factory, CallbackOptions opts = CallbackOptions::Defaults()) const { return impl_->TryAddCallback([&]() { return Callback{callback_factory()}; }, opts); }
template <typename OnSuccess, typename OnFailure> struct ThenOnComplete { static constexpr bool has_no_args = internal::call_traits::argument_count<OnSuccess>::value == 0;
using ContinuedFuture = detail::ContinueFuture::ForSignature< detail::if_has_no_args<OnSuccess, OnSuccess && (), OnSuccess && (const T&)>>;
static_assert( std::is_same<detail::ContinueFuture::ForSignature<OnFailure && (const Status&)>, ContinuedFuture>::value, "OnSuccess and OnFailure must continue with the same future type");
struct DummyOnSuccess { void operator()(const T&); }; using OnSuccessArg = typename std::decay<internal::call_traits::argument_type< 0, detail::if_has_no_args<OnSuccess, DummyOnSuccess, OnSuccess>>>::type;
static_assert( !std::is_same<OnSuccessArg, typename EnsureResult<OnSuccessArg>::type>::value, "OnSuccess' argument should not be a Result");
void operator()(const Result<T>& 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<OnSuccess, std::true_type, std::false_type>{}, 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 <typename OnSuccess> struct PassthruOnFailure { using ContinuedFuture = detail::ContinueFuture::ForSignature< detail::if_has_no_args<OnSuccess, OnSuccess && (), OnSuccess && (const T&)>>;
Result<typename ContinuedFuture::ValueType> 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<V>, a Future<V> will be returned which will complete with the result /// of invoking the callback as soon as the callback runs. /// - Future<V>, a Future<V> 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 OnSuccess, typename OnFailure = PassthruOnFailure<OnSuccess>, typename OnComplete = ThenOnComplete<OnSuccess, OnFailure>, 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<OnSuccess>(on_success), std::forward<OnFailure>(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<ValueType> 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<ValueType>(std::move(s))) {}
protected: void InitializeFromResult(Result<ValueType> 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<ValueType>* GetResult() const { return impl_->CastResult<ValueType>(); }
void SetResult(Result<ValueType> res) { impl_->result_ = {new Result<ValueType>(std::move(res)), [](void* p) { delete static_cast<Result<ValueType>*>(p); }}; }
void DoMarkFinished(Result<ValueType> 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<FutureImpl> impl) : impl_(std::move(impl)) {}
std::shared_ptr<FutureImpl> impl_;
friend struct detail::ContinueFuture;
template <typename U> friend class Future; friend class WeakFuture<T>;
FRIEND_TEST(FutureRefTest, ChainRemoved); FRIEND_TEST(FutureRefTest, TailRemoved); FRIEND_TEST(FutureRefTest, HeadRemoved);};
template <typename T>typename Future<T>::SyncType FutureToSync(const Future<T>& fut) { return fut.result();}
template <>inline typename Future<internal::Empty>::SyncType FutureToSync<internal::Empty>( const Future<internal::Empty>& fut) { return fut.status();}
template <>inline Future<>::Future(Status s) : Future(internal::Empty::ToResult(std::move(s))) {}
template <typename T>class WeakFuture { public: explicit WeakFuture(const Future<T>& future) : impl_(future.impl_) {}
Future<T> get() { return Future<T>{impl_.lock()}; }
private: std::weak_ptr<FutureImpl> impl_;};
/// \defgroup future-utilities Functions for working with Futures/// @{
/// If a Result<Future> holds an error instead of a Future, construct a finished Future/// holding that error.template <typename T>static Future<T> DeferNotOk(Result<Future<T>> maybe_future) { if (ARROW_PREDICT_FALSE(!maybe_future.ok())) { return Future<T>::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 <typename T>Future<std::vector<Result<T>>> All(std::vector<Future<T>> futures) { struct State { explicit State(std::vector<Future<T>> f) : futures(std::move(f)), n_remaining(futures.size()) {}
std::vector<Future<T>> futures; std::atomic<size_t> n_remaining; };
if (futures.size() == 0) { return {std::vector<Result<T>>{}}; }
auto state = std::make_shared<State>(std::move(futures));
auto out = Future<std::vector<Result<T>>>::Make(); for (const Future<T>& future : state->futures) { future.AddCallback([state, out](const Result<T>&) mutable { if (state->n_remaining.fetch_sub(1) != 1) return;
std::vector<Result<T>> 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_EXPORTFuture<> AllComplete(const std::vector<Future<>>& 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_EXPORTFuture<> AllFinished(const std::vector<Future<>>& futures);
/// @}
struct Continue { template <typename T> operator std::optional<T>() && { // NOLINT explicit return {}; }};
template <typename T = internal::Empty>std::optional<T> Break(T break_value = {}) { return std::optional<T>{std::move(break_value)};}
template <typename T = internal::Empty>using ControlFlow = std::optional<T>;
/// \brief Loop through an asynchronous sequence////// \param[in] iterate A generator of Future<ControlFlow<BreakValue>>. 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 Breaktemplate <typename Iterate, typename Control = typename detail::result_of_t<Iterate()>::ValueType, typename BreakValueType = typename Control::value_type>Future<BreakValueType> Loop(Iterate iterate) { struct Callback { bool CheckForTermination(const Result<Control>& 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<Control>& 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<BreakValueType> break_fut; };
auto break_fut = Future<BreakValueType>::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 <typename T>Future<T> ToFuture(T value) { return Future<T>::MakeFinished(std::move(value));}
template <typename T>Future<T> ToFuture(Result<T> maybe_value) { return Future<T>::MakeFinished(std::move(maybe_value));}
template <typename T>Future<T> ToFuture(Future<T> fut) { return fut;}
template <typename T>struct EnsureFuture { using type = decltype(ToFuture(std::declval<T>()));};
} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944// 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.
// Private header, not to be exported
#pragma once
#include <algorithm>#include <cassert>#include <cmath>#include <cstdint>#include <cstring>#include <limits>#include <memory>#include <string>#include <type_traits>#include <utility>#include <vector>
#include "arrow/array/builder_binary.h"#include "arrow/buffer_builder.h"#include "arrow/result.h"#include "arrow/status.h"#include "arrow/type_fwd.h"#include "arrow/type_traits.h"#include "arrow/util/bit_util.h"#include "arrow/util/bitmap_builders.h"#include "arrow/util/endian.h"#include "arrow/util/logging.h"#include "arrow/util/macros.h"#include "arrow/util/ubsan.h"
#define XXH_INLINE_ALL
#include "arrow/vendored/xxhash.h" // IWYU pragma: keep
namespace arrow {namespace internal {
// XXX would it help to have a 32-bit hash value on large datasets?typedef uint64_t hash_t;
// Notes about the choice of a hash function.// - XXH3 is extremely fast on most data sizes, from small to huge;// faster even than HW CRC-based hashing schemes// - our custom hash function for tiny values (< 16 bytes) is still// significantly faster (~30%), at least on this machine and compiler
template <uint64_t AlgNum>inline hash_t ComputeStringHash(const void* data, int64_t length);
/// \brief A hash function for bitmaps that can handle offsets and lengths in/// terms of number of bits. The hash only depends on the bits actually hashed.////// It's the caller's responsibility to ensure that bits_offset + num_bits are/// readable from the bitmap.////// \pre bits_offset >= 0/// \pre num_bits >= 0/// \pre (bits_offset + num_bits + 7) / 8 <= readable length in bytes from bitmap////// \param bitmap The pointer to the bitmap./// \param seed The seed for the hash function (useful when chaining hash functions)./// \param bits_offset The offset in bits relative to the start of the bitmap./// \param num_bits The number of bits after the offset to be hashed.ARROW_EXPORT hash_t ComputeBitmapHash(const uint8_t* bitmap, hash_t seed, int64_t bits_offset, int64_t num_bits);
template <typename Scalar, uint64_t AlgNum>struct ScalarHelperBase { static bool CompareScalars(Scalar u, Scalar v) { return u == v; }
static hash_t ComputeHash(const Scalar& value) { // Generic hash computation for scalars. Simply apply the string hash // to the bit representation of the value.
// XXX in the case of FP values, we'd like equal values to have the same hash, // even if they have different bit representations... return ComputeStringHash<AlgNum>(&value, sizeof(value)); }};
template <typename Scalar, uint64_t AlgNum = 0, typename Enable = void>struct ScalarHelper : public ScalarHelperBase<Scalar, AlgNum> {};
template <typename Scalar, uint64_t AlgNum>struct ScalarHelper<Scalar, AlgNum, enable_if_t<std::is_integral<Scalar>::value>> : public ScalarHelperBase<Scalar, AlgNum> { // ScalarHelper specialization for integers
static hash_t ComputeHash(const Scalar& value) { // Faster hash computation for integers.
// Two of xxhash's prime multipliers (which are chosen for their // bit dispersion properties) static constexpr uint64_t multipliers[] = {11400714785074694791ULL, 14029467366897019727ULL};
// Multiplying by the prime number mixes the low bits into the high bits, // then byte-swapping (which is a single CPU instruction) allows the // combined high and low bits to participate in the initial hash table index. auto h = static_cast<hash_t>(value); return bit_util::ByteSwap(multipliers[AlgNum] * h); }};
template <typename Scalar, uint64_t AlgNum>struct ScalarHelper<Scalar, AlgNum, enable_if_t<std::is_same<std::string_view, Scalar>::value>> : public ScalarHelperBase<Scalar, AlgNum> { // ScalarHelper specialization for std::string_view
static hash_t ComputeHash(std::string_view value) { return ComputeStringHash<AlgNum>(value.data(), static_cast<int64_t>(value.size())); }};
template <typename Scalar, uint64_t AlgNum>struct ScalarHelper<Scalar, AlgNum, enable_if_t<std::is_floating_point<Scalar>::value>> : public ScalarHelperBase<Scalar, AlgNum> { // ScalarHelper specialization for reals
static bool CompareScalars(Scalar u, Scalar v) { if (std::isnan(u)) { // XXX should we do a bit-precise comparison? return std::isnan(v); } return u == v; }};
template <uint64_t AlgNum = 0>hash_t ComputeStringHash(const void* data, int64_t length) { if (ARROW_PREDICT_TRUE(length <= 16)) { // Specialize for small hash strings, as they are quite common as // hash table keys. Even XXH3 isn't quite as fast. auto p = reinterpret_cast<const uint8_t*>(data); auto n = static_cast<uint32_t>(length); if (n <= 8) { if (n <= 3) { if (n == 0) { return 1U; } uint32_t x = (n << 24) ^ (p[0] << 16) ^ (p[n / 2] << 8) ^ p[n - 1]; return ScalarHelper<uint32_t, AlgNum>::ComputeHash(x); } // 4 <= length <= 8 // We can read the string as two overlapping 32-bit ints, apply // different hash functions to each of them in parallel, then XOR // the results uint32_t x, y; hash_t hx, hy; x = util::SafeLoadAs<uint32_t>(p + n - 4); y = util::SafeLoadAs<uint32_t>(p); hx = ScalarHelper<uint32_t, AlgNum>::ComputeHash(x); hy = ScalarHelper<uint32_t, AlgNum ^ 1>::ComputeHash(y); return n ^ hx ^ hy; } // 8 <= length <= 16 // Apply the same principle as above uint64_t x, y; hash_t hx, hy; x = util::SafeLoadAs<uint64_t>(p + n - 8); y = util::SafeLoadAs<uint64_t>(p); hx = ScalarHelper<uint64_t, AlgNum>::ComputeHash(x); hy = ScalarHelper<uint64_t, AlgNum ^ 1>::ComputeHash(y); return n ^ hx ^ hy; }
#if XXH3_SECRET_SIZE_MIN != 136#error XXH3_SECRET_SIZE_MIN changed, please fix kXxh3Secrets#endif
// XXH3_64bits_withSeed generates a secret based on the seed, which is too slow. // Instead, we use hard-coded random secrets. To maximize cache efficiency, // they reuse the same memory area. static constexpr unsigned char kXxh3Secrets[XXH3_SECRET_SIZE_MIN + 1] = { 0xe7, 0x8b, 0x13, 0xf9, 0xfc, 0xb5, 0x8e, 0xef, 0x81, 0x48, 0x2c, 0xbf, 0xf9, 0x9f, 0xc1, 0x1e, 0x43, 0x6d, 0xbf, 0xa6, 0x6d, 0xb5, 0x72, 0xbc, 0x97, 0xd8, 0x61, 0x24, 0x0f, 0x12, 0xe3, 0x05, 0x21, 0xf7, 0x5c, 0x66, 0x67, 0xa5, 0x65, 0x03, 0x96, 0x26, 0x69, 0xd8, 0x29, 0x20, 0xf8, 0xc7, 0xb0, 0x3d, 0xdd, 0x7d, 0x18, 0xa0, 0x60, 0x75, 0x92, 0xa4, 0xce, 0xba, 0xc0, 0x77, 0xf4, 0xac, 0xb7, 0x03, 0x53, 0xf0, 0x98, 0xce, 0xe6, 0x2b, 0x20, 0xc7, 0x82, 0x91, 0xab, 0xbf, 0x68, 0x5c, 0x62, 0x4d, 0x33, 0xa3, 0xe1, 0xb3, 0xff, 0x97, 0x54, 0x4c, 0x44, 0x34, 0xb5, 0xb9, 0x32, 0x4c, 0x75, 0x42, 0x89, 0x53, 0x94, 0xd4, 0x9f, 0x2b, 0x76, 0x4d, 0x4e, 0xe6, 0xfa, 0x15, 0x3e, 0xc1, 0xdb, 0x71, 0x4b, 0x2c, 0x94, 0xf5, 0xfc, 0x8c, 0x89, 0x4b, 0xfb, 0xc1, 0x82, 0xa5, 0x6a, 0x53, 0xf9, 0x4a, 0xba, 0xce, 0x1f, 0xc0, 0x97, 0x1a, 0x87};
static_assert(AlgNum < 2, "AlgNum too large"); static constexpr auto secret = kXxh3Secrets + AlgNum; return XXH3_64bits_withSecret(data, static_cast<size_t>(length), secret, XXH3_SECRET_SIZE_MIN);}
// XXX add a HashEq<ArrowType> struct with both hash and compare functions?
// ----------------------------------------------------------------------// An open-addressing insert-only hash table (no deletes)
template <typename Payload>class HashTable { public: static constexpr hash_t kSentinel = 0ULL; static constexpr int64_t kLoadFactor = 2UL;
struct Entry { hash_t h; Payload payload;
// An entry is valid if the hash is different from the sentinel value operator bool() const { return h != kSentinel; } };
HashTable(MemoryPool* pool, uint64_t capacity) : entries_builder_(pool) { DCHECK_NE(pool, nullptr); // Minimum of 32 elements capacity = std::max<uint64_t>(capacity, 32UL); capacity_ = bit_util::NextPower2(capacity); capacity_mask_ = capacity_ - 1; size_ = 0;
DCHECK_OK(UpsizeBuffer(capacity_)); }
// Lookup with non-linear probing // cmp_func should have signature bool(const Payload*). // Return a (Entry*, found) pair. template <typename CmpFunc> std::pair<Entry*, bool> Lookup(hash_t h, CmpFunc&& cmp_func) { auto p = Lookup<DoCompare, CmpFunc>(h, entries_, capacity_mask_, std::forward<CmpFunc>(cmp_func)); return {&entries_[p.first], p.second}; }
template <typename CmpFunc> std::pair<const Entry*, bool> Lookup(hash_t h, CmpFunc&& cmp_func) const { auto p = Lookup<DoCompare, CmpFunc>(h, entries_, capacity_mask_, std::forward<CmpFunc>(cmp_func)); return {&entries_[p.first], p.second}; }
Status Insert(Entry* entry, hash_t h, const Payload& payload) { // Ensure entry is empty before inserting assert(!*entry); entry->h = FixHash(h); entry->payload = payload; ++size_;
if (ARROW_PREDICT_FALSE(NeedUpsizing())) { // Resize less frequently since it is expensive return Upsize(capacity_ * kLoadFactor * 2); } return Status::OK(); }
uint64_t size() const { return size_; }
// Visit all non-empty entries in the table // The visit_func should have signature void(const Entry*) template <typename VisitFunc> void VisitEntries(VisitFunc&& visit_func) const { for (uint64_t i = 0; i < capacity_; i++) { const auto& entry = entries_[i]; if (entry) { visit_func(&entry); } } }
protected: // NoCompare is for when the value is known not to exist in the table enum CompareKind { DoCompare, NoCompare };
// The workhorse lookup function template <CompareKind CKind, typename CmpFunc> std::pair<uint64_t, bool> Lookup(hash_t h, const Entry* entries, uint64_t size_mask, CmpFunc&& cmp_func) const { static constexpr uint8_t perturb_shift = 5;
uint64_t index, perturb; const Entry* entry;
h = FixHash(h); index = h & size_mask; perturb = (h >> perturb_shift) + 1U;
while (true) { entry = &entries[index]; if (CompareEntry<CKind, CmpFunc>(h, entry, std::forward<CmpFunc>(cmp_func))) { // Found return {index, true}; } if (entry->h == kSentinel) { // Empty slot return {index, false}; }
// Perturbation logic inspired from CPython's set / dict object. // The goal is that all 64 bits of the unmasked hash value eventually // participate in the probing sequence, to minimize clustering. index = (index + perturb) & size_mask; perturb = (perturb >> perturb_shift) + 1U; } }
template <CompareKind CKind, typename CmpFunc> bool CompareEntry(hash_t h, const Entry* entry, CmpFunc&& cmp_func) const { if (CKind == NoCompare) { return false; } else { return entry->h == h && cmp_func(&entry->payload); } }
bool NeedUpsizing() const { // Keep the load factor <= 1/2 return size_ * kLoadFactor >= capacity_; }
Status UpsizeBuffer(uint64_t capacity) { RETURN_NOT_OK(entries_builder_.Resize(capacity)); entries_ = entries_builder_.mutable_data(); memset(static_cast<void*>(entries_), 0, capacity * sizeof(Entry));
return Status::OK(); }
Status Upsize(uint64_t new_capacity) { assert(new_capacity > capacity_); uint64_t new_mask = new_capacity - 1; assert((new_capacity & new_mask) == 0); // it's a power of two
// Stash old entries and seal builder, effectively resetting the Buffer const Entry* old_entries = entries_; ARROW_ASSIGN_OR_RAISE(auto previous, entries_builder_.FinishWithLength(capacity_)); // Allocate new buffer RETURN_NOT_OK(UpsizeBuffer(new_capacity));
for (uint64_t i = 0; i < capacity_; i++) { const auto& entry = old_entries[i]; if (entry) { // Dummy compare function will not be called auto p = Lookup<NoCompare>(entry.h, entries_, new_mask, [](const Payload*) { return false; }); // Lookup<NoCompare> (and CompareEntry<NoCompare>) ensure that an // empty slots is always returned assert(!p.second); entries_[p.first] = entry; } } capacity_ = new_capacity; capacity_mask_ = new_mask;
return Status::OK(); }
hash_t FixHash(hash_t h) const { return (h == kSentinel) ? 42U : h; }
// The number of slots available in the hash table array. uint64_t capacity_; uint64_t capacity_mask_; // The number of used slots in the hash table array. uint64_t size_;
Entry* entries_; TypedBufferBuilder<Entry> entries_builder_;};
// XXX typedef memo_index_t int32_t ?
constexpr int32_t kKeyNotFound = -1;
// ----------------------------------------------------------------------// A base class for memoization table.
class MemoTable { public: virtual ~MemoTable() = default;
virtual int32_t size() const = 0;};
// ----------------------------------------------------------------------// A memoization table for memory-cheap scalar values.
// The memoization table remembers and allows to look up the insertion// index for each key.
template <typename Scalar, template <class> class HashTableTemplateType = HashTable>class ScalarMemoTable : public MemoTable { public: explicit ScalarMemoTable(MemoryPool* pool, int64_t entries = 0) : hash_table_(pool, static_cast<uint64_t>(entries)) {}
int32_t Get(const Scalar& value) const { auto cmp_func = [value](const Payload* payload) -> bool { return ScalarHelper<Scalar, 0>::CompareScalars(payload->value, value); }; hash_t h = ComputeHash(value); auto p = hash_table_.Lookup(h, cmp_func); if (p.second) { return p.first->payload.memo_index; } else { return kKeyNotFound; } }
template <typename Func1, typename Func2> Status GetOrInsert(const Scalar& value, Func1&& on_found, Func2&& on_not_found, int32_t* out_memo_index) { auto cmp_func = [value](const Payload* payload) -> bool { return ScalarHelper<Scalar, 0>::CompareScalars(value, payload->value); }; hash_t h = ComputeHash(value); auto p = hash_table_.Lookup(h, cmp_func); int32_t memo_index; if (p.second) { memo_index = p.first->payload.memo_index; on_found(memo_index); } else { memo_index = size(); RETURN_NOT_OK(hash_table_.Insert(p.first, h, {value, memo_index})); on_not_found(memo_index); } *out_memo_index = memo_index; return Status::OK(); }
Status GetOrInsert(const Scalar& value, int32_t* out_memo_index) { return GetOrInsert( value, [](int32_t i) {}, [](int32_t i) {}, out_memo_index); }
int32_t GetNull() const { return null_index_; }
template <typename Func1, typename Func2> int32_t GetOrInsertNull(Func1&& on_found, Func2&& on_not_found) { int32_t memo_index = GetNull(); if (memo_index != kKeyNotFound) { on_found(memo_index); } else { null_index_ = memo_index = size(); on_not_found(memo_index); } return memo_index; }
int32_t GetOrInsertNull() { return GetOrInsertNull([](int32_t i) {}, [](int32_t i) {}); }
// The number of entries in the memo table +1 if null was added. // (which is also 1 + the largest memo index) int32_t size() const override { return static_cast<int32_t>(hash_table_.size()) + (GetNull() != kKeyNotFound); }
// Copy values starting from index `start` into `out_data` void CopyValues(int32_t start, Scalar* out_data) const { hash_table_.VisitEntries([=](const HashTableEntry* entry) { int32_t index = entry->payload.memo_index - start; if (index >= 0) { out_data[index] = entry->payload.value; } }); // Zero-initialize the null entry if (null_index_ != kKeyNotFound) { int32_t index = null_index_ - start; if (index >= 0) { out_data[index] = Scalar{}; } } }
void CopyValues(Scalar* out_data) const { CopyValues(0, out_data); }
protected: struct Payload { Scalar value; int32_t memo_index; };
using HashTableType = HashTableTemplateType<Payload>; using HashTableEntry = typename HashTableType::Entry; HashTableType hash_table_; int32_t null_index_ = kKeyNotFound;
hash_t ComputeHash(const Scalar& value) const { return ScalarHelper<Scalar, 0>::ComputeHash(value); }
public: // defined here so that `HashTableType` is visible // Merge entries from `other_table` into `this->hash_table_`. Status MergeTable(const ScalarMemoTable& other_table) { const HashTableType& other_hashtable = other_table.hash_table_;
other_hashtable.VisitEntries([this](const HashTableEntry* other_entry) { int32_t unused; DCHECK_OK(this->GetOrInsert(other_entry->payload.value, &unused)); }); // TODO: ARROW-17074 - implement proper error handling return Status::OK(); }};
// ----------------------------------------------------------------------// A memoization table for small scalar values, using direct indexing
template <typename Scalar, typename Enable = void>struct SmallScalarTraits {};
template <>struct SmallScalarTraits<bool> { static constexpr int32_t cardinality = 2;
static uint32_t AsIndex(bool value) { return value ? 1 : 0; }};
template <typename Scalar>struct SmallScalarTraits<Scalar, enable_if_t<std::is_integral<Scalar>::value>> { using Unsigned = typename std::make_unsigned<Scalar>::type;
static constexpr int32_t cardinality = 1U + std::numeric_limits<Unsigned>::max();
static uint32_t AsIndex(Scalar value) { return static_cast<Unsigned>(value); }};
template <typename Scalar, template <class> class HashTableTemplateType = HashTable>class SmallScalarMemoTable : public MemoTable { public: explicit SmallScalarMemoTable(MemoryPool* pool, int64_t entries = 0) { std::fill(value_to_index_, value_to_index_ + cardinality + 1, kKeyNotFound); index_to_value_.reserve(cardinality); }
int32_t Get(const Scalar value) const { auto value_index = AsIndex(value); return value_to_index_[value_index]; }
template <typename Func1, typename Func2> Status GetOrInsert(const Scalar value, Func1&& on_found, Func2&& on_not_found, int32_t* out_memo_index) { auto value_index = AsIndex(value); auto memo_index = value_to_index_[value_index]; if (memo_index == kKeyNotFound) { memo_index = static_cast<int32_t>(index_to_value_.size()); index_to_value_.push_back(value); value_to_index_[value_index] = memo_index; DCHECK_LT(memo_index, cardinality + 1); on_not_found(memo_index); } else { on_found(memo_index); } *out_memo_index = memo_index; return Status::OK(); }
Status GetOrInsert(const Scalar value, int32_t* out_memo_index) { return GetOrInsert( value, [](int32_t i) {}, [](int32_t i) {}, out_memo_index); }
int32_t GetNull() const { return value_to_index_[cardinality]; }
template <typename Func1, typename Func2> int32_t GetOrInsertNull(Func1&& on_found, Func2&& on_not_found) { auto memo_index = GetNull(); if (memo_index == kKeyNotFound) { memo_index = value_to_index_[cardinality] = size(); index_to_value_.push_back(0); on_not_found(memo_index); } else { on_found(memo_index); } return memo_index; }
int32_t GetOrInsertNull() { return GetOrInsertNull([](int32_t i) {}, [](int32_t i) {}); }
// The number of entries in the memo table // (which is also 1 + the largest memo index) int32_t size() const override { return static_cast<int32_t>(index_to_value_.size()); }
// Merge entries from `other_table` into `this`. Status MergeTable(const SmallScalarMemoTable& other_table) { for (const Scalar& other_val : other_table.index_to_value_) { int32_t unused; RETURN_NOT_OK(this->GetOrInsert(other_val, &unused)); } return Status::OK(); }
// Copy values starting from index `start` into `out_data` void CopyValues(int32_t start, Scalar* out_data) const { DCHECK_GE(start, 0); DCHECK_LE(static_cast<size_t>(start), index_to_value_.size()); int64_t offset = start * static_cast<int32_t>(sizeof(Scalar)); memcpy(out_data, index_to_value_.data() + offset, (size() - start) * sizeof(Scalar)); }
void CopyValues(Scalar* out_data) const { CopyValues(0, out_data); }
const std::vector<Scalar>& values() const { return index_to_value_; }
protected: static constexpr auto cardinality = SmallScalarTraits<Scalar>::cardinality; static_assert(cardinality <= 256, "cardinality too large for direct-addressed table");
uint32_t AsIndex(Scalar value) const { return SmallScalarTraits<Scalar>::AsIndex(value); }
// The last index is reserved for the null element. int32_t value_to_index_[cardinality + 1]; std::vector<Scalar> index_to_value_;};
// ----------------------------------------------------------------------// A memoization table for variable-sized binary data.
template <typename BinaryBuilderT>class BinaryMemoTable : public MemoTable { public: using builder_offset_type = typename BinaryBuilderT::offset_type; explicit BinaryMemoTable(MemoryPool* pool, int64_t entries = 0, int64_t values_size = -1) : hash_table_(pool, static_cast<uint64_t>(entries)), binary_builder_(pool) { const int64_t data_size = (values_size < 0) ? entries * 4 : values_size; DCHECK_OK(binary_builder_.Resize(entries)); DCHECK_OK(binary_builder_.ReserveData(data_size)); }
int32_t Get(const void* data, builder_offset_type length) const { hash_t h = ComputeStringHash<0>(data, length); auto p = Lookup(h, data, length); if (p.second) { return p.first->payload.memo_index; } else { return kKeyNotFound; } }
int32_t Get(std::string_view value) const { return Get(value.data(), static_cast<builder_offset_type>(value.length())); }
template <typename Func1, typename Func2> Status GetOrInsert(const void* data, builder_offset_type length, Func1&& on_found, Func2&& on_not_found, int32_t* out_memo_index) { hash_t h = ComputeStringHash<0>(data, length); auto p = Lookup(h, data, length); int32_t memo_index; if (p.second) { memo_index = p.first->payload.memo_index; on_found(memo_index); } else { memo_index = size(); // Insert string value RETURN_NOT_OK(binary_builder_.Append(static_cast<const char*>(data), length)); // Insert hash entry RETURN_NOT_OK( hash_table_.Insert(const_cast<HashTableEntry*>(p.first), h, {memo_index}));
on_not_found(memo_index); } *out_memo_index = memo_index; return Status::OK(); }
template <typename Func1, typename Func2> Status GetOrInsert(std::string_view value, Func1&& on_found, Func2&& on_not_found, int32_t* out_memo_index) { return GetOrInsert(value.data(), static_cast<builder_offset_type>(value.length()), std::forward<Func1>(on_found), std::forward<Func2>(on_not_found), out_memo_index); }
Status GetOrInsert(const void* data, builder_offset_type length, int32_t* out_memo_index) { return GetOrInsert( data, length, [](int32_t i) {}, [](int32_t i) {}, out_memo_index); }
Status GetOrInsert(std::string_view value, int32_t* out_memo_index) { return GetOrInsert(value.data(), static_cast<builder_offset_type>(value.length()), out_memo_index); }
int32_t GetNull() const { return null_index_; }
template <typename Func1, typename Func2> int32_t GetOrInsertNull(Func1&& on_found, Func2&& on_not_found) { int32_t memo_index = GetNull(); if (memo_index == kKeyNotFound) { memo_index = null_index_ = size(); DCHECK_OK(binary_builder_.AppendNull()); on_not_found(memo_index); } else { on_found(memo_index); } return memo_index; }
int32_t GetOrInsertNull() { return GetOrInsertNull([](int32_t i) {}, [](int32_t i) {}); }
// The number of entries in the memo table // (which is also 1 + the largest memo index) int32_t size() const override { return static_cast<int32_t>(hash_table_.size() + (GetNull() != kKeyNotFound)); }
int64_t values_size() const { return binary_builder_.value_data_length(); }
// Copy (n + 1) offsets starting from index `start` into `out_data` template <class Offset> void CopyOffsets(int32_t start, Offset* out_data) const { DCHECK_LE(start, size());
const builder_offset_type* offsets = binary_builder_.offsets_data(); const builder_offset_type delta = start < binary_builder_.length() ? offsets[start] : 0; for (int32_t i = start; i < size(); ++i) { const builder_offset_type adjusted_offset = offsets[i] - delta; Offset cast_offset = static_cast<Offset>(adjusted_offset); assert(static_cast<builder_offset_type>(cast_offset) == adjusted_offset); // avoid truncation *out_data++ = cast_offset; }
// Copy last value since BinaryBuilder only materializes it on in Finish() *out_data = static_cast<Offset>(binary_builder_.value_data_length() - delta); }
template <class Offset> void CopyOffsets(Offset* out_data) const { CopyOffsets(0, out_data); }
// Copy values starting from index `start` into `out_data` void CopyValues(int32_t start, uint8_t* out_data) const { CopyValues(start, -1, out_data); }
// Same as above, but check output size in debug mode void CopyValues(int32_t start, int64_t out_size, uint8_t* out_data) const { DCHECK_LE(start, size());
// The absolute byte offset of `start` value in the binary buffer. const builder_offset_type offset = binary_builder_.offset(start); const auto length = binary_builder_.value_data_length() - static_cast<size_t>(offset);
if (out_size != -1) { assert(static_cast<int64_t>(length) <= out_size); }
auto view = binary_builder_.GetView(start); memcpy(out_data, view.data(), length); }
void CopyValues(uint8_t* out_data) const { CopyValues(0, -1, out_data); }
void CopyValues(int64_t out_size, uint8_t* out_data) const { CopyValues(0, out_size, out_data); }
void CopyFixedWidthValues(int32_t start, int32_t width_size, int64_t out_size, uint8_t* out_data) const { // This method exists to cope with the fact that the BinaryMemoTable does // not know the fixed width when inserting the null value. The data // buffer hold a zero length string for the null value (if found). // // Thus, the method will properly inject an empty value of the proper width // in the output buffer. // if (start >= size()) { return; }
int32_t null_index = GetNull(); if (null_index < start) { // Nothing to skip, proceed as usual. CopyValues(start, out_size, out_data); return; }
builder_offset_type left_offset = binary_builder_.offset(start);
// Ensure that the data length is exactly missing width_size bytes to fit // in the expected output (n_values * width_size).#ifndef NDEBUG int64_t data_length = values_size() - static_cast<size_t>(left_offset); assert(data_length + width_size == out_size); ARROW_UNUSED(data_length);#endif
auto in_data = binary_builder_.value_data() + left_offset; // The null use 0-length in the data, slice the data in 2 and skip by // width_size in out_data. [part_1][width_size][part_2] auto null_data_offset = binary_builder_.offset(null_index); auto left_size = null_data_offset - left_offset; if (left_size > 0) { memcpy(out_data, in_data + left_offset, left_size); } // Zero-initialize the null entry memset(out_data + left_size, 0, width_size);
auto right_size = values_size() - static_cast<size_t>(null_data_offset); if (right_size > 0) { // skip the null fixed size value. auto out_offset = left_size + width_size; assert(out_data + out_offset + right_size == out_data + out_size); memcpy(out_data + out_offset, in_data + null_data_offset, right_size); } }
// Visit the stored values in insertion order. // The visitor function should have the signature `void(std::string_view)` // or `void(const std::string_view&)`. template <typename VisitFunc> void VisitValues(int32_t start, VisitFunc&& visit) const { for (int32_t i = start; i < size(); ++i) { visit(binary_builder_.GetView(i)); } }
protected: struct Payload { int32_t memo_index; };
using HashTableType = HashTable<Payload>; using HashTableEntry = typename HashTable<Payload>::Entry; HashTableType hash_table_; BinaryBuilderT binary_builder_;
int32_t null_index_ = kKeyNotFound;
std::pair<const HashTableEntry*, bool> Lookup(hash_t h, const void* data, builder_offset_type length) const { auto cmp_func = [&](const Payload* payload) { std::string_view lhs = binary_builder_.GetView(payload->memo_index); std::string_view rhs(static_cast<const char*>(data), length); return lhs == rhs; }; return hash_table_.Lookup(h, cmp_func); }
public: Status MergeTable(const BinaryMemoTable& other_table) { other_table.VisitValues(0, [this](std::string_view other_value) { int32_t unused; DCHECK_OK(this->GetOrInsert(other_value, &unused)); }); return Status::OK(); }};
template <typename T, typename Enable = void>struct HashTraits {};
template <>struct HashTraits<BooleanType> { using MemoTableType = SmallScalarMemoTable<bool>;};
template <typename T>struct HashTraits<T, enable_if_8bit_int<T>> { using c_type = typename T::c_type; using MemoTableType = SmallScalarMemoTable<typename T::c_type>;};
template <typename T>struct HashTraits<T, enable_if_t<has_c_type<T>::value && !is_8bit_int<T>::value>> { using c_type = typename T::c_type; using MemoTableType = ScalarMemoTable<c_type, HashTable>;};
template <typename T>struct HashTraits<T, enable_if_t<has_string_view<T>::value && !std::is_base_of<LargeBinaryType, T>::value>> { using MemoTableType = BinaryMemoTable<BinaryBuilder>;};
template <typename T>struct HashTraits<T, enable_if_decimal<T>> { using MemoTableType = BinaryMemoTable<BinaryBuilder>;};
template <typename T>struct HashTraits<T, enable_if_t<std::is_base_of<LargeBinaryType, T>::value>> { using MemoTableType = BinaryMemoTable<LargeBinaryBuilder>;};
template <typename MemoTableType>static inline Status ComputeNullBitmap(MemoryPool* pool, const MemoTableType& memo_table, int64_t start_offset, int64_t* null_count, std::shared_ptr<Buffer>* null_bitmap) { int64_t dict_length = static_cast<int64_t>(memo_table.size()) - start_offset; int64_t null_index = memo_table.GetNull();
*null_count = 0; *null_bitmap = nullptr;
if (null_index != kKeyNotFound && null_index >= start_offset) { null_index -= start_offset; *null_count = 1; ARROW_ASSIGN_OR_RAISE(*null_bitmap, internal::BitmapAllButOne(pool, dict_length, null_index)); }
return Status::OK();}
struct StringViewHash { // std::hash compatible hasher for use with std::unordered_* // (the std::hash specialization provided by nonstd constructs std::string // temporaries then invokes std::hash<std::string> against those) hash_t operator()(std::string_view value) const { return ComputeStringHash<0>(value.data(), static_cast<int64_t>(value.size())); }};
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137// 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 <cstdint>#include <type_traits>
#include "arrow/status.h"
#include "arrow/util/visibility.h"
namespace arrow {
class DataType;struct ArraySpan;struct Scalar;
namespace internal {
ARROW_EXPORTuint8_t DetectUIntWidth(const uint64_t* values, int64_t length, uint8_t min_width = 1);
ARROW_EXPORTuint8_t DetectUIntWidth(const uint64_t* values, const uint8_t* valid_bytes, int64_t length, uint8_t min_width = 1);
ARROW_EXPORTuint8_t DetectIntWidth(const int64_t* values, int64_t length, uint8_t min_width = 1);
ARROW_EXPORTuint8_t DetectIntWidth(const int64_t* values, const uint8_t* valid_bytes, int64_t length, uint8_t min_width = 1);
ARROW_EXPORTvoid DowncastInts(const int64_t* source, int8_t* dest, int64_t length);
ARROW_EXPORTvoid DowncastInts(const int64_t* source, int16_t* dest, int64_t length);
ARROW_EXPORTvoid DowncastInts(const int64_t* source, int32_t* dest, int64_t length);
ARROW_EXPORTvoid DowncastInts(const int64_t* source, int64_t* dest, int64_t length);
ARROW_EXPORTvoid DowncastUInts(const uint64_t* source, uint8_t* dest, int64_t length);
ARROW_EXPORTvoid DowncastUInts(const uint64_t* source, uint16_t* dest, int64_t length);
ARROW_EXPORTvoid DowncastUInts(const uint64_t* source, uint32_t* dest, int64_t length);
ARROW_EXPORTvoid DowncastUInts(const uint64_t* source, uint64_t* dest, int64_t length);
ARROW_EXPORTvoid UpcastInts(const int32_t* source, int64_t* dest, int64_t length);
template <typename InputInt, typename OutputInt>inline typename std::enable_if<(sizeof(InputInt) >= sizeof(OutputInt))>::type CastInts( const InputInt* source, OutputInt* dest, int64_t length) { DowncastInts(source, dest, length);}
template <typename InputInt, typename OutputInt>inline typename std::enable_if<(sizeof(InputInt) < sizeof(OutputInt))>::type CastInts( const InputInt* source, OutputInt* dest, int64_t length) { UpcastInts(source, dest, length);}
template <typename InputInt, typename OutputInt>ARROW_EXPORT void TransposeInts(const InputInt* source, OutputInt* dest, int64_t length, const int32_t* transpose_map);
ARROW_EXPORTStatus TransposeInts(const DataType& src_type, const DataType& dest_type, const uint8_t* src, uint8_t* dest, int64_t src_offset, int64_t dest_offset, int64_t length, const int32_t* transpose_map);
/// \brief Do vectorized boundschecking of integer-type array indices. The/// indices must be nonnegative and strictly less than the passed upper/// limit (which is usually the length of an array that is being indexed-into).ARROW_EXPORTStatus CheckIndexBounds(const ArraySpan& values, uint64_t upper_limit);
/// \brief Boundscheck integer values to determine if they are all between the/// passed upper and lower limits (inclusive). Upper and lower bounds must be/// the same type as the data and are not currently casted.ARROW_EXPORTStatus CheckIntegersInRange(const ArraySpan& values, const Scalar& bound_lower, const Scalar& bound_upper);
/// \brief Use CheckIntegersInRange to determine whether the passed integers/// can fit safely in the passed integer type. This helps quickly determine if/// integer narrowing (e.g. int64->int32) is safe to do.ARROW_EXPORTStatus IntegersCanFit(const ArraySpan& values, const DataType& target_type);
/// \brief Convenience for boundschecking a single Scalar valueARROW_EXPORTStatus IntegersCanFit(const Scalar& value, const DataType& target_type);
/// Upcast an integer to the largest possible width (currently 64 bits)
template <typename Integer>typename std::enable_if< std::is_integral<Integer>::value && std::is_signed<Integer>::value, int64_t>::typeUpcastInt(Integer v) { return v;}
template <typename Integer>typename std::enable_if< std::is_integral<Integer>::value && std::is_unsigned<Integer>::value, uint64_t>::typeUpcastInt(Integer v) { return v;}
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118// 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 <cstdint>#include <limits>#include <type_traits>
#include "arrow/status.h"#include "arrow/util/macros.h"#include "arrow/util/visibility.h"
// "safe-math.h" includes <intsafe.h> 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 <typename SignedInt>SignedInt SafeSignedAdd(SignedInt u, SignedInt v) { using UnsignedInt = typename std::make_unsigned<SignedInt>::type; return static_cast<SignedInt>(static_cast<UnsignedInt>(u) + static_cast<UnsignedInt>(v));}
/// Signed subtraction with well-defined behaviour on overflow (as unsigned)template <typename SignedInt>SignedInt SafeSignedSubtract(SignedInt u, SignedInt v) { using UnsignedInt = typename std::make_unsigned<SignedInt>::type; return static_cast<SignedInt>(static_cast<UnsignedInt>(u) - static_cast<UnsignedInt>(v));}
/// Signed negation with well-defined behaviour on overflow (as unsigned)template <typename SignedInt>SignedInt SafeSignedNegate(SignedInt u) { using UnsignedInt = typename std::make_unsigned<SignedInt>::type; return static_cast<SignedInt>(~static_cast<UnsignedInt>(u) + 1);}
/// Signed left shift with well-defined behaviour on negative numbers or overflowtemplate <typename SignedInt, typename Shift>SignedInt SafeLeftShift(SignedInt u, Shift shift) { using UnsignedInt = typename std::make_unsigned<SignedInt>::type; return static_cast<SignedInt>(static_cast<UnsignedInt>(u) << shift);}
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452// 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
#ifndef _WIN32#define ARROW_HAVE_SIGACTION 1#endif
#include <atomic>#include <memory>#include <optional>#include <string>#include <utility>#include <vector>
#if ARROW_HAVE_SIGACTION#include <csignal> // Needed for struct sigaction#endif
#include "arrow/result.h"#include "arrow/status.h"#include "arrow/type_fwd.h"#include "arrow/util/macros.h"#include "arrow/util/windows_fixup.h"
namespace arrow::internal {
// NOTE: 8-bit path strings on Windows are encoded using UTF-8.// Using MBCS would fail encoding some paths.
#if defined(_WIN32)using NativePathString = std::wstring;#elseusing NativePathString = std::string;#endif
class ARROW_EXPORT PlatformFilename { public: struct Impl;
~PlatformFilename(); PlatformFilename(); PlatformFilename(const PlatformFilename&); PlatformFilename(PlatformFilename&&); PlatformFilename& operator=(const PlatformFilename&); PlatformFilename& operator=(PlatformFilename&&); explicit PlatformFilename(NativePathString path); explicit PlatformFilename(const NativePathString::value_type* path);
const NativePathString& ToNative() const; std::string ToString() const;
PlatformFilename Parent() const; Result<PlatformFilename> Real() const;
// These functions can fail for character encoding reasons. static Result<PlatformFilename> FromString(std::string_view file_name); Result<PlatformFilename> Join(std::string_view child_name) const;
PlatformFilename Join(const PlatformFilename& child_name) const;
bool operator==(const PlatformFilename& other) const; bool operator!=(const PlatformFilename& other) const;
// Made public to avoid the proliferation of friend declarations. const Impl* impl() const { return impl_.get(); }
private: std::unique_ptr<Impl> impl_;
explicit PlatformFilename(Impl impl);};
/// Create a directory if it doesn't exist.////// Return whether the directory was created.ARROW_EXPORTResult<bool> CreateDir(const PlatformFilename& dir_path);
/// Create a directory and its parents if it doesn't exist.////// Return whether the directory was created.ARROW_EXPORTResult<bool> CreateDirTree(const PlatformFilename& dir_path);
/// Delete a directory's contents (but not the directory itself) if it exists.////// Return whether the directory existed.ARROW_EXPORTResult<bool> DeleteDirContents(const PlatformFilename& dir_path, bool allow_not_found = true);
/// Delete a directory tree if it exists.////// Return whether the directory existed.ARROW_EXPORTResult<bool> DeleteDirTree(const PlatformFilename& dir_path, bool allow_not_found = true);
// Non-recursively list the contents of the given directory.// The returned names are the children's base names, not including dir_path.ARROW_EXPORTResult<std::vector<PlatformFilename>> ListDir(const PlatformFilename& dir_path);
/// Delete a file if it exists.////// Return whether the file existed.ARROW_EXPORTResult<bool> DeleteFile(const PlatformFilename& file_path, bool allow_not_found = true);
/// Return whether a file exists.ARROW_EXPORTResult<bool> FileExists(const PlatformFilename& path);
// TODO expose this more publicly to make it available from io/file.h?/// A RAII wrapper for a file descriptor.////// The underlying file descriptor is automatically closed on destruction./// Moving is supported with well-defined semantics./// Furthermore, closing is idempotent.class ARROW_EXPORT FileDescriptor { public: FileDescriptor() = default; explicit FileDescriptor(int fd) : fd_(fd) {} FileDescriptor(FileDescriptor&&); FileDescriptor& operator=(FileDescriptor&&);
~FileDescriptor();
Status Close();
/// May return -1 if closed or default-initialized int fd() const { return fd_.load(); }
/// Detach and return the underlying file descriptor int Detach();
bool closed() const { return fd_.load() == -1; }
protected: static void CloseFromDestructor(int fd);
std::atomic<int> fd_{-1};};
/// Open a file for reading and return a file descriptor.ARROW_EXPORTResult<FileDescriptor> FileOpenReadable(const PlatformFilename& file_name);
/// Open a file for writing and return a file descriptor.ARROW_EXPORTResult<FileDescriptor> FileOpenWritable(const PlatformFilename& file_name, bool write_only = true, bool truncate = true, bool append = false);
/// Read from current file position. Return number of bytes read.ARROW_EXPORTResult<int64_t> FileRead(int fd, uint8_t* buffer, int64_t nbytes);/// Read from given file position. Return number of bytes read.ARROW_EXPORTResult<int64_t> FileReadAt(int fd, uint8_t* buffer, int64_t position, int64_t nbytes);
ARROW_EXPORTStatus FileWrite(int fd, const uint8_t* buffer, const int64_t nbytes);ARROW_EXPORTStatus FileTruncate(int fd, const int64_t size);
ARROW_EXPORTStatus FileSeek(int fd, int64_t pos);ARROW_EXPORTStatus FileSeek(int fd, int64_t pos, int whence);ARROW_EXPORTResult<int64_t> FileTell(int fd);ARROW_EXPORTResult<int64_t> FileGetSize(int fd);
ARROW_EXPORTStatus FileClose(int fd);
struct Pipe { FileDescriptor rfd; FileDescriptor wfd;
Status Close() { return rfd.Close() & wfd.Close(); }};
ARROW_EXPORTResult<Pipe> CreatePipe();
ARROW_EXPORTStatus SetPipeFileDescriptorNonBlocking(int fd);
class ARROW_EXPORT SelfPipe { public: static Result<std::shared_ptr<SelfPipe>> Make(bool signal_safe); virtual ~SelfPipe();
/// \brief Wait for a wakeup. /// /// Status::Invalid is returned if the pipe has been shutdown. /// Otherwise the next sent payload is returned. virtual Result<uint64_t> Wait() = 0;
/// \brief Wake up the pipe by sending a payload. /// /// This method is async-signal-safe if `signal_safe` was set to true. virtual void Send(uint64_t payload) = 0;
/// \brief Wake up the pipe and shut it down. virtual Status Shutdown() = 0;};
ARROW_EXPORTint64_t GetPageSize();
struct MemoryRegion { void* addr; size_t size;};
ARROW_EXPORTStatus MemoryMapRemap(void* addr, size_t old_size, size_t new_size, int fildes, void** new_addr);ARROW_EXPORTStatus MemoryAdviseWillNeed(const std::vector<MemoryRegion>& regions);
ARROW_EXPORTResult<std::string> GetEnvVar(const char* name);ARROW_EXPORTResult<std::string> GetEnvVar(const std::string& name);ARROW_EXPORTResult<NativePathString> GetEnvVarNative(const char* name);ARROW_EXPORTResult<NativePathString> GetEnvVarNative(const std::string& name);
ARROW_EXPORTStatus SetEnvVar(const char* name, const char* value);ARROW_EXPORTStatus SetEnvVar(const std::string& name, const std::string& value);ARROW_EXPORTStatus DelEnvVar(const char* name);ARROW_EXPORTStatus DelEnvVar(const std::string& name);
ARROW_EXPORTstd::string ErrnoMessage(int errnum);#if _WIN32ARROW_EXPORTstd::string WinErrorMessage(int errnum);#endif
ARROW_EXPORTstd::shared_ptr<StatusDetail> StatusDetailFromErrno(int errnum);ARROW_EXPORTstd::optional<int> ErrnoFromStatusDetail(const StatusDetail& detail);#if _WIN32ARROW_EXPORTstd::shared_ptr<StatusDetail> StatusDetailFromWinError(int errnum);#endifARROW_EXPORTstd::shared_ptr<StatusDetail> StatusDetailFromSignal(int signum);
template <typename... Args>Status StatusFromErrno(int errnum, StatusCode code, Args&&... args) { return Status::FromDetailAndArgs(code, StatusDetailFromErrno(errnum), std::forward<Args>(args)...);}
template <typename... Args>Status IOErrorFromErrno(int errnum, Args&&... args) { return StatusFromErrno(errnum, StatusCode::IOError, std::forward<Args>(args)...);}
#if _WIN32template <typename... Args>Status StatusFromWinError(int errnum, StatusCode code, Args&&... args) { return Status::FromDetailAndArgs(code, StatusDetailFromWinError(errnum), std::forward<Args>(args)...);}
template <typename... Args>Status IOErrorFromWinError(int errnum, Args&&... args) { return StatusFromWinError(errnum, StatusCode::IOError, std::forward<Args>(args)...);}#endif
template <typename... Args>Status StatusFromSignal(int signum, StatusCode code, Args&&... args) { return Status::FromDetailAndArgs(code, StatusDetailFromSignal(signum), std::forward<Args>(args)...);}
template <typename... Args>Status CancelledFromSignal(int signum, Args&&... args) { return StatusFromSignal(signum, StatusCode::Cancelled, std::forward<Args>(args)...);}
ARROW_EXPORTint ErrnoFromStatus(const Status&);
// Always returns 0 on non-Windows platforms (for Python).ARROW_EXPORTint WinErrorFromStatus(const Status&);
ARROW_EXPORTint SignalFromStatus(const Status&);
class ARROW_EXPORT TemporaryDir { public: ~TemporaryDir();
/// '/'-terminated path to the temporary dir const PlatformFilename& path() { return path_; }
/// Create a temporary subdirectory in the system temporary dir, /// named starting with `prefix`. static Result<std::unique_ptr<TemporaryDir>> Make(const std::string& prefix);
private: PlatformFilename path_;
explicit TemporaryDir(PlatformFilename&&);};
class ARROW_EXPORT SignalHandler { public: using Callback = void (*)(int);
SignalHandler(); explicit SignalHandler(Callback cb);#if ARROW_HAVE_SIGACTION explicit SignalHandler(const struct sigaction& sa);#endif
Callback callback() const;#if ARROW_HAVE_SIGACTION const struct sigaction& action() const;#endif
protected:#if ARROW_HAVE_SIGACTION // Storing the full sigaction allows to restore the entire signal handling // configuration. struct sigaction sa_;#else Callback cb_;#endif};
/// \brief Return the current handler for the given signal number.ARROW_EXPORTResult<SignalHandler> GetSignalHandler(int signum);
/// \brief Set a new handler for the given signal number.////// The old signal handler is returned.ARROW_EXPORTResult<SignalHandler> SetSignalHandler(int signum, const SignalHandler& handler);
/// \brief Reinstate the signal handler////// For use in signal handlers. This is needed on platforms without sigaction()/// such as Windows, as the default signal handler is restored there as/// soon as a signal is raised.ARROW_EXPORTvoid ReinstateSignalHandler(int signum, SignalHandler::Callback handler);
/// \brief Send a signal to the current process////// The thread which will receive the signal is unspecified.ARROW_EXPORTStatus SendSignal(int signum);
/// \brief Send a signal to the given thread////// This function isn't supported on Windows.ARROW_EXPORTStatus SendSignalToThread(int signum, uint64_t thread_id);
/// \brief Get an unpredictable random seed////// This function may be slightly costly, so should only be used to initialize/// a PRNG, not to generate a large amount of random numbers./// It is better to use this function rather than std::random_device, unless/// absolutely necessary (e.g. to generate a cryptographic secret).ARROW_EXPORTint64_t GetRandomSeed();
/// \brief Get the current thread id////// In addition to having the same properties as std::thread, the returned value/// is a regular integer value, which is more convenient than an opaque type.ARROW_EXPORTuint64_t GetThreadId();
/// \brief Get the current memory used by the current process in bytes////// This function supports Windows, Linux, and Mac and will return 0 otherwiseARROW_EXPORTint64_t GetCurrentRSS();
/// \brief Get the total memory available to the system in bytes////// This function supports Windows, Linux, and Mac and will return 0 otherwiseARROW_EXPORTint64_t GetTotalMemoryBytes();
/// \brief Load a dynamic library////// This wraps dlopen() except on Windows, where LoadLibrary() is called./// These two platforms handle absolute paths consistently; relative paths/// or the library's bare name may be handled but inconsistently.////// \return An opaque handle for the dynamic library, which can be used for/// subsequent symbol lookup. Nullptr will never be returned; instead/// an error will be raised.ARROW_EXPORT Result<void*> LoadDynamicLibrary(const PlatformFilename& path);
/// \brief Load a dynamic library////// An overload taking null terminated string.ARROW_EXPORT Result<void*> LoadDynamicLibrary(const char* path);
/// \brief Retrieve a symbol by name from a library handle.////// This wraps dlsym() except on Windows, where GetProcAddress() is called.////// \return The address associated with the named symbol. Nullptr will never be/// returned; instead an error will be raised.ARROW_EXPORT Result<void*> GetSymbol(void* handle, const char* name);
template <typename T>Result<T*> GetSymbolAs(void* handle, const char* name) { ARROW_ASSIGN_OR_RAISE(void* sym, GetSymbol(handle, name)); return reinterpret_cast<T*>(sym);}
} // namespace arrow::internalvalley/lib/python3.10/site-packages/pyarrow/include/arrow/python/arrow_to_pandas.hAdded+146
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/benchmark.hAdded+36
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/csv.hAdded+42
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/deserialize.hAdded+106
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/gdb.hAdded+29
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/helpers.hAdded+162
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/inference.hAdded+64
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/init.hAdded+26
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/lib_api.hAdded+201
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/numpy_interop.hAdded+103
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/numpy_to_arrow.hAdded+72
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/parquet_encryption.hAdded+132
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/pch.hAdded+24
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/platform.hAdded+41
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/pyarrow.hAdded+89
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/pyarrow_lib.hAdded+19
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/python_test.hAdded+42
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/python_to_arrow.hAdded+80
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/udf.hAdded+81
valley/lib/python3.10/site-packages/pyarrow/include/arrow/python/visibility.hAdded+39
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/algorithm.hAdded+33
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/align_util.hAdded+221
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator.hAdded+2058
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/async_generator_fwd.hAdded+71
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/base64.hAdded+35
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/binary_view_util.hAdded+95
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap.hAdded+466
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_builders.hAdded+43
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_generate.hAdded+112
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_visit.hAdded+88
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitmap_writer.hAdded+286
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bitset_stack.hAdded+89
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking.hAdded+34
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_avx512.hAdded+28
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/bpacking_neon.hAdded+28
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/checked_cast.hAdded+61
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/compression.hAdded+241
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/converter.hAdded+411
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/counting_semaphore.hAdded+60
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/cpu_info.hAdded+114
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/decimal.hAdded+298
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/delimiting.hAdded+181
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/dict_util.hAdded+28
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/dispatch.hAdded+115
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/formatting.hAdded+656
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/future.hAdded+882
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/hashing.hAdded+944
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util.hAdded+137
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/int_util_overflow.hAdded+118
valley/lib/python3.10/site-packages/pyarrow/include/arrow/util/io_util.hAdded+452