Skip to main content

vortex_array/arrays/primitive/compute/
rules.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::Primitive;
11use crate::arrays::PrimitiveArray;
12use crate::arrays::slice::SliceReduceAdaptor;
13use crate::optimizer::rules::ArrayParentReduceRule;
14use crate::optimizer::rules::ParentRuleSet;
15use crate::scalar_fn::fns::mask::MaskReduceAdaptor;
16
17pub(crate) const RULES: ParentRuleSet<Primitive> = ParentRuleSet::new(&[
18    ParentRuleSet::lift(&PrimitiveMaskedValidityRule),
19    ParentRuleSet::lift(&MaskReduceAdaptor(Primitive)),
20    ParentRuleSet::lift(&SliceReduceAdaptor(Primitive)),
21]);
22
23/// Rule to push down validity masking from MaskedArray parent into PrimitiveArray child.
24///
25/// When a PrimitiveArray is wrapped by a MaskedArray, this rule merges the mask's validity
26/// with the PrimitiveArray's existing validity, eliminating the need for the MaskedArray wrapper.
27#[derive(Default, Debug)]
28pub struct PrimitiveMaskedValidityRule;
29
30impl ArrayParentReduceRule<Primitive> for PrimitiveMaskedValidityRule {
31    type Parent = Masked;
32
33    fn reduce_parent(
34        &self,
35        array: ArrayView<'_, Primitive>,
36        parent: ArrayView<'_, Masked>,
37        _child_idx: usize,
38    ) -> VortexResult<Option<ArrayRef>> {
39        // TODO(joe): make this lazy
40        // Merge the parent's validity mask into the child's validity
41        let new_validity = array.validity()?.and(parent.validity()?)?;
42
43        // SAFETY: masking validity does not change PrimitiveArray invariants
44        let masked_array = unsafe {
45            PrimitiveArray::new_unchecked_from_handle(
46                array.buffer_handle().clone(),
47                array.ptype(),
48                new_validity,
49            )
50        };
51
52        Ok(Some(masked_array.into_array()))
53    }
54}