1mod kernel;
5
6use std::fmt::Display;
7use std::fmt::Formatter;
8use std::sync::Arc;
9
10pub use kernel::*;
11use vortex_error::VortexResult;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_err;
14use vortex_mask::Mask;
15use vortex_mask::MaskValues;
16use vortex_session::VortexSession;
17use vortex_session::registry::CachedId;
18
19use crate::ArrayRef;
20use crate::ExecutionCtx;
21use crate::IntoArray;
22use crate::arrays::BoolArray;
23use crate::arrays::ScalarFnArray;
24use crate::arrays::bool::BoolArrayExt;
25use crate::builders::ArrayBuilder;
26use crate::builders::builder_with_capacity_in;
27use crate::builtins::ArrayBuiltins;
28use crate::dtype::DType;
29use crate::dtype::StructFields;
30use crate::expr::Expression;
31use crate::expr::display::ExprDisplay;
32use crate::scalar_fn::Arity;
33use crate::scalar_fn::ChildName;
34use crate::scalar_fn::EmptyOptions;
35use crate::scalar_fn::ExecutionArgs;
36use crate::scalar_fn::ScalarFnId;
37use crate::scalar_fn::ScalarFnVTable;
38use crate::scalar_fn::ScalarFnVTableExt;
39use crate::scalar_fn::SimplifyCtx;
40use crate::scalar_fn::fns::literal::Literal;
41use crate::validity::Validity;
42
43#[derive(Clone)]
51pub struct Zip;
52
53impl Zip {
54 pub fn try_new(
61 if_true: ArrayRef,
62 if_false: ArrayRef,
63 mask: ArrayRef,
64 ) -> VortexResult<ScalarFnArray> {
65 ScalarFnArray::try_new(Zip.bind(EmptyOptions), vec![if_true, if_false, mask])
66 }
67}
68
69impl ScalarFnVTable for Zip {
70 type Options = EmptyOptions;
71
72 fn id(&self) -> ScalarFnId {
73 static ID: CachedId = CachedId::new("vortex.zip");
74 *ID
75 }
76
77 fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
78 Ok(Some(vec![]))
79 }
80
81 fn deserialize(
82 &self,
83 _metadata: &[u8],
84 _session: &VortexSession,
85 ) -> VortexResult<Self::Options> {
86 Ok(EmptyOptions)
87 }
88
89 fn arity(&self, _options: &Self::Options) -> Arity {
90 Arity::Exact(3)
91 }
92
93 fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
94 match child_idx {
95 0 => ChildName::from("if_true"),
96 1 => ChildName::from("if_false"),
97 2 => ChildName::from("mask"),
98 _ => unreachable!("Invalid child index {} for Zip expression", child_idx),
99 }
100 }
101
102 fn fmt_sql(
103 &self,
104 _options: &Self::Options,
105 expr: &dyn ExprDisplay,
106 f: &mut Formatter<'_>,
107 ) -> std::fmt::Result {
108 write!(f, "zip(")?;
109 Display::fmt(expr.display_child(0), f)?;
110 write!(f, ", ")?;
111 Display::fmt(expr.display_child(1), f)?;
112 write!(f, ", ")?;
113 Display::fmt(expr.display_child(2), f)?;
114 write!(f, ")")
115 }
116
117 fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
118 vortex_ensure!(
119 matches!(arg_dtypes[2], DType::Bool(_)),
120 "zip requires mask to be a boolean type, got {}",
121 arg_dtypes[2]
122 );
123 zip_return_dtype(&arg_dtypes[0], &arg_dtypes[1])
124 }
125
126 fn execute(
127 &self,
128 _options: &Self::Options,
129 args: &dyn ExecutionArgs,
130 ctx: &mut ExecutionCtx,
131 ) -> VortexResult<ArrayRef> {
132 let if_true = args.get(0)?;
133 let if_false = args.get(1)?;
134 let mask_array = args.get(2)?;
135
136 let mask = mask_array
137 .execute::<BoolArray>(ctx)?
138 .to_mask_fill_null_false(ctx);
139
140 let return_dtype = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
141
142 if mask.all_true() {
143 return if_true.cast(return_dtype)?.execute(ctx);
144 }
145
146 if mask.all_false() {
147 return if_false.cast(return_dtype)?.execute(ctx);
148 }
149
150 if !if_true.is_canonical() || !if_false.is_canonical() {
151 let if_true = if_true.execute::<ArrayRef>(ctx)?;
152 let if_false = if_false.execute::<ArrayRef>(ctx)?;
153 return mask.into_array().zip(if_true, if_false);
154 }
155
156 zip_impl(&if_true, &if_false, &mask, ctx)
157 }
158
159 fn simplify(
160 &self,
161 _options: &Self::Options,
162 expr: &Expression,
163 _ctx: &dyn SimplifyCtx,
164 ) -> VortexResult<Option<Expression>> {
165 let Some(mask_lit) = expr.child(2).as_opt::<Literal>() else {
166 return Ok(None);
167 };
168
169 if let Some(mask_val) = mask_lit.as_bool().value() {
170 if mask_val {
171 return Ok(Some(expr.child(0).clone()));
172 } else {
173 return Ok(Some(expr.child(1).clone()));
174 }
175 }
176
177 Ok(None)
178 }
179
180 fn is_strict(&self, _options: &Self::Options) -> bool {
181 false
183 }
184
185 fn is_infallible(&self, _options: &Self::Options) -> bool {
186 true
187 }
188}
189
190pub(crate) fn zip_impl(
191 if_true: &ArrayRef,
192 if_false: &ArrayRef,
193 mask: &Mask,
194 ctx: &mut ExecutionCtx,
195) -> VortexResult<ArrayRef> {
196 assert_eq!(
197 if_true.len(),
198 if_false.len(),
199 "zip requires arrays to have the same size"
200 );
201
202 let return_type = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
203
204 let mask_values = match mask {
205 Mask::AllTrue(_) | Mask::AllFalse(0) => return if_true.cast(return_type),
206 Mask::AllFalse(_) => return if_false.cast(return_type),
207 Mask::Values(values) => values,
208 };
209
210 let if_true = if_true.cast(return_type.clone())?;
213 let if_false = if_false.cast(return_type.clone())?;
214
215 zip_impl_with_builder(
216 &if_true,
217 &if_false,
218 mask_values.as_ref(),
219 builder_with_capacity_in(&return_type, if_true.len(), ctx.allocator()),
220 ctx,
221 )
222}
223
224fn zip_return_dtype(if_true: &DType, if_false: &DType) -> VortexResult<DType> {
225 zip_nullability_union(if_true, if_false).ok_or_else(|| {
226 vortex_err!(
227 "zip requires if_true and if_false to have the same base type, got {} and {}",
228 if_true,
229 if_false
230 )
231 })
232}
233
234fn zip_nullability_union(lhs: &DType, rhs: &DType) -> Option<DType> {
235 let nullability = lhs.nullability() | rhs.nullability();
236
237 match (lhs, rhs) {
238 (DType::List(lhs_element, _), DType::List(rhs_element, _)) => Some(DType::List(
239 Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
240 nullability,
241 )),
242 (
243 DType::FixedSizeList(lhs_element, lhs_size, _),
244 DType::FixedSizeList(rhs_element, rhs_size, _),
245 ) if lhs_size == rhs_size => Some(DType::FixedSizeList(
246 Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
247 *lhs_size,
248 nullability,
249 )),
250 (DType::Map(lhs_map, _), DType::Map(rhs_map, _))
251 if lhs_map.keys_sorted() == rhs_map.keys_sorted() =>
252 {
253 DType::map(
254 zip_nullability_union(&lhs_map.key_dtype(), &rhs_map.key_dtype())?,
255 zip_nullability_union(&lhs_map.value_dtype(), &rhs_map.value_dtype())?,
256 lhs_map.keys_sorted(),
257 nullability,
258 )
259 .ok()
260 }
261 (DType::Struct(lhs_fields, _), DType::Struct(rhs_fields, _))
262 if lhs_fields.names() == rhs_fields.names() =>
263 {
264 let fields = lhs_fields
265 .fields()
266 .zip(rhs_fields.fields())
267 .map(|(lhs, rhs)| zip_nullability_union(&lhs, &rhs))
268 .collect::<Option<Vec<_>>>()?;
269 Some(DType::Struct(
270 StructFields::new(lhs_fields.names().clone(), fields),
271 nullability,
272 ))
273 }
274 (DType::Union(lhs_variants, _), DType::Union(rhs_variants, _))
275 if lhs_variants == rhs_variants =>
276 {
277 Some(DType::Union(lhs_variants.clone(), nullability))
278 }
279 _ if lhs.eq_ignore_nullability(rhs) => Some(lhs.with_nullability(nullability)),
280 _ => None,
281 }
282}
283
284fn zip_impl_with_builder(
285 if_true: &ArrayRef,
286 if_false: &ArrayRef,
287 mask: &MaskValues,
288 mut builder: Box<dyn ArrayBuilder>,
289 ctx: &mut ExecutionCtx,
290) -> VortexResult<ArrayRef> {
291 for (start, end) in mask.slices() {
292 if builder.len() < *start {
293 if_false
294 .slice(builder.len()..*start)?
295 .append_to_builder(builder.as_mut(), ctx)?;
296 }
297 if_true
298 .slice(*start..*end)?
299 .append_to_builder(builder.as_mut(), ctx)?;
300 }
301 if builder.len() < if_false.len() {
302 if_false
303 .slice(builder.len()..if_false.len())?
304 .append_to_builder(builder.as_mut(), ctx)?;
305 }
306 Ok(builder.finish())
307}
308
309pub(crate) fn zip_validity(
318 if_true: Validity,
319 if_false: Validity,
320 mask: &Mask,
321) -> VortexResult<Validity> {
322 match (&if_true, &if_false) {
323 (Validity::NonNullable, Validity::NonNullable) => return Ok(Validity::NonNullable),
324 (Validity::AllValid, Validity::AllValid) => return Ok(Validity::AllValid),
325 (Validity::AllInvalid, Validity::AllInvalid) => return Ok(Validity::AllInvalid),
326 _ => {}
327 }
328
329 let len = mask.len();
330 let validity = mask
331 .clone()
332 .into_array()
333 .zip(if_true.to_array(len), if_false.to_array(len))?;
334 Ok(Validity::Array(validity))
335}
336
337#[cfg(test)]
338mod tests {
339 use vortex_buffer::buffer;
340 use vortex_error::VortexResult;
341 use vortex_mask::Mask;
342
343 use super::zip_impl;
344 use crate::ArrayRef;
345 use crate::IntoArray;
346 use crate::VortexSessionExecute;
347 use crate::array_session;
348 use crate::arrays::ConstantArray;
349 use crate::arrays::PrimitiveArray;
350 use crate::arrays::Struct;
351 use crate::arrays::StructArray;
352 use crate::arrays::VarBinView;
353 use crate::arrays::VarBinViewArray;
354 use crate::assert_arrays_eq;
355 use crate::builders::ArrayBuilder;
356 use crate::builders::BufferGrowthStrategy;
357 use crate::builders::VarBinViewBuilder;
358 use crate::builtins::ArrayBuiltins;
359 use crate::columnar::Columnar;
360 use crate::dtype::DType;
361 use crate::dtype::Nullability;
362 use crate::dtype::PType;
363 use crate::expr::lit;
364 use crate::expr::root;
365 use crate::expr::zip_expr;
366 use crate::scalar::Scalar;
367
368 #[test]
369 fn dtype() {
370 let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
371 let expr = zip_expr(lit(true), root(), lit(0i32));
372 let result_dtype = expr.return_dtype(&dtype).unwrap();
373 assert_eq!(
374 result_dtype,
375 DType::Primitive(PType::I32, Nullability::NonNullable)
376 );
377 }
378
379 #[test]
380 fn test_display() {
381 let expr = zip_expr(lit(true), root(), lit(0i32));
382 assert_eq!(expr.to_string(), "zip($, 0i32, true)");
383 }
384
385 #[test]
386 fn test_zip_basic() {
387 let mut ctx = array_session().create_execution_ctx();
388 let mask = Mask::from_iter([true, false, false, true, false]);
389 let if_true = buffer![10, 20, 30, 40, 50].into_array();
390 let if_false = buffer![1, 2, 3, 4, 5].into_array();
391
392 let result = mask.into_array().zip(if_true, if_false).unwrap();
393 let expected = buffer![10, 2, 3, 40, 5].into_array();
394
395 assert_arrays_eq!(result, expected, &mut ctx);
396 }
397
398 #[test]
399 fn test_zip_all_true() {
400 let mut ctx = array_session().create_execution_ctx();
401 let mask = Mask::new_true(4);
402 let if_true = buffer![10, 20, 30, 40].into_array();
403 let if_false =
404 PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();
405
406 let result = mask.into_array().zip(if_true, if_false.clone()).unwrap();
407 let expected =
408 PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), Some(40)]).into_array();
409
410 assert_arrays_eq!(result, expected, &mut ctx);
411 assert_eq!(result.dtype(), if_false.dtype())
412 }
413
414 #[test]
415 fn test_zip_all_false_widens_nullability() {
416 let mut ctx = array_session().create_execution_ctx();
417 let mask = Mask::new_false(4);
418 let if_true =
419 PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
420 let if_false = buffer![1i32, 2, 3, 4].into_array();
421
422 let result = mask.into_array().zip(if_true.clone(), if_false).unwrap();
423 let expected =
424 PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), Some(4)]).into_array();
425
426 assert_arrays_eq!(result, expected, &mut ctx);
427 assert_eq!(result.dtype(), if_true.dtype());
428 }
429
430 #[test]
431 fn test_zip_impl_all_true_widens_nullability() -> VortexResult<()> {
432 let mask = Mask::new_true(4);
433 let if_true = buffer![10i32, 20, 30, 40].into_array();
434 let if_false =
435 PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();
436
437 let mut ctx = array_session().create_execution_ctx();
438 let result = zip_impl(&if_true, &if_false, &mask, &mut ctx)?;
439 assert_arrays_eq!(
440 result,
441 PrimitiveArray::from_option_iter([Some(10i32), Some(20), Some(30), Some(40)])
442 .into_array(),
443 &mut ctx
444 );
445 assert_eq!(result.dtype(), if_false.dtype());
446 Ok(())
447 }
448
449 #[test]
450 fn test_zip_impl_all_false_widens_nullability() -> VortexResult<()> {
451 let mask = Mask::new_false(4);
452 let if_true =
453 PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
454 let if_false = buffer![1i32, 2, 3, 4].into_array();
455
456 let mut ctx = array_session().create_execution_ctx();
457 let result = zip_impl(&if_true, &if_false, &mask, &mut ctx)?;
458 assert_arrays_eq!(
459 result,
460 PrimitiveArray::from_option_iter([Some(1i32), Some(2), Some(3), Some(4)]).into_array(),
461 &mut ctx
462 );
463 assert_eq!(result.dtype(), if_true.dtype());
464 Ok(())
465 }
466
467 #[test]
468 #[should_panic]
469 fn test_invalid_lengths() {
470 let mask = Mask::new_false(4);
471 let if_true = buffer![10, 20, 30].into_array();
472 let if_false = buffer![1, 2, 3, 4].into_array();
473
474 let _result = mask.into_array().zip(if_true, if_false).unwrap();
475 }
476
477 #[test]
478 fn test_fragmentation() -> VortexResult<()> {
479 let len = 100;
480
481 let const1 = ConstantArray::new(
482 Scalar::utf8("hello_this_is_a_longer_string", Nullability::Nullable),
483 len,
484 )
485 .into_array();
486
487 let const2 = ConstantArray::new(
488 Scalar::utf8("world_this_is_another_string", Nullability::Nullable),
489 len,
490 )
491 .into_array();
492
493 let indices: Vec<usize> = (0..len).step_by(2).collect();
494 let mask = Mask::from_indices(len, indices);
495 let mask_array = mask.into_array();
496
497 let mut ctx = array_session().create_execution_ctx();
498 let result = mask_array
499 .zip(const1.clone(), const2.clone())?
500 .execute::<Columnar>(&mut ctx)?
501 .into_array();
502
503 insta::assert_snapshot!(result.display_tree(), @r"
504 root: vortex.varbinview(utf8?, len=100) nbytes=1.66 kB (100.00%) [all_valid]
505 metadata:
506 buffer: buffer_0 host 29 B (align=1) (1.75%)
507 buffer: buffer_1 host 28 B (align=1) (1.69%)
508 buffer: views host 1.60 kB (align=16) (96.56%)
509 ");
510
511 let wrapped1 = StructArray::try_from_iter([("nested", const1)])?.into_array();
512 let wrapped2 = StructArray::try_from_iter([("nested", const2)])?.into_array();
513
514 let wrapped_result = mask_array
515 .zip(wrapped1, wrapped2)?
516 .execute::<ArrayRef>(&mut ctx)?;
517 assert!(wrapped_result.is::<Struct>());
518
519 Ok(())
520 }
521
522 #[test]
523 fn test_varbinview_zip() {
524 let if_true = {
525 let mut builder = VarBinViewBuilder::new_in(
526 DType::Utf8(Nullability::NonNullable),
527 10,
528 Default::default(),
529 BufferGrowthStrategy::fixed(64 * 1024),
530 0.0,
531 vortex_buffer::BufferAllocatorRef::statically_allocated(),
532 );
533 for _ in 0..100 {
534 builder.append_value("Hello");
535 builder.append_value("Hello this is a long string that won't be inlined.");
536 }
537 builder.finish()
538 };
539
540 let if_false = {
541 let mut builder = VarBinViewBuilder::new_in(
542 DType::Utf8(Nullability::NonNullable),
543 10,
544 Default::default(),
545 BufferGrowthStrategy::fixed(64 * 1024),
546 0.0,
547 vortex_buffer::BufferAllocatorRef::statically_allocated(),
548 );
549 for _ in 0..100 {
550 builder.append_value("Hello2");
551 builder.append_value("Hello2 this is a long string that won't be inlined.");
552 }
553 builder.finish()
554 };
555
556 let mask = Mask::from_indices(200, (0..100).filter(|i| i % 3 != 0));
557 let mask_array = mask.clone().into_array();
558
559 let mut ctx = array_session().create_execution_ctx();
560 let zipped = mask_array
561 .zip(if_true, if_false)
562 .unwrap()
563 .execute::<ArrayRef>(&mut ctx)
564 .unwrap();
565 let zipped = zipped.as_opt::<VarBinView>().unwrap();
566 assert_eq!(zipped.data_buffers().len(), 2);
567
568 let true_value = |i: usize| {
569 if i.is_multiple_of(2) {
570 "Hello"
571 } else {
572 "Hello this is a long string that won't be inlined."
573 }
574 };
575 let false_value = |i: usize| {
576 if i.is_multiple_of(2) {
577 "Hello2"
578 } else {
579 "Hello2 this is a long string that won't be inlined."
580 }
581 };
582 let expected = VarBinViewArray::from_iter_str((0..200).map(|i| {
583 if mask.value(i) {
584 true_value(i)
585 } else {
586 false_value(i)
587 }
588 }));
589 assert_arrays_eq!(zipped.array().clone(), expected, &mut ctx);
590 }
591}