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::BoundExpression;
31use crate::expr::bound;
32use crate::expr::display::ExprDisplay;
33use crate::scalar_fn::Arity;
34use crate::scalar_fn::ChildName;
35use crate::scalar_fn::EmptyOptions;
36use crate::scalar_fn::ExecutionArgs;
37use crate::scalar_fn::ScalarFnId;
38use crate::scalar_fn::ScalarFnVTable;
39use crate::scalar_fn::ScalarFnVTableExt;
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), [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 let Mask::Values(mask) = mask else {
157 unreachable!("trivial masks returned above");
158 };
159 zip_impl(&if_true, &if_false, &mask, ctx)
160 }
161
162 fn simplify(
163 &self,
164 _options: &Self::Options,
165 expr: &BoundExpression,
166 ) -> VortexResult<Option<BoundExpression>> {
167 let Some(mask_lit) = expr.child(2).as_opt::<Literal>() else {
168 return Ok(None);
169 };
170
171 if let Some(mask_val) = mask_lit.as_bool().value() {
172 let selected = if mask_val {
173 expr.child(0).clone()
174 } else {
175 expr.child(1).clone()
176 };
177 return Ok(Some(if selected.dtype() == expr.dtype() {
180 selected
181 } else {
182 bound::cast(selected, expr.dtype().clone())
183 }));
184 }
185
186 Ok(None)
187 }
188
189 fn is_strict(&self, _options: &Self::Options) -> bool {
190 false
192 }
193
194 fn is_infallible(&self, _options: &Self::Options) -> bool {
195 true
196 }
197}
198
199fn zip_impl(
200 if_true: &ArrayRef,
201 if_false: &ArrayRef,
202 mask: &MaskValues,
203 ctx: &mut ExecutionCtx,
204) -> VortexResult<ArrayRef> {
205 assert_eq!(
206 if_true.len(),
207 if_false.len(),
208 "zip requires arrays to have the same size"
209 );
210
211 let return_type = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
212
213 let if_true = if_true.cast(return_type.clone())?;
216 let if_false = if_false.cast(return_type.clone())?;
217
218 zip_impl_with_builder(
219 &if_true,
220 &if_false,
221 mask,
222 builder_with_capacity_in(&return_type, if_true.len(), ctx.allocator()),
223 ctx,
224 )
225}
226
227fn zip_return_dtype(if_true: &DType, if_false: &DType) -> VortexResult<DType> {
228 zip_nullability_union(if_true, if_false).ok_or_else(|| {
229 vortex_err!(
230 "zip requires if_true and if_false to have the same base type, got {} and {}",
231 if_true,
232 if_false
233 )
234 })
235}
236
237pub(crate) fn zip_nullability_union(lhs: &DType, rhs: &DType) -> Option<DType> {
241 let nullability = lhs.nullability() | rhs.nullability();
242
243 match (lhs, rhs) {
244 (DType::List(lhs_element, _), DType::List(rhs_element, _)) => Some(DType::List(
245 Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
246 nullability,
247 )),
248 (
249 DType::FixedSizeList(lhs_element, lhs_size, _),
250 DType::FixedSizeList(rhs_element, rhs_size, _),
251 ) if lhs_size == rhs_size => Some(DType::FixedSizeList(
252 Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
253 *lhs_size,
254 nullability,
255 )),
256 (DType::Map(lhs_map, _), DType::Map(rhs_map, _))
257 if lhs_map.keys_sorted() == rhs_map.keys_sorted() =>
258 {
259 DType::map(
260 zip_nullability_union(&lhs_map.key_dtype(), &rhs_map.key_dtype())?,
261 zip_nullability_union(&lhs_map.value_dtype(), &rhs_map.value_dtype())?,
262 lhs_map.keys_sorted(),
263 nullability,
264 )
265 .ok()
266 }
267 (DType::Struct(lhs_fields, _), DType::Struct(rhs_fields, _))
268 if lhs_fields.names() == rhs_fields.names() =>
269 {
270 let fields = lhs_fields
271 .fields()
272 .zip(rhs_fields.fields())
273 .map(|(lhs, rhs)| zip_nullability_union(&lhs, &rhs))
274 .collect::<Option<Vec<_>>>()?;
275 Some(DType::Struct(
276 StructFields::new(lhs_fields.names().clone(), fields),
277 nullability,
278 ))
279 }
280 (DType::Union(lhs_variants, _), DType::Union(rhs_variants, _))
281 if lhs_variants == rhs_variants =>
282 {
283 Some(DType::Union(lhs_variants.clone(), nullability))
284 }
285 _ if lhs.eq_ignore_nullability(rhs) => Some(lhs.with_nullability(nullability)),
286 _ => None,
287 }
288}
289
290fn zip_impl_with_builder(
291 if_true: &ArrayRef,
292 if_false: &ArrayRef,
293 mask: &MaskValues,
294 mut builder: Box<dyn ArrayBuilder>,
295 ctx: &mut ExecutionCtx,
296) -> VortexResult<ArrayRef> {
297 for (start, end) in mask.slices() {
298 if builder.len() < *start {
299 if_false
300 .slice(builder.len()..*start)?
301 .append_to_builder(builder.as_mut(), ctx)?;
302 }
303 if_true
304 .slice(*start..*end)?
305 .append_to_builder(builder.as_mut(), ctx)?;
306 }
307 if builder.len() < if_false.len() {
308 if_false
309 .slice(builder.len()..if_false.len())?
310 .append_to_builder(builder.as_mut(), ctx)?;
311 }
312 Ok(builder.finish())
313}
314
315pub(crate) fn zip_validity(
324 if_true: Validity,
325 if_false: Validity,
326 mask: &Mask,
327) -> VortexResult<Validity> {
328 match (&if_true, &if_false) {
329 (Validity::NonNullable, Validity::NonNullable) => return Ok(Validity::NonNullable),
330 (Validity::AllValid, Validity::AllValid) => return Ok(Validity::AllValid),
331 (Validity::AllInvalid, Validity::AllInvalid) => return Ok(Validity::AllInvalid),
332 _ => {}
333 }
334
335 let len = mask.len();
336 let validity = mask
337 .clone()
338 .into_array()
339 .zip(if_true.to_array(len), if_false.to_array(len))?;
340 Ok(Validity::Array(validity))
341}
342
343#[cfg(test)]
344mod tests {
345 use vortex_buffer::buffer;
346 use vortex_error::VortexResult;
347 use vortex_mask::Mask;
348
349 use crate::ArrayRef;
350 use crate::IntoArray;
351 use crate::VortexSessionExecute;
352 use crate::array_session;
353 use crate::arrays::ConstantArray;
354 use crate::arrays::PrimitiveArray;
355 use crate::arrays::Struct;
356 use crate::arrays::StructArray;
357 use crate::arrays::VarBinView;
358 use crate::arrays::VarBinViewArray;
359 use crate::assert_arrays_eq;
360 use crate::builders::ArrayBuilder;
361 use crate::builders::BufferGrowthStrategy;
362 use crate::builders::VarBinViewBuilder;
363 use crate::builtins::ArrayBuiltins;
364 use crate::columnar::Columnar;
365 use crate::dtype::DType;
366 use crate::dtype::Nullability;
367 use crate::dtype::PType;
368 use crate::expr::lit;
369 use crate::expr::root;
370 use crate::expr::zip_expr;
371 use crate::scalar::Scalar;
372
373 #[test]
374 fn dtype() {
375 let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
376 let expr = zip_expr(lit(true), root(), lit(0i32));
377 let result_dtype = expr.return_dtype(&dtype).unwrap();
378 assert_eq!(
379 result_dtype,
380 DType::Primitive(PType::I32, Nullability::NonNullable)
381 );
382 }
383
384 #[test]
385 fn test_display() {
386 let expr = zip_expr(lit(true), root(), lit(0i32));
387 assert_eq!(expr.to_string(), "zip($, 0i32, true)");
388 }
389
390 #[test]
391 fn test_zip_basic() {
392 let mut ctx = array_session().create_execution_ctx();
393 let mask = Mask::from_iter([true, false, false, true, false]);
394 let if_true = buffer![10, 20, 30, 40, 50].into_array();
395 let if_false = buffer![1, 2, 3, 4, 5].into_array();
396
397 let result = mask.into_array().zip(if_true, if_false).unwrap();
398 let expected = buffer![10, 2, 3, 40, 5].into_array();
399
400 assert_arrays_eq!(result, expected, &mut ctx);
401 }
402
403 #[test]
404 fn test_zip_all_true() {
405 let mut ctx = array_session().create_execution_ctx();
406 let mask = Mask::new_true(4);
407 let if_true = buffer![10, 20, 30, 40].into_array();
408 let if_false =
409 PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();
410
411 let result = mask.into_array().zip(if_true, if_false.clone()).unwrap();
412 let expected =
413 PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), Some(40)]).into_array();
414
415 assert_arrays_eq!(result, expected, &mut ctx);
416 assert_eq!(result.dtype(), if_false.dtype())
417 }
418
419 #[test]
420 fn test_zip_all_false_widens_nullability() {
421 let mut ctx = array_session().create_execution_ctx();
422 let mask = Mask::new_false(4);
423 let if_true =
424 PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
425 let if_false = buffer![1i32, 2, 3, 4].into_array();
426
427 let result = mask.into_array().zip(if_true.clone(), if_false).unwrap();
428 let expected =
429 PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), Some(4)]).into_array();
430
431 assert_arrays_eq!(result, expected, &mut ctx);
432 assert_eq!(result.dtype(), if_true.dtype());
433 }
434
435 #[test]
436 fn test_invalid_lengths() {
437 let mask = Mask::new_false(4);
438 let if_true = buffer![10, 20, 30].into_array();
439 let if_false = buffer![1, 2, 3, 4].into_array();
440
441 let error = mask.into_array().zip(if_true, if_false).unwrap_err();
442 assert!(
443 error
444 .to_string()
445 .contains("children equal to the array length")
446 );
447 }
448
449 #[test]
450 fn test_fragmentation() -> VortexResult<()> {
451 let len = 100;
452
453 let const1 = ConstantArray::new(
454 Scalar::utf8("hello_this_is_a_longer_string", Nullability::Nullable),
455 len,
456 )
457 .into_array();
458
459 let const2 = ConstantArray::new(
460 Scalar::utf8("world_this_is_another_string", Nullability::Nullable),
461 len,
462 )
463 .into_array();
464
465 let indices: Vec<usize> = (0..len).step_by(2).collect();
466 let mask = Mask::from_indices(len, indices);
467 let mask_array = mask.into_array();
468
469 let mut ctx = array_session().create_execution_ctx();
470 let result = mask_array
471 .zip(const1.clone(), const2.clone())?
472 .execute::<Columnar>(&mut ctx)?
473 .into_array();
474
475 insta::assert_snapshot!(result.display_tree(), @r"
476 root: vortex.varbinview(utf8?, len=100) nbytes=1.66 kB (100.00%) [all_valid]
477 metadata:
478 buffer: buffer_0 host 29 B (align=1) (1.75%)
479 buffer: buffer_1 host 28 B (align=1) (1.69%)
480 buffer: views host 1.60 kB (align=16) (96.56%)
481 ");
482
483 let expected = VarBinViewArray::from_iter_nullable_str((0..len).map(|index| {
484 Some(if index % 2 == 0 {
485 "hello_this_is_a_longer_string"
486 } else {
487 "world_this_is_another_string"
488 })
489 }));
490 assert_arrays_eq!(result, expected, &mut ctx);
491
492 let wrapped1 = StructArray::try_from_iter([("nested", const1)])?.into_array();
493 let wrapped2 = StructArray::try_from_iter([("nested", const2)])?.into_array();
494
495 let wrapped_result = mask_array
496 .zip(wrapped1, wrapped2)?
497 .execute::<ArrayRef>(&mut ctx)?;
498 assert!(wrapped_result.is::<Struct>());
499 assert_arrays_eq!(
500 wrapped_result,
501 StructArray::try_from_iter([("nested", expected.into_array())])?,
502 &mut ctx
503 );
504
505 Ok(())
506 }
507
508 #[test]
509 fn test_varbinview_zip() {
510 let if_true = {
511 let mut builder = VarBinViewBuilder::new_in(
512 DType::Utf8(Nullability::NonNullable),
513 10,
514 Default::default(),
515 BufferGrowthStrategy::fixed(64 * 1024),
516 0.0,
517 vortex_buffer::BufferAllocatorRef::statically_allocated(),
518 );
519 for _ in 0..100 {
520 builder.append_value("Hello");
521 builder.append_value("Hello this is a long string that won't be inlined.");
522 }
523 builder.finish()
524 };
525
526 let if_false = {
527 let mut builder = VarBinViewBuilder::new_in(
528 DType::Utf8(Nullability::NonNullable),
529 10,
530 Default::default(),
531 BufferGrowthStrategy::fixed(64 * 1024),
532 0.0,
533 vortex_buffer::BufferAllocatorRef::statically_allocated(),
534 );
535 for _ in 0..100 {
536 builder.append_value("Hello2");
537 builder.append_value("Hello2 this is a long string that won't be inlined.");
538 }
539 builder.finish()
540 };
541
542 let mask = Mask::from_indices(200, (0..100).filter(|i| i % 3 != 0));
543 let mask_array = mask.clone().into_array();
544
545 let mut ctx = array_session().create_execution_ctx();
546 let zipped = mask_array
547 .zip(if_true, if_false)
548 .unwrap()
549 .execute::<ArrayRef>(&mut ctx)
550 .unwrap();
551 let zipped = zipped.as_opt::<VarBinView>().unwrap();
552 assert_eq!(zipped.data_buffers().len(), 2);
553
554 let true_value = |i: usize| {
555 if i.is_multiple_of(2) {
556 "Hello"
557 } else {
558 "Hello this is a long string that won't be inlined."
559 }
560 };
561 let false_value = |i: usize| {
562 if i.is_multiple_of(2) {
563 "Hello2"
564 } else {
565 "Hello2 this is a long string that won't be inlined."
566 }
567 };
568 let expected = VarBinViewArray::from_iter_str((0..200).map(|i| {
569 if mask.value(i) {
570 true_value(i)
571 } else {
572 false_value(i)
573 }
574 }));
575 assert_arrays_eq!(zipped.array().clone(), expected, &mut ctx);
576 }
577}