vortex_array/arrays/masked/vtable/
mod.rs1mod operations;
4mod plugin;
5mod validity;
6
7use std::hash::Hasher;
8
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_ensure_eq;
13use vortex_error::vortex_panic;
14use vortex_session::registry::CachedId;
15
16use crate::AnyCanonical;
17use crate::ArrayEq;
18use crate::ArrayHash;
19use crate::ArrayParts;
20use crate::ArrayRef;
21use crate::Canonical;
22use crate::EqMode;
23use crate::IntoArray;
24use crate::array::Array;
25use crate::array::ArrayId;
26use crate::array::ArrayView;
27use crate::array::VTable;
28use crate::array::with_empty_buffers;
29use crate::arrays::ConstantArray;
30use crate::arrays::masked::MaskedArrayExt;
31use crate::arrays::masked::MaskedArraySlotsExt;
32use crate::arrays::masked::MaskedData;
33use crate::arrays::masked::array::MaskedSlots;
34use crate::arrays::masked::mask_validity_canonical;
35use crate::buffer::BufferHandle;
36use crate::dtype::DType;
37use crate::executor::ExecutionCtx;
38use crate::executor::ExecutionResult;
39use crate::require_child;
40use crate::scalar::Scalar;
41pub type MaskedArray = Array<Masked>;
43
44#[derive(Clone, Debug)]
45pub struct Masked;
46
47impl ArrayHash for MaskedData {
48 fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {}
49}
50
51impl ArrayEq for MaskedData {
52 fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
53 true
54 }
55}
56
57impl VTable for Masked {
58 type TypedArrayData = MaskedData;
59
60 type OperationsVTable = Self;
61 type ValidityVTable = Self;
62
63 fn id(&self) -> ArrayId {
64 static ID: CachedId = CachedId::new("vortex.masked");
65 *ID
66 }
67
68 fn validate(
69 &self,
70 _data: &MaskedData,
71 dtype: &DType,
72 len: usize,
73 slots: &[Option<ArrayRef>],
74 ) -> VortexResult<()> {
75 vortex_ensure!(
76 slots[MaskedSlots::CHILD].is_some(),
77 "MaskedArray child slot must be present"
78 );
79 let child = slots[MaskedSlots::CHILD]
80 .as_ref()
81 .vortex_expect("validated child slot");
82 vortex_ensure_eq!(child.len(), len, "MaskedArray child length mismatch");
83 vortex_ensure_eq!(
84 child.dtype().as_nullable(),
85 *dtype,
86 "MaskedArray dtype does not match child and validity",
87 );
88 Ok(())
89 }
90
91 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
92 0
93 }
94
95 fn buffer(_array: ArrayView<'_, Self>, _idx: usize) -> BufferHandle {
96 vortex_panic!("MaskedArray has no buffers")
97 }
98
99 fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
100 None
101 }
102
103 fn with_buffers(
104 &self,
105 array: ArrayView<'_, Self>,
106 buffers: &[BufferHandle],
107 ) -> VortexResult<ArrayParts<Self>> {
108 with_empty_buffers(self, array, buffers)
109 }
110
111 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
112 let array = require_child!(array, array.child(), MaskedSlots::CHILD => AnyCanonical);
113
114 let validity = array.masked_validity();
115
116 if validity.definitely_all_null() {
118 return Ok(ExecutionResult::done(
119 ConstantArray::new(Scalar::null(array.dtype().as_nullable()), array.len())
120 .into_array(),
121 ));
122 }
123
124 let child = Canonical::from(array.child().as_::<AnyCanonical>());
131 Ok(ExecutionResult::done(
132 mask_validity_canonical(child, validity, ctx)?.into_array(),
133 ))
134 }
135
136 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
137 MaskedSlots::NAMES[idx].to_string()
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use std::sync::LazyLock;
144
145 use rstest::rstest;
146 use vortex_buffer::ByteBufferMut;
147 use vortex_error::VortexError;
148 use vortex_session::VortexSession;
149 use vortex_session::registry::ReadContext;
150
151 use crate::ArrayContext;
152 use crate::Canonical;
153 use crate::IntoArray;
154 use crate::VortexSessionExecute;
155 use crate::arrays::Masked;
156 use crate::arrays::MaskedArray;
157 use crate::arrays::PrimitiveArray;
158 use crate::assert_arrays_eq;
159 use crate::dtype::Nullability;
160 use crate::serde::SerializeOptions;
161 use crate::serde::SerializedArray;
162 use crate::validity::Validity;
163
164 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
165
166 #[rstest]
167 #[case(
168 MaskedArray::try_new(
169 PrimitiveArray::from_iter([1i32, 2, 3]).into_array(),
170 Validity::AllValid,
171 &mut SESSION.create_execution_ctx(),
172 ).unwrap()
173 )]
174 #[case(
175 MaskedArray::try_new(
176 PrimitiveArray::from_iter([1i32, 2, 3, 4, 5]).into_array(),
177 Validity::from_iter([true, true, false, true, false]),
178 &mut SESSION.create_execution_ctx(),
179 ).unwrap()
180 )]
181 #[case(
182 MaskedArray::try_new(
183 PrimitiveArray::from_iter(0..100).into_array(),
184 Validity::from_iter((0..100).map(|i| i % 3 != 0)),
185 &mut SESSION.create_execution_ctx(),
186 ).unwrap()
187 )]
188 fn test_serde_roundtrip(#[case] array: MaskedArray) {
189 let dtype = array.dtype().clone();
190 let len = array.len();
191
192 let ctx = ArrayContext::empty();
193 let serialized = array
194 .clone()
195 .into_array()
196 .serialize(&ctx, &VortexSession::empty(), &SerializeOptions::default())
197 .unwrap();
198
199 let mut concat = ByteBufferMut::empty();
201 for buf in serialized {
202 concat.extend_from_slice(buf.as_ref());
203 }
204 let concat = concat.freeze();
205
206 let parts = SerializedArray::try_from(concat).unwrap();
207 let decoded = parts
208 .decode(
209 &dtype,
210 len,
211 &ReadContext::new(ctx.to_ids()),
212 &VortexSession::empty(),
213 )
214 .unwrap();
215
216 assert!(decoded.is::<Masked>());
217 assert_arrays_eq!(decoded, array, &mut SESSION.create_execution_ctx());
218 }
219
220 #[test]
226 fn test_execute_with_all_valid_preserves_nullable_dtype() -> Result<(), VortexError> {
227 let mut ctx = SESSION.create_execution_ctx();
228 let child = PrimitiveArray::from_iter([1i32, 2, 3]).into_array();
232 assert_eq!(child.dtype().nullability(), Nullability::NonNullable);
233
234 let array = MaskedArray::try_new(child, Validity::AllValid, &mut ctx)?;
235 assert_eq!(array.dtype().nullability(), Nullability::Nullable);
236
237 let mut ctx = SESSION.create_execution_ctx();
239 let result: Canonical = array.into_array().execute(&mut ctx)?;
240
241 assert_eq!(
242 result.dtype().nullability(),
243 Nullability::Nullable,
244 "MaskedArray execute should produce Nullable dtype"
245 );
246
247 Ok(())
248 }
249}