Skip to main content

vortex_array/arrays/runend/compute/
take.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use num_traits::AsPrimitive;
5use num_traits::NumCast;
6use vortex_buffer::Buffer;
7use vortex_buffer::BufferMut;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_mask::AllOr;
11use vortex_mask::Mask;
12
13use crate::ArrayRef;
14use crate::ArrayView;
15use crate::ExecutionCtx;
16use crate::IntoArray;
17use crate::arrays::ConstantArray;
18use crate::arrays::PrimitiveArray;
19use crate::arrays::dict::TakeExecute;
20use crate::arrays::primitive::PrimitiveArrayExt;
21use crate::arrays::runend::RunEnd;
22use crate::arrays::runend::array::RunEndArrayExt;
23use crate::arrays::runend::array::RunEndArraySlotsExt;
24use crate::arrays::runend::iter::slice_relative_ends;
25use crate::dtype::UnsignedPType;
26use crate::match_each_unsigned_integer_ptype;
27use crate::scalar::Scalar;
28use crate::validity::Validity;
29
30const SORTED_LINEAR_RUNS_PER_INDEX_THRESHOLD: usize = 16;
31const UNSORTED_LINEAR_RUNS_PER_INDEX_THRESHOLD: usize = 4;
32/// Sorting the indices and merging only beats per-index binary search once the run ends are too
33/// large to stay cache-resident; below this run count binary search wins.
34const UNSORTED_LINEAR_MIN_RUNS: usize = 1 << 19;
35/// Use a dense logical-position-to-run-index table when the array length is at most this many
36/// times the number of valid indices: building the table is O(array_len) and each index then
37/// resolves with a single unconditional gather.
38const TABLE_LEN_PER_INDEX_THRESHOLD: usize = 8;
39
40impl TakeExecute for RunEnd {
41    fn take(
42        array: ArrayView<'_, Self>,
43        indices: &ArrayRef,
44        ctx: &mut ExecutionCtx,
45    ) -> VortexResult<Option<ArrayRef>> {
46        let primitive_indices = indices.clone().execute::<PrimitiveArray>(ctx)?;
47        // Indices are non-negative; read them through their unsigned reinterpretation so the
48        // kernel monomorphizes over 4 index widths instead of 8.
49        let primitive_indices =
50            primitive_indices.reinterpret_cast(primitive_indices.ptype().to_unsigned());
51        let indices_validity = primitive_indices.validity()?;
52        let indices_mask = indices_validity.execute_mask(primitive_indices.len(), ctx)?;
53
54        let taken = match_each_unsigned_integer_ptype!(primitive_indices.ptype(), |P| {
55            take_indices(
56                array,
57                primitive_indices.as_slice::<P>(),
58                &indices_validity,
59                &indices_mask,
60                true,
61                ctx,
62            )?
63        });
64
65        Ok(Some(taken))
66    }
67}
68
69/// Perform a take operation on a RunEndArray without bounds-checking the indices.
70///
71/// The caller must guarantee that all valid indices are in bounds for the array.
72pub fn take_indices_unchecked<T: AsPrimitive<usize>>(
73    array: ArrayView<'_, RunEnd>,
74    indices: &[T],
75    validity: &Validity,
76    ctx: &mut ExecutionCtx,
77) -> VortexResult<ArrayRef> {
78    let validity_mask = validity.execute_mask(indices.len(), ctx)?;
79    take_indices(array, indices, validity, &validity_mask, false, ctx)
80}
81
82fn take_indices<T: AsPrimitive<usize>>(
83    array: ArrayView<'_, RunEnd>,
84    indices: &[T],
85    validity: &Validity,
86    validity_mask: &Mask,
87    check_bounds: bool,
88    ctx: &mut ExecutionCtx,
89) -> VortexResult<ArrayRef> {
90    if validity_mask.all_false() {
91        return Ok(
92            ConstantArray::new(Scalar::null(array.dtype().as_nullable()), indices.len())
93                .into_array(),
94        );
95    }
96
97    let stats = valid_indices_stats(indices, validity_mask, array.len(), check_bounds)?;
98    let ends = array.ends().clone().execute::<PrimitiveArray>(ctx)?;
99
100    let physical_indices = match_each_unsigned_integer_ptype!(ends.ptype(), |I| {
101        let ends = ends.as_slice::<I>();
102        // Run indices fit in u32 for any realistic array; the narrower physical indices halve
103        // the memory traffic of the downstream take on the values.
104        if ends.len() <= u32::MAX as usize {
105            PrimitiveArray::new(
106                physical_indices_with_stats::<_, _, u32>(
107                    ends,
108                    array.offset(),
109                    array.len(),
110                    indices,
111                    validity_mask,
112                    stats,
113                ),
114                validity.clone(),
115            )
116        } else {
117            PrimitiveArray::new(
118                physical_indices_with_stats::<_, _, u64>(
119                    ends,
120                    array.offset(),
121                    array.len(),
122                    indices,
123                    validity_mask,
124                    stats,
125                ),
126                validity.clone(),
127            )
128        }
129    });
130
131    array.values().take(physical_indices.into_array())
132}
133
134#[derive(Clone, Copy)]
135struct ValidIndicesStats {
136    count: usize,
137    sorted: bool,
138}
139
140fn physical_indices_with_stats<I, T, O>(
141    ends: &[I],
142    offset: usize,
143    array_len: usize,
144    indices: &[T],
145    validity_mask: &Mask,
146    stats: ValidIndicesStats,
147) -> Buffer<O>
148where
149    I: UnsignedPType,
150    T: AsPrimitive<usize>,
151    O: UnsignedPType,
152    usize: AsPrimitive<O>,
153{
154    if stats.count == 0 {
155        return Buffer::zeroed(indices.len());
156    }
157
158    if stats.sorted
159        && prefer_linear_scan(
160            ends.len(),
161            stats.count,
162            SORTED_LINEAR_RUNS_PER_INDEX_THRESHOLD,
163        )
164    {
165        return physical_indices_linear_sorted(ends, offset, indices, validity_mask);
166    }
167
168    // A dense take resolves fastest through the position table regardless of index ordering.
169    // Sorted indices reach here only when there are too many runs for the sorted linear scan,
170    // for example a narrow slice of a heavily run-encoded array where runs far exceed array_len.
171    if array_len <= stats.count.saturating_mul(TABLE_LEN_PER_INDEX_THRESHOLD) {
172        return physical_indices_table(ends, offset, array_len, indices, validity_mask);
173    }
174
175    if ends.len() >= UNSORTED_LINEAR_MIN_RUNS
176        && prefer_linear_scan(
177            ends.len(),
178            stats.count,
179            UNSORTED_LINEAR_RUNS_PER_INDEX_THRESHOLD,
180        )
181    {
182        return physical_indices_linear_unsorted(ends, offset, indices, validity_mask, stats.count);
183    }
184
185    physical_indices_binary(ends, offset, indices, validity_mask)
186}
187
188/// Count the valid indices and determine whether they are sorted, bounds-checking each valid
189/// index against `array_len` when `check_bounds` is set.
190fn valid_indices_stats<T: AsPrimitive<usize>>(
191    indices: &[T],
192    validity_mask: &Mask,
193    array_len: usize,
194    check_bounds: bool,
195) -> VortexResult<ValidIndicesStats> {
196    debug_assert_eq!(indices.len(), validity_mask.len());
197
198    let count = validity_mask.true_count();
199    if count == 0 {
200        return Ok(ValidIndicesStats {
201            count,
202            sorted: true,
203        });
204    }
205
206    let sorted = match validity_mask.bit_buffer() {
207        AllOr::All => valid_indices_sorted_all(indices, array_len, check_bounds)?,
208        AllOr::None => true,
209        AllOr::Some(validity) => {
210            valid_indices_sorted_masked(indices, validity.iter(), array_len, check_bounds)?
211        }
212    };
213
214    Ok(ValidIndicesStats { count, sorted })
215}
216
217fn valid_indices_sorted_all<T: AsPrimitive<usize>>(
218    indices: &[T],
219    array_len: usize,
220    check_bounds: bool,
221) -> VortexResult<bool> {
222    // Seed the comparison with the first index; an empty or single-element slice is trivially
223    // sorted, so the loop below starts from the second element.
224    let Some((first, rest)) = indices.split_first() else {
225        return Ok(true);
226    };
227
228    let mut previous_idx = first.as_();
229    if check_bounds {
230        check_index(previous_idx, array_len)?;
231    }
232
233    let mut sorted = true;
234    for idx in rest {
235        let idx = idx.as_();
236        if check_bounds {
237            check_index(idx, array_len)?;
238        }
239        if previous_idx > idx {
240            sorted = false;
241            if !check_bounds {
242                break;
243            }
244        }
245        previous_idx = idx;
246    }
247
248    Ok(sorted)
249}
250
251fn valid_indices_sorted_masked<T: AsPrimitive<usize>>(
252    indices: &[T],
253    is_valid: impl Iterator<Item = bool>,
254    array_len: usize,
255    check_bounds: bool,
256) -> VortexResult<bool> {
257    // Invalid positions are skipped without a bounds check, matching the take path that never
258    // dereferences them.
259    let mut valid = is_valid
260        .zip(indices.iter())
261        .filter(|(is_valid, _)| *is_valid)
262        .map(|(_, idx)| idx.as_());
263
264    // Seed the comparison with the first valid index; zero or one valid index is trivially
265    // sorted, so the loop below starts from the second valid index.
266    let Some(mut previous_idx) = valid.next() else {
267        return Ok(true);
268    };
269    if check_bounds {
270        check_index(previous_idx, array_len)?;
271    }
272
273    let mut sorted = true;
274    for idx in valid {
275        if check_bounds {
276            check_index(idx, array_len)?;
277        }
278        if previous_idx > idx {
279            sorted = false;
280            if !check_bounds {
281                break;
282            }
283        }
284        previous_idx = idx;
285    }
286
287    Ok(sorted)
288}
289
290fn prefer_linear_scan(
291    ends_len: usize,
292    valid_count: usize,
293    runs_per_index_threshold: usize,
294) -> bool {
295    ends_len <= valid_count.saturating_mul(runs_per_index_threshold)
296}
297
298fn check_index(index: usize, array_len: usize) -> VortexResult<()> {
299    if index >= array_len {
300        vortex_bail!("index {} out of bounds from {} to {}", index, 0, array_len);
301    }
302    Ok(())
303}
304
305fn physical_indices_linear_sorted<I, T, O>(
306    ends: &[I],
307    offset: usize,
308    indices: &[T],
309    validity_mask: &Mask,
310) -> Buffer<O>
311where
312    I: UnsignedPType,
313    T: AsPrimitive<usize>,
314    O: UnsignedPType,
315    usize: AsPrimitive<O>,
316{
317    let mut run_idx = 0;
318
319    match validity_mask.bit_buffer() {
320        AllOr::All => Buffer::from_trusted_len_iter(indices.iter().map(|idx| {
321            advance_run(ends, &mut run_idx, idx.as_() + offset);
322            run_idx.as_()
323        })),
324        AllOr::None => unreachable!("AllInvalid indices have been handled earlier"),
325        AllOr::Some(validity) => {
326            // Invalid positions keep physical index zero, which is always in-bounds for the
327            // values and masked out by the result validity.
328            let mut physical_indices = BufferMut::zeroed(indices.len());
329            for (idx_pos, (is_valid, idx)) in validity.iter().zip(indices.iter()).enumerate() {
330                if !is_valid {
331                    continue;
332                }
333
334                advance_run(ends, &mut run_idx, idx.as_() + offset);
335                physical_indices[idx_pos] = run_idx.as_();
336            }
337            physical_indices.freeze()
338        }
339    }
340}
341
342/// Resolve indices through a dense logical-position-to-run-index table.
343///
344/// Building the table costs O(array_len), but every index then resolves with an unconditional
345/// gather, which beats per-index binary search and sort-then-merge for dense takes. Invalid
346/// indices may hold arbitrary values (even out of bounds), so they are redirected to position
347/// zero instead of branching; the result validity masks whatever they resolve to.
348fn physical_indices_table<I, T, O>(
349    ends: &[I],
350    offset: usize,
351    array_len: usize,
352    indices: &[T],
353    validity_mask: &Mask,
354) -> Buffer<O>
355where
356    I: UnsignedPType,
357    T: AsPrimitive<usize>,
358    O: UnsignedPType,
359    usize: AsPrimitive<O>,
360{
361    let table = run_index_table::<I, O>(ends, offset, array_len);
362    let table = table.as_slice();
363
364    match validity_mask.bit_buffer() {
365        AllOr::All => Buffer::from_trusted_len_iter(indices.iter().map(|idx| table[idx.as_()])),
366        AllOr::None => unreachable!("AllInvalid indices have been handled earlier"),
367        AllOr::Some(validity) => Buffer::from_trusted_len_iter(
368            validity
369                .iter()
370                .zip(indices.iter())
371                .map(|(is_valid, idx)| table[if is_valid { idx.as_() } else { 0 }]),
372        ),
373    }
374}
375
376/// Materialize the run index of every logical position in `[0, len)`.
377fn run_index_table<I, O>(ends: &[I], offset: usize, len: usize) -> Buffer<O>
378where
379    I: UnsignedPType,
380    O: UnsignedPType,
381    usize: AsPrimitive<O>,
382{
383    let mut table = BufferMut::with_capacity(len);
384    let mut run_start = 0;
385    for (run_idx, run_end) in slice_relative_ends(ends, offset, len).enumerate() {
386        table.push_n(run_idx.as_(), run_end - run_start);
387        run_start = run_end;
388    }
389    table.freeze()
390}
391
392fn physical_indices_linear_unsorted<I, T, O>(
393    ends: &[I],
394    offset: usize,
395    indices: &[T],
396    validity_mask: &Mask,
397    valid_count: usize,
398) -> Buffer<O>
399where
400    I: UnsignedPType,
401    T: AsPrimitive<usize>,
402    O: UnsignedPType,
403    usize: AsPrimitive<O>,
404{
405    let mut pairs = Vec::with_capacity(valid_count);
406    match validity_mask.bit_buffer() {
407        AllOr::All => {
408            pairs.extend(
409                indices
410                    .iter()
411                    .enumerate()
412                    .map(|(idx_pos, idx)| (idx.as_(), idx_pos)),
413            );
414        }
415        AllOr::None => unreachable!("AllInvalid indices have been handled earlier"),
416        AllOr::Some(validity) => {
417            for (idx_pos, (is_valid, idx)) in validity.iter().zip(indices.iter()).enumerate() {
418                if is_valid {
419                    pairs.push((idx.as_(), idx_pos));
420                }
421            }
422        }
423    }
424    pairs.sort_unstable();
425
426    let mut physical_indices = BufferMut::zeroed(indices.len());
427    let mut run_idx = 0;
428
429    for (idx, idx_pos) in pairs {
430        advance_run(ends, &mut run_idx, idx + offset);
431        physical_indices[idx_pos] = run_idx.as_();
432    }
433
434    physical_indices.freeze()
435}
436
437fn physical_indices_binary<I, T, O>(
438    ends: &[I],
439    offset: usize,
440    indices: &[T],
441    validity_mask: &Mask,
442) -> Buffer<O>
443where
444    I: UnsignedPType,
445    T: AsPrimitive<usize>,
446    O: UnsignedPType,
447    usize: AsPrimitive<O>,
448{
449    match validity_mask.bit_buffer() {
450        AllOr::All => Buffer::from_trusted_len_iter(
451            indices
452                .iter()
453                .map(|idx| physical_index_binary(ends, idx.as_() + offset).as_()),
454        ),
455        AllOr::None => Buffer::zeroed(indices.len()),
456        AllOr::Some(validity) => {
457            let mut physical_indices = BufferMut::zeroed(indices.len());
458            for (idx_pos, (is_valid, idx)) in validity.iter().zip(indices.iter()).enumerate() {
459                if !is_valid {
460                    continue;
461                }
462
463                physical_indices[idx_pos] = physical_index_binary(ends, idx.as_() + offset).as_();
464            }
465            physical_indices.freeze()
466        }
467    }
468}
469
470fn physical_index_binary<I: UnsignedPType>(ends: &[I], logical_idx: usize) -> usize {
471    let index = match <I as NumCast>::from(logical_idx) {
472        Some(logical_idx) => ends.partition_point(|end| *end <= logical_idx),
473        None => ends.len(),
474    };
475    index.min(ends.len() - 1)
476}
477
478fn advance_run<I: UnsignedPType>(ends: &[I], run_idx: &mut usize, logical_idx: usize) {
479    // A logical index that overflows the run-end type sits past every run, so it lands in the
480    // final run; otherwise advance while the current run ends at or before it.
481    let Some(logical_idx) = I::from(logical_idx) else {
482        *run_idx = ends.len().saturating_sub(1);
483        return;
484    };
485    while *run_idx + 1 < ends.len() && ends[*run_idx] <= logical_idx {
486        *run_idx += 1;
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use std::sync::LazyLock;
493
494    use rstest::rstest;
495    use vortex_buffer::buffer;
496    use vortex_mask::Mask;
497    use vortex_session::VortexSession;
498
499    use super::physical_indices_binary;
500    use super::physical_indices_linear_sorted;
501    use super::physical_indices_linear_unsorted;
502    use super::physical_indices_table;
503    use crate::ArrayRef;
504    use crate::Canonical;
505    use crate::IntoArray;
506    use crate::VortexSessionExecute;
507    use crate::arrays::BoolArray;
508    use crate::arrays::PrimitiveArray;
509    use crate::arrays::runend::RunEnd;
510    use crate::arrays::runend::RunEndArray;
511    use crate::assert_arrays_eq;
512    use crate::compute::conformance::take::test_take_conformance;
513    use crate::validity::Validity;
514
515    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
516
517    fn ree_array() -> RunEndArray {
518        RunEnd::encode(
519            buffer![1, 1, 1, 4, 4, 4, 2, 2, 5, 5, 5, 5].into_array(),
520            &mut SESSION.create_execution_ctx(),
521        )
522        .unwrap()
523    }
524
525    #[test]
526    fn ree_take() {
527        let taken = ree_array().take(buffer![9, 8, 1, 3].into_array()).unwrap();
528        let expected = PrimitiveArray::from_iter(vec![5i32, 5, 1, 4]).into_array();
529        assert_arrays_eq!(taken, expected, &mut SESSION.create_execution_ctx());
530    }
531
532    #[test]
533    fn ree_take_end() {
534        let taken = ree_array().take(buffer![11].into_array()).unwrap();
535        let expected = PrimitiveArray::from_iter(vec![5i32]).into_array();
536        assert_arrays_eq!(taken, expected, &mut SESSION.create_execution_ctx());
537    }
538
539    #[test]
540    fn ree_take_sorted_boundaries() {
541        let taken = ree_array()
542            .take(buffer![0, 2, 3, 6, 8, 11].into_array())
543            .unwrap();
544        let expected = PrimitiveArray::from_iter(vec![1i32, 1, 4, 2, 5, 5]).into_array();
545        assert_arrays_eq!(taken, expected, &mut SESSION.create_execution_ctx());
546    }
547
548    #[test]
549    #[should_panic]
550    fn ree_take_out_of_bounds() {
551        let _array = ree_array()
552            .take(buffer![12].into_array())
553            .unwrap()
554            .execute::<Canonical>(&mut SESSION.create_execution_ctx())
555            .unwrap();
556    }
557
558    #[test]
559    fn sliced_take() {
560        let sliced = ree_array().slice(4..9).unwrap();
561        let taken = sliced.take(buffer![1, 3, 4].into_array()).unwrap();
562
563        let expected = PrimitiveArray::from_iter(vec![4i32, 2, 5]).into_array();
564        assert_arrays_eq!(taken, expected, &mut SESSION.create_execution_ctx());
565    }
566
567    #[test]
568    fn sliced_take_unsorted_dense() {
569        let sliced = ree_array().slice(4..9).unwrap();
570        let taken = sliced.take(buffer![4, 0, 2, 1].into_array()).unwrap();
571
572        let expected = PrimitiveArray::from_iter(vec![5i32, 4, 2, 4]).into_array();
573        assert_arrays_eq!(taken, expected, &mut SESSION.create_execution_ctx());
574    }
575
576    #[test]
577    fn ree_take_nullable() {
578        let taken = ree_array()
579            .take(PrimitiveArray::from_option_iter([Some(1), None]).into_array())
580            .unwrap();
581
582        let expected = PrimitiveArray::from_option_iter([Some(1i32), None]);
583        assert_arrays_eq!(
584            taken,
585            expected.into_array(),
586            &mut SESSION.create_execution_ctx()
587        );
588    }
589
590    #[test]
591    fn ree_take_all_null_indices() {
592        let taken = ree_array()
593            .take(PrimitiveArray::from_option_iter([None::<u64>, None]).into_array())
594            .unwrap();
595
596        let expected = PrimitiveArray::from_option_iter([None::<i32>, None]);
597        assert_arrays_eq!(
598            taken,
599            expected.into_array(),
600            &mut SESSION.create_execution_ctx()
601        );
602    }
603
604    #[test]
605    fn ree_take_null_index_skips_out_of_bounds_value() {
606        let indices = PrimitiveArray::new(
607            buffer![1u64, 12],
608            Validity::Array(BoolArray::from_iter([true, false]).into_array()),
609        );
610        let taken = ree_array().take(indices.into_array()).unwrap();
611
612        let expected = PrimitiveArray::from_option_iter([Some(1i32), None]);
613        assert_arrays_eq!(
614            taken,
615            expected.into_array(),
616            &mut SESSION.create_execution_ctx()
617        );
618    }
619
620    #[test]
621    fn ree_take_unsorted_null_index_skips_out_of_bounds_value() {
622        let indices = PrimitiveArray::new(
623            buffer![3u64, 12, 1],
624            Validity::Array(BoolArray::from_iter([true, false, true]).into_array()),
625        );
626        let taken = ree_array().take(indices.into_array()).unwrap();
627
628        let expected = PrimitiveArray::from_option_iter([Some(4i32), None, Some(1)]);
629        assert_arrays_eq!(
630            taken,
631            expected.into_array(),
632            &mut SESSION.create_execution_ctx()
633        );
634    }
635
636    #[test]
637    fn ree_take_dense_null_index_skips_out_of_bounds_value() {
638        let indices = PrimitiveArray::new(
639            buffer![0u64, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12],
640            Validity::Array(
641                BoolArray::from_iter([
642                    true, true, true, true, true, true, true, true, true, true, true, false,
643                ])
644                .into_array(),
645            ),
646        );
647        let taken = ree_array().take(indices.into_array()).unwrap();
648
649        let expected = PrimitiveArray::from_option_iter([
650            Some(1i32),
651            Some(1),
652            Some(1),
653            Some(4),
654            Some(4),
655            Some(4),
656            Some(2),
657            Some(2),
658            Some(5),
659            Some(5),
660            Some(5),
661            None,
662        ]);
663        assert_arrays_eq!(
664            taken,
665            expected.into_array(),
666            &mut SESSION.create_execution_ctx()
667        );
668    }
669
670    #[rstest]
671    #[case(vec![3u32, 6, 8, 12], 0, 12, vec![0u64, 11, 3, 3, 7, 2, 9], Mask::new_true(7), vec![0u64, 3, 1, 1, 2, 0, 3])]
672    #[case(vec![3u32, 6, 8, 12], 0, 12, vec![5u64, 100, 2, 11, 0], Mask::from_indices(5, [0, 2, 3, 4]), vec![1u64, 0, 0, 3, 0])]
673    #[case(vec![6u32, 8, 12], 4, 5, vec![4u64, 0, 2, 1, 3], Mask::new_true(5), vec![2u64, 0, 1, 0, 1])]
674    fn unsorted_strategies_agree(
675        #[case] ends: Vec<u32>,
676        #[case] offset: usize,
677        #[case] len: usize,
678        #[case] indices: Vec<u64>,
679        #[case] mask: Mask,
680        #[case] expected: Vec<u64>,
681    ) {
682        let binary = physical_indices_binary::<u32, u64, u64>(&ends, offset, &indices, &mask);
683        let table = physical_indices_table::<u32, u64, u64>(&ends, offset, len, &indices, &mask);
684        let sort_merge = physical_indices_linear_unsorted::<u32, u64, u64>(
685            &ends,
686            offset,
687            &indices,
688            &mask,
689            mask.true_count(),
690        );
691
692        assert_eq!(binary.as_slice(), expected.as_slice());
693        assert_eq!(binary.as_slice(), table.as_slice());
694        assert_eq!(binary.as_slice(), sort_merge.as_slice());
695    }
696
697    #[rstest]
698    #[case(vec![3u32, 6, 8, 12], 0, 12, vec![0u64, 2, 3, 6, 8, 11], Mask::new_true(6), vec![0u64, 0, 1, 2, 3, 3])]
699    #[case(vec![3u32, 6, 8, 12], 0, 12, vec![1u64, 100, 5, 9], Mask::from_indices(4, [0, 2, 3]), vec![0u64, 0, 1, 3])]
700    #[case(vec![6u32, 8, 12], 4, 5, vec![0u64, 1, 3, 4], Mask::new_true(4), vec![0u64, 0, 1, 2])]
701    fn sorted_strategies_agree(
702        #[case] ends: Vec<u32>,
703        #[case] offset: usize,
704        #[case] len: usize,
705        #[case] indices: Vec<u64>,
706        #[case] mask: Mask,
707        #[case] expected: Vec<u64>,
708    ) {
709        let binary = physical_indices_binary::<u32, u64, u64>(&ends, offset, &indices, &mask);
710        let table = physical_indices_table::<u32, u64, u64>(&ends, offset, len, &indices, &mask);
711        let sorted =
712            physical_indices_linear_sorted::<u32, u64, u64>(&ends, offset, &indices, &mask);
713
714        assert_eq!(binary.as_slice(), expected.as_slice());
715        assert_eq!(binary.as_slice(), table.as_slice());
716        assert_eq!(binary.as_slice(), sorted.as_slice());
717    }
718
719    #[rstest]
720    #[case(ree_array())]
721    #[case(RunEnd::encode(
722        buffer![1u8, 1, 2, 2, 2, 3, 3, 3, 3, 4].into_array(),
723        &mut SESSION.create_execution_ctx(),
724    ).unwrap())]
725    #[case(RunEnd::encode(
726        PrimitiveArray::from_option_iter([
727            Some(10),
728            Some(10),
729            None,
730            None,
731            Some(20),
732            Some(20),
733            Some(20),
734        ])
735        .into_array(),
736        &mut SESSION.create_execution_ctx(),
737    ).unwrap())]
738    #[case(RunEnd::encode(buffer![42i32, 42, 42, 42, 42].into_array(),
739        &mut SESSION.create_execution_ctx())
740        .unwrap())]
741    #[case(RunEnd::encode(
742        buffer![1i32, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_array(),
743        &mut SESSION.create_execution_ctx(),
744    ).unwrap())]
745    #[case({
746        let mut values = Vec::new();
747        for i in 0..20 {
748            for _ in 0..=i {
749                values.push(i);
750            }
751        }
752        RunEnd::encode(
753            PrimitiveArray::from_iter(values).into_array(),
754            &mut SESSION.create_execution_ctx(),
755        )
756        .unwrap()
757    })]
758    fn test_take_runend_conformance(#[case] array: RunEndArray) {
759        test_take_conformance(&array.into_array(), &mut SESSION.create_execution_ctx());
760    }
761
762    #[rstest]
763    #[case(ree_array().slice(3..6).unwrap())]
764    #[case({
765        let array = RunEnd::encode(
766            buffer![1i32, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3].into_array(),
767            &mut SESSION.create_execution_ctx(),
768        )
769        .unwrap();
770        array.slice(2..8).unwrap()
771    })]
772    fn test_take_sliced_runend_conformance(#[case] sliced: ArrayRef) {
773        test_take_conformance(&sliced, &mut SESSION.create_execution_ctx());
774    }
775}