diff --git a/cpp/src/arrow/api.h b/cpp/src/arrow/api.h index 8958eaf1c9ae..1aabee35b10f 100644 --- a/cpp/src/arrow/api.h +++ b/cpp/src/arrow/api.h @@ -38,6 +38,8 @@ #include "arrow/tensor.h" // IYWU pragma: export #include "arrow/type.h" // IYWU pragma: export #include "arrow/util/key_value_metadata.h" // IWYU pragma: export +#include "arrow/visit_array_inline.h" // IYWU pragma: export +#include "arrow/visit_scalar_inline.h" // IYWU pragma: export #include "arrow/visitor.h" // IYWU pragma: export /// \brief Top-level namespace for Apache Arrow C++ API diff --git a/cpp/src/arrow/type_traits.h b/cpp/src/arrow/type_traits.h index 4b4cb5d15d3d..80d7d66f2fdd 100644 --- a/cpp/src/arrow/type_traits.h +++ b/cpp/src/arrow/type_traits.h @@ -85,12 +85,22 @@ TYPE_ID_TRAIT(EXTENSION, ExtensionType) // Per-type type traits // +/// \addtogroup type-traits +/// \brief Base template for type traits of Arrow data types +/// Type traits provide various information about a type at compile time, such +/// as the associated ArrayType, BuilderType, and ScalarType. Not all types +/// provide all information. +/// \tparam T An Arrow data type template struct TypeTraits {}; +/// \brief Base template for type traits of C++ types +/// \tparam T A standard C++ type template struct CTypeTraits {}; +/// \addtogroup type-traits +/// @{ template <> struct TypeTraits { using ArrayType = NullArray; @@ -115,7 +125,9 @@ struct TypeTraits { constexpr static bool is_parameter_free = true; static inline std::shared_ptr type_singleton() { return boolean(); } }; +/// @} +/// \addtogroup c-type-traits template <> struct CTypeTraits : public TypeTraits { using ArrowType = BooleanType; @@ -162,6 +174,8 @@ PRIMITIVE_TYPE_TRAITS_DEF(double, Double, float64) #undef PRIMITIVE_TYPE_TRAITS_DEF #undef PRIMITIVE_TYPE_TRAITS_DEF_ +/// \addtogroup type-traits +/// @{ template <> struct TypeTraits { using ArrayType = Date64Array; @@ -367,6 +381,10 @@ struct TypeTraits { static inline std::shared_ptr type_singleton() { return large_utf8(); } }; +/// @} + +/// \addtogroup c-type-traits +/// @{ template <> struct CTypeTraits : public TypeTraits { using ArrowType = StringType; @@ -383,7 +401,10 @@ struct CTypeTraits : public TypeTraits { using ArrowType = DayTimeIntervalType; }; +/// @} +/// \addtogroup type-traits +/// @{ template <> struct TypeTraits { using ArrayType = ListArray; @@ -426,7 +447,9 @@ struct TypeTraits { using ScalarType = FixedSizeListScalar; constexpr static bool is_parameter_free = false; }; +/// @} +/// \addtogroup c-type-traits template struct CTypeTraits> : public TypeTraits { using ArrowType = ListType; @@ -436,6 +459,8 @@ struct CTypeTraits> : public TypeTraits { } }; +/// \addtogroup type-traits +/// @{ template <> struct TypeTraits { using ArrayType = StructArray; @@ -473,6 +498,7 @@ struct TypeTraits { using ScalarType = ExtensionScalar; constexpr static bool is_parameter_free = false; }; +/// @} namespace internal { @@ -490,6 +516,9 @@ using void_t = typename make_void::type; // Useful type predicates // +/// \addtogroup type-predicates +/// @{ + // only in C++14 template using enable_if_t = typename std::enable_if::type; @@ -813,6 +842,10 @@ template using enable_if_physical_floating_point = enable_if_t::value, R>; +/// @} + +/// \addtogroup runtime-type-predicates +/// @{ static inline bool is_integer(Type::type type_id) { switch (type_id) { case Type::UINT8: @@ -1057,4 +1090,6 @@ static inline int offset_bit_width(Type::type type_id) { return 0; } +/// @} + } // namespace arrow diff --git a/cpp/src/arrow/visit_array_inline.h b/cpp/src/arrow/visit_array_inline.h index ecb9b6d39c36..895cc3744577 100644 --- a/cpp/src/arrow/visit_array_inline.h +++ b/cpp/src/arrow/visit_array_inline.h @@ -29,6 +29,23 @@ namespace arrow { internal::checked_cast::ArrayType&>( \ array)); +/// \brief Apply the visitors Visit() method specialized to the array type +/// +/// \tparam VISITOR Visitor type that implements Visit() for all array types. +/// \return Status +/// +/// A visitor is a type that implements specialized logic for each Arrow type. +/// Example usage: +/// +/// ``` +/// class ExampleVisitor { +/// arrow::Status Visit(arrow::NumericArray arr) { ... } +/// arrow::Status Visit(arrow::NumericArray arr) { ... } +/// ... +/// } +/// ExampleVisitor visitor; +/// VisitArrayInline(some_array, &visitor); +/// ``` template inline Status VisitArrayInline(const Array& array, VISITOR* visitor) { switch (array.type_id()) { diff --git a/cpp/src/arrow/visit_scalar_inline.h b/cpp/src/arrow/visit_scalar_inline.h index cad861b7a009..f3e8108e9c36 100644 --- a/cpp/src/arrow/visit_scalar_inline.h +++ b/cpp/src/arrow/visit_scalar_inline.h @@ -32,6 +32,23 @@ namespace arrow { case TYPE_CLASS##Type::type_id: \ return visitor->Visit(internal::checked_cast(scalar)); +/// \brief Apply the visitors Visit() method specialized to the scalar type +/// +/// \tparam VISITOR Visitor type that implements Visit() for all scalar types. +/// \return Status +/// +/// A visitor is a type that implements specialized logic for each Arrow type. +/// Example usage: +/// +/// ``` +/// class ExampleVisitor { +/// arrow::Status Visit(arrow::Int32Scalar arr) { ... } +/// arrow::Status Visit(arrow::Int64Scalar arr) { ... } +/// ... +/// } +/// ExampleVisitor visitor; +/// VisitScalarInline(some_scalar, &visitor); +/// ``` template inline Status VisitScalarInline(const Scalar& scalar, VISITOR* visitor) { switch (scalar.type->id()) { diff --git a/cpp/src/arrow/visit_type_inline.h b/cpp/src/arrow/visit_type_inline.h index 2b60de2a5e13..6897d12b3cf9 100644 --- a/cpp/src/arrow/visit_type_inline.h +++ b/cpp/src/arrow/visit_type_inline.h @@ -28,6 +28,23 @@ namespace arrow { case TYPE_CLASS##Type::type_id: \ return visitor->Visit(internal::checked_cast(type)); +/// \brief Calls `visitor` with the corresponding concrete type class +/// +/// \tparam VISITOR Visitor type that implements Visit() for all Arrow types. +/// \return Status +/// +/// A visitor is a type that implements specialized logic for each Arrow type. +/// Example usage: +/// +/// ``` +/// class ExampleVisitor { +/// arrow::Status Visit(const arrow::Int32Type& type) { ... } +/// arrow::Status Visit(const arrow::Int64Type& type) { ... } +/// ... +/// } +/// ExampleVisitor visitor; +/// VisitTypeInline(some_type, &visitor); +/// ``` template inline Status VisitTypeInline(const DataType& type, VISITOR* visitor) { switch (type.id()) { @@ -46,7 +63,10 @@ inline Status VisitTypeInline(const DataType& type, VISITOR* visitor) { return visitor->Visit(concrete_ptr); \ } -// Calls `visitor` with a nullptr of the corresponding concrete type class +/// \brief Calls `visitor` with a nullptr of the corresponding concrete type class +/// +/// \tparam VISITOR Visitor type that implements Visit() for all Arrow types. +/// \return Status template inline Status VisitTypeIdInline(Type::type id, VISITOR* visitor) { switch (id) { diff --git a/docs/source/cpp/api/utilities.rst b/docs/source/cpp/api/utilities.rst index 0c29bab80594..a0043ff9ca9a 100644 --- a/docs/source/cpp/api/utilities.rst +++ b/docs/source/cpp/api/utilities.rst @@ -56,3 +56,132 @@ Compression .. doxygenclass:: arrow::util::Decompressor :members: + +Visitors +======== + +.. doxygenfunction:: arrow::VisitTypeInline + :project: arrow_cpp + +.. doxygenfunction:: arrow::VisitTypeIdInline + :project: arrow_cpp + +.. doxygenfunction:: arrow::VisitScalarInline + :project: arrow_cpp + +.. doxygenfunction:: arrow::VisitArrayInline + :project: arrow_cpp + + +.. _type-traits: + +Type Traits +=========== + +These types provide relationships between Arrow types at compile time. :cpp:type:`TypeTraits` +maps Arrow DataTypes to other types, and :cpp:type:`CTypeTraits ` maps C types to +Arrow types. + +TypeTraits +---------- + +Each specialized type defines the following associated types: + +.. cpp:type:: TypeTraits::ArrayType + + Corresponding :doc:`Arrow array type ` + +.. cpp:type:: TypeTraits::BuilderType + + Corresponding :doc:`array builder type ` + +.. cpp:type:: TypeTraits::ScalarType + + Corresponding :doc:`Arrow scalar type ` + +.. cpp:var:: TypeTraits::is_parameter_free + + Whether the type has any type parameters, such as field types in nested types + or scale and precision in decimal types. + + +In addition, the following are defined for many but not all of the types: + +.. cpp:type:: TypeTraits::CType + + Corresponding C type. For example, ``int64_t`` for ``Int64Array``. + +.. cpp:type:: TypeTraits::TensorType + + Corresponding :doc:`Arrow tensor type ` + +.. cpp:function:: static inline constexpr int64_t bytes_required(int64_t elements) + + Return the number of bytes required for given number of elements. Defined for + types with a fixed size. + +.. cpp:function:: static inline std::shared_ptr TypeTraits::type_singleton() + + For types where is_parameter_free is true, returns an instance of the data type. + + +.. doxygengroup:: type-traits + :content-only: + :members: + :undoc-members: + +CTypeTraits +----------- + +Each specialized type defines the following associated types: + +.. cpp:type:: CTypeTraits::ArrowType + + Corresponding :doc:`Arrow type ` + +.. doxygengroup:: c-type-traits + :content-only: + :members: + :undoc-members: + + +.. _type-predicates-api: + +Type Predicates +--------------- + +Type predicates that can be used with templates. Predicates of the form ``is_XXX`` +resolve to constant boolean values, while predicates of the form ``enable_if_XXX`` +resolve to the second type parameter ``R`` if the first parameter ``T`` passes +the test. + +Example usage: + +.. code-block:: cpp + + template + arrow::enable_if_number MyFunction(const TypeClass& type) { + .. + } + + template + arrow::enable_if_number MyFunction(const ArrayType& array) { + .. + } + + +.. doxygengroup:: type-predicates + :content-only: + :members: + :undoc-members: + + +Runtime Type Predicates +----------------------- + +Type predicates that can be applied at runtime. + +.. doxygengroup:: runtime-type-predicates + :content-only: + :members: + :undoc-members: \ No newline at end of file diff --git a/docs/source/cpp/conventions.rst b/docs/source/cpp/conventions.rst index f4167683eabe..07af8f0937ab 100644 --- a/docs/source/cpp/conventions.rst +++ b/docs/source/cpp/conventions.rst @@ -106,17 +106,3 @@ For example:: .. seealso:: :doc:`API reference for error reporting ` -Visitor Pattern ---------------- - -Several types, including :class:`arrow::DataType`, :class:`arrow::Scalar`, and -:class:`arrow::Array`, have sub-types specialized to their corresponding Arrow -types. For example, for the Arrow boolean type there is :class:`arrow::BooleanType`, -:class:`arrow::BooleanScalar`, and :class:`arrow::BooleanArray`. In order to -process these entities, you may need to write write logic that specializes based -on the particular Arrow type. In these cases, use the -`visitor pattern `_. - -Arrow provides abstract visitor classes (:class:`arrow::TypeVisitor`, -:class:`arrow::ScalarVisitor`, :class:`arrow::ArrayVisitor`) and an ``Accept()`` -method on each of the corresponding base types (e.g. :func:`arrow::Array::Accept`). diff --git a/docs/source/cpp/datatypes.rst b/docs/source/cpp/datatypes.rst index 9149420a484f..5428fbd008cf 100644 --- a/docs/source/cpp/datatypes.rst +++ b/docs/source/cpp/datatypes.rst @@ -66,3 +66,141 @@ To instantiate data types, it is recommended to call the provided type = arrow::timestamp(arrow::TimeUnit::MICRO); // A list type of single-precision floating-point values type = arrow::list(arrow::float32()); + + + +Type Traits +----------- + +Writing code that can handle concrete :class:`arrow::DataType` subclasses would +be verbose, if it weren't for type traits. Arrow's type traits map the Arrow +data types to the specialized array, scalar, builder, and other associated types. +For example, the Boolean type has traits: + +.. code-block:: cpp + + template <> + struct TypeTraits { + using ArrayType = BooleanArray; + using BuilderType = BooleanBuilder; + using ScalarType = BooleanScalar; + using CType = bool; + + static constexpr int64_t bytes_required(int64_t elements) { + return bit_util::BytesForBits(elements); + } + constexpr static bool is_parameter_free = true; + static inline std::shared_ptr type_singleton() { return boolean(); } + }; + +See the :ref:`type-traits` for an explanation of each of these fields. + +Using type traits, one can write template functions that can handle a variety +of Arrow types. For example, to write a function that creates an array of +Fibonacci values for any Arrow numeric type: + +.. code-block:: cpp + + template ::BuilderType, + typename ArrayType = typename arrow::TypeTraits::ArrayType, + typename CType = typename arrow::TypeTraits::CType> + arrow::Result> MakeFibonacci(int32_t n) { + BuilderType builder; + CType val = 0; + CType next_val = 1; + for (int32_t i = 0; i < n; ++i) { + builder.Append(val); + CType temp = val + next_val; + val = next_val; + next_val = temp; + } + std::shared_ptr out; + ARROW_RETURN_NOT_OK(builder.Finish(&out)); + return out; + } + +For some common cases, there are type associations on the classes themselves. Use: + +* ``Scalar::TypeClass`` to get data type class of a scalar +* ``Array::TypeClass`` to get data type class of an array +* ``DataType::c_type`` to get associated C type of an Arrow data type + +Similar to the type traits provided in +`std::type_traits `_, +Arrow provides type predicates such as ``is_number_type`` as well as +corresponding templates that wrap ``std::enable_if_t`` such as ``enable_if_number``. +These can constrain template functions to only compile for relevant types, which +is useful if other overloads need to be implemented. For example, to write a sum +function for any numeric (integer or float) array: + +.. code-block:: cpp + + template + arrow::enable_if_number SumArray(const ArrayType& array) { + CType sum = 0; + for (arrow::util::optional value : array) { + if (value.has_value()) { + sum += value.value(); + } + } + return sum; + } + +See :ref:`type-predicates-api` for a list of these. + + +Visitor Pattern +--------------- + +In order to process :class:`arrow::DataType`, :class:`arrow::Scalar`, or +:class:`arrow::Array`, you may need to write write logic that specializes based +on the particular Arrow type. In these cases, use the +`visitor pattern `_. Arrow provides +the template functions: + +* :func:`arrow::VisitTypeInline` +* :func:`arrow::VisitScalarInline` +* :func:`arrow::VisitArrayInline` + +To use these, implement ``Status Visit()`` methods for each specialized type, then +pass the class instance to the inline visit function. To avoid repetitive code, +use type traits as documented in the previous section. As a brief example, +here is how one might sum across columns of arbitrary numeric types: + +.. code-block:: cpp + + class TableSummation { + double partial = 0.0; + public: + + arrow::Result Compute(std::shared_ptr batch) { + for (std::shared_ptr array : batch->columns()) { + ARROW_RETURN_NOT_OK(arrow::VisitArrayInline(*array, this)); + } + return partial; + } + + // Default implementation + arrow::Status Visit(const arrow::Array& array) { + return arrow::Status::NotImplemented("Can not compute sum for array of type ", + array.type()->ToString()); + } + + template + arrow::enable_if_number Visit(const ArrayType& array) { + for (arrow::util::optional value : array) { + if (value.has_value()) { + partial += static_cast(value.value()); + } + } + return arrow::Status::OK(); + } + }; + +Arrow also provides abstract visitor classes (:class:`arrow::TypeVisitor`, +:class:`arrow::ScalarVisitor`, :class:`arrow::ArrayVisitor`) and an ``Accept()`` +method on each of the corresponding base types (e.g. :func:`arrow::Array::Accept`). +However, these are not able to be implemented using template functions, so you +will typically prefer using the inline type visitors. \ No newline at end of file