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::Array;
7use crate::ArrayRef;
8use crate::ExecutionCtx;
9use crate::IntoArray;
10use crate::arrays::MaskedArray;
11use crate::arrays::MaskedVTable;
12use crate::arrays::TakeExecute;
13use crate::builtins::ArrayBuiltins;
14use crate::scalar::Scalar;
15use crate::vtable::ValidityHelper;
16
17impl TakeExecute for MaskedVTable {
18    fn take(
19        array: &MaskedArray,
20        indices: &dyn Array,
21        _ctx: &mut ExecutionCtx,
22    ) -> VortexResult<Option<ArrayRef>> {
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.to_array().fill_null(fill_scalar)?;
27            array
28                .child
29                .take(filled_take_indices)?
30                .to_canonical()?
31                .into_array()
32        } else {
33            array
34                .child
35                .take(indices.to_array())?
36                .to_canonical()?
37                .into_array()
38        };
39
40        // Compute the new validity by taking from array's validity and merging with indices validity
41        let taken_validity = array.validity().take(indices)?;
42
43        // Construct new MaskedArray
44        Ok(Some(
45            MaskedArray::try_new(taken_child, taken_validity)?.into_array(),
46        ))
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use rstest::rstest;
53
54    use crate::IntoArray;
55    use crate::arrays::MaskedArray;
56    use crate::arrays::PrimitiveArray;
57    use crate::compute::conformance::take::test_take_conformance;
58    use crate::validity::Validity;
59
60    #[rstest]
61    #[case(
62        MaskedArray::try_new(
63            PrimitiveArray::from_iter([1i32, 2, 3, 4, 5]).into_array(),
64            Validity::from_iter([true, true, false, true, false])
65        ).unwrap()
66    )]
67    #[case(
68        MaskedArray::try_new(
69            PrimitiveArray::from_iter([10i32, 20, 30]).into_array(),
70            Validity::AllValid
71        ).unwrap()
72    )]
73    #[case(
74        MaskedArray::try_new(
75            PrimitiveArray::from_iter(0..100).into_array(),
76            Validity::from_iter((0..100).map(|i| i % 3 != 0))
77        ).unwrap()
78    )]
79    fn test_take_masked_conformance(#[case] array: MaskedArray) {
80        test_take_conformance(array.as_ref());
81    }
82}