diff --git a/cpp/src/arrow/array/array_list_test.cc b/cpp/src/arrow/array/array_list_test.cc index 4901a1e6fa6a..8e5ec541e6c0 100644 --- a/cpp/src/arrow/array/array_list_test.cc +++ b/cpp/src/arrow/array/array_list_test.cc @@ -1048,6 +1048,43 @@ class TestListConversions : public ::testing::Test { *checked_pointer_cast(list_view_wo_nulls), pool_)); ASSERT_OK(result->ValidateFull()); AssertArraysEqual(*expected_list_wo_nulls, *result, /*verbose=*/true); + + // The views are contiguous, so the values are kept as they are (GH-51612). + ASSERT_EQ(result->values()->data()->buffers[1].get(), + checked_pointer_cast(list_view_wo_nulls) + ->values() + ->data() + ->buffers[1] + .get()); + } + + template + void DoTestListFromSlicedListView() { + using SrcListViewArrayClass = typename TypeTraits::ArrayType; + using DestListArrayClass = typename TypeTraits::ArrayType; + auto list_view_type = std::make_shared(int32()); + auto list_type = std::make_shared(int32()); + + auto list_view = + ArrayFromJSON(list_view_type, "[[1, 2], [3], null, [], [4], [5, 6], null, [7]]"); + + auto check = [&](const Array& sliced, const std::shared_ptr& expected) { + ASSERT_OK_AND_ASSIGN( + auto result, DestListArrayClass::FromListView( + checked_cast(sliced), pool_)); + ASSERT_OK(result->ValidateFull()); + AssertArraysEqual(*expected, *result, /*verbose=*/true); + }; + + // A slice whose element offset is not a multiple of 8, so the bitmap's bit + // offset and byte offset differ (GH-51613). + check(*list_view->Slice(1, 6), + ArrayFromJSON(list_type, "[[3], null, [], [4], [5, 6], null]")); + // A slice starting on a byte boundary, so that the bit offset is zero. + check(*list_view->Slice(2, 4), ArrayFromJSON(list_type, "[null, [], [4], [5, 6]]")); + // A slice whose only null is the last slot. + check(*list_view->Slice(0, 8), + ArrayFromJSON(list_type, "[[1, 2], [3], null, [], [4], [5, 6], null, [7]]")); } }; @@ -1061,6 +1098,11 @@ TEST_F(TestListConversions, ListFromListView) { this->DoTestListFromListView(); } +TEST_F(TestListConversions, ListFromSlicedListView) { + this->DoTestListFromSlicedListView(); + this->DoTestListFromSlicedListView(); +} + // ---------------------------------------------------------------------- // Map tests diff --git a/cpp/src/arrow/array/array_nested.cc b/cpp/src/arrow/array/array_nested.cc index 6849aca089b7..48337bc95817 100644 --- a/cpp/src/arrow/array/array_nested.cc +++ b/cpp/src/arrow/array/array_nested.cc @@ -42,7 +42,6 @@ #include "arrow/util/bitmap_ops.h" #include "arrow/util/checked_cast.h" #include "arrow/util/int_util_overflow.h" -#include "arrow/util/list_util.h" #include "arrow/util/logging_internal.h" #include "arrow/util/unreachable.h" @@ -279,9 +278,11 @@ Result> FlattenListViewArray(const ListViewArrayT& list_v } // If the list array is *all* nulls, then just return an empty array. + // Slicing (rather than MakeEmptyArray) also works for value types that have + // no builder, such as extension types nested in a struct. if constexpr (HasNulls) { if (list_view_array.null_count() == list_view_array.length()) { - return MakeEmptyArray(value_array->type(), memory_pool); + return SliceArrayWithOffsets(*value_array, 0, 0); } } @@ -305,7 +306,7 @@ Result> FlattenListViewArray(const ListViewArrayT& list_v } // If all list-views are empty, return an empty array. if (first_i == list_view_array_length) { - return MakeEmptyArray(value_array->type(), memory_pool); + return SliceArrayWithOffsets(*value_array, 0, 0); } std::vector> slices; @@ -416,36 +417,38 @@ Result> ListFromListViewImpl( typename DestListType::offset_type>::value, "Offset types between list type and list-view type are expected to match"); using offset_type = typename DestListType::offset_type; - using ListBuilderType = typename TypeTraits::BuilderType; + using ListViewArrayType = typename TypeTraits::ArrayType; + + const ListViewArrayType list_view_array(list_view_data); + const int64_t length = list_view_array.length(); + + // The views may be out of order, overlap or leave gaps, so the values they + // reference are packed in list order. Contiguous views are sliced, not copied. + ARROW_ASSIGN_OR_RAISE(auto values, list_view_array.Flatten(pool)); + + ARROW_ASSIGN_OR_RAISE(auto offsets_buffer, + AllocateBuffer(sizeof(offset_type) * (length + 1), pool)); + auto* offsets = offsets_buffer->mutable_data_as(); + offset_type offset = 0; + for (int64_t i = 0; i < length; ++i) { + offsets[i] = offset; + if (list_view_array.IsValid(i)) { + offset += list_view_array.value_length(i); + } + } + offsets[length] = offset; + + std::shared_ptr null_bitmap = list_view_data->buffers[0]; + if (null_bitmap && list_view_data->offset != 0) { + ARROW_ASSIGN_OR_RAISE(null_bitmap, CopyBitmap(pool, null_bitmap->data(), + list_view_data->offset, length)); + } const auto& list_view_type = checked_cast(*list_view_data->type); - const auto& value_type = list_view_type.value_type(); - const auto list_type = std::make_shared(value_type); - - ARROW_ASSIGN_OR_RAISE(auto sum_of_list_view_sizes, - list_util::internal::SumOfLogicalListSizes(*list_view_data)); - ARROW_ASSIGN_OR_RAISE(std::shared_ptr value_builder, - MakeBuilder(value_type, pool)); - RETURN_NOT_OK(value_builder->Reserve(sum_of_list_view_sizes)); - auto list_builder = std::make_shared(pool, value_builder, list_type); - RETURN_NOT_OK(list_builder->Reserve(list_view_data->length)); - - ArraySpan values{*list_view_data->child_data[0]}; - const auto* in_validity_bitmap = list_view_data->GetValues(0); - const auto* in_offsets = list_view_data->GetValues(1); - const auto* in_sizes = list_view_data->GetValues(2); - for (int64_t i = 0; i < list_view_data->length; ++i) { - const bool is_valid = - !in_validity_bitmap || - bit_util::GetBit(in_validity_bitmap, list_view_data->offset + i); - const int64_t size = is_valid ? in_sizes[i] : 0; - RETURN_NOT_OK(list_builder->Append(is_valid, size)); - RETURN_NOT_OK(value_builder->AppendArraySlice(values, in_offsets[i], size)); - } - std::shared_ptr list_array_data; - RETURN_NOT_OK(list_builder->FinishInternal(&list_array_data)); - return list_array_data; + return ArrayData::Make(std::make_shared(list_view_type.value_type()), + length, {std::move(null_bitmap), std::move(offsets_buffer)}, + {values->data()}, list_view_array.null_count()); } } // namespace diff --git a/cpp/src/arrow/compute/kernels/scalar_cast_nested.cc b/cpp/src/arrow/compute/kernels/scalar_cast_nested.cc index 392fd9fbb705..311bbfa3141f 100644 --- a/cpp/src/arrow/compute/kernels/scalar_cast_nested.cc +++ b/cpp/src/arrow/compute/kernels/scalar_cast_nested.cc @@ -105,6 +105,44 @@ struct CastList { return Status::OK(); } + /// \brief Pack the values referenced by list-views in sequence + /// + /// The views may be out of order, overlap or leave gaps between them, so + /// their offsets cannot be reused as list offsets (GH-51612). The values + /// referenced by the valid views are packed in sequence instead (contiguous + /// views are sliced rather than copied), and the list offsets are computed + /// from the views' sizes. + static Status HandleListViewOffsets(KernelContext* ctx, const ArraySpan& in_array, + ArrayData* out_array, + std::shared_ptr* values) { + using ListViewArrayType = typename TypeTraits::ArrayType; + const ListViewArrayType list_view_array(in_array.ToArrayData()); + + ARROW_ASSIGN_OR_RAISE(auto packed_values, + list_view_array.Flatten(ctx->memory_pool())); + if constexpr (is_downcast) { + if (packed_values->length() > std::numeric_limits::max()) { + return Status::Invalid("Array of type ", in_array.type->ToString(), + " too large to convert to ", out_array->type->ToString()); + } + } + + ARROW_ASSIGN_OR_RAISE(out_array->buffers[1], ctx->Allocate(sizeof(dest_offset_type) * + (in_array.length + 1))); + auto* out_offsets = out_array->GetMutableValues(1); + dest_offset_type offset = 0; + for (int64_t i = 0; i < in_array.length; ++i) { + out_offsets[i] = offset; + if (list_view_array.IsValid(i)) { + offset += static_cast(list_view_array.value_length(i)); + } + } + out_offsets[in_array.length] = offset; + + *values = packed_values->data(); + return Status::OK(); + } + static Status Exec(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) { const CastOptions& options = CastState::Get(ctx); @@ -115,11 +153,15 @@ struct CastList { ArrayData* out_array = out->array_data().get(); ARROW_ASSIGN_OR_RAISE(out_array->buffers[0], GetOrCopyNullBitmapBuffer(in_array, ctx->memory_pool())); - out_array->buffers[1] = in_array.GetBuffer(1); - std::shared_ptr values = in_array.child_data[0].ToArrayData(); - - RETURN_NOT_OK(HandleOffsets(ctx, in_array, out_array, &values)); + std::shared_ptr values; + if constexpr (is_list_view(SrcType::type_id)) { + RETURN_NOT_OK(HandleListViewOffsets(ctx, in_array, out_array, &values)); + } else { + out_array->buffers[1] = in_array.GetBuffer(1); + values = in_array.child_data[0].ToArrayData(); + RETURN_NOT_OK(HandleOffsets(ctx, in_array, out_array, &values)); + } // Handle values ARROW_ASSIGN_OR_RAISE(Datum cast_values, diff --git a/cpp/src/arrow/compute/kernels/scalar_cast_test.cc b/cpp/src/arrow/compute/kernels/scalar_cast_test.cc index 864ec4afce0c..d6e80d53fb6b 100644 --- a/cpp/src/arrow/compute/kernels/scalar_cast_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_cast_test.cc @@ -3616,6 +3616,398 @@ static void CheckListToList(const std::vector>& value_ } } +TEST(Cast, ListViewToList) { + // Views may be out of order or overlapping, so the referenced values have to + // be gathered rather than reinterpreted (GH-51612). + auto values = ArrayFromJSON(int32(), "[1, 2, 3, 4]"); + + // Out of order and overlapping views. + auto offsets = ArrayFromJSON(int32(), "[2, 0, 1]"); + auto sizes = ArrayFromJSON(int32(), "[2, 2, 1]"); + ASSERT_OK_AND_ASSIGN(auto list_view, + ListViewArray::FromArrays(*offsets, *sizes, *values)); + CheckCast(list_view, ArrayFromJSON(list(int32()), "[[3, 4], [1, 2], [2]]")); + // Same offset width, larger offset width, and a child type change. + CheckCast(list_view, ArrayFromJSON(large_list(int32()), "[[3, 4], [1, 2], [2]]")); + CheckCast(list_view, ArrayFromJSON(list(int64()), "[[3, 4], [1, 2], [2]]")); + CheckCast(list_view, ArrayFromJSON(large_list(float32()), "[[3, 4], [1, 2], [2]]")); + + // The large_list_view source, narrowing as well as widening the offset width. + ASSERT_OK_AND_ASSIGN( + auto large_list_view, + LargeListViewArray::FromArrays(*ArrayFromJSON(int64(), "[2, 0, 1]"), + *ArrayFromJSON(int64(), "[2, 2, 1]"), *values)); + CheckCast(large_list_view, ArrayFromJSON(large_list(int32()), "[[3, 4], [1, 2], [2]]")); + CheckCast(large_list_view, ArrayFromJSON(list(int32()), "[[3, 4], [1, 2], [2]]")); + + // Views that happen to be contiguous, i.e. what a list array would look like. + ASSERT_OK_AND_ASSIGN(list_view, ListViewArray::FromArrays( + *ArrayFromJSON(int32(), "[0, 2, 4]"), + *ArrayFromJSON(int32(), "[2, 2, 0]"), *values)); + CheckCast(list_view, ArrayFromJSON(list(int32()), "[[1, 2], [3, 4], []]")); + + // Nulls. + { + auto list_view_w_nulls = MaskArrayWithNullsAt(list_view, {0}); + CheckCast(list_view_w_nulls, ArrayFromJSON(list(int32()), "[null, [3, 4], []]")); + } + { + // A null view contributes no values, whatever size it declares. + ASSERT_OK_AND_ASSIGN(auto lv, ListViewArray::FromArrays( + *ArrayFromJSON(int32(), "[0, 2, 2]"), + *ArrayFromJSON(int32(), "[2, 2, 2]"), *values)); + CheckCast(MaskArrayWithNullsAt(lv, {2}), + ArrayFromJSON(list(int32()), "[[1, 2], [3, 4], null]")); + } + + // Sliced list-view. + { + ASSERT_OK_AND_ASSIGN( + auto lv, ListViewArray::FromArrays(*ArrayFromJSON(int32(), "[0, 2, 0, 1, 2, 0]"), + *ArrayFromJSON(int32(), "[2, 2, 2, 0, 2, 2]"), + *values)); + CheckCast(lv->Slice(2, 3), ArrayFromJSON(list(int32()), "[[1, 2], [], [3, 4]]")); + CheckCast(lv->Slice(1, 4), + ArrayFromJSON(large_list(int32()), "[[3, 4], [1, 2], [], [3, 4]]")); + } + + // Options pass through to the child cast. + { + ASSERT_OK_AND_ASSIGN( + auto lv, ListViewArray::FromArrays( + *ArrayFromJSON(int32(), "[0, 2]"), *ArrayFromJSON(int32(), "[2, 2]"), + *ArrayFromJSON(int64(), "[87654321, 0, 0, 0]"))); + auto options = CastOptions::Safe(list(int16())); + CheckCastFails(lv, options); + options.allow_int_overflow = true; + CheckCast(lv, ArrayFromJSON(list(int16()), "[[32689, 0], [0, 0]]"), options); + } +} + +TEST(Cast, ListViewToListKeepsContiguousValues) { + // Views that are in order and contiguous describe a list already: the cast + // slices the values instead of gathering them (GH-51612). + auto values = ArrayFromJSON(int32(), "[1, 2, 3, 4]"); + + auto check = [&](const std::string& name, const std::shared_ptr& list_view, + const std::shared_ptr& expected_values, + const std::shared_ptr& expected) { + ARROW_SCOPED_TRACE(name); + ASSERT_OK_AND_ASSIGN(Datum out, Cast(list_view, expected->type())); + AssertDatumsEqual(expected, out); + const auto out_values = MakeArray(out.array()->child_data[0]); + ASSERT_OK(out_values->ValidateFull()); + AssertBufferSame(*expected_values, *out_values, 1); + }; + + ASSERT_OK_AND_ASSIGN( + auto contiguous, + ListViewArray::FromArrays(*ArrayFromJSON(int32(), "[0, 2, 4]"), + *ArrayFromJSON(int32(), "[2, 2, 0]"), *values)); + check("contiguous", contiguous, values, + ArrayFromJSON(list(int32()), "[[1, 2], [3, 4], []]")); + check("contiguous", contiguous, values, + ArrayFromJSON(large_list(int32()), "[[1, 2], [3, 4], []]")); + + ASSERT_OK_AND_ASSIGN( + auto large_contiguous, + LargeListViewArray::FromArrays(*ArrayFromJSON(int64(), "[0, 2, 4]"), + *ArrayFromJSON(int64(), "[2, 2, 0]"), *values)); + check("large_contiguous", large_contiguous, values, + ArrayFromJSON(list(int32()), "[[1, 2], [3, 4], []]")); + check("large_contiguous", large_contiguous, values, + ArrayFromJSON(large_list(int32()), "[[1, 2], [3, 4], []]")); + + { + // The kept values are still cast to the destination value type. + ASSERT_OK_AND_ASSIGN(Datum out, Cast(contiguous, list(int64()))); + AssertDatumsEqual(ArrayFromJSON(list(int64()), "[[1, 2], [3, 4], []]"), out); + } + + { + // An empty view references no values: neither its offset nor its position + // can force the values to be gathered. + ASSERT_OK_AND_ASSIGN( + auto empty_view, + ListViewArray::FromArrays(*ArrayFromJSON(int32(), "[0, 0, 2]"), + *ArrayFromJSON(int32(), "[2, 0, 2]"), *values)); + check("empty view", empty_view, values, + ArrayFromJSON(list(int32()), "[[1, 2], [], [3, 4]]")); + check("empty view", empty_view, values, + ArrayFromJSON(large_list(int32()), "[[1, 2], [], [3, 4]]")); + } + + { + // A null view keeps no value: the values that only it references are + // dropped, which narrows the kept values without copying them. + ASSERT_OK_AND_ASSIGN(auto lv, ListViewArray::FromArrays( + *ArrayFromJSON(int32(), "[0, 2, 4]"), + *ArrayFromJSON(int32(), "[2, 2, 0]"), *values)); + check("null view", MaskArrayWithNullsAt(lv, {0}), values, + ArrayFromJSON(list(int32()), "[null, [3, 4], []]")); + } + + { + // A sliced contiguous list-view keeps its values too, and its validity + // bitmap is copied out of the way of the slice. + auto lv = ArrayFromJSON(list_view(int32()), "[[1, 2], [3, 4], [5], [6, 7, 8]]"); + auto lv_values = checked_cast(*lv).values(); + auto sliced = MaskArrayWithNullsAt(lv, {3})->Slice(1, 3); + check("sliced", sliced, lv_values, + ArrayFromJSON(list(int32()), "[[3, 4], [5], null]")); + } + + // Out-of-order views cannot be sliced: their values are gathered instead. + ASSERT_OK_AND_ASSIGN( + auto out_of_order, + ListViewArray::FromArrays(*ArrayFromJSON(int32(), "[2, 0, 1]"), + *ArrayFromJSON(int32(), "[2, 2, 1]"), *values)); + ASSERT_OK_AND_ASSIGN(Datum out, Cast(out_of_order, list(int32()))); + AssertDatumsEqual(ArrayFromJSON(list(int32()), "[[3, 4], [1, 2], [2]]"), out); + const auto gathered = MakeArray(out.array()->child_data[0]); + ASSERT_NE(gathered->data()->buffers[1].get(), values->data()->buffers[1].get()); +} + +TEST(Cast, ListViewToListWithExtensionChild) { + // MakeBuilder does not support extension types, but the cast used to work by + // reusing the child array. The gathered values must keep working for both an + // extension destination and its storage type. + auto smallint_type = std::make_shared(); + ExtensionTypeGuard smallint_guard(smallint_type); + + auto values = + ExtensionType::WrapArray(smallint_type, ArrayFromJSON(int16(), "[1, 2, 3, 4]")); + ASSERT_OK_AND_ASSIGN( + auto list_view, + ListViewArray::FromArrays(*ArrayFromJSON(int32(), "[2, 0, 1]"), + *ArrayFromJSON(int32(), "[2, 2, 1]"), *values)); + CheckCast(list_view, ArrayFromJSON(list(int16()), "[[3, 4], [1, 2], [2]]")); + + auto expected_values = + ExtensionType::WrapArray(smallint_type, ArrayFromJSON(int16(), "[3, 4, 1, 2, 2]")); + ASSERT_OK_AND_ASSIGN( + auto expected_extension, + ListArray::FromArrays(*ArrayFromJSON(int32(), "[0, 2, 4, 5]"), *expected_values)); + CheckCast(list_view, expected_extension); +} + +TEST(Cast, ListViewToListWithNestedExtensionChild) { + auto smallint_type = std::make_shared(); + ExtensionTypeGuard smallint_guard(smallint_type); + + auto storage = ArrayFromJSON(int16(), "[1, 2]"); + auto values = ExtensionType::WrapArray(smallint_type, storage); + ASSERT_OK_AND_ASSIGN(auto nested, StructArray::Make({values}, {"e"})); + ASSERT_OK_AND_ASSIGN(auto plain_nested, StructArray::Make({storage}, {"e"})); + + auto offsets = ArrayFromJSON(int32(), "[0, 1, 2]"); + auto sizes = ArrayFromJSON(int32(), "[1, 1]"); + ASSERT_OK_AND_ASSIGN(auto view, + ListViewArray::FromArrays(*offsets->Slice(0, 2), *sizes, *nested)); + // Struct child with an extension field, targeting both the nested extension + // and its storage type. + for (const auto& child : ArrayVector{nested, plain_nested}) { + ASSERT_OK_AND_ASSIGN(auto expected, ListArray::FromArrays(*offsets, *child)); + CheckCast(view, expected); + } + + // Same with a list-valued child whose values are extensions. + ASSERT_OK_AND_ASSIGN( + auto nested_list, + ListArray::FromArrays(*ArrayFromJSON(int32(), "[0, 1, 2]"), *values)); + ASSERT_OK_AND_ASSIGN( + auto plain_nested_list, + ListArray::FromArrays(*ArrayFromJSON(int32(), "[0, 1, 2]"), *storage)); + ASSERT_OK_AND_ASSIGN( + auto list_view, + ListViewArray::FromArrays(*ArrayFromJSON(int32(), "[0, 1]"), *sizes, *nested_list)); + for (const auto& child : ArrayVector{nested_list, plain_nested_list}) { + ASSERT_OK_AND_ASSIGN(auto expected, ListArray::FromArrays(*offsets, *child)); + CheckCast(list_view, expected); + } +} + +// An extension type over a run-end encoded storage, to check that packing the +// values of a list-view goes through the extension's storage (GH-51612). +class RunEndEncodedExtensionArray : public ExtensionArray { + public: + using ExtensionArray::ExtensionArray; +}; + +class RunEndEncodedExtensionType : public ExtensionType { + public: + RunEndEncodedExtensionType() : ExtensionType(run_end_encoded(int32(), int32())) {} + + std::string extension_name() const override { return "ree-extension"; } + + bool ExtensionEquals(const ExtensionType& other) const override { + return other.extension_name() == extension_name(); + } + + std::shared_ptr MakeArray(std::shared_ptr data) const override { + return std::make_shared(std::move(data)); + } + + Result> Deserialize(std::shared_ptr storage_type, + const std::string&) const override { + return std::make_shared(); + } + + std::string Serialize() const override { return ""; } +}; + +TEST(Cast, ListViewToListWithRunEndEncodedChild) { + auto ree_ext_type = std::make_shared(); + ExtensionTypeGuard ree_ext_guard(ree_ext_type); + + // values = [1, 2, 3, 4], as a run-end encoded array and as an extension of it + ASSERT_OK_AND_ASSIGN(auto ree_values, + RunEndEncodedArray::Make(4, ArrayFromJSON(int32(), "[1, 2, 3, 4]"), + ArrayFromJSON(int32(), "[1, 2, 3, 4]"))); + auto ext_values = ExtensionType::WrapArray(ree_ext_type, ree_values); + + // views = [[3, 4], [1, 2], [2]], gathering [3, 4, 1, 2, 2] in list order + auto offsets = ArrayFromJSON(int32(), "[2, 0, 1]"); + auto sizes = ArrayFromJSON(int32(), "[2, 2, 1]"); + auto list_offsets = ArrayFromJSON(int32(), "[0, 2, 4, 5]"); + ASSERT_OK_AND_ASSIGN( + auto gathered_ree, + RunEndEncodedArray::Make(5, ArrayFromJSON(int32(), "[1, 2, 3, 4, 5]"), + ArrayFromJSON(int32(), "[3, 4, 1, 2, 2]"))); + ASSERT_OK_AND_ASSIGN(auto expected_ree, + ListArray::FromArrays(*list_offsets, *gathered_ree)); + + // A run-end encoded child is gathered through its own type. + ASSERT_OK_AND_ASSIGN(auto list_view, + ListViewArray::FromArrays(*offsets, *sizes, *ree_values)); + ASSERT_OK_AND_ASSIGN(Datum out, Cast(list_view, expected_ree->type())); + AssertDatumsEqual(expected_ree, out); + + ASSERT_OK_AND_ASSIGN( + auto expected_large, + LargeListArray::FromArrays(*ArrayFromJSON(int64(), "[0, 2, 4, 5]"), *gathered_ree)); + ASSERT_OK_AND_ASSIGN(out, Cast(list_view, expected_large->type())); + AssertDatumsEqual(expected_large, out); + + // An extension child is gathered through its storage type. + ASSERT_OK_AND_ASSIGN( + auto expected_ext, + ListArray::FromArrays(*list_offsets, + *ExtensionType::WrapArray(ree_ext_type, gathered_ree))); + ASSERT_OK_AND_ASSIGN(list_view, + ListViewArray::FromArrays(*offsets, *sizes, *ext_values)); + ASSERT_OK_AND_ASSIGN(out, Cast(list_view, expected_ext->type())); + ASSERT_TRUE(out.type()->Equals(*expected_ext->type())); + ASSERT_OK(MakeArray(out.array())->ValidateFull()); + // Extension arrays whose storage is run-end encoded cannot be compared, so + // compare the offsets and the gathered storage values instead. + const auto out_child_array = MakeArray(out.array()->child_data[0]); + const auto& out_child = checked_cast(*out_child_array); + ASSERT_OK_AND_ASSIGN(auto storage_list, + ListArray::FromArrays(*list_offsets, *out_child.storage())); + AssertArraysEqual(*expected_ree, *storage_list); +} + +TEST(Cast, ListViewToListWithNestedRunEndEncodedChild) { + auto smallint_type = smallint(); + ExtensionTypeGuard smallint_guard(smallint_type); + + // values = [1, 2, 3, 4], with the extension type as the value type of the runs + ASSERT_OK_AND_ASSIGN(auto ree_values, + RunEndEncodedArray::Make( + 4, ArrayFromJSON(int32(), "[1, 2, 3, 4]"), + ExtensionType::WrapArray( + smallint_type, ArrayFromJSON(int16(), "[1, 2, 3, 4]")))); + + ASSERT_OK_AND_ASSIGN(auto nested, StructArray::Make({ree_values}, {"e"})); + + // Contiguous views are sliced, so they cast whatever the value type of the + // runs: views = [[1, 2], [3, 4]]. + auto offsets = ArrayFromJSON(int32(), "[0, 2]"); + auto sizes = ArrayFromJSON(int32(), "[2, 2]"); + auto list_offsets = ArrayFromJSON(int32(), "[0, 2, 4]"); + for (const auto& values : ArrayVector{ree_values, nested}) { + ARROW_SCOPED_TRACE(values->type()->ToString()); + ASSERT_OK_AND_ASSIGN(auto expected, ListArray::FromArrays(*list_offsets, *values)); + ASSERT_OK_AND_ASSIGN(auto list_view, + ListViewArray::FromArrays(*offsets, *sizes, *values)); + ASSERT_OK_AND_ASSIGN(Datum out, Cast(list_view, expected->type())); + AssertDatumsEqual(expected, out); + } + + // Out-of-order views are packed with Concatenate, which cannot build run-end + // encoded arrays whose runs have an extension type yet. + offsets = ArrayFromJSON(int32(), "[2, 0, 1]"); + sizes = ArrayFromJSON(int32(), "[2, 2, 1]"); + for (const auto& values : ArrayVector{ree_values, nested}) { + ARROW_SCOPED_TRACE(values->type()->ToString()); + ASSERT_OK_AND_ASSIGN(auto list_view, + ListViewArray::FromArrays(*offsets, *sizes, *values)); + ASSERT_RAISES(NotImplemented, Cast(list_view, list(values->type()))); + } +} + +TEST(Cast, ListViewToListEdgeCases) { + auto values = ArrayFromJSON(int32(), "[1, 2, 3, 4]"); + + auto make = [](const char* offsets, const char* sizes, + const std::shared_ptr& values) { + return ListViewArray::FromArrays(*ArrayFromJSON(int32(), offsets), + *ArrayFromJSON(int32(), sizes), *values); + }; + + // Zero-length list-view. + CheckCast(ArrayFromJSON(list_view(int32()), "[]"), ArrayFromJSON(list(int32()), "[]")); + CheckCast(ArrayFromJSON(large_list_view(int32()), "[]"), + ArrayFromJSON(large_list(int32()), "[]")); + + // All views null, several with a non-zero declared size: no value is gathered. + { + ASSERT_OK_AND_ASSIGN(auto lv, make("[0, 2, 4]", "[2, 2, 2]", values)); + CheckCast(MaskArrayWithNullsAt(lv, {0, 1, 2}), + ArrayFromJSON(list(int32()), "[null, null, null]")); + } + + // Out-of-order/overlapping views combined with nulls. + { + ASSERT_OK_AND_ASSIGN(auto lv, make("[2, 0, 1]", "[2, 2, 1]", values)); + CheckCast(MaskArrayWithNullsAt(lv, {1}), + ArrayFromJSON(list(int32()), "[[3, 4], null, [2]]")); + } + + // A view of size zero interleaved with out-of-order views. + { + ASSERT_OK_AND_ASSIGN(auto lv, make("[1, 3, 0, 2]", "[0, 1, 4, 2]", values)); + CheckCast(lv, ArrayFromJSON(list(int32()), "[[], [4], [1, 2, 3, 4], [3, 4]]")); + } + + // The list-view's child array is itself sliced, i.e. has a non-zero offset. + { + auto sliced_values = ArrayFromJSON(int32(), "[9, 1, 2, 3, 4, 9]")->Slice(1, 4); + ASSERT_OK_AND_ASSIGN(auto lv, make("[2, 0, 1]", "[2, 2, 1]", sliced_values)); + CheckCast(lv, ArrayFromJSON(list(int32()), "[[3, 4], [1, 2], [2]]")); + } + + // Nested list-view, exercising the gather on a non-primitive child. + { + auto nested_values = + ArrayFromJSON(list(int32()), "[[10], [20, 21], [30, 31, 32], [40]]"); + ASSERT_OK_AND_ASSIGN(auto lv, make("[1, 0, 2]", "[1, 2, 2]", nested_values)); + CheckCast(lv, ArrayFromJSON(large_list(list(int64())), + "[[[20, 21]], [[10], [20, 21]], [[30, 31, 32], [40]]]")); + } + + // A sliced list-view whose validity bitmap bit offset is non-zero. + { + auto lv = ArrayFromJSON(list_view(int32()), + "[[1, 2], [3], null, [], [4], [5, 6], null, [7], [8, 9]]"); + CheckCast(lv->Slice(1, 7), + ArrayFromJSON(list(int32()), "[[3], null, [], [4], [5, 6], null, [7]]")); + CheckCast(lv->Slice(1, 7), ArrayFromJSON(large_list(int64()), + "[[3], null, [], [4], [5, 6], null, [7]]")); + } +} + TEST(Cast, ListToList) { CheckListToList({int32(), float32(), int64()}, "[[0], [1], null, [2, 3, 4], [5, 6], null, [], [7], [8, 9]]"); diff --git a/python/pyarrow/tests/test_array.py b/python/pyarrow/tests/test_array.py index 74ff837e16e8..18837d6b57eb 100644 --- a/python/pyarrow/tests/test_array.py +++ b/python/pyarrow/tests/test_array.py @@ -4538,6 +4538,60 @@ def test_list_view_slice(list_view_type): assert sliced_array[0].as_py() == sliced_array.values[i:j].to_pylist() == [4] +@pytest.mark.parametrize( + ('list_view_array_type', 'offset_type', 'list_factory'), + [ + (pa.ListViewArray, pa.int32(), pa.list_), + (pa.ListViewArray, pa.int32(), pa.large_list), + (pa.LargeListViewArray, pa.int64(), pa.list_), + (pa.LargeListViewArray, pa.int64(), pa.large_list), + ]) +def test_cast_list_view_to_list(list_view_array_type, offset_type, list_factory): + # Casting a list-view to a list has to gather the values referenced by each + # view: views are neither required to be laid out in order nor to be + # non-overlapping. See GH-51612. + views = list_view_array_type.from_arrays( + pa.array([2, 0, 1], type=offset_type), # offsets + pa.array([2, 2, 1], type=offset_type), # sizes + pa.array([1, 2, 3, 4], type=pa.int32()), # values + ) + + assert views.to_pylist() == [[3, 4], [1, 2], [2]] + + # The child values are cast as well. + for value_type, expected in [ + (pa.int32(), [[3, 4], [1, 2], [2]]), + (pa.int64(), [[3, 4], [1, 2], [2]]), + (pa.float64(), [[3.0, 4.0], [1.0, 2.0], [2.0]])]: + assert views.cast(list_factory(value_type)).to_pylist() == expected + + +def test_cast_list_view_to_list_nulls(): + # A null view must not contribute any values, whatever size it declares. + views = pa.ListViewArray.from_arrays( + pa.array([0, 2, 2], type=pa.int32()), # offsets + pa.array([2, 2, 2], type=pa.int32()), # sizes + pa.array([1, 2, 3, 4], type=pa.int32()), # values + mask=pa.array([False, True, False]), # True means null + ) + + assert views.to_pylist() == [[1, 2], None, [3, 4]] + assert views.cast(pa.list_(pa.int32())).to_pylist() == [[1, 2], None, [3, 4]] + + +def test_cast_list_view_to_list_sliced(): + # The validity bitmap of a sliced list-view must be read with the element + # offset applied as a bit offset. See GH-51613. + views = pa.array( + [[1, 2], [3], None, [], [4], [5, 6], None, [7], [8, 9]], + type=pa.list_view(pa.int32()), + ) + + sliced = views.slice(1, 7) + assert sliced.cast(pa.list_(pa.int32())).to_pylist() == [ + [3], None, [], [4], [5, 6], None, [7]] + + @pytest.mark.numpy @pytest.mark.parametrize('numpy_native_dtype', ['u2', 'i4', 'f8']) def test_swapped_byte_order_fails(numpy_native_dtype):