Skip to main content

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;
5
6use crate::ArrayRef;
7use crate::IntoArray;
8use crate::array::ArrayView;
9use crate::arrays::Masked;
10use crate::arrays::MaskedArray;
11use crate::arrays::dict::TakeReduce;
12use crate::arrays::masked::MaskedArrayExt;
13use crate::builtins::ArrayBuiltins;
14use crate::scalar::Scalar;
15use crate::validity::Validity;
16
17impl TakeReduce for Masked {
18    fn take(array: ArrayView<'_, Masked>, indices: &ArrayRef) -> VortexResult<Option<ArrayRef>> {
19        let indices_all_valid = matches!(
20            indices.validity()?,
21            Validity::NonNullable | Validity::AllValid
22        );
23        let taken_child = if !indices_all_valid {
24            // This is safe because we'll mask out these positions in the validity.
25            let fill_scalar = Scalar::zero_value(indices.dtype());
26            let filled_take_indices = indices.clone().fill_null(fill_scalar)?;
27            array.child().take(filled_take_indices)?
28        } else {
29            array.child().take(indices.clone())?
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(Some(
37            MaskedArray::try_new(taken_child, taken_validity)?.into_array(),
38        ))
39    }
40}
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.into_array());
73    }
74}