Skip to main content

vortex_array/arrays/bool/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use smallvec::smallvec;
8use vortex_buffer::BitBuffer;
9use vortex_buffer::BitBufferMeta;
10use vortex_buffer::BitBufferMut;
11use vortex_buffer::BitBufferView;
12use vortex_error::VortexExpect;
13use vortex_error::VortexResult;
14use vortex_error::vortex_ensure;
15use vortex_error::vortex_ensure_eq;
16use vortex_mask::Mask;
17
18use crate::ArrayRef;
19use crate::ArraySlots;
20use crate::ExecutionCtx;
21use crate::IntoArray;
22use crate::array::Array;
23use crate::array::ArrayParts;
24use crate::array::TypedArrayRef;
25use crate::array::child_to_validity;
26use crate::array::validity_to_child;
27use crate::array_slots;
28use crate::arrays::Bool;
29use crate::arrays::BoolArray;
30use crate::buffer::BufferHandle;
31use crate::dtype::DType;
32use crate::validity::Validity;
33
34#[array_slots(Bool)]
35pub struct BoolSlots {
36    /// The validity bitmap indicating which elements are non-null.
37    #[slot(0)]
38    pub validity_child: Option<ArrayRef>,
39}
40
41/// Inner data for a boolean array that stores true/false values in a compact bit-packed format.
42///
43/// This mirrors the Apache Arrow Boolean array encoding, where each boolean value
44/// is stored as a single bit rather than a full byte.
45///
46/// The data layout uses:
47/// - A bit-packed buffer where each bit represents one boolean value (0 = false, 1 = true)
48/// - An optional validity child array, which must be of type `Bool(NonNullable)`, where true values
49///   indicate valid and false indicates null. if the i-th value is null in the validity child,
50///   the i-th packed bit in the buffer may be 0 or 1, i.e. it is undefined.
51/// - Bit-level slicing is supported with minimal overhead
52///
53/// # Examples
54///
55/// ```
56/// # fn main() -> vortex_error::VortexResult<()> {
57/// use vortex_array::arrays::BoolArray;
58/// use vortex_array::{IntoArray, VortexSessionExecute};
59/// use vortex_session::VortexSession;
60///
61/// // Create from iterator using FromIterator impl
62/// let array: BoolArray = [true, false, true, false].into_iter().collect();
63///
64/// // Slice the array
65/// let sliced = array.slice(1..3)?;
66/// assert_eq!(sliced.len(), 2);
67///
68/// // Access individual values
69/// let mut ctx = VortexSession::empty().create_execution_ctx();
70/// let value = array.execute_scalar(0, &mut ctx).unwrap();
71/// assert_eq!(value, true.into());
72/// # Ok(())
73/// # }
74/// ```
75#[derive(Clone, Debug)]
76pub struct BoolData {
77    pub(super) bits: BufferHandle,
78    pub(super) meta: BitBufferMeta,
79}
80
81impl Display for BoolData {
82    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
83        write!(f, "offset: {}", self.meta.offset())
84    }
85}
86
87pub struct BoolDataParts {
88    pub bits: BufferHandle,
89    pub meta: BitBufferMeta,
90}
91
92pub trait BoolArrayExt: TypedArrayRef<Bool> {
93    fn nullability(&self) -> crate::dtype::Nullability {
94        match self.dtype() {
95            DType::Bool(nullability) => *nullability,
96            _ => unreachable!("BoolArrayExt requires a bool dtype"),
97        }
98    }
99
100    fn validity(&self) -> Validity {
101        child_to_validity(self.validity_child(), self.nullability())
102    }
103
104    fn to_bit_buffer(&self) -> BitBuffer {
105        let buffer = self.bits.as_host().clone();
106        BitBuffer::new_with_offset(buffer, self.meta.len(), self.meta.offset())
107    }
108
109    /// Borrow the array's packed bits as a [`BitBufferView`] without cloning the backing buffer.
110    fn bit_buffer_view(&self) -> BitBufferView<'_> {
111        BitBufferView::from_meta(self.bits.as_host().as_slice(), self.meta)
112    }
113
114    fn maybe_execute_mask(&self, ctx: &mut ExecutionCtx) -> VortexResult<Option<Mask>> {
115        let all_valid = match &BoolArrayExt::validity(self) {
116            Validity::NonNullable | Validity::AllValid => true,
117            Validity::AllInvalid => false,
118            Validity::Array(a) => a.statistics().compute_min::<bool>(ctx).unwrap_or(false),
119        };
120        Ok(all_valid.then(|| Mask::from_buffer(self.to_bit_buffer())))
121    }
122
123    fn execute_mask(&self, ctx: &mut ExecutionCtx) -> Mask {
124        self.maybe_execute_mask(ctx)
125            .vortex_expect("failed to check validity")
126            .vortex_expect("cannot convert nullable boolean array to mask")
127    }
128
129    fn to_mask_fill_null_false(&self, ctx: &mut ExecutionCtx) -> Mask {
130        let validity_mask = BoolArrayExt::validity(self)
131            .execute_mask(self.len(), ctx)
132            .vortex_expect("Failed to compute validity mask");
133        let buffer = match validity_mask {
134            Mask::AllTrue(_) => self.to_bit_buffer(),
135            Mask::AllFalse(_) => return Mask::new_false(self.len()),
136            Mask::Values(validity) => validity.bit_buffer() & self.to_bit_buffer(),
137        };
138        Mask::from_buffer(buffer)
139    }
140}
141impl<T: TypedArrayRef<Bool>> BoolArrayExt for T {}
142
143/// Field accessors and non-consuming methods on the inner bool data.
144impl BoolData {
145    /// Splits into owned parts
146    #[inline]
147    pub fn into_parts(self, len: usize) -> BoolDataParts {
148        BoolDataParts {
149            bits: self.bits,
150            meta: BitBufferMeta::new(self.meta.offset(), len),
151        }
152    }
153
154    pub(crate) fn make_slots(validity: &Validity, len: usize) -> ArraySlots {
155        smallvec![validity_to_child(validity, len)]
156    }
157}
158
159/// Constructors and consuming methods for [`BoolArray`].
160impl Array<Bool> {
161    /// Constructs a new [`BoolArray`].
162    ///
163    /// # Panics
164    ///
165    /// Panics if the validity length is not equal to the bit buffer length.
166    pub fn new(bits: BitBuffer, validity: Validity) -> Self {
167        Self::try_new(bits, validity).vortex_expect("Failed to create BoolArray")
168    }
169
170    /// Constructs a new [`BoolArray`] from a [`BufferHandle`].
171    ///
172    /// # Panics
173    ///
174    /// Panics if the validity length is not equal to the bit buffer length.
175    pub fn new_handle(handle: BufferHandle, offset: usize, len: usize, validity: Validity) -> Self {
176        Self::try_new_from_handle(handle, offset, len, validity)
177            .vortex_expect("Failed to create BoolArray from BufferHandle")
178    }
179
180    /// Constructs a new `BoolArray`.
181    ///
182    /// # Errors
183    ///
184    /// Returns an error if the provided components do not satisfy the invariants.
185    pub fn try_new(bits: BitBuffer, validity: Validity) -> VortexResult<Self> {
186        let dtype = DType::Bool(validity.nullability());
187        let len = bits.len();
188        let slots = BoolData::make_slots(&validity, len);
189        let data = BoolData::try_new(bits, validity)?;
190        Ok(unsafe { Array::from_parts_unchecked(ArrayParts::new(Bool, dtype, len, data, slots)) })
191    }
192
193    /// Build a new bool array from a `BufferHandle`, returning an error if the offset is
194    /// too large or the buffer is not large enough to hold the values.
195    pub fn try_new_from_handle(
196        bits: BufferHandle,
197        offset: usize,
198        len: usize,
199        validity: Validity,
200    ) -> VortexResult<Self> {
201        let dtype = DType::Bool(validity.nullability());
202        let slots = BoolData::make_slots(&validity, len);
203        let data = BoolData::try_new_from_handle(bits, offset, len, validity)?;
204        Ok(unsafe { Array::from_parts_unchecked(ArrayParts::new(Bool, dtype, len, data, slots)) })
205    }
206
207    /// Creates a new [`BoolArray`] without validation.
208    ///
209    /// # Safety
210    ///
211    /// The caller must ensure that the validity length is equal to the bit buffer length.
212    pub unsafe fn new_unchecked(bits: BitBuffer, validity: Validity) -> Self {
213        let dtype = DType::Bool(validity.nullability());
214        let len = bits.len();
215        let slots = BoolData::make_slots(&validity, len);
216        // SAFETY: caller guarantees validity length equals bit buffer length.
217        let data = unsafe { BoolData::new_unchecked(bits, validity) };
218        unsafe { Array::from_parts_unchecked(ArrayParts::new(Bool, dtype, len, data, slots)) }
219    }
220
221    /// Validates the components that would be used to create a [`BoolArray`].
222    pub fn validate(bits: &BitBuffer, validity: &Validity) -> VortexResult<()> {
223        BoolData::validate(bits, validity)
224    }
225
226    /// Create a new BoolArray from a set of indices and a length.
227    ///
228    /// All indices must be less than the length.
229    pub fn from_indices<I: IntoIterator<Item = usize>>(
230        length: usize,
231        indices: I,
232        validity: Validity,
233    ) -> Self {
234        let mut buffer = BitBufferMut::new_unset(length);
235        indices.into_iter().for_each(|idx| buffer.set(idx));
236        Self::new(buffer.freeze(), validity)
237    }
238
239    /// Returns the underlying [`BitBuffer`] of the array, consuming self.
240    pub fn into_bit_buffer(self) -> BitBuffer {
241        let len = self.len();
242        let data = self.into_data();
243        let buffer = data.bits.unwrap_host();
244        BitBuffer::new_with_offset(buffer, len, data.meta.offset())
245    }
246}
247
248// Internal constructors on BoolData (used by [`BoolArray`] constructors and [`VTable::build`]).
249impl BoolData {
250    pub(super) fn try_new(bits: BitBuffer, validity: Validity) -> VortexResult<Self> {
251        let bits = bits.shrink_offset();
252        Self::validate(&bits, &validity)?;
253
254        let (offset, len, buffer) = bits.into_inner();
255
256        Ok(Self {
257            bits: BufferHandle::new_host(buffer),
258            meta: BitBufferMeta::new(offset, len),
259        })
260    }
261
262    pub(super) fn try_new_from_handle(
263        bits: BufferHandle,
264        offset: usize,
265        len: usize,
266        validity: Validity,
267    ) -> VortexResult<Self> {
268        vortex_ensure!(offset < 8, "BitBuffer offset must be <8, got {}", offset);
269        if let Some(validity_len) = validity.maybe_len() {
270            vortex_ensure_eq!(
271                validity_len,
272                len,
273                "BoolArray validity length does not match array length",
274            );
275        }
276
277        vortex_ensure!(
278            bits.len() * 8 >= (len + offset),
279            "provided BufferHandle with offset {offset} len {len} had size {} bits",
280            bits.len() * 8,
281        );
282
283        Ok(Self {
284            bits,
285            meta: BitBufferMeta::new(offset, len),
286        })
287    }
288
289    pub(super) unsafe fn new_unchecked(bits: BitBuffer, validity: Validity) -> Self {
290        if cfg!(debug_assertions) {
291            Self::try_new(bits, validity).vortex_expect("Failed to create BoolData")
292        } else {
293            let (offset, len, buffer) = bits.into_inner();
294
295            Self {
296                bits: BufferHandle::new_host(buffer),
297                meta: BitBufferMeta::new(offset, len),
298            }
299        }
300    }
301
302    pub(super) fn validate(bits: &BitBuffer, validity: &Validity) -> VortexResult<()> {
303        vortex_ensure!(
304            bits.offset() < 8,
305            "BitBuffer offset must be <8, got {}",
306            bits.offset()
307        );
308
309        if let Some(validity_len) = validity.maybe_len() {
310            vortex_ensure_eq!(
311                validity_len,
312                bits.len(),
313                "BoolArray validity length does not match array length",
314            );
315        }
316
317        Ok(())
318    }
319}
320
321impl From<BitBuffer> for BoolArray {
322    fn from(value: BitBuffer) -> Self {
323        BoolArray::new(value, Validity::NonNullable)
324    }
325}
326
327impl FromIterator<bool> for BoolArray {
328    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
329        BoolArray::from(BitBuffer::from_iter(iter))
330    }
331}
332
333impl FromIterator<Option<bool>> for BoolArray {
334    fn from_iter<I: IntoIterator<Item = Option<bool>>>(iter: I) -> Self {
335        let iter = iter.into_iter();
336        let capacity = iter.size_hint().0;
337        let mut bits = BitBufferMut::with_capacity(capacity);
338        let mut validity = BitBufferMut::with_capacity(capacity);
339        for value in iter {
340            bits.append(value.unwrap_or_default());
341            validity.append(value.is_some());
342        }
343
344        BoolArray::new(bits.freeze(), Validity::from(validity.freeze()))
345    }
346}
347
348impl IntoArray for BitBuffer {
349    fn into_array(self) -> ArrayRef {
350        BoolArray::new(self, Validity::NonNullable).into_array()
351    }
352}
353
354impl IntoArray for BitBufferMut {
355    fn into_array(self) -> ArrayRef {
356        self.freeze().into_array()
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use std::iter::once;
363    use std::iter::repeat_n;
364    use std::sync::LazyLock;
365
366    use vortex_buffer::Alignment;
367    use vortex_buffer::BitBuffer;
368    use vortex_buffer::BitBufferMut;
369    use vortex_buffer::ByteBuffer;
370    use vortex_buffer::buffer;
371    use vortex_error::VortexResult;
372    use vortex_session::VortexSession;
373
374    use crate::IntoArray;
375    use crate::VortexSessionExecute;
376    use crate::arrays::BoolArray;
377    use crate::arrays::PrimitiveArray;
378    use crate::arrays::bool::BoolArrayExt;
379    use crate::assert_arrays_eq;
380    use crate::buffer::BufferHandle;
381    use crate::patches::Patches;
382    use crate::validity::Validity;
383
384    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
385
386    #[test]
387    fn bool_array() {
388        let mut ctx = SESSION.create_execution_ctx();
389
390        let arr = BoolArray::from_iter([true, false, true]);
391        let scalar = bool::try_from(&arr.execute_scalar(0, &mut ctx).unwrap()).unwrap();
392        assert!(scalar);
393    }
394
395    #[test]
396    fn test_all_some_iter() {
397        let mut ctx = SESSION.create_execution_ctx();
398
399        let arr = BoolArray::from_iter([Some(true), Some(false)]);
400
401        assert!(matches!(arr.validity(), Ok(Validity::AllValid)));
402
403        let scalar = bool::try_from(&arr.execute_scalar(0, &mut ctx).unwrap()).unwrap();
404        assert!(scalar);
405        let scalar = bool::try_from(&arr.execute_scalar(1, &mut ctx).unwrap()).unwrap();
406        assert!(!scalar);
407    }
408
409    #[test]
410    fn test_bool_from_iter() {
411        let mut ctx = SESSION.create_execution_ctx();
412        let arr = BoolArray::from_iter([Some(true), Some(true), None, Some(false), None]);
413
414        let scalar = bool::try_from(&arr.execute_scalar(0, &mut ctx).unwrap()).unwrap();
415        assert!(scalar);
416
417        let scalar = bool::try_from(&arr.execute_scalar(1, &mut ctx).unwrap()).unwrap();
418        assert!(scalar);
419
420        let scalar = arr.execute_scalar(2, &mut ctx).unwrap();
421        assert!(scalar.is_null());
422
423        let scalar = bool::try_from(&arr.execute_scalar(3, &mut ctx).unwrap()).unwrap();
424        assert!(!scalar);
425
426        let scalar = arr.execute_scalar(4, &mut ctx).unwrap();
427        assert!(scalar.is_null());
428    }
429
430    #[test]
431    fn patch_sliced_bools() {
432        let mut ctx = SESSION.create_execution_ctx();
433        let arr = BoolArray::from(BitBuffer::new_set(12));
434        let sliced = arr.slice(4..12).unwrap();
435        assert_arrays_eq!(sliced, BoolArray::from_iter([true; 8]), &mut ctx);
436
437        let arr = {
438            let mut builder = BitBufferMut::new_unset(12);
439            (1..12).for_each(|i| builder.set(i));
440            BoolArray::from(builder.freeze())
441        };
442        let sliced = arr.slice(4..12).unwrap();
443        let expected_slice: Vec<bool> = (4..12).map(|i| (1..12).contains(&i)).collect();
444        assert_arrays_eq!(
445            sliced,
446            BoolArray::from_iter(expected_slice.clone()),
447            &mut ctx
448        );
449
450        // patch the underlying array at index 4 to false
451        let patches = Patches::new(
452            arr.len(),
453            0,
454            buffer![4u32].into_array(),
455            BoolArray::from(BitBuffer::new_unset(1)).into_array(),
456            None,
457            &mut ctx,
458        )
459        .unwrap();
460        let arr = arr.patch(&patches, &mut ctx).unwrap();
461        // After patching index 4 to false: indices 1-3 and 5-11 are true, index 0 and 4 are false
462        let expected_patched: Vec<bool> = (0..12).map(|i| (1..12).contains(&i) && i != 4).collect();
463        assert_arrays_eq!(arr, BoolArray::from_iter(expected_patched), &mut ctx);
464
465        // the slice should be unchanged (still has original values before patch)
466        assert_arrays_eq!(sliced, BoolArray::from_iter(expected_slice), &mut ctx);
467    }
468
469    #[test]
470    fn slice_array_in_middle() {
471        let mut ctx = SESSION.create_execution_ctx();
472        let arr = BoolArray::from(BitBuffer::new_set(16));
473        let sliced = arr.slice(4..12).unwrap();
474        assert_arrays_eq!(sliced, BoolArray::from_iter([true; 8]), &mut ctx);
475    }
476
477    #[test]
478    fn slice_aligned_host_handle_at_unaligned_byte() -> VortexResult<()> {
479        let bits: ByteBuffer = buffer![0b1010_1100_u8, 0b0110_1001, 0];
480        let bits = bits.aligned(Alignment::of::<u64>());
481        let array =
482            BoolArray::new_handle(BufferHandle::new_host(bits), 0, 16, Validity::NonNullable)
483                .into_array();
484
485        let sliced = array.slice(9..15)?;
486
487        let mut ctx = SESSION.create_execution_ctx();
488        assert_arrays_eq!(
489            sliced,
490            BoolArray::from_iter([false, false, true, false, true, true]),
491            &mut ctx
492        );
493        Ok(())
494    }
495
496    #[test]
497    fn patch_bools_owned() {
498        let mut ctx = SESSION.create_execution_ctx();
499        let arr = BoolArray::from(BitBuffer::new_set(16));
500        let buf_ptr = arr.to_bit_buffer().inner().as_ptr();
501
502        let patches = Patches::new(
503            arr.len(),
504            0,
505            PrimitiveArray::new(buffer![0u32], Validity::NonNullable).into_array(),
506            BoolArray::from(BitBuffer::new_unset(1)).into_array(),
507            None,
508            &mut ctx,
509        )
510        .unwrap();
511        let arr = arr.patch(&patches, &mut ctx).unwrap();
512        // Verify buffer was reused in place
513        assert_eq!(arr.to_bit_buffer().inner().as_ptr(), buf_ptr);
514
515        // After patching index 0 to false: [false, true, true, ..., true] (16 values)
516        let expected: BoolArray = once(false).chain(repeat_n(true, 15)).collect();
517        assert_arrays_eq!(arr, expected, &mut ctx);
518    }
519
520    #[test]
521    fn patch_sliced_bools_offset() {
522        let mut ctx = SESSION.create_execution_ctx();
523        let arr = BoolArray::from(BitBuffer::new_set(15));
524        let sliced = arr.slice(4..15).unwrap();
525        assert_arrays_eq!(sliced, BoolArray::from_iter([true; 11]), &mut ctx);
526    }
527}