Skip to main content

vortex_functions/zip/
primitive.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::ArrayRef;
5use vortex_array::ArrayView;
6use vortex_array::ExecutionCtx;
7use vortex_array::arrays::Primitive;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10
11use crate::zip::ZipKernel;
12use crate::zip::fixed_width::zip_fixed_width;
13
14/// A dedicated primitive zip kernel that selects values branchlessly per row.
15///
16/// The row selection is shared with [`Decimal`](vortex_array::arrays::Decimal) through
17/// `zip_fixed_width`.
18impl ZipKernel for Primitive {
19    fn zip(
20        if_true: ArrayView<'_, Primitive>,
21        if_false: &ArrayRef,
22        mask: &ArrayRef,
23        ctx: &mut ExecutionCtx,
24    ) -> VortexResult<Option<ArrayRef>> {
25        let Some(if_false) = if_false.as_opt::<Primitive>() else {
26            return Ok(None);
27        };
28
29        if if_true.ptype() != if_false.ptype() {
30            vortex_bail!(
31                "zip requires if_true and if_false to share a primitive type, got {} and {}",
32                if_true.ptype(),
33                if_false.ptype()
34            );
35        }
36
37        zip_fixed_width(if_true, if_false, mask, ctx)
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    #![allow(
44        clippy::cast_possible_truncation,
45        reason = "test fixtures use small indices that fit the target widths"
46    )]
47
48    use std::sync::LazyLock;
49
50    use vortex_array::ArrayRef;
51    use vortex_array::IntoArray;
52    use vortex_array::VortexSessionExecute;
53    use vortex_array::arrays::Primitive;
54    use vortex_array::arrays::PrimitiveArray;
55    use vortex_array::assert_arrays_eq;
56    use vortex_error::VortexResult;
57    use vortex_mask::Mask;
58    use vortex_session::VortexSession;
59
60    use crate::builtins::ArrayFunctions;
61
62    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
63        let session = VortexSession::empty();
64
65        vortex_array::initialize(&session);
66
67        crate::initialize(&session);
68
69        session
70    });
71
72    /// The branchless kernel must agree with the scalar reference across the chunk boundary (index
73    /// 63/64) and the trailing remainder, for non-nullable inputs.
74    #[test]
75    fn zip_nonnull_spans_mask_chunks() -> VortexResult<()> {
76        let len = 150usize;
77        let if_true = PrimitiveArray::from_iter(0..len as i64).into_array();
78        let if_false = PrimitiveArray::from_iter((0..len as i64).map(|i| 1_000 + i)).into_array();
79
80        let bits: Vec<bool> = (0..len).map(|i| i.is_multiple_of(3) || i == 64).collect();
81        let mask = Mask::from_iter(bits.iter().copied());
82
83        let mut ctx = SESSION.create_execution_ctx();
84        let result = mask
85            .into_array()
86            .zip(if_true, if_false)?
87            .execute::<ArrayRef>(&mut ctx)?;
88        assert!(result.is::<Primitive>());
89
90        let expected = PrimitiveArray::from_iter(
91            (0..len).map(|i| if bits[i] { i as i64 } else { 1_000 + i as i64 }),
92        )
93        .into_array();
94        assert_arrays_eq!(result, expected, &mut ctx);
95        Ok(())
96    }
97
98    /// With `Validity::Array` on both sides the kernel must select values and validity from the
99    /// chosen side across the chunk boundary.
100    #[test]
101    fn zip_nullable_selects_values_and_validity() -> VortexResult<()> {
102        let len = 130usize;
103        let if_true =
104            PrimitiveArray::from_option_iter((0..len as i64).map(|i| (i % 4 != 0).then_some(i)))
105                .into_array();
106        let if_false = PrimitiveArray::from_option_iter(
107            (0..len as i64).map(|i| (i % 5 != 0).then_some(1_000 + i)),
108        )
109        .into_array();
110
111        let bits: Vec<bool> = (0..len).map(|i| i.is_multiple_of(2)).collect();
112        let mask = Mask::from_iter(bits.iter().copied());
113
114        let mut ctx = SESSION.create_execution_ctx();
115        let result = mask
116            .into_array()
117            .zip(if_true, if_false)?
118            .execute::<ArrayRef>(&mut ctx)?;
119        assert!(result.is::<Primitive>());
120
121        let expected = PrimitiveArray::from_option_iter((0..len).map(|i| {
122            let v = i as i64;
123            if bits[i] {
124                (!i.is_multiple_of(4)).then_some(v)
125            } else {
126                (!i.is_multiple_of(5)).then_some(1_000 + v)
127            }
128        }))
129        .into_array();
130        assert_arrays_eq!(result, expected, &mut ctx);
131        Ok(())
132    }
133}