vortex_array/arrays/masked/compute/
take.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5use vortex_scalar::Scalar;
6
7use crate::Array;
8use crate::ArrayRef;
9use crate::IntoArray;
10use crate::arrays::MaskedArray;
11use crate::arrays::MaskedVTable;
12use crate::compute::TakeKernel;
13use crate::compute::TakeKernelAdapter;
14use crate::compute::fill_null;
15use crate::compute::take;
16use crate::register_kernel;
17use crate::vtable::ValidityHelper;
18
19impl TakeKernel for MaskedVTable {
20    fn take(&self, array: &MaskedArray, indices: &dyn Array) -> VortexResult<ArrayRef> {
21        let taken_child = if !indices.all_valid() {
22            // This is safe because we'll mask out these positions in the validity
23            let filled_take = fill_null(
24                indices,
25                &Scalar::default_value(indices.dtype().clone().as_nonnullable()),
26            )?;
27            take(&array.child, &filled_take)?
28        } else {
29            take(&array.child, indices)?
30        };
31
32        // Compute the new validity by taking from array's validity and merging with indices validity
33        let taken_validity = array.validity().take(indices)?;
34
35        // Construct new MaskedArray
36        Ok(MaskedArray::try_new(taken_child, taken_validity)?.into_array())
37    }
38}
39
40register_kernel!(TakeKernelAdapter(MaskedVTable).lift());
41
42#[cfg(test)]
43mod tests {
44    use rstest::rstest;
45
46    use crate::IntoArray;
47    use crate::arrays::MaskedArray;
48    use crate::arrays::PrimitiveArray;
49    use crate::compute::conformance::take::test_take_conformance;
50    use crate::validity::Validity;
51
52    #[rstest]
53    #[case(
54        MaskedArray::try_new(
55            PrimitiveArray::from_iter([1i32, 2, 3, 4, 5]).into_array(),
56            Validity::from_iter([true, true, false, true, false])
57        ).unwrap()
58    )]
59    #[case(
60        MaskedArray::try_new(
61            PrimitiveArray::from_iter([10i32, 20, 30]).into_array(),
62            Validity::AllValid
63        ).unwrap()
64    )]
65    #[case(
66        MaskedArray::try_new(
67            PrimitiveArray::from_iter(0..100).into_array(),
68            Validity::from_iter((0..100).map(|i| i % 3 != 0))
69        ).unwrap()
70    )]
71    fn test_take_masked_conformance(#[case] array: MaskedArray) {
72        test_take_conformance(array.as_ref());
73    }
74}