diff --git a/cpp/src/arrow/compute/kernels/vector_pairwise.cc b/cpp/src/arrow/compute/kernels/vector_pairwise.cc index 51d6f959acf..55dedeef849 100644 --- a/cpp/src/arrow/compute/kernels/vector_pairwise.cc +++ b/cpp/src/arrow/compute/kernels/vector_pairwise.cc @@ -73,10 +73,12 @@ Status PairwiseExecImpl(KernelContext* ctx, const ArraySpan& input, } result->null_count = null_count; // prepare input span + // SetSlice overwrites offset. Keep the input's offset so a sliced + // array is not read from the start of the parent buffer. ArraySpan left(input); - left.SetSlice(left_start, computed_length); + left.SetSlice(input.offset + left_start, computed_length); ArraySpan right(input); - right.SetSlice(right_start, computed_length); + right.SetSlice(input.offset + right_start, computed_length); // prepare output span ArraySpan output_span; output_span.SetMembers(*result); diff --git a/cpp/src/arrow/compute/kernels/vector_pairwise_test.cc b/cpp/src/arrow/compute/kernels/vector_pairwise_test.cc index cae9469c3c9..7a13f5b5341 100644 --- a/cpp/src/arrow/compute/kernels/vector_pairwise_test.cc +++ b/cpp/src/arrow/compute/kernels/vector_pairwise_test.cc @@ -151,6 +151,26 @@ TEST_F(TestPairwiseDiff, Numeric) { } } +TEST_F(TestPairwiseDiff, SlicedInput) { + // Slice() keeps a nonzero offset into the parent buffer. The kernel + // used to treat that offset as zero and read values before the slice. + auto base = ArrayFromJSON(int64(), "[99, 1, 4, 9, 16, 88]"); + auto sliced = base->Slice(1, 4); + + { + PairwiseOptions options(1); + auto expected = ArrayFromJSON(int64(), "[null, 3, 5, 7]"); + CheckVectorUnary("pairwise_diff", sliced, expected, &options); + CheckVectorUnary("pairwise_diff_checked", sliced, expected, &options); + } + { + PairwiseOptions options(-1); + auto expected = ArrayFromJSON(int64(), "[-3, -5, -7, null]"); + CheckVectorUnary("pairwise_diff", sliced, expected, &options); + CheckVectorUnary("pairwise_diff_checked", sliced, expected, &options); + } +} + TEST_F(TestPairwiseDiff, Overflow) { { PairwiseOptions options(1);