Skip to main content

vortex_functions/zip/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod bool;
5mod chunked;
6mod decimal;
7mod extension;
8mod fixed_size_list;
9mod fixed_width;
10mod kernel;
11mod listview;
12mod map;
13mod null;
14mod paired_chunks;
15mod primitive;
16mod struct_;
17mod varbinview;
18mod widen;
19
20use std::fmt::Display;
21use std::fmt::Formatter;
22use std::sync::Arc;
23
24pub use kernel::*;
25use vortex_array::ArrayRef;
26use vortex_array::ExecutionCtx;
27use vortex_array::IntoArray;
28use vortex_array::arrays::Bool;
29use vortex_array::arrays::BoolArray;
30use vortex_array::arrays::Chunked;
31use vortex_array::arrays::Decimal;
32use vortex_array::arrays::Extension;
33use vortex_array::arrays::FixedSizeList;
34use vortex_array::arrays::ListView;
35use vortex_array::arrays::Map;
36use vortex_array::arrays::Null;
37use vortex_array::arrays::Primitive;
38use vortex_array::arrays::ScalarFnArray;
39use vortex_array::arrays::Struct;
40use vortex_array::arrays::VarBinView;
41use vortex_array::arrays::Widen;
42use vortex_array::arrays::bool::BoolArrayExt;
43use vortex_array::builders::ArrayBuilder;
44use vortex_array::builders::builder_with_capacity_in;
45use vortex_array::builtins::ArrayBuiltins;
46use vortex_array::dtype::DType;
47use vortex_array::dtype::StructFields;
48use vortex_array::optimizer::ArrayOptimizer;
49use vortex_array::optimizer::kernels::ArrayKernelsExt;
50use vortex_array::scalar_fn::Arity;
51use vortex_array::scalar_fn::ChildName;
52use vortex_array::scalar_fn::EmptyOptions;
53use vortex_array::scalar_fn::ExecutionArgs;
54use vortex_array::scalar_fn::ReduceNode;
55use vortex_array::scalar_fn::ScalarFnId;
56use vortex_array::scalar_fn::ScalarFnVTable;
57use vortex_array::scalar_fn::ScalarFnVTableExt;
58use vortex_array::scalar_fn::builtin::cast::Cast;
59use vortex_array::scalar_fn::display::ExprDisplay;
60use vortex_array::scalar_fn::session::ScalarFnSessionExt;
61use vortex_array::validity::Validity;
62use vortex_error::VortexResult;
63use vortex_error::vortex_bail;
64use vortex_error::vortex_ensure;
65use vortex_error::vortex_err;
66use vortex_mask::Mask;
67use vortex_mask::MaskValues;
68use vortex_session::VortexSession;
69use vortex_session::registry::CachedId;
70
71use crate::builtins::ArrayFunctions;
72
73/// Registers [`Zip`] and its kernels for vortex-array's canonical encodings.
74pub(crate) fn initialize(session: &VortexSession) {
75    session.scalar_fns().register(Zip);
76    let kernels = session.kernels();
77    kernels.register_execute_parent_kernel(Zip.id(), Bool, ZipExecuteAdaptor(Bool));
78    kernels.register_execute_parent_kernel(Zip.id(), Chunked, ZipExecuteAdaptor(Chunked));
79    kernels.register_execute_parent_kernel(Zip.id(), Decimal, ZipExecuteAdaptor(Decimal));
80    kernels.register_execute_parent_kernel(
81        Zip.id(),
82        FixedSizeList,
83        ZipExecuteAdaptor(FixedSizeList),
84    );
85    kernels.register_execute_parent_kernel(Zip.id(), ListView, ZipExecuteAdaptor(ListView));
86    kernels.register_execute_parent_kernel(Zip.id(), Map, ZipExecuteAdaptor(Map));
87    kernels.register_execute_parent_kernel(Zip.id(), Primitive, ZipExecuteAdaptor(Primitive));
88    kernels.register_execute_parent_kernel(Zip.id(), Struct, ZipExecuteAdaptor(Struct));
89    kernels.register_execute_parent_kernel(Zip.id(), VarBinView, ZipExecuteAdaptor(VarBinView));
90    kernels.register_execute_parent_kernel(Zip.id(), Widen, ZipExecuteAdaptor(Widen));
91    kernels.register_reduce_parent_rule(Zip, Extension, const { &ZipReduceAdaptor(Extension) });
92    kernels.register_reduce_parent_rule(Zip, Null, const { &ZipReduceAdaptor(Null) });
93}
94
95/// An expression that conditionally selects between two arrays based on a boolean mask.
96///
97/// For each position `i`, `result[i] = if mask[i] then if_true[i] else if_false[i]`.
98///
99/// Null values in the mask are treated as false (selecting `if_false`). This follows
100/// SQL semantics (DuckDB, Trino) where a null condition falls through to the ELSE branch,
101/// rather than Arrow's `if_else` which propagates null conditions to the output.
102#[derive(Clone)]
103pub struct Zip;
104
105impl Zip {
106    /// Creates a lazy conditional selection between `if_true` and `if_false`.
107    ///
108    /// # Errors
109    ///
110    /// Returns an error if the children have different lengths, the values have incompatible
111    /// dtypes, or `mask` is not boolean data.
112    pub fn try_new(
113        if_true: ArrayRef,
114        if_false: ArrayRef,
115        mask: ArrayRef,
116    ) -> VortexResult<ScalarFnArray> {
117        ScalarFnArray::try_new(Zip.bind(EmptyOptions), [if_true, if_false, mask])
118    }
119}
120
121impl ScalarFnVTable for Zip {
122    type Options = EmptyOptions;
123
124    fn id(&self) -> ScalarFnId {
125        static ID: CachedId = CachedId::new("vortex.zip");
126        *ID
127    }
128
129    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
130        Ok(Some(vec![]))
131    }
132
133    fn deserialize(
134        &self,
135        _metadata: &[u8],
136        _session: &VortexSession,
137    ) -> VortexResult<Self::Options> {
138        Ok(EmptyOptions)
139    }
140
141    fn arity(&self, _options: &Self::Options) -> Arity {
142        Arity::Exact(3)
143    }
144
145    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
146        match child_idx {
147            0 => ChildName::from("if_true"),
148            1 => ChildName::from("if_false"),
149            2 => ChildName::from("mask"),
150            _ => unreachable!("Invalid child index {} for Zip expression", child_idx),
151        }
152    }
153
154    fn fmt_sql(
155        &self,
156        _options: &Self::Options,
157        expr: &dyn ExprDisplay,
158        f: &mut Formatter<'_>,
159    ) -> std::fmt::Result {
160        write!(f, "zip(")?;
161        Display::fmt(expr.display_child(0), f)?;
162        write!(f, ", ")?;
163        Display::fmt(expr.display_child(1), f)?;
164        write!(f, ", ")?;
165        Display::fmt(expr.display_child(2), f)?;
166        write!(f, ")")
167    }
168
169    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
170        vortex_ensure!(
171            matches!(arg_dtypes[2], DType::Bool(_)),
172            "zip requires mask to be a boolean type, got {}",
173            arg_dtypes[2]
174        );
175        zip_return_dtype(&arg_dtypes[0], &arg_dtypes[1])
176    }
177
178    fn execute(
179        &self,
180        _options: &Self::Options,
181        args: &dyn ExecutionArgs,
182        ctx: &mut ExecutionCtx,
183    ) -> VortexResult<ArrayRef> {
184        let if_true = args.get(0)?;
185        let if_false = args.get(1)?;
186        let mask_array = args.get(2)?;
187
188        let mask = mask_array
189            .execute::<BoolArray>(ctx)?
190            .to_mask_fill_null_false(ctx);
191
192        let return_dtype = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
193
194        if mask.all_true() {
195            return if_true.cast(return_dtype);
196        }
197
198        if mask.all_false() {
199            return if_false.cast(return_dtype);
200        }
201
202        if !if_true.is_canonical() || !if_false.is_canonical() {
203            let if_true = if_true.execute::<ArrayRef>(ctx)?;
204            let if_false = if_false.execute::<ArrayRef>(ctx)?;
205            return mask.into_array().zip(if_true, if_false);
206        }
207
208        let Mask::Values(mask) = mask else {
209            unreachable!("trivial masks returned above");
210        };
211        zip_impl(&if_true, &if_false, &mask, ctx)
212    }
213
214    fn simplify<T: ReduceNode>(
215        &self,
216        _options: &Self::Options,
217        node: &T,
218    ) -> VortexResult<Option<T>> {
219        let mask = node.child(2);
220        let Some(mask_constant) = mask.as_constant() else {
221            return Ok(None);
222        };
223
224        if let Some(mask_value) = mask_constant.as_bool().value() {
225            let selected = if mask_value {
226                node.child(0)
227            } else {
228                node.child(1)
229            };
230            // The selected branch can be less nullable than the zip result, which unions
231            // both branches' nullability, so keep the dtype that binding inferred.
232            let dtype = node.node_dtype()?;
233            return Ok(Some(if selected.node_dtype()? == dtype {
234                selected
235            } else {
236                selected.new_node(Cast.bind(dtype), std::slice::from_ref(&selected))?
237            }));
238        }
239
240        Ok(None)
241    }
242
243    fn is_strict(&self, _options: &Self::Options) -> bool {
244        // A null in an unselected branch does not force a null output.
245        false
246    }
247
248    fn is_infallible(&self, _options: &Self::Options) -> bool {
249        true
250    }
251}
252
253fn zip_impl(
254    if_true: &ArrayRef,
255    if_false: &ArrayRef,
256    mask: &MaskValues,
257    ctx: &mut ExecutionCtx,
258) -> VortexResult<ArrayRef> {
259    assert_eq!(
260        if_true.len(),
261        if_false.len(),
262        "zip requires arrays to have the same size"
263    );
264
265    let return_type = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
266    if !has_builder(&return_type) {
267        vortex_bail!(
268            "zip of {return_type} arrays with a mixed mask is not supported: the dtype has no \
269             zip kernel and no array builder"
270        );
271    }
272
273    // `append_to_builder` requires exact dtype equality, so normalize branch
274    // nullability to the output dtype before appending slices into the builder.
275    let if_true = if_true.cast(return_type.clone())?.optimize_ctx(ctx)?;
276    let if_false = if_false.cast(return_type.clone())?.optimize_ctx(ctx)?;
277
278    zip_impl_with_builder(
279        &if_true,
280        &if_false,
281        mask,
282        builder_with_capacity_in(&return_type, if_true.len(), ctx.allocator()),
283        ctx,
284    )
285}
286
287/// Returns whether [`builder_with_capacity_in`] supports `dtype`, which has no builder when it is
288/// or contains a union.
289fn has_builder(dtype: &DType) -> bool {
290    match dtype {
291        DType::Union(..) => false,
292        DType::List(element, _) | DType::FixedSizeList(element, ..) => has_builder(element),
293        DType::Map(map, _) => has_builder(&map.key_dtype()) && has_builder(&map.value_dtype()),
294        DType::Struct(fields, _) => fields.fields().all(|field| has_builder(&field)),
295        DType::Extension(ext) => has_builder(ext.storage_dtype()),
296        DType::Null
297        | DType::Bool(_)
298        | DType::Primitive(..)
299        | DType::Decimal(..)
300        | DType::Utf8(_)
301        | DType::Binary(_)
302        | DType::Variant(_) => true,
303    }
304}
305
306fn zip_return_dtype(if_true: &DType, if_false: &DType) -> VortexResult<DType> {
307    zip_nullability_union(if_true, if_false).ok_or_else(|| {
308        vortex_err!(
309            "zip requires if_true and if_false to have the same base type, got {} and {}",
310            if_true,
311            if_false
312        )
313    })
314}
315
316/// Unions the nullability of two dtypes at every nesting level.
317///
318/// Returns `None` when the dtypes differ in more than nullability.
319pub fn zip_nullability_union(lhs: &DType, rhs: &DType) -> Option<DType> {
320    let nullability = lhs.nullability() | rhs.nullability();
321
322    match (lhs, rhs) {
323        (DType::List(lhs_element, _), DType::List(rhs_element, _)) => Some(DType::List(
324            Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
325            nullability,
326        )),
327        (
328            DType::FixedSizeList(lhs_element, lhs_size, _),
329            DType::FixedSizeList(rhs_element, rhs_size, _),
330        ) if lhs_size == rhs_size => Some(DType::FixedSizeList(
331            Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
332            *lhs_size,
333            nullability,
334        )),
335        (DType::Map(lhs_map, _), DType::Map(rhs_map, _))
336            if lhs_map.keys_sorted() == rhs_map.keys_sorted() =>
337        {
338            DType::map(
339                zip_nullability_union(&lhs_map.key_dtype(), &rhs_map.key_dtype())?,
340                zip_nullability_union(&lhs_map.value_dtype(), &rhs_map.value_dtype())?,
341                lhs_map.keys_sorted(),
342                nullability,
343            )
344            .ok()
345        }
346        (DType::Struct(lhs_fields, _), DType::Struct(rhs_fields, _))
347            if lhs_fields.names() == rhs_fields.names() =>
348        {
349            let fields = lhs_fields
350                .fields()
351                .zip(rhs_fields.fields())
352                .map(|(lhs, rhs)| zip_nullability_union(&lhs, &rhs))
353                .collect::<Option<Vec<_>>>()?;
354            Some(DType::Struct(
355                StructFields::new(lhs_fields.names().clone(), fields),
356                nullability,
357            ))
358        }
359        (DType::Union(lhs_variants, _), DType::Union(rhs_variants, _))
360            if lhs_variants == rhs_variants =>
361        {
362            Some(DType::Union(lhs_variants.clone(), nullability))
363        }
364        _ if lhs.eq_ignore_nullability(rhs) => Some(lhs.with_nullability(nullability)),
365        _ => None,
366    }
367}
368
369fn zip_impl_with_builder(
370    if_true: &ArrayRef,
371    if_false: &ArrayRef,
372    mask: &MaskValues,
373    mut builder: Box<dyn ArrayBuilder>,
374    ctx: &mut ExecutionCtx,
375) -> VortexResult<ArrayRef> {
376    for (start, end) in mask.slices() {
377        if builder.len() < *start {
378            if_false
379                .slice(builder.len()..*start)?
380                .append_to_builder(builder.as_mut(), ctx)?;
381        }
382        if_true
383            .slice(*start..*end)?
384            .append_to_builder(builder.as_mut(), ctx)?;
385    }
386    if builder.len() < if_false.len() {
387        if_false
388            .slice(builder.len()..if_false.len())?
389            .append_to_builder(builder.as_mut(), ctx)?;
390    }
391    Ok(builder.finish())
392}
393
394/// Combine two validities for a row-wise zip: take `if_true`'s validity where `mask` is set and
395/// `if_false`'s where it is not.
396///
397/// That selection is itself a zip over the two boolean validity bitmaps, so it is built as a (lazy)
398/// zip array — reusing the zip machinery rather than re-deriving the mask algebra. Trivial cases
399/// where both sides' validity already agrees skip the zip. `mask` must already be null-filled so the
400/// selection matches the accompanying value selection. Shared by the per-encoding zip kernels (e.g.
401/// `Bool`, `Primitive`) that build their result directly.
402pub(crate) fn zip_validity(
403    if_true: Validity,
404    if_false: Validity,
405    mask: &Mask,
406) -> VortexResult<Validity> {
407    match (&if_true, &if_false) {
408        (Validity::NonNullable, Validity::NonNullable) => return Ok(Validity::NonNullable),
409        (Validity::AllValid, Validity::AllValid) => return Ok(Validity::AllValid),
410        (Validity::AllInvalid, Validity::AllInvalid) => return Ok(Validity::AllInvalid),
411        _ => {}
412    }
413
414    let len = mask.len();
415    let validity = mask
416        .clone()
417        .into_array()
418        .zip(if_true.to_array(len), if_false.to_array(len))?;
419    Ok(Validity::Array(validity))
420}
421
422#[cfg(test)]
423mod tests {
424    use std::sync::LazyLock;
425
426    use rstest::rstest;
427    use vortex_array::ArrayRef;
428    use vortex_array::Canonical;
429    use vortex_array::Columnar;
430    use vortex_array::IntoArray;
431    use vortex_array::VortexSessionExecute;
432    use vortex_array::arrays::Constant;
433    use vortex_array::arrays::ConstantArray;
434    use vortex_array::arrays::PrimitiveArray;
435    use vortex_array::arrays::Struct;
436    use vortex_array::arrays::StructArray;
437    use vortex_array::arrays::UnionArray;
438    use vortex_array::arrays::VarBinView;
439    use vortex_array::arrays::VarBinViewArray;
440    use vortex_array::arrays::VariantArray;
441    use vortex_array::assert_arrays_eq;
442    use vortex_array::builders::ArrayBuilder;
443    use vortex_array::builders::BufferGrowthStrategy;
444    use vortex_array::builders::VarBinViewBuilder;
445    use vortex_array::dtype::DType;
446    use vortex_array::dtype::Nullability;
447    use vortex_array::dtype::PType;
448    use vortex_array::dtype::UnionVariants;
449    use vortex_array::scalar::Scalar;
450    use vortex_buffer::buffer;
451    use vortex_error::VortexResult;
452    use vortex_expr::Expression;
453    use vortex_expr::lit;
454    use vortex_expr::root;
455    use vortex_mask::Mask;
456    use vortex_session::VortexSession;
457
458    use crate::builtins::ArrayFunctions;
459    use crate::expr::zip_expr;
460
461    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
462        let session = VortexSession::empty();
463
464        vortex_array::initialize(&session);
465
466        crate::initialize(&session);
467
468        session
469    });
470
471    #[test]
472    fn dtype() {
473        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
474        let expr = zip_expr(lit(true), root(), lit(0i32));
475        let result_dtype = expr.return_dtype(&dtype).unwrap();
476        assert_eq!(
477            result_dtype,
478            DType::Primitive(PType::I32, Nullability::NonNullable)
479        );
480    }
481
482    #[test]
483    fn test_display() {
484        let expr = zip_expr(lit(true), root(), lit(0i32));
485        assert_eq!(expr.to_string(), "zip($, 0i32, true)");
486    }
487
488    #[test]
489    fn test_zip_basic() {
490        let mut ctx = SESSION.create_execution_ctx();
491        let mask = Mask::from_iter([true, false, false, true, false]);
492        let if_true = buffer![10, 20, 30, 40, 50].into_array();
493        let if_false = buffer![1, 2, 3, 4, 5].into_array();
494
495        let result = mask.into_array().zip(if_true, if_false).unwrap();
496        let expected = buffer![10, 2, 3, 40, 5].into_array();
497
498        assert_arrays_eq!(result, expected, &mut ctx);
499    }
500
501    #[test]
502    fn test_zip_all_true() {
503        let mut ctx = SESSION.create_execution_ctx();
504        let mask = Mask::new_true(4);
505        let if_true = buffer![10, 20, 30, 40].into_array();
506        let if_false =
507            PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();
508
509        let result = mask.into_array().zip(if_true, if_false.clone()).unwrap();
510        let expected =
511            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), Some(40)]).into_array();
512
513        assert_arrays_eq!(result, expected, &mut ctx);
514        assert_eq!(result.dtype(), if_false.dtype())
515    }
516
517    #[test]
518    fn test_zip_all_false_widens_nullability() {
519        let mut ctx = SESSION.create_execution_ctx();
520        let mask = Mask::new_false(4);
521        let if_true =
522            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
523        let if_false = buffer![1i32, 2, 3, 4].into_array();
524
525        let result = mask.into_array().zip(if_true.clone(), if_false).unwrap();
526        let expected =
527            PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), Some(4)]).into_array();
528
529        assert_arrays_eq!(result, expected, &mut ctx);
530        assert_eq!(result.dtype(), if_true.dtype());
531    }
532
533    #[rstest]
534    #[case::all_true(Some(true), 10)]
535    #[case::all_false(Some(false), 20)]
536    #[case::null_mask(None, 20)]
537    fn test_zip_constant_mask_preserves_constant(
538        #[case] mask: Option<bool>,
539        #[case] expected: i32,
540        #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability,
541    ) -> VortexResult<()> {
542        let mut ctx = SESSION.create_execution_ctx();
543        let if_true = ConstantArray::new(10i32, 4).into_array();
544        let if_false = ConstantArray::new(Scalar::primitive(20i32, nullability), 4).into_array();
545        let result = ConstantArray::new(mask, 4)
546            .into_array()
547            .zip(if_true, if_false)?
548            .execute::<Columnar>(&mut ctx)?
549            .into_array();
550
551        assert!(result.is::<Constant>());
552        let expected = ConstantArray::new(Scalar::primitive(expected, nullability), 4);
553        assert_arrays_eq!(result, expected, &mut ctx);
554        Ok(())
555    }
556
557    #[test]
558    fn test_invalid_lengths() {
559        let mask = Mask::new_false(4);
560        let if_true = buffer![10, 20, 30].into_array();
561        let if_false = buffer![1, 2, 3, 4].into_array();
562
563        let error = mask.into_array().zip(if_true, if_false).unwrap_err();
564        assert!(
565            error
566                .to_string()
567                .contains("children equal to the array length")
568        );
569    }
570
571    #[test]
572    fn test_fragmentation() -> VortexResult<()> {
573        let len = 100;
574
575        let const1 = ConstantArray::new(
576            Scalar::utf8("hello_this_is_a_longer_string", Nullability::Nullable),
577            len,
578        )
579        .into_array();
580
581        let const2 = ConstantArray::new(
582            Scalar::utf8("world_this_is_another_string", Nullability::Nullable),
583            len,
584        )
585        .into_array();
586
587        let indices: Vec<usize> = (0..len).step_by(2).collect();
588        let mask = Mask::from_indices(len, indices);
589        let mask_array = mask.into_array();
590
591        let mut ctx = SESSION.create_execution_ctx();
592        let result = mask_array
593            .zip(const1.clone(), const2.clone())?
594            .execute::<Columnar>(&mut ctx)?
595            .into_array();
596
597        insta::assert_snapshot!(result.display_tree(), @r"
598        root: vortex.varbinview(utf8?, len=100) nbytes=1.66 kB (100.00%) [all_valid]
599          metadata: 
600          buffer: buffer_0 host 29 B (align=1) (1.75%)
601          buffer: buffer_1 host 28 B (align=1) (1.69%)
602          buffer: views host 1.60 kB (align=16) (96.56%)
603        ");
604
605        let expected = VarBinViewArray::from_iter_nullable_str((0..len).map(|index| {
606            Some(if index % 2 == 0 {
607                "hello_this_is_a_longer_string"
608            } else {
609                "world_this_is_another_string"
610            })
611        }));
612        assert_arrays_eq!(result, expected, &mut ctx);
613
614        let wrapped1 = StructArray::try_from_iter([("nested", const1)])?.into_array();
615        let wrapped2 = StructArray::try_from_iter([("nested", const2)])?.into_array();
616
617        let wrapped_result = mask_array
618            .zip(wrapped1, wrapped2)?
619            .execute::<ArrayRef>(&mut ctx)?;
620        assert!(wrapped_result.is::<Struct>());
621        assert_arrays_eq!(
622            wrapped_result,
623            StructArray::try_from_iter([("nested", expected.into_array())])?,
624            &mut ctx
625        );
626
627        Ok(())
628    }
629
630    #[test]
631    fn test_varbinview_zip() {
632        let if_true = {
633            let mut builder = VarBinViewBuilder::new_in(
634                DType::Utf8(Nullability::NonNullable),
635                10,
636                Default::default(),
637                BufferGrowthStrategy::fixed(64 * 1024),
638                0.0,
639                vortex_buffer::BufferAllocatorRef::statically_allocated(),
640            );
641            for _ in 0..100 {
642                builder.append_value("Hello");
643                builder.append_value("Hello this is a long string that won't be inlined.");
644            }
645            builder.finish()
646        };
647
648        let if_false = {
649            let mut builder = VarBinViewBuilder::new_in(
650                DType::Utf8(Nullability::NonNullable),
651                10,
652                Default::default(),
653                BufferGrowthStrategy::fixed(64 * 1024),
654                0.0,
655                vortex_buffer::BufferAllocatorRef::statically_allocated(),
656            );
657            for _ in 0..100 {
658                builder.append_value("Hello2");
659                builder.append_value("Hello2 this is a long string that won't be inlined.");
660            }
661            builder.finish()
662        };
663
664        let mask = Mask::from_indices(200, (0..100).filter(|i| i % 3 != 0));
665        let mask_array = mask.clone().into_array();
666
667        let mut ctx = SESSION.create_execution_ctx();
668        let zipped = mask_array
669            .zip(if_true, if_false)
670            .unwrap()
671            .execute::<ArrayRef>(&mut ctx)
672            .unwrap();
673        let zipped = zipped.as_opt::<VarBinView>().unwrap();
674        assert_eq!(zipped.data_buffers().len(), 2);
675
676        let true_value = |i: usize| {
677            if i.is_multiple_of(2) {
678                "Hello"
679            } else {
680                "Hello this is a long string that won't be inlined."
681            }
682        };
683        let false_value = |i: usize| {
684            if i.is_multiple_of(2) {
685                "Hello2"
686            } else {
687                "Hello2 this is a long string that won't be inlined."
688            }
689        };
690        let expected = VarBinViewArray::from_iter_str((0..200).map(|i| {
691            if mask.value(i) {
692                true_value(i)
693            } else {
694                false_value(i)
695            }
696        }));
697        assert_arrays_eq!(zipped.array().clone(), expected, &mut ctx);
698    }
699    #[rstest::rstest]
700    #[case::zip_true(
701        zip_expr(lit(true), lit(1i32), root()),
702        DType::Primitive(PType::I32, Nullability::Nullable)
703    )]
704    #[case::zip_false(
705        zip_expr(lit(false), root(), lit(1i32)),
706        DType::Primitive(PType::I32, Nullability::Nullable)
707    )]
708    fn literal_simplification_preserves_result_dtype(
709        #[case] expr: Expression,
710        #[case] scope: DType,
711    ) -> VortexResult<()> {
712        let original = expr.bind(&scope)?;
713        let optimized = expr.bind(&scope)?.optimize_recursive()?;
714        assert_eq!(optimized.dtype(), original.dtype());
715        Ok(())
716    }
717
718    /// Unshredded Variant arrays have a builder, so a mixed mask zips them through the fallback.
719    #[test]
720    fn test_zip_variant_mixed_mask() -> VortexResult<()> {
721        let variants = |value: i32| -> VortexResult<ArrayRef> {
722            let scalar = Scalar::variant(Scalar::primitive(value, Nullability::NonNullable));
723            let core_storage = ConstantArray::new(scalar, 4).into_array();
724            Ok(VariantArray::try_new(core_storage, None)?.into_array())
725        };
726
727        let mut ctx = SESSION.create_execution_ctx();
728        let zipped = Mask::from_iter([true, false, true, false])
729            .into_array()
730            .zip(variants(1)?, variants(2)?)?
731            .execute::<Canonical>(&mut ctx)?
732            .into_array();
733
734        for (i, expected) in [1i32, 2, 1, 2].into_iter().enumerate() {
735            assert_eq!(
736                zipped.execute_scalar(i, &mut ctx)?,
737                Scalar::variant(Scalar::primitive(expected, Nullability::NonNullable)),
738            );
739        }
740        Ok(())
741    }
742
743    /// Union arrays have no zip kernel and no builder, so a mixed mask fails with an error
744    /// instead of a panic.
745    #[test]
746    fn test_zip_union_mixed_mask_errors() -> VortexResult<()> {
747        let variants = UnionVariants::try_new(
748            ["num"].into(),
749            vec![DType::Primitive(PType::I32, Nullability::NonNullable)],
750            vec![0],
751        )?;
752        let union_of = |value: i32| -> VortexResult<ArrayRef> {
753            Ok(UnionArray::try_new(
754                PrimitiveArray::from_iter([0u8, 0]).into_array(),
755                variants.clone(),
756                vec![PrimitiveArray::from_iter([value, value]).into_array()],
757            )?
758            .into_array())
759        };
760
761        let mut ctx = SESSION.create_execution_ctx();
762        let error = Mask::from_iter([true, false])
763            .into_array()
764            .zip(union_of(1)?, union_of(2)?)?
765            .execute::<Canonical>(&mut ctx)
766            .unwrap_err();
767        assert!(error.to_string().contains("is not supported"), "{error}");
768        Ok(())
769    }
770}