Skip to main content

vortex_functions/zip/
bool.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::IntoArray;
8use vortex_array::arrays::Bool;
9use vortex_array::arrays::BoolArray;
10use vortex_array::arrays::bool::BoolArrayExt;
11use vortex_array::builtins::ArrayBuiltins;
12use vortex_buffer::BitBuffer;
13use vortex_buffer::BufferMut;
14use vortex_error::VortexResult;
15use vortex_mask::Mask;
16
17use crate::zip::ZipKernel;
18use crate::zip::zip_validity;
19
20/// A branchless boolean zip kernel that blends the two value bitmaps with the mask in one pass.
21///
22/// Booleans are bit-packed, so selecting `if_true` where the mask is set and `if_false` where it is
23/// not is a single bitwise blend over the packed words — `(true & mask) | (false & !mask)` — instead
24/// of the generic per-run builder. Validity is combined with the shared `zip_validity`, which itself
25/// reuses this kernel (terminating immediately, since validity bitmaps are non-nullable).
26impl ZipKernel for Bool {
27    fn zip(
28        if_true: ArrayView<'_, Bool>,
29        if_false: &ArrayRef,
30        mask: &ArrayRef,
31        ctx: &mut ExecutionCtx,
32    ) -> VortexResult<Option<ArrayRef>> {
33        let Some(if_false) = if_false.as_opt::<Bool>() else {
34            return Ok(None);
35        };
36
37        // Null mask entries select `if_false`, matching `Zip`'s SQL ELSE semantics.
38        let mask = mask.clone().fill_null(false)?.execute::<Mask>(ctx)?;
39        let mask_values = match &mask {
40            // Defer trivial masks to the generic zip, which just casts the surviving side.
41            Mask::AllTrue(_) | Mask::AllFalse(_) => return Ok(None),
42            Mask::Values(values) => values,
43        };
44        let mask_bits = mask_values.bit_buffer();
45
46        let values = zip_value_bits(
47            &if_true.to_bit_buffer(),
48            &if_false.to_bit_buffer(),
49            mask_bits,
50        );
51
52        let validity = zip_validity(if_true.validity()?, if_false.validity()?, &mask)?;
53
54        Ok(Some(BoolArray::new(values, validity).into_array()))
55    }
56}
57
58fn zip_value_bits(if_true: &BitBuffer, if_false: &BitBuffer, mask: &BitBuffer) -> BitBuffer {
59    assert_eq!(if_true.len(), if_false.len());
60    assert_eq!(if_true.len(), mask.len());
61
62    let true_chunks = if_true.chunks();
63    let false_chunks = if_false.chunks();
64    let mask_chunks = mask.chunks();
65
66    let mut values = BufferMut::<u64>::with_capacity(true_chunks.num_u64s());
67    for ((true_bits, false_bits), mask_bits) in true_chunks
68        .iter()
69        .zip(false_chunks.iter())
70        .zip(mask_chunks.iter())
71    {
72        values.push((true_bits & mask_bits) | (false_bits & !mask_bits));
73    }
74
75    if true_chunks.remainder_len() != 0 {
76        let true_bits = true_chunks.remainder_bits();
77        let false_bits = false_chunks.remainder_bits();
78        let mask_bits = mask_chunks.remainder_bits();
79        values.push((true_bits & mask_bits) | (false_bits & !mask_bits));
80    }
81
82    BitBuffer::new(values.freeze().into_byte_buffer(), if_true.len())
83}
84
85#[cfg(test)]
86mod tests {
87    use std::sync::LazyLock;
88
89    use vortex_array::ArrayRef;
90    use vortex_array::IntoArray;
91    use vortex_array::VortexSessionExecute;
92    use vortex_array::arrays::Bool;
93    use vortex_array::arrays::BoolArray;
94    use vortex_array::assert_arrays_eq;
95    use vortex_error::VortexResult;
96    use vortex_mask::Mask;
97    use vortex_session::VortexSession;
98
99    use super::zip_value_bits;
100    use crate::builtins::ArrayFunctions;
101
102    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
103        let session = VortexSession::empty();
104
105        vortex_array::initialize(&session);
106
107        crate::initialize(&session);
108
109        session
110    });
111
112    #[test]
113    fn blend_value_bits_boundaries() {
114        for len in [0usize, 1, 2, 7, 8, 9, 63, 64, 65, 127, 128] {
115            let if_true = (0..len).map(|i| i.is_multiple_of(2)).collect();
116            let if_false = (0..len).map(|i| i.is_multiple_of(3)).collect();
117            let mask = (0..len).map(|i| i % 3 != 1).collect();
118
119            let values = zip_value_bits(&if_true, &if_false, &mask);
120
121            assert_eq!(values.len(), len);
122            assert_eq!(
123                values.iter().collect::<Vec<_>>(),
124                (0..len)
125                    .map(|i| {
126                        if i % 3 != 1 {
127                            i.is_multiple_of(2)
128                        } else {
129                            i.is_multiple_of(3)
130                        }
131                    })
132                    .collect::<Vec<_>>(),
133                "failed for len {len}",
134            );
135        }
136    }
137
138    /// Blend two non-nullable bool arrays across the 64-bit mask chunk boundary + remainder.
139    #[test]
140    fn zip_nonnull_spans_mask_chunks() -> VortexResult<()> {
141        let len = 150usize;
142        let if_true = BoolArray::from_iter((0..len).map(|i| i.is_multiple_of(2))).into_array();
143        let if_false = BoolArray::from_iter((0..len).map(|i| i.is_multiple_of(3))).into_array();
144
145        let bits: Vec<bool> = (0..len).map(|i| i.is_multiple_of(5) || i == 64).collect();
146        let mask = Mask::from_iter(bits.iter().copied());
147
148        let mut ctx = SESSION.create_execution_ctx();
149        let result = mask
150            .into_array()
151            .zip(if_true, if_false)?
152            .execute::<ArrayRef>(&mut ctx)?;
153        assert!(result.is::<Bool>());
154
155        let expected = BoolArray::from_iter((0..len).map(|i| {
156            if bits[i] {
157                i.is_multiple_of(2)
158            } else {
159                i.is_multiple_of(3)
160            }
161        }))
162        .into_array();
163        assert_arrays_eq!(result, expected, &mut ctx);
164        Ok(())
165    }
166
167    /// With `Validity::Array` on both sides, select values and validity from the chosen side.
168    #[test]
169    fn zip_nullable_selects_values_and_validity() -> VortexResult<()> {
170        let len = 130usize;
171        let if_true = BoolArray::from_iter(
172            (0..len).map(|i| (!i.is_multiple_of(4)).then_some(i.is_multiple_of(2))),
173        )
174        .into_array();
175        let if_false = BoolArray::from_iter(
176            (0..len).map(|i| (!i.is_multiple_of(5)).then_some(i.is_multiple_of(3))),
177        )
178        .into_array();
179
180        let bits: Vec<bool> = (0..len).map(|i| i.is_multiple_of(2)).collect();
181        let mask = Mask::from_iter(bits.iter().copied());
182
183        let mut ctx = SESSION.create_execution_ctx();
184        let result = mask
185            .into_array()
186            .zip(if_true, if_false)?
187            .execute::<ArrayRef>(&mut ctx)?;
188        assert!(result.is::<Bool>());
189
190        let expected = BoolArray::from_iter((0..len).map(|i| {
191            if bits[i] {
192                (!i.is_multiple_of(4)).then_some(i.is_multiple_of(2))
193            } else {
194                (!i.is_multiple_of(5)).then_some(i.is_multiple_of(3))
195            }
196        }))
197        .into_array();
198        assert_arrays_eq!(result, expected, &mut ctx);
199        Ok(())
200    }
201}