You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "felipecrv (via GitHub)" <gi...@apache.org> on 2024/04/18 18:06:14 UTC

[PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

felipecrv opened a new pull request, #41297:
URL: https://github.com/apache/arrow/pull/41297

   
   ### Rationale for this change
   
   Introduce utilities for dealing with fixed-width types (including fixed-size lists of fixed-width types) generically. And use it for initial optimizations of `Take` and `Filter`.
   
   
   ### What changes are included in this PR?
   
   - [x] Introduce utilities for dealing with fixed-width types generically
   - [x] Use faster `Take` kernel on small power-of-2 byte widths of fixed-width types
   - [ ] Take on any fixed-width type
   - [ ] Filter
   
   ### Are these changes tested?
   
   By existing and new tests.
   
   ### Are there any user-facing changes?
   
   Some functions added to the `arrow::util` namespace and documented inline.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2093258518

   @ursabot please benchmark lang=R
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "bkietz (via GitHub)" <gi...@apache.org>.
bkietz commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588421228


##########
cpp/src/arrow/util/fixed_width_test.cc:
##########
@@ -0,0 +1,181 @@
+// 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 <cmath>
+// #include <string>
+
+#include <gtest/gtest.h>
+
+#include "arrow/array/array_base.h"
+#include "arrow/array/data.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/type.h"
+#include "arrow/util/fixed_width_internal.h"
+
+namespace arrow::util {
+
+namespace {
+bool NotBool(const DataType& type) { return type.id() != Type::BOOL; }
+bool NotInt32(const DataType& type) { return type.id() != Type::INT32; }
+}  // namespace
+
+class TestFixedWidth : public ::testing::Test {
+ protected:
+  std::shared_ptr<Array> bool_array_array_;
+  std::shared_ptr<Array> int_array_array_;
+  std::shared_ptr<Array> fsl_bool_array_;
+  std::shared_ptr<Array> fsl_int_array_;
+  std::shared_ptr<Array> fsl_int_nulls_array_;
+  std::shared_ptr<Array> fsl_int_inner_nulls_array_;
+
+  std::shared_ptr<DataType> fsl(int32_t list_size,
+                                const std::shared_ptr<DataType>& value_type) {
+    return fixed_size_list(value_type, list_size);
+  }
+
+ public:
+  void SetUp() override {
+    bool_array_array_ = ArrayFromJSON(boolean(), "[true, false, null]");
+    int_array_array_ = ArrayFromJSON(int32(), "[1, 0, null]");
+    fsl_bool_array_ = ArrayFromJSON(fsl(2, boolean()), "[[true, false]]");
+    fsl_int_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3]]");
+    fsl_int_nulls_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], null, [1, 2]]");
+    fsl_int_inner_nulls_array_ =
+        ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3], [null, 2]]");
+  }
+};
+
+TEST_F(TestFixedWidth, IsFixedWidth) {
+  auto arr = ArraySpan{*bool_array_array_->data()};
+  // force_null_count doesn't matter because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotInt32));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+
+  arr = ArraySpan{*int_array_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+}
+
+TEST_F(TestFixedWidth, IsFixedWidthLike) {
+  auto arr = ArraySpan{*fsl_bool_array_->data()};
+  // bools wrapped by fixed-size-list are not fixed-width because the
+  // innermost data buffer is a bitmap and won't byte-align.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  arr = ArraySpan{*fsl_int_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  arr.null_count = kUnknownNullCount;
+  // force_null_count=true isn't necessary because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr.child_data[0].null_count = kUnknownNullCount;
+  // inner nulls are not allowed by IsFixedWidthLike...
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  // ...but forcing null counting at on every internal array increases
+  // the chances of IsFixedWidthLike returning true.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  // Excluding INT32 from the internal array checks.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true, NotInt32));
+
+  arr = ArraySpan{*fsl_int_nulls_array_->data()};
+  // Nulls at the top-level of the array are allowed by IsFixedWidthLike.
+  //
+  // TODO(GH-10157): ArrayFromJSON uses FixedSizeListBuilder which currently
+  // produces nulls on the child data if one of the list-typed elements is null.
+  // ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr = ArraySpan{*fsl_int_inner_nulls_array_->data()};
+  // Inner nulls are not allowed by IsFixedWidthLike.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+}
+
+TEST_F(TestFixedWidth, MeasureWidthInBytes) {
+  auto b = boolean();
+  auto i8 = int8();
+  auto i32 = int32();
+  auto varlen = utf8();

Review Comment:
   You're right, my concern isn't pertinent to this test: I was thinking that the fast path with PrimitiveFilterExec will also be applied to FSB which happens to have small power-of-2 size? For example, the UUID extension type?



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+int64_t FixedWidthInBytes(const DataType& type);

Review Comment:
   I expect most of the Windows failures https://github.com/apache/arrow/actions/runs/8929734699/job/24528249637?pr=41297 are due to the lack of _declspec(dllexport)
   ```suggestion
   ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588286261


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   I pushed a commit removing all the inline code from the `.h` except for the template function.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "conbench-apache-arrow[bot] (via GitHub)" <gi...@apache.org>.
conbench-apache-arrow[bot] commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2093594471

   Thanks for your patience. Conbench analyzed the 6 benchmarking runs that have been run so far on PR commit 0034a043553c75ba5e13768eb5b9ceddbbc5c768.
   
   There were no benchmark performance regressions. 🎉
   
   The [full Conbench report](https://github.com/apache/arrow/runs/24568649715) has more details.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591474754


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.

Review Comment:
   I started without `BOOL` then almost every `IsFixedWidthLike` check in the `Take` kernel had to have `|| type->id() == BOOL`.
   
   Additionally, excluding `BOOL` would put this function in conflict with `is_fixed_width()`. I wanted to preserve the property that the set of arrays that passes this predicate is a superset of the arrays that can pass `is_fixed_width(type->id())`. How could an array be `[Is]FixedWidthLike` if it's not even `[is_]fixed_width()`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "benibus (via GitHub)" <gi...@apache.org>.
benibus commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1579688136


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   What's the intention behind the `*Fallback` functions? Are there plans to introduce faster paths later or are they just meant to hide implementation details?



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(
+    const ArraySpan& source);
+
+/// \pre same as MutableFixedWidthValuesPointer
+/// \pre mutable_array->type->id() == Type::FIXED_SIZE_LIST
+ARROW_EXPORT uint8_t* MutableFixedWidthValuesPointerFallback(
+    ArrayData* mutable_fsl_array);
+
+}  // namespace internal
+
+/// \brief Get the pointer to the fixed-width values of a fixed-width like array.
+///
+/// This function might return NULLPTR if the type of the array is BOOL or
+/// if the pre-conditions listed are not satisfied. The converse is not true
+/// (i.e. not getting NULLPTR doesn't guarantee that source is a fixed-width
+/// like array).
+///
+/// \pre `IsFixedWidthLike(source)` or the more restrictive
+///      is_fixed_width(*mutable_array->type) SHOULD be true
+/// \return The pointer to the fixed-width values of an array or NULLPTR
+///         if pre-conditions are not satisfied.
+inline const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source) {
+  auto type_id = source.type->id();
+  if (ARROW_PREDICT_TRUE(is_fixed_width(type_id))) {
+    if (ARROW_PREDICT_FALSE(type_id == Type::BOOL)) {
+      // BOOL arrays are bit-packed, thus a byte-aligned pointer cannot be produced in the
+      // general case. Returning something for BOOL arrays that happen to byte-align
+      // because offset=0 would create too much confusion.
+      return nullptr;
+    }
+    return source.GetValues<uint8_t>(1, 0) + source.offset * source.type->byte_width();
+  }
+  return internal::OffsetPointerOfFixedWidthValuesFallback(source);
+}
+
+/// \brief Get the mutable pointer to the fixed-width values of an array
+///        allocated by PreallocateFixedWidthArrayData.
+///
+/// \pre mutable_array->offset and the offset of child array (if it's a
+///      FixedSizeList) MUST be 0 (recursively).
+/// \pre IsFixedWidthLike(ArraySpan(mutable_array)) or the more restrictive
+///      is_fixed_width(*mutable_array->type) MUST be true
+/// \return The mutable pointer to the fixed-width byte blocks of the array. If
+///         pre-conditions are not satisfied, the return values is undefined.
+inline uint8_t* MutableFixedWidthValuesPointer(ArrayData* mutable_array) {
+  auto type_id = mutable_array->type->id();
+  if (ARROW_PREDICT_FALSE(type_id == Type::FIXED_SIZE_LIST)) {
+    return internal::MutableFixedWidthValuesPointerFallback(mutable_array);
+  }
+  assert(mutable_array->offset == 0);
+  // BOOL is allowed here only because the offset is expected to be 0,
+  // so the byte-aligned pointer also points to the first *bit* of the buffer.
+  assert(is_fixed_width(type_id));

Review Comment:
   Why use `assert` here instead of `DCHECK`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv merged PR #41297:
URL: https://github.com/apache/arrow/pull/41297


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1592639365


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,

Review Comment:
   I will fix this in one of the `Take` PRs as I want to ensure we zero the values only once.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591478519


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.

Review Comment:
   I explained this in the long comment above. If I were to include BOOL in this, I would have to measure everything in bits and would not be able to produce a base pointer that can be written to with `memcpy` as I do in `OffsetPointerOfFixedWidthValues`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1592441092


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in

Review Comment:
   `\brief` is for a one-liner introductory sentence, but if every non-trivial API function gets a 150-line docstring, then nobody will read them anymore (and, besides, even the source code will become impossible to navigate).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2093636978

   @ursabot please benchmark lang=C++


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591489407


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+}  // namespace internal
+
+/// \brief Get the pointer to the fixed-width values of a fixed-width like array.
+///
+/// This function might return NULLPTR if the type of the array is BOOL or
+/// if the pre-conditions listed are not satisfied. The converse is not true
+/// (i.e. not getting NULLPTR doesn't guarantee that source is a fixed-width
+/// like array).
+///
+/// \pre `IsFixedWidthLike(source)` or the more restrictive
+///      is_fixed_width(*mutable_array->type) SHOULD be true
+/// \return The pointer to the fixed-width values of an array or NULLPTR
+///         if pre-conditions are not satisfied.
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source);

Review Comment:
   The inconsistency with `MutableFixedWidthValuesPointer` was on purpose because that one requires the input to have `offset==0`.
   
   > Most if not all API functions operating on arrays take the offset into account...
   
   And the pointers they return can easily have the offset applied to them after the fact. I gave the `Offset-` prefix to this one so it works as a reminder to the caller that `ptr + arr.offset` won't work (it might by accident), but it's not correct for the general case. The actual offset is a complicated sum of offset products.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591058749


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count

Review Comment:
   Is this parameter actually useful?



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.

Review Comment:
   You need to add `\param` entries for all parameters if you have any of them. I'm expecting this docstring to fail on some compilers such as clang when the corresponding warnings are enabled.



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in

Review Comment:
   In general, it's nice for docstrings to be precise and explanatory, but a 150-lines long docstring ensures that most readers won't read it in entirety. Can you try to distill it down a bit?



##########
cpp/src/arrow/util/fixed_width_test_util.h:
##########
@@ -0,0 +1,203 @@
+// 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 <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+#include "arrow/array/builder_primitive.h"
+#include "arrow/builder.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::util::internal {
+
+class NestedListGenerator {
+ public:
+  /// \brief Create a nested FixedSizeListType.
+  ///
+  /// \return `fixed_size_list(fixed_size_list(..., sizes[1]), sizes[0])`
+  static std::shared_ptr<DataType> NestedFSLType(

Review Comment:
   Most function definitions here should be moved into a dedicated `.cc` file. This would also avoid including too much in this header file, such as `builder.h` and `builder_primitive.h`.



##########
cpp/src/arrow/util/fixed_width_test_util.h:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   Can this file please be moved into `arrow/testing`, since those are testing utilities?



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.

Review Comment:
   What does byte alignment have to do with it? This seems extremely specialized.



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,

Review Comment:
   This could pretty much take a `MemoryPool*` instead of the `KernelContext*`.



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+}  // namespace internal
+
+/// \brief Get the pointer to the fixed-width values of a fixed-width like array.
+///
+/// This function might return NULLPTR if the type of the array is BOOL or
+/// if the pre-conditions listed are not satisfied. The converse is not true
+/// (i.e. not getting NULLPTR doesn't guarantee that source is a fixed-width
+/// like array).
+///
+/// \pre `IsFixedWidthLike(source)` or the more restrictive
+///      is_fixed_width(*mutable_array->type) SHOULD be true
+/// \return The pointer to the fixed-width values of an array or NULLPTR
+///         if pre-conditions are not satisfied.
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source);
+
+/// \brief Get the mutable pointer to the fixed-width values of an array
+///        allocated by PreallocateFixedWidthArrayData.
+///
+/// \pre mutable_array->offset and the offset of child array (if it's a
+///      FixedSizeList) MUST be 0 (recursively).

Review Comment:
   Why is that? It would cost almost nothing to compute the proper physical offset.



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.

Review Comment:
   This is a rather weird API design choice. Won't it confuse callers?



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+}  // namespace internal
+
+/// \brief Get the pointer to the fixed-width values of a fixed-width like array.
+///
+/// This function might return NULLPTR if the type of the array is BOOL or
+/// if the pre-conditions listed are not satisfied. The converse is not true
+/// (i.e. not getting NULLPTR doesn't guarantee that source is a fixed-width
+/// like array).
+///
+/// \pre `IsFixedWidthLike(source)` or the more restrictive
+///      is_fixed_width(*mutable_array->type) SHOULD be true
+/// \return The pointer to the fixed-width values of an array or NULLPTR
+///         if pre-conditions are not satisfied.
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source);

Review Comment:
   Most if not all API functions operating on arrays take the offset into account, so adding "Offset" to the function name does not bring any additional information. `FixedWidthValuesPointer` would be shorter and more consistent with `MutableFixedWidthValuesPointer` below.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1580296198


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   For instance, loop I just wrote:
   
   ```cpp
     for (size_t i = 0; i < num_chunks; ++i) {
       const ArraySpan chunk{*chunks[i]->data()};
       if (chunk.type->id() == Type::BOOL) {
         src_chunks_[i] = chunk.GetValues<uint8_t>(1, 0);
         src_offsets_[i] = chunk.offset;
       } else {
         src_chunks_[i] = util::OffsetPointerOfFixedWidthValues(chunk);
         src_offsets_[i] = 0;
       }
     }
   ```
   
   The inliner can consider what to do with the conditional checks in `OffsetPointerOfFixedWidthValues` in this specific context where the type id is known to not be `BOOL` and the fallback call ensures body of the loop is small: less instruction decoding and potential I-cache waste.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "benibus (via GitHub)" <gi...@apache.org>.
benibus commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1580079298


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   Sounds good! Thanks for the explanation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591502216


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in

Review Comment:
   Isn't that what `\brief` is for? It's rather long because of the examples.
   
   Without them, it's really hard to understand the intricacies of this concept.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1594702143


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in

Review Comment:
   Changed this in #41597.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "ursabot (via GitHub)" <gi...@apache.org>.
ursabot commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2093258682

   Benchmark runs are scheduled for commit 0034a043553c75ba5e13768eb5b9ceddbbc5c768. Watch https://buildkite.com/apache-arrow and https://conbench.ursa.dev for updates. A comment will be posted here when the runs are complete.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "bkietz (via GitHub)" <gi...@apache.org>.
bkietz commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1587864064


##########
cpp/src/arrow/compute/kernels/vector_selection_take_internal.cc:
##########
@@ -333,33 +334,36 @@ using TakeState = OptionsWrapper<TakeOptions>;
 /// use the logical Arrow type but rather the physical C type. This way we
 /// only generate one take function for each byte width.
 ///
-/// This function assumes that the indices have been boundschecked.
+/// Also note that this function can also handle fixed-size-list arrays if
+/// they fit the criteria described in fixed_width_internal.h, so use the
+/// function defined in that file to access values and destination pointers
+/// and DO NOT ASSUME `values.type()` is a primitive type.
+///
+/// \pre the indices have been boundschecked
 template <typename IndexCType, typename ValueWidthConstant>
 struct PrimitiveTakeImpl {
   static constexpr int kValueWidth = ValueWidthConstant::value;
 
   static void Exec(const ArraySpan& values, const ArraySpan& indices,
                    ArrayData* out_arr) {
-    DCHECK_EQ(values.type->byte_width(), kValueWidth);
-    const auto* values_data =
-        values.GetValues<uint8_t>(1, 0) + kValueWidth * values.offset;
+    DCHECK_EQ(util::FixedWidthInBytes(*values.type), kValueWidth);
+    const auto* values_data = util::OffsetPointerOfFixedWidthValues(values);
     const uint8_t* values_is_valid = values.buffers[0].data;
     auto values_offset = values.offset;
 
     const auto* indices_data = indices.GetValues<IndexCType>(1);
     const uint8_t* indices_is_valid = indices.buffers[0].data;
     auto indices_offset = indices.offset;
 
-    auto out = out_arr->GetMutableValues<uint8_t>(1, 0) + kValueWidth * out_arr->offset;
+    DCHECK_EQ(out_arr->offset, 0);
+    auto* out = util::MutableFixedWidthValuesPointer(out_arr);
     auto out_is_valid = out_arr->buffers[0]->mutable_data();
-    auto out_offset = out_arr->offset;

Review Comment:
   :+1:



##########
cpp/src/arrow/util/fixed_width_test.cc:
##########
@@ -0,0 +1,181 @@
+// 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 <cmath>
+// #include <string>
+
+#include <gtest/gtest.h>
+
+#include "arrow/array/array_base.h"
+#include "arrow/array/data.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/type.h"
+#include "arrow/util/fixed_width_internal.h"
+
+namespace arrow::util {
+
+namespace {
+bool NotBool(const DataType& type) { return type.id() != Type::BOOL; }
+bool NotInt32(const DataType& type) { return type.id() != Type::INT32; }
+}  // namespace
+
+class TestFixedWidth : public ::testing::Test {
+ protected:
+  std::shared_ptr<Array> bool_array_array_;
+  std::shared_ptr<Array> int_array_array_;
+  std::shared_ptr<Array> fsl_bool_array_;
+  std::shared_ptr<Array> fsl_int_array_;
+  std::shared_ptr<Array> fsl_int_nulls_array_;
+  std::shared_ptr<Array> fsl_int_inner_nulls_array_;
+
+  std::shared_ptr<DataType> fsl(int32_t list_size,
+                                const std::shared_ptr<DataType>& value_type) {
+    return fixed_size_list(value_type, list_size);
+  }
+
+ public:
+  void SetUp() override {
+    bool_array_array_ = ArrayFromJSON(boolean(), "[true, false, null]");
+    int_array_array_ = ArrayFromJSON(int32(), "[1, 0, null]");
+    fsl_bool_array_ = ArrayFromJSON(fsl(2, boolean()), "[[true, false]]");
+    fsl_int_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3]]");
+    fsl_int_nulls_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], null, [1, 2]]");
+    fsl_int_inner_nulls_array_ =
+        ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3], [null, 2]]");
+  }
+};
+
+TEST_F(TestFixedWidth, IsFixedWidth) {
+  auto arr = ArraySpan{*bool_array_array_->data()};
+  // force_null_count doesn't matter because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotInt32));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+
+  arr = ArraySpan{*int_array_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+}
+
+TEST_F(TestFixedWidth, IsFixedWidthLike) {
+  auto arr = ArraySpan{*fsl_bool_array_->data()};
+  // bools wrapped by fixed-size-list are not fixed-width because the
+  // innermost data buffer is a bitmap and won't byte-align.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  arr = ArraySpan{*fsl_int_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  arr.null_count = kUnknownNullCount;
+  // force_null_count=true isn't necessary because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr.child_data[0].null_count = kUnknownNullCount;
+  // inner nulls are not allowed by IsFixedWidthLike...
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  // ...but forcing null counting at on every internal array increases
+  // the chances of IsFixedWidthLike returning true.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  // Excluding INT32 from the internal array checks.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true, NotInt32));
+
+  arr = ArraySpan{*fsl_int_nulls_array_->data()};
+  // Nulls at the top-level of the array are allowed by IsFixedWidthLike.
+  //
+  // TODO(GH-10157): ArrayFromJSON uses FixedSizeListBuilder which currently
+  // produces nulls on the child data if one of the list-typed elements is null.
+  // ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr = ArraySpan{*fsl_int_inner_nulls_array_->data()};
+  // Inner nulls are not allowed by IsFixedWidthLike.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+}
+
+TEST_F(TestFixedWidth, MeasureWidthInBytes) {
+  auto b = boolean();
+  auto i8 = int8();
+  auto i32 = int32();
+  auto varlen = utf8();

Review Comment:
   Should this also exercise dictionary?



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width

Review Comment:
   I think it'd be better to remove this parameter. I don't see any calls to this function outside test cases where dictionary types would be allowed except in [PrimitiveFilterExec](https://github.com/apache/arrow/pull/41297/files#diff-4cfb0a80bffceb56ab86e33ed3079239d4d5b624ff962d8a0d89315202dbf646R472)... which confusingly is mentioned to not support dictionary in another comment https://github.com/apache/arrow/pull/41297/files#diff-ba605eb57f856219c34f6c5fbf3ab1601d9705bf1ead3d2181b9808f03df823eR902-R903
   
   If we do need to allow dictionary sometimes, `bool allow_dictionary` should be sufficient



##########
cpp/src/arrow/util/fixed_width_test_util.h:
##########
@@ -0,0 +1,203 @@
+// 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 <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+#include "arrow/array/builder_primitive.h"
+#include "arrow/builder.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::util::internal {
+
+class NestedListGenerator {
+ public:
+  /// \brief Create a nested FixedSizeListType.
+  ///
+  /// \return `fixed_size_list(fixed_size_list(..., sizes[1]), sizes[0])`
+  static std::shared_ptr<DataType> NestedFSLType(
+      const std::shared_ptr<DataType>& inner_type, const std::vector<int>& sizes) {
+    auto type = inner_type;
+    for (auto it = sizes.rbegin(); it != sizes.rend(); it++) {
+      type = fixed_size_list(std::move(type), *it);
+    }
+    return type;
+  }
+
+  /// \brief Create a nested FixedListType.
+  ///
+  /// \return `list(list(...))`
+  static std::shared_ptr<DataType> NestedListType(
+      const std::shared_ptr<DataType>& inner_type, size_t depth) {
+    auto list_type = list(inner_type);
+    for (size_t i = 1; i < depth; i++) {
+      list_type = list(std::move(list_type));
+    }
+    return list_type;
+  }
+
+ private:
+  template <typename ArrowType>
+  static Status AppendNumeric(ArrayBuilder* builder, int64_t* next_value) {

Review Comment:
   IIUC this could be simplified with
   ```c++
   template <typename T>
   Result<std::shared_ptr<Buffer>> IotaBuffer(int64_t length, T increment) {
     ARROW_ASSIGN_OR_RAISE(auto buf, AllocateBuffer(sizeof(T) * length));
     T value = 0;
     for (T& element : buf->mutable_span_as<T>()) {
       element = value;
       value += incrememnt; // handle overflow...
     }
     return buf;
   }
   ```
   
   This could be used to build the values in the non-list array, and to create the offsets for the nested list array.



##########
cpp/src/arrow/util/fixed_width_test.cc:
##########
@@ -0,0 +1,181 @@
+// 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 <cmath>
+// #include <string>
+
+#include <gtest/gtest.h>
+
+#include "arrow/array/array_base.h"
+#include "arrow/array/data.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/type.h"
+#include "arrow/util/fixed_width_internal.h"
+
+namespace arrow::util {
+
+namespace {
+bool NotBool(const DataType& type) { return type.id() != Type::BOOL; }
+bool NotInt32(const DataType& type) { return type.id() != Type::INT32; }
+}  // namespace
+
+class TestFixedWidth : public ::testing::Test {
+ protected:
+  std::shared_ptr<Array> bool_array_array_;
+  std::shared_ptr<Array> int_array_array_;
+  std::shared_ptr<Array> fsl_bool_array_;
+  std::shared_ptr<Array> fsl_int_array_;
+  std::shared_ptr<Array> fsl_int_nulls_array_;
+  std::shared_ptr<Array> fsl_int_inner_nulls_array_;
+
+  std::shared_ptr<DataType> fsl(int32_t list_size,
+                                const std::shared_ptr<DataType>& value_type) {
+    return fixed_size_list(value_type, list_size);
+  }
+
+ public:
+  void SetUp() override {
+    bool_array_array_ = ArrayFromJSON(boolean(), "[true, false, null]");
+    int_array_array_ = ArrayFromJSON(int32(), "[1, 0, null]");
+    fsl_bool_array_ = ArrayFromJSON(fsl(2, boolean()), "[[true, false]]");
+    fsl_int_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3]]");
+    fsl_int_nulls_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], null, [1, 2]]");
+    fsl_int_inner_nulls_array_ =
+        ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3], [null, 2]]");
+  }
+};
+
+TEST_F(TestFixedWidth, IsFixedWidth) {
+  auto arr = ArraySpan{*bool_array_array_->data()};
+  // force_null_count doesn't matter because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotInt32));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+
+  arr = ArraySpan{*int_array_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+}
+
+TEST_F(TestFixedWidth, IsFixedWidthLike) {
+  auto arr = ArraySpan{*fsl_bool_array_->data()};
+  // bools wrapped by fixed-size-list are not fixed-width because the
+  // innermost data buffer is a bitmap and won't byte-align.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  arr = ArraySpan{*fsl_int_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  arr.null_count = kUnknownNullCount;
+  // force_null_count=true isn't necessary because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr.child_data[0].null_count = kUnknownNullCount;
+  // inner nulls are not allowed by IsFixedWidthLike...
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  // ...but forcing null counting at on every internal array increases
+  // the chances of IsFixedWidthLike returning true.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  // Excluding INT32 from the internal array checks.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true, NotInt32));
+
+  arr = ArraySpan{*fsl_int_nulls_array_->data()};
+  // Nulls at the top-level of the array are allowed by IsFixedWidthLike.
+  //
+  // TODO(GH-10157): ArrayFromJSON uses FixedSizeListBuilder which currently
+  // produces nulls on the child data if one of the list-typed elements is null.
+  // ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr = ArraySpan{*fsl_int_inner_nulls_array_->data()};
+  // Inner nulls are not allowed by IsFixedWidthLike.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+}
+
+TEST_F(TestFixedWidth, MeasureWidthInBytes) {
+  auto b = boolean();
+  auto i8 = int8();
+  auto i32 = int32();
+  auto varlen = utf8();

Review Comment:
   ... and fixed size binary?



##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   In general I'm skeptical that we need these functions to inline so aggressively. AFAICT, they'll only be used in loops over chunks or for pre-allocation before a hot loop. Am I missing something?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "ursabot (via GitHub)" <gi...@apache.org>.
ursabot commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2093637036

   Commit 0034a043553c75ba5e13768eb5b9ceddbbc5c768 already has scheduled benchmark runs.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1592437240


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.

Review Comment:
   My "weird API design choice" comment was about the "if not nested under FSL" part :-)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588271994


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width

Review Comment:
   I'm adding a version that takes `bool exclude_dictionary=false` and keeping the templated version because it's very possible that a kernel under development (unlike `Take`) doesn't handle all fixed-width types right away (e.g. it could be handling only the power-of-2 sizes and not the arbitrary-length types).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591497159


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+}  // namespace internal
+
+/// \brief Get the pointer to the fixed-width values of a fixed-width like array.
+///
+/// This function might return NULLPTR if the type of the array is BOOL or
+/// if the pre-conditions listed are not satisfied. The converse is not true
+/// (i.e. not getting NULLPTR doesn't guarantee that source is a fixed-width
+/// like array).
+///
+/// \pre `IsFixedWidthLike(source)` or the more restrictive
+///      is_fixed_width(*mutable_array->type) SHOULD be true
+/// \return The pointer to the fixed-width values of an array or NULLPTR
+///         if pre-conditions are not satisfied.
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source);
+
+/// \brief Get the mutable pointer to the fixed-width values of an array
+///        allocated by PreallocateFixedWidthArrayData.
+///
+/// \pre mutable_array->offset and the offset of child array (if it's a
+///      FixedSizeList) MUST be 0 (recursively).

Review Comment:
   Yes, it would be the same code I wrote for doing just that in `OffsetPointerOfFixedWidthValues` but it seemed overkill to bother with offsets on output arrays allocated by `PreallocateFixedWidthArrayData`. This `offset==0` requirement also makes it possible to use this on `BOOL` arrays.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591479789


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.

Review Comment:
   I never had problems omitting `\param` for obvious parameters like `KernelContext* ctx`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591510419


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+}  // namespace internal
+
+/// \brief Get the pointer to the fixed-width values of a fixed-width like array.
+///
+/// This function might return NULLPTR if the type of the array is BOOL or
+/// if the pre-conditions listed are not satisfied. The converse is not true
+/// (i.e. not getting NULLPTR doesn't guarantee that source is a fixed-width
+/// like array).
+///
+/// \pre `IsFixedWidthLike(source)` or the more restrictive
+///      is_fixed_width(*mutable_array->type) SHOULD be true
+/// \return The pointer to the fixed-width values of an array or NULLPTR
+///         if pre-conditions are not satisfied.
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source);
+
+/// \brief Get the mutable pointer to the fixed-width values of an array
+///        allocated by PreallocateFixedWidthArrayData.
+///
+/// \pre mutable_array->offset and the offset of child array (if it's a
+///      FixedSizeList) MUST be 0 (recursively).

Review Comment:
   If I extend these functions to support bit-sized types I will write a function that returns an (offset, ptr) pair instead of just a pointer.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591512334


##########
cpp/src/arrow/util/fixed_width_test_util.h:
##########
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   Opened #41558



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1592441751


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.

Review Comment:
   Hmm, weird. It *used* to trigger warnings on some builds, but perhaps that was relaxed recently...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1579984364


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   It's to allow the hot code path to be inlined while the cold code stays behind the function call.
   
   ```cpp
   inline const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source) {
     auto type_id = source.type->id();
     if (ARROW_PREDICT_TRUE(is_fixed_width(type_id))) {
       if (ARROW_PREDICT_FALSE(type_id == Type::BOOL)) {
         // BOOL arrays are bit-packed, thus a byte-aligned pointer cannot be produced in the
         // general case. Returning something for BOOL arrays that happen to byte-align
         // because offset=0 would create too much confusion.
         return nullptr;
       }
       return source.GetValues<uint8_t>(1, 0) + source.offset * source.type->byte_width();
     }
     return internal::OffsetPointerOfFixedWidthValuesFallback(source);
   }
   ```
   
   This is good for binary size while still allowing code like
   
   ```cpp
   if (is_fixed_width(array.type->id())) {
     auto ptr = OffsetPointerOfFixedWidthValues(array);
     ptr->...
   }
   ```
   
   to lower to the equivalent of
   
   ```cpp
   return source.GetValues<uint8_t>(1, 0) + source.offset * source.type->byte_width();
   ```
   
   The binary size savings add up because the number of templates specializations using these functions is a proportional to `O(number of small powers-of-2 * index types * ...)` and replacing a `GetValues` call with `OffsetPointerOfFixedWidthValues` costs nothing for the common fixed-width types.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591512744


##########
cpp/src/arrow/util/fixed_width_test_util.h:
##########
@@ -0,0 +1,203 @@
+// 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 <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+#include "arrow/array/builder_primitive.h"
+#include "arrow/builder.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::util::internal {
+
+class NestedListGenerator {
+ public:
+  /// \brief Create a nested FixedSizeListType.
+  ///
+  /// \return `fixed_size_list(fixed_size_list(..., sizes[1]), sizes[0])`
+  static std::shared_ptr<DataType> NestedFSLType(

Review Comment:
   Will do that in #41558 as well.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588103560


##########
cpp/src/arrow/util/fixed_width_test_util.h:
##########
@@ -0,0 +1,203 @@
+// 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 <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+#include "arrow/array/builder_primitive.h"
+#include "arrow/builder.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::util::internal {
+
+class NestedListGenerator {
+ public:
+  /// \brief Create a nested FixedSizeListType.
+  ///
+  /// \return `fixed_size_list(fixed_size_list(..., sizes[1]), sizes[0])`
+  static std::shared_ptr<DataType> NestedFSLType(
+      const std::shared_ptr<DataType>& inner_type, const std::vector<int>& sizes) {
+    auto type = inner_type;
+    for (auto it = sizes.rbegin(); it != sizes.rend(); it++) {
+      type = fixed_size_list(std::move(type), *it);
+    }
+    return type;
+  }
+
+  /// \brief Create a nested FixedListType.
+  ///
+  /// \return `list(list(...))`
+  static std::shared_ptr<DataType> NestedListType(
+      const std::shared_ptr<DataType>& inner_type, size_t depth) {
+    auto list_type = list(inner_type);
+    for (size_t i = 1; i < depth; i++) {
+      list_type = list(std::move(list_type));
+    }
+    return list_type;
+  }
+
+ private:
+  template <typename ArrowType>
+  static Status AppendNumeric(ArrayBuilder* builder, int64_t* next_value) {

Review Comment:
   I don't understand. My function calls `Append` on a values builder, yours allocates a `Buffer`. If I go this route, I will have to use very low-level code to build the other buffers of the lists. I would do that in production code, but this is test code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588076996


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   I'm not inlining the entire function, just the cases where it lowers to a simple `GetValues` and exposing the conditionals so the compiler can avoid performing redundant checks where possible.
   
   I understand it looks obsessive, but do you want me to put effort to undo this work?
   
   Keeping the top-level checks in the header also serves as documentation.
   
   ```cpp
   const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source) {
     auto type_id = source.type->id();
     if (ARROW_PREDICT_TRUE(is_fixed_width(type_id))) {
       if (ARROW_PREDICT_FALSE(type_id == Type::BOOL)) {
         // BOOL arrays are bit-packed, thus a byte-aligned pointer cannot be produced in the
         // general case. Returning something for BOOL arrays that happen to byte-align
         // because offset=0 would create too much confusion.
         return nullptr;
       }
       return source.GetValues<uint8_t>(1, 0) + source.offset * source.type->byte_width();
     }
     return internal::OffsetPointerOfFixedWidthValuesFallback(source);
   }
   ```
   
   This is how I use it in a loop
   
   ```cpp
     src_chunks_.resize(chunks.size());
     for (size_t i = 0; i < chunks.size(); ++i) {
       const ArraySpan chunk{*chunks[i]->data()};
       DCHECK(util::IsFixedWidthLike(chunk));
       if (chunk.type->id() == Type::BOOL) {
         src_chunks_[i] = chunk.GetValues<uint8_t>(1, 0);
       } else {
         src_chunks_[i] = util::OffsetPointerOfFixedWidthValues(chunk);
       }
     }
   ```
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588076996


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   I'm not inlining the entire function, just the cases where it lowers to a simple `GetValues` and exposing the conditionals so the compiler can avoid performing redundant checks where possible.
   
   I understand it looks obsessive, but do you want me to put effort to undo this work?
   
   Keeping the top-level checks in the header also serves as documentation.
   
   ```
   const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source) {
     auto type_id = source.type->id();
     if (ARROW_PREDICT_TRUE(is_fixed_width(type_id))) {
       if (ARROW_PREDICT_FALSE(type_id == Type::BOOL)) {
         // BOOL arrays are bit-packed, thus a byte-aligned pointer cannot be produced in the
         // general case. Returning something for BOOL arrays that happen to byte-align
         // because offset=0 would create too much confusion.
         return nullptr;
       }
       return source.GetValues<uint8_t>(1, 0) + source.offset * source.type->byte_width();
     }
     return internal::OffsetPointerOfFixedWidthValuesFallback(source);
   }
   ```
   
   This is how I use it in a loop
   
   ```cpp
     src_chunks_.resize(chunks.size());
     for (size_t i = 0; i < chunks.size(); ++i) {
       const ArraySpan chunk{*chunks[i]->data()};
       DCHECK(util::IsFixedWidthLike(chunk));
       if (chunk.type->id() == Type::BOOL) {
         src_chunks_[i] = chunk.GetValues<uint8_t>(1, 0);
       } else {
         src_chunks_[i] = util::OffsetPointerOfFixedWidthValues(chunk);
       }
     }
   ```
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2091796762

   @bkietz linker errors fixed.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1592618072


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in

Review Comment:
   I will remove the comments from the `///` and spread the explanation, but I think this concept is complicated enough that having a long comment in the source code is worth it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591481068


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,

Review Comment:
   That's what I'm solving soon, but I couldn't do it easily because the allocators in `KernelContext` zero-initialize the buffers unlike the allocators in the `MemoryPool`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2096840738

   @pitrou replied to your comments, please resolve the ones that you think are acceptable and discuss further the ones you still think need to be addressed.
   
   Many questions revolve around the handling of `BOOL` and offsets. Do you think I should extend this to support `BOOL` as well? With all the extra complexity that would bring?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2091282216

   This push was just a rebase. Fixes coming next.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588450139


##########
cpp/src/arrow/util/fixed_width_test.cc:
##########
@@ -0,0 +1,181 @@
+// 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 <cmath>
+// #include <string>
+
+#include <gtest/gtest.h>
+
+#include "arrow/array/array_base.h"
+#include "arrow/array/data.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/type.h"
+#include "arrow/util/fixed_width_internal.h"
+
+namespace arrow::util {
+
+namespace {
+bool NotBool(const DataType& type) { return type.id() != Type::BOOL; }
+bool NotInt32(const DataType& type) { return type.id() != Type::INT32; }
+}  // namespace
+
+class TestFixedWidth : public ::testing::Test {
+ protected:
+  std::shared_ptr<Array> bool_array_array_;
+  std::shared_ptr<Array> int_array_array_;
+  std::shared_ptr<Array> fsl_bool_array_;
+  std::shared_ptr<Array> fsl_int_array_;
+  std::shared_ptr<Array> fsl_int_nulls_array_;
+  std::shared_ptr<Array> fsl_int_inner_nulls_array_;
+
+  std::shared_ptr<DataType> fsl(int32_t list_size,
+                                const std::shared_ptr<DataType>& value_type) {
+    return fixed_size_list(value_type, list_size);
+  }
+
+ public:
+  void SetUp() override {
+    bool_array_array_ = ArrayFromJSON(boolean(), "[true, false, null]");
+    int_array_array_ = ArrayFromJSON(int32(), "[1, 0, null]");
+    fsl_bool_array_ = ArrayFromJSON(fsl(2, boolean()), "[[true, false]]");
+    fsl_int_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3]]");
+    fsl_int_nulls_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], null, [1, 2]]");
+    fsl_int_inner_nulls_array_ =
+        ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3], [null, 2]]");
+  }
+};
+
+TEST_F(TestFixedWidth, IsFixedWidth) {
+  auto arr = ArraySpan{*bool_array_array_->data()};
+  // force_null_count doesn't matter because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotInt32));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+
+  arr = ArraySpan{*int_array_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+}
+
+TEST_F(TestFixedWidth, IsFixedWidthLike) {
+  auto arr = ArraySpan{*fsl_bool_array_->data()};
+  // bools wrapped by fixed-size-list are not fixed-width because the
+  // innermost data buffer is a bitmap and won't byte-align.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  arr = ArraySpan{*fsl_int_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  arr.null_count = kUnknownNullCount;
+  // force_null_count=true isn't necessary because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr.child_data[0].null_count = kUnknownNullCount;
+  // inner nulls are not allowed by IsFixedWidthLike...
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  // ...but forcing null counting at on every internal array increases
+  // the chances of IsFixedWidthLike returning true.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  // Excluding INT32 from the internal array checks.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true, NotInt32));
+
+  arr = ArraySpan{*fsl_int_nulls_array_->data()};
+  // Nulls at the top-level of the array are allowed by IsFixedWidthLike.
+  //
+  // TODO(GH-10157): ArrayFromJSON uses FixedSizeListBuilder which currently
+  // produces nulls on the child data if one of the list-typed elements is null.
+  // ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr = ArraySpan{*fsl_int_inner_nulls_array_->data()};
+  // Inner nulls are not allowed by IsFixedWidthLike.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+}
+
+TEST_F(TestFixedWidth, MeasureWidthInBytes) {
+  auto b = boolean();
+  auto i8 = int8();
+  auto i32 = int32();
+  auto varlen = utf8();

Review Comment:
   A-ha. That's up to the kernel implementation. It could choose to always `memcpy` to a runtime-known `byte_width` or have specializations (still using `memcpy` that specializes) of the well-known power-of-2 lengths. That's what what `Take` will be doing: a switch on byte width with `case` 1/2/4...256 and a `default` that uses the `byte_width` variable.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "conbench-apache-arrow[bot] (via GitHub)" <gi...@apache.org>.
conbench-apache-arrow[bot] commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2092338211

   After merging your PR, Conbench analyzed the 7 benchmarking runs that have been run so far on merge-commit 9749d7d653e1b106d0662624b22b2982b3ad0516.
   
   There was 1 benchmark result indicating a performance regression:
   
   - Commit Run on `ursa-i9-9960x` at [2024-05-03 01:10:02Z](https://conbench.ursa.dev/compare/runs/91736b6c37d743f0b3fa7ab6550fefb9...a6d62af6226c4fbb93f1702dc7adff7c/)
     - [`tpch` (R) with engine=arrow, format=parquet, language=R, memory_map=False, query_id=TPCH-08, scale_factor=1](https://conbench.ursa.dev/compare/benchmarks/066342e2941377ae800004481ebd9d57...066345ad40677332800031a6a5b1fd6c)
   
   The [full Conbench report](https://github.com/apache/arrow/runs/24541735426) has more details. It also includes information about 41 possible false positives for unstable benchmarks that are known to sometimes produce them.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1580296198


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(

Review Comment:
   For instance, loop I just wrote:
   
   ```cpp
     for (size_t i = 0; i < num_chunks; ++i) {
       const ArraySpan chunk{*chunks[i]->data()};
       if (chunk.type->id() == Type::BOOL) {
         src_chunks_[i] = chunk.GetValues<uint8_t>(1, 0);
         src_offsets_[i] = chunk.offset;
       } else {
         src_chunks_[i] = util::OffsetPointerOfFixedWidthValues(chunk);
         src_offsets_[i] = 0;
       }
     }
   ```
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1580295504


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+namespace internal {
+ARROW_EXPORT int64_t FixedWidthInBytesFallback(const FixedSizeListType&);
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+inline int64_t FixedWidthInBytes(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    const int32_t num_bits = type.bit_width();
+    return (type_id == Type::BOOL) ? -1 : num_bits / 8;
+  }
+  if (type_id == Type::FIXED_SIZE_LIST) {
+    auto& fsl = ::arrow::internal::checked_cast<const FixedSizeListType&>(type);
+    return internal::FixedWidthInBytesFallback(fsl);
+  }
+  return -1;
+}
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+inline int64_t FixedWidthInBits(const DataType& type) {
+  auto type_id = type.id();
+  if (is_fixed_width(type_id)) {
+    return type.bit_width();
+  }
+  const int64_t byte_width = FixedWidthInBytes(type);
+  if (ARROW_PREDICT_FALSE(byte_width < 0)) {
+    return -1;
+  }
+  return byte_width * 8;
+}
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,
+                                                   int64_t length,
+                                                   const ArraySpan& source,
+                                                   bool allocate_validity,
+                                                   ArrayData* out);
+
+/// \pre same as OffsetPointerOfFixedWidthValues
+/// \pre source.type->id() != Type::BOOL
+ARROW_EXPORT const uint8_t* OffsetPointerOfFixedWidthValuesFallback(
+    const ArraySpan& source);
+
+/// \pre same as MutableFixedWidthValuesPointer
+/// \pre mutable_array->type->id() == Type::FIXED_SIZE_LIST
+ARROW_EXPORT uint8_t* MutableFixedWidthValuesPointerFallback(
+    ArrayData* mutable_fsl_array);
+
+}  // namespace internal
+
+/// \brief Get the pointer to the fixed-width values of a fixed-width like array.
+///
+/// This function might return NULLPTR if the type of the array is BOOL or
+/// if the pre-conditions listed are not satisfied. The converse is not true
+/// (i.e. not getting NULLPTR doesn't guarantee that source is a fixed-width
+/// like array).
+///
+/// \pre `IsFixedWidthLike(source)` or the more restrictive
+///      is_fixed_width(*mutable_array->type) SHOULD be true
+/// \return The pointer to the fixed-width values of an array or NULLPTR
+///         if pre-conditions are not satisfied.
+inline const uint8_t* OffsetPointerOfFixedWidthValues(const ArraySpan& source) {
+  auto type_id = source.type->id();
+  if (ARROW_PREDICT_TRUE(is_fixed_width(type_id))) {
+    if (ARROW_PREDICT_FALSE(type_id == Type::BOOL)) {
+      // BOOL arrays are bit-packed, thus a byte-aligned pointer cannot be produced in the
+      // general case. Returning something for BOOL arrays that happen to byte-align
+      // because offset=0 would create too much confusion.
+      return nullptr;
+    }
+    return source.GetValues<uint8_t>(1, 0) + source.offset * source.type->byte_width();
+  }
+  return internal::OffsetPointerOfFixedWidthValuesFallback(source);
+}
+
+/// \brief Get the mutable pointer to the fixed-width values of an array
+///        allocated by PreallocateFixedWidthArrayData.
+///
+/// \pre mutable_array->offset and the offset of child array (if it's a
+///      FixedSizeList) MUST be 0 (recursively).
+/// \pre IsFixedWidthLike(ArraySpan(mutable_array)) or the more restrictive
+///      is_fixed_width(*mutable_array->type) MUST be true
+/// \return The mutable pointer to the fixed-width byte blocks of the array. If
+///         pre-conditions are not satisfied, the return values is undefined.
+inline uint8_t* MutableFixedWidthValuesPointer(ArrayData* mutable_array) {
+  auto type_id = mutable_array->type->id();
+  if (ARROW_PREDICT_FALSE(type_id == Type::FIXED_SIZE_LIST)) {
+    return internal::MutableFixedWidthValuesPointerFallback(mutable_array);
+  }
+  assert(mutable_array->offset == 0);
+  // BOOL is allowed here only because the offset is expected to be 0,
+  // so the byte-aligned pointer also points to the first *bit* of the buffer.
+  assert(is_fixed_width(type_id));

Review Comment:
   To not include `logging.h` in headers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1594703511


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.

Review Comment:
   API change in #41597.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588096437


##########
cpp/src/arrow/util/fixed_width_test.cc:
##########
@@ -0,0 +1,181 @@
+// 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 <cmath>
+// #include <string>
+
+#include <gtest/gtest.h>
+
+#include "arrow/array/array_base.h"
+#include "arrow/array/data.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/type.h"
+#include "arrow/util/fixed_width_internal.h"
+
+namespace arrow::util {
+
+namespace {
+bool NotBool(const DataType& type) { return type.id() != Type::BOOL; }
+bool NotInt32(const DataType& type) { return type.id() != Type::INT32; }
+}  // namespace
+
+class TestFixedWidth : public ::testing::Test {
+ protected:
+  std::shared_ptr<Array> bool_array_array_;
+  std::shared_ptr<Array> int_array_array_;
+  std::shared_ptr<Array> fsl_bool_array_;
+  std::shared_ptr<Array> fsl_int_array_;
+  std::shared_ptr<Array> fsl_int_nulls_array_;
+  std::shared_ptr<Array> fsl_int_inner_nulls_array_;
+
+  std::shared_ptr<DataType> fsl(int32_t list_size,
+                                const std::shared_ptr<DataType>& value_type) {
+    return fixed_size_list(value_type, list_size);
+  }
+
+ public:
+  void SetUp() override {
+    bool_array_array_ = ArrayFromJSON(boolean(), "[true, false, null]");
+    int_array_array_ = ArrayFromJSON(int32(), "[1, 0, null]");
+    fsl_bool_array_ = ArrayFromJSON(fsl(2, boolean()), "[[true, false]]");
+    fsl_int_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3]]");
+    fsl_int_nulls_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], null, [1, 2]]");
+    fsl_int_inner_nulls_array_ =
+        ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3], [null, 2]]");
+  }
+};
+
+TEST_F(TestFixedWidth, IsFixedWidth) {
+  auto arr = ArraySpan{*bool_array_array_->data()};
+  // force_null_count doesn't matter because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotInt32));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+
+  arr = ArraySpan{*int_array_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+}
+
+TEST_F(TestFixedWidth, IsFixedWidthLike) {
+  auto arr = ArraySpan{*fsl_bool_array_->data()};
+  // bools wrapped by fixed-size-list are not fixed-width because the
+  // innermost data buffer is a bitmap and won't byte-align.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  arr = ArraySpan{*fsl_int_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  arr.null_count = kUnknownNullCount;
+  // force_null_count=true isn't necessary because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr.child_data[0].null_count = kUnknownNullCount;
+  // inner nulls are not allowed by IsFixedWidthLike...
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  // ...but forcing null counting at on every internal array increases
+  // the chances of IsFixedWidthLike returning true.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  // Excluding INT32 from the internal array checks.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true, NotInt32));
+
+  arr = ArraySpan{*fsl_int_nulls_array_->data()};
+  // Nulls at the top-level of the array are allowed by IsFixedWidthLike.
+  //
+  // TODO(GH-10157): ArrayFromJSON uses FixedSizeListBuilder which currently
+  // produces nulls on the child data if one of the list-typed elements is null.
+  // ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr = ArraySpan{*fsl_int_inner_nulls_array_->data()};
+  // Inner nulls are not allowed by IsFixedWidthLike.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+}
+
+TEST_F(TestFixedWidth, MeasureWidthInBytes) {
+  auto b = boolean();
+  auto i8 = int8();
+  auto i32 = int32();
+  auto varlen = utf8();

Review Comment:
   I will add. But note that the algorithm only branches on `BOOL`, `is_fixed_width(t)`, and `FIXED_SIZE_LIST`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588103560


##########
cpp/src/arrow/util/fixed_width_test_util.h:
##########
@@ -0,0 +1,203 @@
+// 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 <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+#include "arrow/array/builder_primitive.h"
+#include "arrow/builder.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::util::internal {
+
+class NestedListGenerator {
+ public:
+  /// \brief Create a nested FixedSizeListType.
+  ///
+  /// \return `fixed_size_list(fixed_size_list(..., sizes[1]), sizes[0])`
+  static std::shared_ptr<DataType> NestedFSLType(
+      const std::shared_ptr<DataType>& inner_type, const std::vector<int>& sizes) {
+    auto type = inner_type;
+    for (auto it = sizes.rbegin(); it != sizes.rend(); it++) {
+      type = fixed_size_list(std::move(type), *it);
+    }
+    return type;
+  }
+
+  /// \brief Create a nested FixedListType.
+  ///
+  /// \return `list(list(...))`
+  static std::shared_ptr<DataType> NestedListType(
+      const std::shared_ptr<DataType>& inner_type, size_t depth) {
+    auto list_type = list(inner_type);
+    for (size_t i = 1; i < depth; i++) {
+      list_type = list(std::move(list_type));
+    }
+    return list_type;
+  }
+
+ private:
+  template <typename ArrowType>
+  static Status AppendNumeric(ArrayBuilder* builder, int64_t* next_value) {

Review Comment:
   I don't understand. My functions calls `Append` on a values builder, yours allocates a `Buffer`. If I go this route, I will have to use very low-level code to build the other buffers of the lists. I would do that in production code, but this is test code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588285198


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,364 @@
+// 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 <cassert>
+#include <cstdint>
+
+#include "arrow/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+#include "arrow/util/checked_cast.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source,
+                                   bool force_null_count = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width

Review Comment:
   Pushed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1588284848


##########
cpp/src/arrow/util/fixed_width_test.cc:
##########
@@ -0,0 +1,181 @@
+// 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 <cmath>
+// #include <string>
+
+#include <gtest/gtest.h>
+
+#include "arrow/array/array_base.h"
+#include "arrow/array/data.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/type.h"
+#include "arrow/util/fixed_width_internal.h"
+
+namespace arrow::util {
+
+namespace {
+bool NotBool(const DataType& type) { return type.id() != Type::BOOL; }
+bool NotInt32(const DataType& type) { return type.id() != Type::INT32; }
+}  // namespace
+
+class TestFixedWidth : public ::testing::Test {
+ protected:
+  std::shared_ptr<Array> bool_array_array_;
+  std::shared_ptr<Array> int_array_array_;
+  std::shared_ptr<Array> fsl_bool_array_;
+  std::shared_ptr<Array> fsl_int_array_;
+  std::shared_ptr<Array> fsl_int_nulls_array_;
+  std::shared_ptr<Array> fsl_int_inner_nulls_array_;
+
+  std::shared_ptr<DataType> fsl(int32_t list_size,
+                                const std::shared_ptr<DataType>& value_type) {
+    return fixed_size_list(value_type, list_size);
+  }
+
+ public:
+  void SetUp() override {
+    bool_array_array_ = ArrayFromJSON(boolean(), "[true, false, null]");
+    int_array_array_ = ArrayFromJSON(int32(), "[1, 0, null]");
+    fsl_bool_array_ = ArrayFromJSON(fsl(2, boolean()), "[[true, false]]");
+    fsl_int_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3]]");
+    fsl_int_nulls_array_ = ArrayFromJSON(fsl(2, int32()), "[[1, 0], null, [1, 2]]");
+    fsl_int_inner_nulls_array_ =
+        ArrayFromJSON(fsl(2, int32()), "[[1, 0], [2, 3], [null, 2]]");
+  }
+};
+
+TEST_F(TestFixedWidth, IsFixedWidth) {
+  auto arr = ArraySpan{*bool_array_array_->data()};
+  // force_null_count doesn't matter because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotInt32));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+
+  arr = ArraySpan{*int_array_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false, NotBool));
+}
+
+TEST_F(TestFixedWidth, IsFixedWidthLike) {
+  auto arr = ArraySpan{*fsl_bool_array_->data()};
+  // bools wrapped by fixed-size-list are not fixed-width because the
+  // innermost data buffer is a bitmap and won't byte-align.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+
+  arr = ArraySpan{*fsl_int_array_->data()};
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  arr.null_count = kUnknownNullCount;
+  // force_null_count=true isn't necessary because nulls at the top-level
+  // of the array are allowed by IsFixedWidthLike.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr.child_data[0].null_count = kUnknownNullCount;
+  // inner nulls are not allowed by IsFixedWidthLike...
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+  // ...but forcing null counting at on every internal array increases
+  // the chances of IsFixedWidthLike returning true.
+  ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+  // Excluding INT32 from the internal array checks.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true, NotInt32));
+
+  arr = ArraySpan{*fsl_int_nulls_array_->data()};
+  // Nulls at the top-level of the array are allowed by IsFixedWidthLike.
+  //
+  // TODO(GH-10157): ArrayFromJSON uses FixedSizeListBuilder which currently
+  // produces nulls on the child data if one of the list-typed elements is null.
+  // ASSERT_TRUE(IsFixedWidthLike(arr, /*force_null_count=*/false));
+
+  arr = ArraySpan{*fsl_int_inner_nulls_array_->data()};
+  // Inner nulls are not allowed by IsFixedWidthLike.
+  ASSERT_FALSE(IsFixedWidthLike(arr, /*force_null_count=*/true));
+}
+
+TEST_F(TestFixedWidth, MeasureWidthInBytes) {
+  auto b = boolean();
+  auto i8 = int8();
+  auto i32 = int32();
+  auto varlen = utf8();

Review Comment:
   Done.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1591470308


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count

Review Comment:
   I didn't feel comfortable having `DCHECK(IsFixedWidthLike(array));` changing `null_count` from `kUnknownNullCount` to `0` or the actual null count depending on whether it's a debug build or not. And since this predicate is used for routing kernel calls, I wanted to leave it up to the implementer to decide if it's worth paying the bitmap scan cost of `GetNullCount()` at every inner array.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1592442520


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param exclude_dictionary If true, DICTIONARY is excluded from the
+///                           is_fixed_width() types. Default: false.
+ARROW_EXPORT bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count = false,
+                                   bool exclude_dictionary = false);
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// This function is a more general version of
+/// `IsFixedWidthLike(const ArraySpan&, bool)` that allows the caller to further
+/// restrict the inner value types that should be considered fixed-width.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count
+/// \param extra_predicate A DataType predicate that can be used to further
+///                        restrict the types that are considered fixed-width
+template <class ExtraPred>
+inline bool IsFixedWidthLike(const ArraySpan& source, bool force_null_count,
+                             ExtraPred extra_predicate) {
+  const auto* type = source.type;
+  // BOOL is considered fixed-width if not nested under FIXED_SIZE_LIST.
+  if (is_fixed_width(type->id()) && extra_predicate(*type)) {
+    return true;
+  }
+  if (type->id() == Type::FIXED_SIZE_LIST) {
+    // All the inner arrays must not contain any nulls.
+    const auto* values = &source.child_data[0];
+    while ((force_null_count ? values->GetNullCount() : values->null_count) == 0) {
+      type = values->type;
+      if (type->id() == Type::FIXED_SIZE_LIST) {
+        values = &values->child_data[0];
+        continue;
+      }
+      // BOOL has to be excluded because it's not byte-aligned.
+      return type->id() != Type::BOOL && is_fixed_width(type->id()) &&
+             extra_predicate(*type);
+    }
+  }
+  return false;
+}
+
+/// \brief Get the fixed-width in bytes of a type if it is a fixed-width like
+/// type, but not BOOL.
+///
+/// If the array is a FixedSizeList (of any level of nesting), the byte width of
+/// the values is the product of all fixed-list sizes and the byte width of the
+/// innermost fixed-width value type.
+///
+/// IsFixedWidthLike(array) performs more checks than this function and should
+/// be used to guarantee that, if type is not BOOL, this function will not return -1.
+///
+/// NOTE: this function translates `DataType::bit_width()` to bytes differently from
+/// `DataType::byte_width()`. `DataType::byte_width()` will return 0 for
+/// BOOL, while this function will return `-1`. This is done because 0 is
+/// a valid return value for FIXED_SIZE_LIST with size 0 or `FIXED_SIZE_BINARY` with
+/// size 0.
+///
+/// \pre The instance of the array where this type is from must pass
+///      `IsFixedWidthLike(array)` and should not be BOOL.
+/// \return The fixed-byte width of the values or -1 if the type is BOOL or not
+///         fixed-width like. 0 is a valid return value as fixed-size-lists
+///         and fixed-size-binary with size 0 are allowed.
+ARROW_EXPORT int64_t FixedWidthInBytes(const DataType& type);
+
+/// \brief Get the fixed-width in bits of a type if it is a fixed-width like
+/// type.
+///
+/// \return The bit-width of the values or -1
+/// \see FixedWidthInBytes
+ARROW_EXPORT int64_t FixedWidthInBits(const DataType& type);
+
+namespace internal {
+
+/// \brief Allocate an ArrayData for a type that is fixed-width like.
+///
+/// This function performs the same checks performed by
+/// `IsFixedWidthLike(source, false)`. If `source.type` is not a simple
+/// fixed-width type, caller should make sure it passes the
+/// `IsFixedWidthLike(source)` checks. That guarantees that it's possible to
+/// allocate an array that can serve as a destination for a kernel that writes values
+/// through a single pointer to fixed-width byte blocks.
+///
+/// \param[in] length The length of the array to allocate (unrelated to the length of
+///                   the source array)
+/// \param[in] source The source array that carries the type information and the
+///                   validity bitmaps that are relevant for the type validation
+///                   when the source is a FixedSizeList.
+/// \see IsFixedWidthLike
+ARROW_EXPORT Status PreallocateFixedWidthArrayData(::arrow::compute::KernelContext* ctx,

Review Comment:
   Hmm, only the bitmap buffers should be zero-initialized, IIRC? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #41297:
URL: https://github.com/apache/arrow/pull/41297#discussion_r1592442771


##########
cpp/src/arrow/util/fixed_width_internal.h:
##########
@@ -0,0 +1,307 @@
+// 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/array/data.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/type_traits.h"
+
+namespace arrow::compute {
+// XXX: remove dependency on compute::KernelContext
+class KernelContext;
+}  // namespace arrow::compute
+
+namespace arrow::util {
+
+/// \brief Checks if the given array has a fixed-width type or if it's an array of
+/// fixed-size list that can be flattened to an array of fixed-width values.
+///
+/// Fixed-width types are the ones defined by the is_fixed_width() predicate in
+/// type_traits.h. They are all the types that passes any of the following
+/// predicates:
+///
+///  - is_primitive()
+///  - is_fixed_size_binary()
+///  - is_dictionary()
+///
+/// At least 3 types in this set require special care:
+///  - `Type::BOOL` is fixed-width, but it's a 1-bit type and pointers to first bit
+///    in boolean buffers are not always aligned to byte boundaries.
+///  - `Type::DICTIONARY` is fixed-width because the indices are fixed-width, but the
+///    dictionary values are not necessarily fixed-width and have to be managed
+///    by separate operations.
+///  - Type::FIXED_SIZE_BINARY unlike other fixed-width types, fixed-size binary
+///    values are defined by a size attribute that is not known at compile time.
+///    The other types have power-of-2 byte widths, while fixed-size binary can
+///    have any byte width including 0.
+///
+/// Additionally, we say that a type is "fixed-width like" if it's a fixed-width as
+/// defined above, or if it's a fixed-size list (or nested fixed-size lists) and
+/// the innermost type is fixed-width and the following restrictions also apply:
+///  - The value type of the innermost fixed-size list is not BOOL (it has to be excluded
+///    because a 1-bit type doesn't byte-align)
+///  - Only the top-level array may have nulls, all the inner array have to be completely
+///    free of nulls so we don't need to manage internal validity bitmaps.
+///
+/// Take the following `fixed_size_list<fixed_size_list<int32, 2>, 3>` array as an
+/// example:
+///
+///     [
+///       [[1, 2], [3,  4], [ 5,  6]],
+///       null,
+///       [[7, 8], [9, 10], [11, 12]]
+///     ]
+///
+/// in memory, it would look like:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        length: 3,
+///        null_count: 1,
+///        offset: 0,
+///        buffers: [
+///          0: [0b00000101]
+///        ],
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            length: 9,
+///            null_count: 0,
+///            offset: 0,
+///            buffers: [0: NULL],
+///            child_data: [
+///              0: {
+///                type: int32,
+///                length: 18,
+///                null_count: 0,
+///                offset: 0,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1,  2,  3,  4,  5,  6,
+///                       0,  0,  0,  0,  0,  0
+///                       7,  8,  9, 10, 11, 12 ]
+///                ],
+///                child_data: []
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// This layout fits the fixed-width like definition because the innermost type
+/// is byte-aligned fixed-width (int32 = 4 bytes) and the internal arrays don't
+/// have nulls. The validity bitmap is only needed at the top-level array.
+///
+/// Writing to this array can be done in the same way writing to a flat fixed-width
+/// array is done, by:
+/// 1. Updating the validity bitmap at the top-level array if nulls are present.
+/// 2. Updating a continuous fixed-width block of memory through a single pointer.
+///
+/// The length of this block of memory is the product of the list sizes in the
+/// `FixedSizeList` types and the byte width of the innermost fixed-width type:
+///
+///     3 * 2 * 4 = 24 bytes
+///
+/// Writing the `[[1, 2], [3, 4], [5, 6]]` value at a given index can be done by
+/// simply setting the validity bit to 1 and writing the 24-byte sequence of
+/// integers `[1, 2, 3, 4, 5, 6]` to the memory block at `byte_ptr + index * 24`.
+///
+/// The length of the top-level array fully defines the lengths that all the nested
+/// arrays must have, which makes defining all the lengths as easy as defining the
+/// length of the top-level array.
+///
+///     length = 3
+///     child_data[0].length == 3 * 3 == 9
+///     child_data[0].child_data[0].length == 3 * 3 * 2 == 18
+///
+///     child_data[0].child_data[0].buffers[1].size() >=
+///       (3 * (3 * 2 * sizeof(int32)) == 3 * 24 == 72)
+///
+/// Dealing with offsets is a bit involved. Let's say the array described above has
+/// the offsets 2, 5, and 7:
+///
+///     {
+///        type: fixed_size_list<fixed_size_list<int32, 2>, 3>,
+///        offset: 2,
+///        ...
+///        child_data: [
+///          0: {
+///            type: fixed_size_list<int32, 2>,
+///            offset: 5,
+///            ...
+///            child_data: [
+///              0: {
+///                type: int32,
+///                offset: 7,
+///                buffers: [
+///                  0: NULL,
+///                  1: [ 1, 1, 1, 1, 1, 1, 1,      // 7 values skipped
+///                       0,1, 0,1, 0,1, 0,1, 0,1,  // 5 [x,x] values skipped
+///
+///                       0,0,0,0,0,1,  //
+///                       0,0,0,0,0,1,  // 2 [[x,x], [x,x], [x,x]] values skipped
+///
+///                       1,  2,  3,  4,  5,  6,  //
+///                       0,  0,  0,  0,  0,  0   // the actual values
+///                       7,  8,  9, 10, 11, 12   //
+///                     ]
+///                ],
+///              }
+///            ]
+///          }
+///        ]
+///     }
+///
+/// The offset of the innermost values buffer, in bytes, is calculated as:
+///
+///     ((2 * 3) + (5 * 2) + 7) * sizeof(int32) = 29 * 4 bytes = 116 bytes
+///
+/// In general, the formula to calculate the offset of the innermost values buffer is:
+///
+///     ((off_0 * fsl_size_0) + (off_1 * fsl_size_1) + ... + innermost_off)
+///        * sizeof(innermost_type)
+///
+/// `OffsetPointerOfFixedWidthValues()` can calculate this byte offset and return the
+/// pointer to the first relevant byte of the innermost values buffer.
+///
+/// \param source The array to check
+/// \param force_null_count If true, GetNullCount() is used instead of null_count

Review Comment:
   Ok, that's reasonable.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-39798: [C++] Optimize Take for fixed-size types including nested fixed-size lists [arrow]

Posted by "felipecrv (via GitHub)" <gi...@apache.org>.
felipecrv commented on PR #41297:
URL: https://github.com/apache/arrow/pull/41297#issuecomment-2091973309

   CI failures are unrelated. I'm going to merge now, but more feedback can be posted here or on the follow-up PRs that use and extend this work.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org