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