vortex_array/arrays/masked/vtable/
mod.rs1mod canonical;
4mod operations;
5mod validity;
6
7use std::hash::Hash;
8use std::sync::Arc;
9
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_panic;
15use vortex_session::VortexSession;
16
17use crate::ArrayRef;
18use crate::Canonical;
19use crate::EmptyMetadata;
20use crate::IntoArray;
21use crate::Precision;
22use crate::arrays::ConstantArray;
23use crate::arrays::MaskedArray;
24use crate::arrays::masked::compute::rules::PARENT_RULES;
25use crate::arrays::masked::mask_validity_canonical;
26use crate::buffer::BufferHandle;
27use crate::dtype::DType;
28use crate::executor::ExecutionCtx;
29use crate::executor::ExecutionResult;
30use crate::hash::ArrayEq;
31use crate::hash::ArrayHash;
32use crate::scalar::Scalar;
33use crate::serde::ArrayChildren;
34use crate::stats::StatsSetRef;
35use crate::validity::Validity;
36use crate::vtable;
37use crate::vtable::Array;
38use crate::vtable::ArrayId;
39use crate::vtable::VTable;
40use crate::vtable::ValidityVTableFromValidityHelper;
41use crate::vtable::validity_nchildren;
42use crate::vtable::validity_to_child;
43vtable!(Masked);
44
45#[derive(Clone, Debug)]
46pub struct Masked;
47
48impl Masked {
49 pub const ID: ArrayId = ArrayId::new_ref("vortex.masked");
50}
51
52impl VTable for Masked {
53 type Array = MaskedArray;
54
55 type Metadata = EmptyMetadata;
56 type OperationsVTable = Self;
57 type ValidityVTable = ValidityVTableFromValidityHelper;
58
59 fn vtable(_array: &Self::Array) -> &Self {
60 &Masked
61 }
62
63 fn id(&self) -> ArrayId {
64 Self::ID
65 }
66
67 fn len(array: &MaskedArray) -> usize {
68 array.child.len()
69 }
70
71 fn dtype(array: &MaskedArray) -> &DType {
72 &array.dtype
73 }
74
75 fn stats(array: &MaskedArray) -> StatsSetRef<'_> {
76 array.stats.to_ref(array.as_ref())
77 }
78
79 fn array_hash<H: std::hash::Hasher>(array: &MaskedArray, state: &mut H, precision: Precision) {
80 array.child.array_hash(state, precision);
81 array.validity.array_hash(state, precision);
82 array.dtype.hash(state);
83 }
84
85 fn array_eq(array: &MaskedArray, other: &MaskedArray, precision: Precision) -> bool {
86 array.child.array_eq(&other.child, precision)
87 && array.validity.array_eq(&other.validity, precision)
88 && array.dtype == other.dtype
89 }
90
91 fn nbuffers(_array: &Self::Array) -> usize {
92 0
93 }
94
95 fn buffer(_array: &Self::Array, _idx: usize) -> BufferHandle {
96 vortex_panic!("MaskedArray has no buffers")
97 }
98
99 fn buffer_name(_array: &Self::Array, _idx: usize) -> Option<String> {
100 None
101 }
102
103 fn nchildren(array: &Self::Array) -> usize {
104 1 + validity_nchildren(&array.validity)
105 }
106
107 fn child(array: &Self::Array, idx: usize) -> ArrayRef {
108 match idx {
109 0 => array.child.clone(),
110 1 => validity_to_child(&array.validity, array.child.len())
111 .vortex_expect("MaskedArray validity child out of bounds"),
112 _ => vortex_panic!("MaskedArray child index {idx} out of bounds"),
113 }
114 }
115
116 fn child_name(_array: &Self::Array, idx: usize) -> String {
117 match idx {
118 0 => "child".to_string(),
119 1 => "validity".to_string(),
120 _ => vortex_panic!("MaskedArray child_name index {idx} out of bounds"),
121 }
122 }
123
124 fn metadata(_array: &MaskedArray) -> VortexResult<Self::Metadata> {
125 Ok(EmptyMetadata)
126 }
127
128 fn serialize(_metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
129 Ok(Some(vec![]))
130 }
131
132 fn deserialize(
133 _bytes: &[u8],
134 _dtype: &DType,
135 _len: usize,
136 _buffers: &[BufferHandle],
137 _session: &VortexSession,
138 ) -> VortexResult<Self::Metadata> {
139 Ok(EmptyMetadata)
140 }
141
142 fn build(
143 dtype: &DType,
144 len: usize,
145 _metadata: &Self::Metadata,
146 buffers: &[BufferHandle],
147 children: &dyn ArrayChildren,
148 ) -> VortexResult<MaskedArray> {
149 if !buffers.is_empty() {
150 vortex_bail!("Expected 0 buffer, got {}", buffers.len());
151 }
152
153 let child = children.get(0, &dtype.as_nonnullable(), len)?;
154
155 let validity = if children.len() == 1 {
156 Validity::from(dtype.nullability())
157 } else if children.len() == 2 {
158 let validity = children.get(1, &Validity::DTYPE, len)?;
159 Validity::Array(validity)
160 } else {
161 vortex_bail!(
162 "`MaskedArray::build` expects 1 or 2 children, got {}",
163 children.len()
164 );
165 };
166
167 MaskedArray::try_new(child, validity)
168 }
169
170 fn execute(array: Arc<Array<Self>>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
171 let validity_mask = array.validity_mask()?;
172
173 if validity_mask.all_false() {
175 return Ok(ExecutionResult::done(
176 ConstantArray::new(Scalar::null(array.dtype().as_nullable()), array.len())
177 .into_array(),
178 ));
179 }
180
181 let child = array.child().clone().execute::<Canonical>(ctx)?;
188 Ok(ExecutionResult::done(
189 mask_validity_canonical(child, &validity_mask, ctx)?.into_array(),
190 ))
191 }
192
193 fn reduce_parent(
194 array: &Array<Self>,
195 parent: &ArrayRef,
196 child_idx: usize,
197 ) -> VortexResult<Option<ArrayRef>> {
198 PARENT_RULES.evaluate(array, parent, child_idx)
199 }
200
201 fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
202 vortex_ensure!(
203 children.len() == 1 || children.len() == 2,
204 "MaskedArray expects 1 or 2 children, got {}",
205 children.len()
206 );
207
208 let mut iter = children.into_iter();
209 let child = iter
210 .next()
211 .vortex_expect("children length already validated");
212 let validity = if let Some(validity_array) = iter.next() {
213 Validity::Array(validity_array)
214 } else {
215 Validity::from(array.dtype.nullability())
216 };
217
218 let new_array = MaskedArray::try_new(child, validity)?;
219 *array = new_array;
220 Ok(())
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use rstest::rstest;
227 use vortex_buffer::ByteBufferMut;
228 use vortex_error::VortexError;
229 use vortex_session::registry::ReadContext;
230
231 use crate::ArrayContext;
232 use crate::Canonical;
233 use crate::IntoArray;
234 use crate::LEGACY_SESSION;
235 use crate::VortexSessionExecute;
236 use crate::arrays::Masked;
237 use crate::arrays::MaskedArray;
238 use crate::arrays::PrimitiveArray;
239 use crate::dtype::Nullability;
240 use crate::serde::ArrayParts;
241 use crate::serde::SerializeOptions;
242 use crate::validity::Validity;
243
244 #[rstest]
245 #[case(
246 MaskedArray::try_new(
247 PrimitiveArray::from_iter([1i32, 2, 3]).into_array(),
248 Validity::AllValid
249 ).unwrap()
250 )]
251 #[case(
252 MaskedArray::try_new(
253 PrimitiveArray::from_iter([1i32, 2, 3, 4, 5]).into_array(),
254 Validity::from_iter([true, true, false, true, false])
255 ).unwrap()
256 )]
257 #[case(
258 MaskedArray::try_new(
259 PrimitiveArray::from_iter(0..100).into_array(),
260 Validity::from_iter((0..100).map(|i| i % 3 != 0))
261 ).unwrap()
262 )]
263 fn test_serde_roundtrip(#[case] array: MaskedArray) {
264 let dtype = array.dtype().clone();
265 let len = array.len();
266
267 let ctx = ArrayContext::empty();
268 let serialized = array
269 .clone()
270 .into_array()
271 .serialize(&ctx, &SerializeOptions::default())
272 .unwrap();
273
274 let mut concat = ByteBufferMut::empty();
276 for buf in serialized {
277 concat.extend_from_slice(buf.as_ref());
278 }
279 let concat = concat.freeze();
280
281 let parts = ArrayParts::try_from(concat).unwrap();
282 let decoded = parts
283 .decode(
284 &dtype,
285 len,
286 &ReadContext::new(ctx.to_ids()),
287 &LEGACY_SESSION,
288 )
289 .unwrap();
290
291 assert!(decoded.is::<Masked>());
292 assert_eq!(
293 array.as_ref().display_values().to_string(),
294 decoded.display_values().to_string()
295 );
296 }
297
298 #[test]
304 fn test_execute_with_all_valid_preserves_nullable_dtype() -> Result<(), VortexError> {
305 let child = PrimitiveArray::from_iter([1i32, 2, 3]).into_array();
309 assert_eq!(child.dtype().nullability(), Nullability::NonNullable);
310
311 let array = MaskedArray::try_new(child, Validity::AllValid)?;
312 assert_eq!(array.dtype().nullability(), Nullability::Nullable);
313
314 let mut ctx = LEGACY_SESSION.create_execution_ctx();
316 let result: Canonical = array.into_array().execute(&mut ctx)?;
317
318 assert_eq!(
319 result.as_ref().dtype().nullability(),
320 Nullability::Nullable,
321 "MaskedArray execute should produce Nullable dtype"
322 );
323
324 Ok(())
325 }
326}