Skip to main content

vortex_array/scalar_fn/builtin/boolean/
kernel.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::iter::repeat_n;
5
6use vortex_buffer::BitBuffer;
7use vortex_buffer::BufferAllocatorRef;
8use vortex_buffer::BufferMut;
9use vortex_buffer::read_u64_le;
10use vortex_error::VortexResult;
11use vortex_error::vortex_err;
12use vortex_mask::AllOr;
13use vortex_mask::Mask;
14
15use crate::ArrayRef;
16use crate::Canonical;
17use crate::ExecutionCtx;
18use crate::IntoArray;
19use crate::array::ArrayView;
20use crate::array::VTable;
21use crate::arrays::BoolArray;
22use crate::arrays::Constant;
23use crate::arrays::ConstantArray;
24use crate::arrays::ScalarFn;
25use crate::arrays::scalar_fn::ExactScalarFn;
26use crate::arrays::scalar_fn::ScalarFnArrayExt;
27use crate::arrays::scalar_fn::ScalarFnArrayView;
28use crate::builtins::ArrayBuiltins;
29use crate::dtype::DType;
30use crate::dtype::Nullability;
31use crate::kernel::ExecuteParentKernel;
32use crate::scalar::BoolScalar;
33use crate::scalar::Scalar;
34use crate::scalar_fn::builtin::boolean::Boolean;
35use crate::scalar_fn::builtin::operators::BooleanOperator;
36use crate::validity::Validity;
37
38/// Trait for encoding-specific boolean kernels that operate in encoded space.
39///
40/// Implementations receive the encoded array as the left operand. `rhs` may be any boolean array
41/// encoding or a constant; implementations should return `Ok(None)` when they cannot handle that
42/// operand without falling back to ordinary execution.
43///
44/// Vortex's boolean [`BooleanOperator::And`] and [`BooleanOperator::Or`] variants use Kleene semantics; there is
45/// no separate two-valued boolean operator path to dispatch here. Consequently, they are not
46/// strict: `false AND null` is `false`, and `true OR null` is `true`.
47pub trait BooleanKernel: VTable {
48    /// Execute `lhs <operator> rhs` using Kleene boolean semantics.
49    fn boolean(
50        lhs: ArrayView<'_, Self>,
51        rhs: &ArrayRef,
52        operator: BooleanOperator,
53        ctx: &mut ExecutionCtx,
54    ) -> VortexResult<Option<ArrayRef>>;
55}
56
57/// Adaptor that bridges [`BooleanKernel`] implementations to [`ExecuteParentKernel`].
58///
59/// When a `ScalarFnArray(Boolean, And|Or)` wraps a child implementing [`BooleanKernel`], this
60/// adaptor extracts the other operand and delegates to the encoding-specific kernel.
61#[derive(Default, Debug)]
62pub struct BooleanExecuteAdaptor<V>(pub V);
63
64impl<V> ExecuteParentKernel<V> for BooleanExecuteAdaptor<V>
65where
66    V: BooleanKernel,
67{
68    type Parent = ExactScalarFn<Boolean>;
69
70    fn execute_parent(
71        &self,
72        array: ArrayView<'_, V>,
73        parent: ScalarFnArrayView<'_, Boolean>,
74        child_idx: usize,
75        ctx: &mut ExecutionCtx,
76    ) -> VortexResult<Option<ArrayRef>> {
77        let op = *parent.options;
78
79        let Some(scalar_fn_array) = parent.as_opt::<ScalarFn>() else {
80            return Ok(None);
81        };
82        let other = match child_idx {
83            0 => scalar_fn_array.get_child(1),
84            1 => scalar_fn_array.get_child(0),
85            _ => return Ok(None),
86        };
87
88        if let Some(result) = constant_boolean(array.array(), other, op)? {
89            return Ok(Some(result));
90        }
91
92        V::boolean(array, other, op, ctx)
93    }
94}
95
96/// Point-wise Kleene logical _and_ between two Boolean arrays.
97#[deprecated(note = "Use `ArrayBuiltins::boolean` instead")]
98pub fn and_kleene(lhs: &ArrayRef, rhs: &ArrayRef) -> VortexResult<ArrayRef> {
99    lhs.clone().boolean(rhs.clone(), BooleanOperator::And)
100}
101
102/// Point-wise Kleene logical _or_ between two Boolean arrays.
103#[deprecated(note = "Use `ArrayBuiltins::boolean` instead")]
104pub fn or_kleene(lhs: &ArrayRef, rhs: &ArrayRef) -> VortexResult<ArrayRef> {
105    lhs.clone().boolean(rhs.clone(), BooleanOperator::Or)
106}
107
108/// Execute a Kleene boolean operation between two arrays.
109///
110/// This is the entry point for boolean operations from the [`Boolean`] function.
111/// Handles constants and canonical boolean arrays directly, otherwise falls back to Arrow.
112pub(super) fn execute_boolean(
113    lhs: ArrayRef,
114    rhs: ArrayRef,
115    op: BooleanOperator,
116    ctx: &mut ExecutionCtx,
117) -> VortexResult<ArrayRef> {
118    let nullable = boolean_nullability(&lhs, &rhs);
119
120    if lhs.is_empty() {
121        return Ok(Canonical::empty(&DType::Bool(nullable)).into_array());
122    }
123
124    if let Some(result) = constant_boolean(&lhs, &rhs, op)? {
125        return Ok(result);
126    }
127
128    let lhs = lhs.execute::<BoolArray>(ctx)?;
129    let lhs_validity = lhs.validity()?;
130
131    if let Some(rhs) = rhs.as_opt::<Constant>() {
132        let rhs = rhs
133            .scalar()
134            .as_bool_opt()
135            .ok_or_else(|| vortex_err!("expected boolean scalar"))?;
136        return kleene_boolean_buffer_scalar(
137            lhs.into_bit_buffer(),
138            lhs_validity,
139            &rhs,
140            op,
141            nullable,
142            ctx,
143        );
144    }
145
146    let rhs = rhs.execute::<BoolArray>(ctx)?;
147    let rhs_validity = rhs.validity()?;
148    kleene_boolean_buffers(
149        lhs.into_bit_buffer(),
150        lhs_validity,
151        rhs.into_bit_buffer(),
152        rhs_validity,
153        op,
154        nullable,
155        ctx,
156    )
157}
158
159/// Handles boolean operations where at least one operand is a constant array.
160fn constant_boolean(
161    lhs: &ArrayRef,
162    rhs: &ArrayRef,
163    op: BooleanOperator,
164) -> VortexResult<Option<ArrayRef>> {
165    let nullable = boolean_nullability(lhs, rhs);
166
167    match (lhs.as_opt::<Constant>(), rhs.as_opt::<Constant>()) {
168        (Some(lhs), Some(rhs)) => {
169            let result = boolean_scalar_scalar(
170                bool_scalar_value(lhs.scalar())?,
171                bool_scalar_value(rhs.scalar())?,
172                op,
173            )?;
174
175            Ok(Some(constant_bool_result(result, lhs.len(), nullable)))
176        }
177        (Some(lhs), None) => constant_array_boolean(lhs.scalar(), rhs, op, nullable),
178        (None, Some(rhs)) => constant_array_boolean(rhs.scalar(), lhs, op, nullable),
179        (None, None) => Ok(None),
180    }
181}
182
183fn constant_array_boolean(
184    constant: &Scalar,
185    array: &ArrayRef,
186    op: BooleanOperator,
187    nullability: Nullability,
188) -> VortexResult<Option<ArrayRef>> {
189    match (op, bool_scalar_value(constant)?) {
190        (BooleanOperator::And, Some(false)) => Ok(Some(constant_bool_result(
191            Some(false),
192            array.len(),
193            nullability,
194        ))),
195        (BooleanOperator::And, Some(true)) => Ok(Some(cast_bool_nullability(array, nullability)?)),
196        (BooleanOperator::Or, Some(true)) => Ok(Some(constant_bool_result(
197            Some(true),
198            array.len(),
199            nullability,
200        ))),
201        (BooleanOperator::Or, Some(false)) => Ok(Some(cast_bool_nullability(array, nullability)?)),
202        (BooleanOperator::And | BooleanOperator::Or, None) => Ok(None),
203    }
204}
205
206fn boolean_scalar_scalar(
207    lhs: Option<bool>,
208    rhs: Option<bool>,
209    op: BooleanOperator,
210) -> VortexResult<Option<bool>> {
211    Ok(match op {
212        BooleanOperator::And => match (lhs, rhs) {
213            (Some(false), _) | (_, Some(false)) => Some(false),
214            (None, _) | (_, None) => None,
215            (Some(l), Some(r)) => Some(l & r),
216        },
217        BooleanOperator::Or => match (lhs, rhs) {
218            (Some(true), _) | (_, Some(true)) => Some(true),
219            (None, _) | (_, None) => None,
220            (Some(l), Some(r)) => Some(l | r),
221        },
222    })
223}
224
225fn bool_scalar_value(scalar: &Scalar) -> VortexResult<Option<bool>> {
226    Ok(scalar
227        .as_bool_opt()
228        .ok_or_else(|| vortex_err!("expected boolean scalar"))?
229        .value())
230}
231
232/// Execute a Kleene boolean operation from boolean value bitmaps and validity values.
233pub fn kleene_boolean_buffers(
234    lhs_values: BitBuffer,
235    lhs_validity: Validity,
236    rhs_values: BitBuffer,
237    rhs_validity: Validity,
238    operator: BooleanOperator,
239    nullability: Nullability,
240    ctx: &mut ExecutionCtx,
241) -> VortexResult<ArrayRef> {
242    let len = lhs_values.len();
243    debug_assert_eq!(rhs_values.len(), len);
244
245    if lhs_validity.definitely_no_nulls() && rhs_validity.definitely_no_nulls() {
246        let values = match operator {
247            BooleanOperator::And => lhs_values & rhs_values,
248            BooleanOperator::Or => lhs_values | rhs_values,
249        };
250        return Ok(BoolArray::try_new(values, Validity::from(nullability))?.into_array());
251    }
252
253    let lhs_valid = lhs_validity.execute_mask(len, ctx)?;
254    let rhs_valid = rhs_validity.execute_mask(len, ctx)?;
255    fused_boolean_buffers(
256        len,
257        &lhs_values,
258        &lhs_valid,
259        &rhs_values,
260        &rhs_valid,
261        operator,
262        nullability,
263        ctx.allocator(),
264    )
265}
266
267/// Execute a Kleene boolean operation between boolean value bits and a scalar.
268pub fn kleene_boolean_buffer_scalar(
269    values: BitBuffer,
270    validity: Validity,
271    scalar: &BoolScalar<'_>,
272    operator: BooleanOperator,
273    nullability: Nullability,
274    ctx: &mut ExecutionCtx,
275) -> VortexResult<ArrayRef> {
276    let scalar_value = scalar.value();
277    let len = values.len();
278    let result = match (operator, scalar_value) {
279        (BooleanOperator::And, Some(false)) => {
280            return Ok(constant_bool_result(Some(false), len, nullability));
281        }
282        (BooleanOperator::And, Some(true)) => {
283            return Ok(
284                BoolArray::try_new(values, validity.union_nullability(nullability))?.into_array(),
285            );
286        }
287        (BooleanOperator::Or, Some(true)) => {
288            return Ok(constant_bool_result(Some(true), len, nullability));
289        }
290        (BooleanOperator::Or, Some(false)) => {
291            return Ok(
292                BoolArray::try_new(values, validity.union_nullability(nullability))?.into_array(),
293            );
294        }
295        (BooleanOperator::And, None) => {
296            let valid = validity
297                .execute_mask(len, ctx)?
298                .bitand_not(&Mask::from_buffer(values));
299            BoolArray::try_new(
300                BitBuffer::new_unset_in(len, ctx.allocator().clone()),
301                Validity::from_mask(valid, nullability),
302            )?
303        }
304        (BooleanOperator::Or, None) => {
305            let valid = validity.execute_mask(len, ctx)? & &Mask::from_buffer(values);
306            BoolArray::try_new(
307                BitBuffer::new_set_in(len, ctx.allocator().clone()),
308                Validity::from_mask(valid, nullability),
309            )?
310        }
311    };
312
313    Ok(result.into_array())
314}
315
316#[expect(
317    clippy::too_many_arguments,
318    reason = "four buffers plus result options"
319)]
320fn fused_boolean_buffers(
321    len: usize,
322    lhs_values: &BitBuffer,
323    lhs_validity: &Mask,
324    rhs_values: &BitBuffer,
325    rhs_validity: &Mask,
326    operator: BooleanOperator,
327    nullability: Nullability,
328    allocator: &BufferAllocatorRef,
329) -> VortexResult<ArrayRef> {
330    if let Some(result) = fused_boolean_buffers_aligned(
331        len,
332        lhs_values,
333        lhs_validity,
334        rhs_values,
335        rhs_validity,
336        operator,
337        nullability,
338        allocator,
339    )? {
340        return Ok(result);
341    }
342
343    let n_words = len.div_ceil(64);
344
345    macro_rules! fuse {
346        ($lhs_valid_words:expr, $rhs_valid_words:expr) => {
347            fused_boolean_words(
348                len,
349                lhs_values.chunks().iter_padded(),
350                rhs_values.chunks().iter_padded(),
351                $lhs_valid_words,
352                $rhs_valid_words,
353                operator,
354                nullability,
355                allocator,
356            )
357        };
358    }
359
360    match (lhs_validity.bit_buffer(), rhs_validity.bit_buffer()) {
361        (AllOr::All, AllOr::All) => {
362            fuse!(repeat_n(u64::MAX, n_words), repeat_n(u64::MAX, n_words))
363        }
364        (AllOr::All, AllOr::None) => {
365            fuse!(repeat_n(u64::MAX, n_words), repeat_n(0, n_words))
366        }
367        (AllOr::All, AllOr::Some(rhs_validity)) => fuse!(
368            repeat_n(u64::MAX, n_words),
369            rhs_validity.chunks().iter_padded()
370        ),
371        (AllOr::None, AllOr::All) => {
372            fuse!(repeat_n(0, n_words), repeat_n(u64::MAX, n_words))
373        }
374        (AllOr::None, AllOr::None) => {
375            fuse!(repeat_n(0, n_words), repeat_n(0, n_words))
376        }
377        (AllOr::None, AllOr::Some(rhs_validity)) => {
378            fuse!(repeat_n(0, n_words), rhs_validity.chunks().iter_padded())
379        }
380        (AllOr::Some(lhs_validity), AllOr::All) => fuse!(
381            lhs_validity.chunks().iter_padded(),
382            repeat_n(u64::MAX, n_words)
383        ),
384        (AllOr::Some(lhs_validity), AllOr::None) => {
385            fuse!(lhs_validity.chunks().iter_padded(), repeat_n(0, n_words))
386        }
387        (AllOr::Some(lhs_validity), AllOr::Some(rhs_validity)) => fuse!(
388            lhs_validity.chunks().iter_padded(),
389            rhs_validity.chunks().iter_padded()
390        ),
391    }
392}
393
394#[derive(Clone, Copy)]
395enum WordSource<'a> {
396    Fill(u64),
397    Bytes(&'a [u8]),
398}
399
400impl WordSource<'_> {
401    #[inline]
402    fn word_at(self, byte_offset: usize, len: usize) -> u64 {
403        match self {
404            Self::Fill(word) => word,
405            Self::Bytes(bytes) => read_u64_le(&bytes[byte_offset..byte_offset + len]),
406        }
407    }
408}
409
410#[expect(
411    clippy::too_many_arguments,
412    reason = "four buffers plus result options"
413)]
414fn fused_boolean_buffers_aligned(
415    len: usize,
416    lhs_values: &BitBuffer,
417    lhs_validity: &Mask,
418    rhs_values: &BitBuffer,
419    rhs_validity: &Mask,
420    operator: BooleanOperator,
421    nullability: Nullability,
422    allocator: &BufferAllocatorRef,
423) -> VortexResult<Option<ArrayRef>> {
424    let Some(lhs_values) = word_source_from_bit_buffer(lhs_values) else {
425        return Ok(None);
426    };
427    let Some(rhs_values) = word_source_from_bit_buffer(rhs_values) else {
428        return Ok(None);
429    };
430    let Some(lhs_validity) = word_source_from_mask(lhs_validity) else {
431        return Ok(None);
432    };
433    let Some(rhs_validity) = word_source_from_mask(rhs_validity) else {
434        return Ok(None);
435    };
436
437    Ok(Some(fused_boolean_word_sources(
438        len,
439        lhs_values,
440        rhs_values,
441        lhs_validity,
442        rhs_validity,
443        operator,
444        nullability,
445        allocator,
446    )?))
447}
448
449fn word_source_from_bit_buffer(buffer: &BitBuffer) -> Option<WordSource<'_>> {
450    buffer.byte_aligned_bytes().map(WordSource::Bytes)
451}
452
453fn word_source_from_mask(mask: &Mask) -> Option<WordSource<'_>> {
454    match mask.bit_buffer() {
455        AllOr::All => Some(WordSource::Fill(u64::MAX)),
456        AllOr::None => Some(WordSource::Fill(0)),
457        AllOr::Some(buffer) => word_source_from_bit_buffer(buffer),
458    }
459}
460
461#[expect(
462    clippy::too_many_arguments,
463    reason = "four word sources plus result options"
464)]
465fn fused_boolean_word_sources(
466    len: usize,
467    lhs_words: WordSource<'_>,
468    rhs_words: WordSource<'_>,
469    lhs_valid_words: WordSource<'_>,
470    rhs_valid_words: WordSource<'_>,
471    operator: BooleanOperator,
472    nullability: Nullability,
473    allocator: &BufferAllocatorRef,
474) -> VortexResult<ArrayRef> {
475    match operator {
476        BooleanOperator::And => fused_boolean_and_word_sources(
477            len,
478            lhs_words,
479            rhs_words,
480            lhs_valid_words,
481            rhs_valid_words,
482            nullability,
483            allocator,
484        ),
485        BooleanOperator::Or => fused_boolean_or_word_sources(
486            len,
487            lhs_words,
488            rhs_words,
489            lhs_valid_words,
490            rhs_valid_words,
491            nullability,
492            allocator,
493        ),
494    }
495}
496
497fn fused_boolean_and_word_sources(
498    len: usize,
499    lhs_words: WordSource<'_>,
500    rhs_words: WordSource<'_>,
501    lhs_valid_words: WordSource<'_>,
502    rhs_valid_words: WordSource<'_>,
503    nullability: Nullability,
504    allocator: &BufferAllocatorRef,
505) -> VortexResult<ArrayRef> {
506    let n_bytes = len.div_ceil(8);
507    let n_words = n_bytes.div_ceil(8);
508    let full_bytes = n_bytes - n_bytes % 8;
509    let mut values = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
510    let mut validity = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
511
512    for byte_offset in (0..full_bytes).step_by(8) {
513        let lhs = lhs_words.word_at(byte_offset, 8);
514        let rhs = rhs_words.word_at(byte_offset, 8);
515        let lhs_valid = lhs_valid_words.word_at(byte_offset, 8);
516        let rhs_valid = rhs_valid_words.word_at(byte_offset, 8);
517
518        // SAFETY: both buffers were allocated with exactly `n_words` capacity, and this
519        // loop plus the optional tail push emits at most `n_words` words.
520        unsafe {
521            values.push_unchecked(lhs & rhs);
522            validity
523                .push_unchecked((lhs_valid & rhs_valid) | (lhs_valid & !lhs) | (rhs_valid & !rhs));
524        }
525    }
526
527    if full_bytes != n_bytes {
528        let tail_len = n_bytes - full_bytes;
529        let lhs = lhs_words.word_at(full_bytes, tail_len);
530        let rhs = rhs_words.word_at(full_bytes, tail_len);
531        let lhs_valid = lhs_valid_words.word_at(full_bytes, tail_len);
532        let rhs_valid = rhs_valid_words.word_at(full_bytes, tail_len);
533
534        // SAFETY: see the loop safety comment above.
535        unsafe {
536            values.push_unchecked(lhs & rhs);
537            validity
538                .push_unchecked((lhs_valid & rhs_valid) | (lhs_valid & !lhs) | (rhs_valid & !rhs));
539        }
540    }
541
542    finish_fused_boolean_words(len, n_bytes, values, validity, nullability)
543}
544
545fn fused_boolean_or_word_sources(
546    len: usize,
547    lhs_words: WordSource<'_>,
548    rhs_words: WordSource<'_>,
549    lhs_valid_words: WordSource<'_>,
550    rhs_valid_words: WordSource<'_>,
551    nullability: Nullability,
552    allocator: &BufferAllocatorRef,
553) -> VortexResult<ArrayRef> {
554    let n_bytes = len.div_ceil(8);
555    let n_words = n_bytes.div_ceil(8);
556    let full_bytes = n_bytes - n_bytes % 8;
557    let mut values = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
558    let mut validity = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
559
560    for byte_offset in (0..full_bytes).step_by(8) {
561        let lhs = lhs_words.word_at(byte_offset, 8);
562        let rhs = rhs_words.word_at(byte_offset, 8);
563        let lhs_valid = lhs_valid_words.word_at(byte_offset, 8);
564        let rhs_valid = rhs_valid_words.word_at(byte_offset, 8);
565
566        // SAFETY: both buffers were allocated with exactly `n_words` capacity, and this
567        // loop plus the optional tail push emits at most `n_words` words.
568        unsafe {
569            values.push_unchecked(lhs | rhs);
570            validity
571                .push_unchecked((lhs_valid & rhs_valid) | (lhs_valid & lhs) | (rhs_valid & rhs));
572        }
573    }
574
575    if full_bytes != n_bytes {
576        let tail_len = n_bytes - full_bytes;
577        let lhs = lhs_words.word_at(full_bytes, tail_len);
578        let rhs = rhs_words.word_at(full_bytes, tail_len);
579        let lhs_valid = lhs_valid_words.word_at(full_bytes, tail_len);
580        let rhs_valid = rhs_valid_words.word_at(full_bytes, tail_len);
581
582        // SAFETY: see the loop safety comment above.
583        unsafe {
584            values.push_unchecked(lhs | rhs);
585            validity
586                .push_unchecked((lhs_valid & rhs_valid) | (lhs_valid & lhs) | (rhs_valid & rhs));
587        }
588    }
589
590    finish_fused_boolean_words(len, n_bytes, values, validity, nullability)
591}
592
593fn finish_fused_boolean_words(
594    len: usize,
595    n_bytes: usize,
596    values: BufferMut<u64>,
597    validity: BufferMut<u64>,
598    nullability: Nullability,
599) -> VortexResult<ArrayRef> {
600    let mut values = values.into_byte_buffer();
601    values.truncate(n_bytes);
602    let mut validity = validity.into_byte_buffer();
603    validity.truncate(n_bytes);
604    Ok(BoolArray::try_new(
605        BitBuffer::new(values.freeze(), len),
606        Validity::from_mask(
607            Mask::from_buffer(BitBuffer::new(validity.freeze(), len)),
608            nullability,
609        ),
610    )?
611    .into_array())
612}
613
614#[expect(
615    clippy::too_many_arguments,
616    reason = "four word iterators plus result options"
617)]
618fn fused_boolean_words<L, R, LV, RV>(
619    len: usize,
620    lhs_words: L,
621    rhs_words: R,
622    lhs_valid_words: LV,
623    rhs_valid_words: RV,
624    operator: BooleanOperator,
625    nullability: Nullability,
626    allocator: &BufferAllocatorRef,
627) -> VortexResult<ArrayRef>
628where
629    L: Iterator<Item = u64>,
630    R: Iterator<Item = u64>,
631    LV: Iterator<Item = u64>,
632    RV: Iterator<Item = u64>,
633{
634    match operator {
635        BooleanOperator::And => fused_boolean_and_words(
636            len,
637            lhs_words,
638            rhs_words,
639            lhs_valid_words,
640            rhs_valid_words,
641            nullability,
642            allocator,
643        ),
644        BooleanOperator::Or => fused_boolean_or_words(
645            len,
646            lhs_words,
647            rhs_words,
648            lhs_valid_words,
649            rhs_valid_words,
650            nullability,
651            allocator,
652        ),
653    }
654}
655
656fn fused_boolean_and_words<L, R, LV, RV>(
657    len: usize,
658    lhs_words: L,
659    rhs_words: R,
660    lhs_valid_words: LV,
661    rhs_valid_words: RV,
662    nullability: Nullability,
663    allocator: &BufferAllocatorRef,
664) -> VortexResult<ArrayRef>
665where
666    L: Iterator<Item = u64>,
667    R: Iterator<Item = u64>,
668    LV: Iterator<Item = u64>,
669    RV: Iterator<Item = u64>,
670{
671    let n_words = len.div_ceil(64);
672    let mut values = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
673    let mut validity = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
674
675    for (((lhs, rhs), lhs_valid), rhs_valid) in lhs_words
676        .zip(rhs_words)
677        .zip(lhs_valid_words)
678        .zip(rhs_valid_words)
679        .take(n_words)
680    {
681        // SAFETY: both buffers were allocated with exactly `n_words` capacity, and this loop is
682        // capped at `n_words`.
683        unsafe {
684            values.push_unchecked(lhs & rhs);
685            validity
686                .push_unchecked((lhs_valid & rhs_valid) | (lhs_valid & !lhs) | (rhs_valid & !rhs));
687        }
688    }
689
690    finish_fused_boolean_words(len, len.div_ceil(8), values, validity, nullability)
691}
692
693fn fused_boolean_or_words<L, R, LV, RV>(
694    len: usize,
695    lhs_words: L,
696    rhs_words: R,
697    lhs_valid_words: LV,
698    rhs_valid_words: RV,
699    nullability: Nullability,
700    allocator: &BufferAllocatorRef,
701) -> VortexResult<ArrayRef>
702where
703    L: Iterator<Item = u64>,
704    R: Iterator<Item = u64>,
705    LV: Iterator<Item = u64>,
706    RV: Iterator<Item = u64>,
707{
708    let n_words = len.div_ceil(64);
709    let mut values = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
710    let mut validity = BufferMut::<u64>::with_capacity_in(n_words, allocator.clone());
711
712    for (((lhs, rhs), lhs_valid), rhs_valid) in lhs_words
713        .zip(rhs_words)
714        .zip(lhs_valid_words)
715        .zip(rhs_valid_words)
716        .take(n_words)
717    {
718        // SAFETY: both buffers were allocated with exactly `n_words` capacity, and this loop is
719        // capped at `n_words`.
720        unsafe {
721            values.push_unchecked(lhs | rhs);
722            validity
723                .push_unchecked((lhs_valid & rhs_valid) | (lhs_valid & lhs) | (rhs_valid & rhs));
724        }
725    }
726
727    finish_fused_boolean_words(len, len.div_ceil(8), values, validity, nullability)
728}
729
730fn constant_bool_result(value: Option<bool>, len: usize, nullability: Nullability) -> ArrayRef {
731    let scalar = value
732        .map(|b| Scalar::bool(b, nullability))
733        .unwrap_or_else(|| Scalar::null(DType::Bool(nullability)));
734
735    ConstantArray::new(scalar, len).into_array()
736}
737
738fn cast_bool_nullability(array: &ArrayRef, nullability: Nullability) -> VortexResult<ArrayRef> {
739    let dtype = DType::Bool(nullability);
740    if array.dtype() == &dtype {
741        Ok(array.clone())
742    } else {
743        array.cast(dtype)
744    }
745}
746
747fn boolean_nullability(lhs: &ArrayRef, rhs: &ArrayRef) -> Nullability {
748    lhs.dtype().nullability() | rhs.dtype().nullability()
749}
750
751#[cfg(test)]
752mod tests {
753    use std::sync::LazyLock;
754
755    use rstest::rstest;
756    use vortex_error::VortexResult;
757    use vortex_session::VortexSession;
758
759    use super::execute_boolean;
760    use crate::ArrayRef;
761    use crate::IntoArray;
762    use crate::VortexSessionExecute;
763    use crate::arrays::BoolArray;
764    use crate::arrays::ConstantArray;
765    use crate::arrays::bool::BoolArrayExt;
766    use crate::assert_arrays_eq;
767    use crate::builtins::ArrayBuiltins;
768    use crate::dtype::DType;
769    use crate::dtype::Nullability;
770    use crate::scalar::Scalar;
771    use crate::scalar_fn::builtin::operators::BooleanOperator;
772
773    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
774
775    #[test]
776    fn test_kleene_truth_table() -> VortexResult<()> {
777        let mut ctx = SESSION.create_execution_ctx();
778        let lhs = BoolArray::from_iter([
779            Some(true),
780            Some(true),
781            Some(true),
782            Some(false),
783            Some(false),
784            Some(false),
785            None,
786            None,
787            None,
788        ])
789        .into_array();
790        let rhs = BoolArray::from_iter([
791            Some(true),
792            Some(false),
793            None,
794            Some(true),
795            Some(false),
796            None,
797            Some(true),
798            Some(false),
799            None,
800        ])
801        .into_array();
802
803        assert_arrays_eq!(
804            lhs.boolean(rhs.clone(), BooleanOperator::And)?,
805            BoolArray::from_iter([
806                Some(true),
807                Some(false),
808                None,
809                Some(false),
810                Some(false),
811                Some(false),
812                None,
813                Some(false),
814                None,
815            ]),
816            &mut ctx
817        );
818
819        assert_arrays_eq!(
820            lhs.boolean(rhs, BooleanOperator::Or)?,
821            BoolArray::from_iter([
822                Some(true),
823                Some(true),
824                Some(true),
825                Some(true),
826                Some(false),
827                None,
828                Some(true),
829                None,
830                None,
831            ]),
832            &mut ctx
833        );
834
835        Ok(())
836    }
837
838    #[test]
839    fn test_null_constant_kleene() -> VortexResult<()> {
840        let mut ctx = SESSION.create_execution_ctx();
841        let lhs = BoolArray::from_iter([Some(false), Some(true), None]).into_array();
842        let null = ConstantArray::new(Scalar::null(DType::Bool(Nullability::Nullable)), lhs.len())
843            .into_array();
844
845        assert_arrays_eq!(
846            lhs.boolean(null.clone(), BooleanOperator::And)?,
847            BoolArray::from_iter([Some(false), None, None]),
848            &mut ctx
849        );
850        assert_arrays_eq!(
851            lhs.boolean(null, BooleanOperator::Or)?,
852            BoolArray::from_iter([None, Some(true), None]),
853            &mut ctx
854        );
855
856        Ok(())
857    }
858
859    #[test]
860    fn test_buffer_reused() -> VortexResult<()> {
861        let mut ctx = SESSION.create_execution_ctx();
862
863        let lhs = BoolArray::from_iter([true, true, false, false]);
864        let lhs_ptr = lhs.to_bit_buffer().inner().as_ptr();
865        let rhs = BoolArray::from_iter([true, false, true, false]).into_array();
866        let and = execute_boolean(lhs.into_array(), rhs, BooleanOperator::And, &mut ctx)?
867            .execute::<BoolArray>(&mut ctx)?;
868        assert_eq!(and.to_bit_buffer().inner().as_ptr(), lhs_ptr);
869        assert_arrays_eq!(
870            and,
871            BoolArray::from_iter([true, false, false, false]),
872            &mut ctx
873        );
874
875        let lhs = BoolArray::from_iter([true, true, false, false]);
876        let _lhs_bits = lhs.to_bit_buffer();
877        let rhs = BoolArray::from_iter([true, false, true, false]);
878        let rhs_ptr = rhs.to_bit_buffer().inner().as_ptr();
879        let or = execute_boolean(
880            lhs.into_array(),
881            rhs.into_array(),
882            BooleanOperator::Or,
883            &mut ctx,
884        )?
885        .execute::<BoolArray>(&mut ctx)?;
886        assert_eq!(or.to_bit_buffer().inner().as_ptr(), rhs_ptr);
887        assert_arrays_eq!(
888            or,
889            BoolArray::from_iter([true, true, true, false]),
890            &mut ctx
891        );
892
893        Ok(())
894    }
895
896    #[rstest]
897    #[case(
898        BoolArray::from_iter([Some(true), Some(true), Some(false), Some(false)]).into_array(),
899        BoolArray::from_iter([Some(true), Some(false), Some(true), Some(false)]).into_array(),
900    )]
901    #[case(
902        BoolArray::from_iter([Some(true), Some(false), Some(true), Some(false)]).into_array(),
903        BoolArray::from_iter([Some(true), Some(true), Some(false), Some(false)]).into_array(),
904    )]
905    fn test_or(#[case] lhs: ArrayRef, #[case] rhs: ArrayRef) {
906        let mut ctx = SESSION.create_execution_ctx();
907        let r = lhs.boolean(rhs, BooleanOperator::Or).unwrap();
908        let r = r.execute::<BoolArray>(&mut ctx).unwrap().into_array();
909
910        let v0 = r
911            .execute_scalar(0, &mut SESSION.create_execution_ctx())
912            .unwrap()
913            .as_bool()
914            .value();
915        let v1 = r
916            .execute_scalar(1, &mut SESSION.create_execution_ctx())
917            .unwrap()
918            .as_bool()
919            .value();
920        let v2 = r
921            .execute_scalar(2, &mut SESSION.create_execution_ctx())
922            .unwrap()
923            .as_bool()
924            .value();
925        let v3 = r
926            .execute_scalar(3, &mut SESSION.create_execution_ctx())
927            .unwrap()
928            .as_bool()
929            .value();
930
931        assert!(v0.unwrap());
932        assert!(v1.unwrap());
933        assert!(v2.unwrap());
934        assert!(!v3.unwrap());
935    }
936
937    #[rstest]
938    #[case(
939        BoolArray::from_iter([Some(true), Some(true), Some(false), Some(false)]).into_array(),
940        BoolArray::from_iter([Some(true), Some(false), Some(true), Some(false)]).into_array(),
941    )]
942    #[case(
943        BoolArray::from_iter([Some(true), Some(false), Some(true), Some(false)]).into_array(),
944        BoolArray::from_iter([Some(true), Some(true), Some(false), Some(false)]).into_array(),
945    )]
946    fn test_and(#[case] lhs: ArrayRef, #[case] rhs: ArrayRef) {
947        let mut ctx = SESSION.create_execution_ctx();
948        let r = lhs
949            .boolean(rhs, BooleanOperator::And)
950            .unwrap()
951            .execute::<BoolArray>(&mut ctx)
952            .unwrap()
953            .into_array();
954
955        let v0 = r
956            .execute_scalar(0, &mut SESSION.create_execution_ctx())
957            .unwrap()
958            .as_bool()
959            .value();
960        let v1 = r
961            .execute_scalar(1, &mut SESSION.create_execution_ctx())
962            .unwrap()
963            .as_bool()
964            .value();
965        let v2 = r
966            .execute_scalar(2, &mut SESSION.create_execution_ctx())
967            .unwrap()
968            .as_bool()
969            .value();
970        let v3 = r
971            .execute_scalar(3, &mut SESSION.create_execution_ctx())
972            .unwrap()
973            .as_bool()
974            .value();
975
976        assert!(v0.unwrap());
977        assert!(!v1.unwrap());
978        assert!(!v2.unwrap());
979        assert!(!v3.unwrap());
980    }
981}