Skip to main content

vortex_array/arrays/masked/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use smallvec::smallvec;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10
11use crate::ArrayRef;
12use crate::ExecutionCtx;
13use crate::array::Array;
14use crate::array::ArrayParts;
15use crate::array::TypedArrayRef;
16use crate::array::child_to_validity;
17use crate::array::validity_to_child;
18use crate::array_slots;
19use crate::arrays::Masked;
20use crate::validity::Validity;
21
22#[array_slots(Masked)]
23pub struct MaskedSlots {
24    /// The underlying child array being masked.
25    #[slot(0)]
26    pub child: ArrayRef,
27    /// The validity bitmap defining which elements are non-null.
28    #[slot(1)]
29    pub validity_child: Option<ArrayRef>,
30}
31
32#[derive(Clone, Debug)]
33pub struct MaskedData;
34
35impl Display for MaskedData {
36    fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
37        Ok(())
38    }
39}
40
41pub trait MaskedArrayExt: TypedArrayRef<Masked> {
42    fn masked_validity(&self) -> Validity {
43        child_to_validity(self.validity_child(), self.dtype().nullability())
44    }
45}
46impl<T: TypedArrayRef<Masked>> MaskedArrayExt for T {}
47
48impl MaskedData {
49    pub(crate) fn try_new(
50        child_len: usize,
51        child_all_valid: bool,
52        validity: Validity,
53    ) -> VortexResult<Self> {
54        if matches!(validity, Validity::NonNullable) {
55            vortex_bail!("MaskedArray must have nullable validity, got {validity:?}")
56        }
57
58        if !child_all_valid {
59            vortex_bail!("MaskedArray children must not have nulls");
60        }
61
62        if let Some(validity_len) = validity.maybe_len()
63            && validity_len != child_len
64        {
65            vortex_bail!("Validity must be the same length as a MaskedArray's child");
66        }
67
68        // MaskedArray's nullability is determined solely by its validity, not the child's dtype.
69        // The child can have nullable dtype but must not have any actual null values.
70        Ok(Self)
71    }
72}
73
74impl Array<Masked> {
75    /// Constructs a new `MaskedArray`.
76    pub fn try_new(
77        child: ArrayRef,
78        validity: Validity,
79        ctx: &mut ExecutionCtx,
80    ) -> VortexResult<Self> {
81        let dtype = child.dtype().as_nullable();
82        let len = child.len();
83        let validity_child = validity_to_child(&validity, len);
84        let data = MaskedData::try_new(len, child.all_valid(ctx)?, validity)?;
85        Ok(unsafe {
86            Array::from_parts_unchecked(ArrayParts::new(
87                Masked,
88                dtype,
89                len,
90                data,
91                smallvec![Some(child), validity_child],
92            ))
93        })
94    }
95
96    /// Constructs a new `MaskedArray` without validating the child or validity.
97    ///
98    /// # Safety
99    ///
100    /// The caller must ensure that `child` contains no nulls, that `validity` is nullable, and
101    /// that an array-backed `validity` has the same length as `child`.
102    pub unsafe fn new_unchecked(child: ArrayRef, validity: Validity) -> Self {
103        let dtype = child.dtype().as_nullable();
104        let len = child.len();
105        let validity_child = validity_to_child(&validity, len);
106        unsafe {
107            Array::from_parts_unchecked(ArrayParts::new(
108                Masked,
109                dtype,
110                len,
111                MaskedData,
112                smallvec![Some(child), validity_child],
113            ))
114        }
115    }
116}