Skip to main content

arrow_buffer/buffer/
boolean.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::bit_chunk_iterator::{BitChunks, UnalignedBitChunk};
6use crate::bit_iterator::{
7    BitIndexIterator, BitIndexU32Iterator, BitIterator, BitSliceIterator, SetBitCounter,
8};
9use crate::bit_util::read_u64;
10use crate::{
11    BooleanBufferBuilder, Buffer, MutableBuffer, bit_util, buffer_bin_and, buffer_bin_or,
12    buffer_bin_xor,
13};
14
15use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};
16
17/// A slice-able [`Buffer`] containing bit-packed booleans
18///
19/// This structure represents a sequence of boolean values packed into a
20/// byte-aligned [`Buffer`]. Both the offset and length are represented in bits.
21///
22/// # Layout
23///
24/// The values are represented as little endian bit-packed values, where the
25/// least significant bit of each byte represents the first boolean value and
26/// then proceeding to the most significant bit.
27///
28/// For example, the 10 bit bitmask `0b0111001101` has length 10, and is
29/// represented using 2 bytes with offset 0 like this:
30///
31/// ```text
32///        ┌─────────────────────────────────┐    ┌─────────────────────────────────┐
33///        │┌───┬───┬───┬───┬───┬───┬───┬───┐│    │┌───┬───┬───┬───┬───┬───┬───┬───┐│
34///        ││ 1 │ 0 │ 1 │ 1 │ 0 │ 0 │ 1 │ 1 ││    ││ 1 │ 0 │ ? │ ? │ ? │ ? │ ? │ ? ││
35///        │└───┴───┴───┴───┴───┴───┴───┴───┘│    │└───┴───┴───┴───┴───┴───┴───┴───┘│
36/// bit    └─────────────────────────────────┘    └─────────────────────────────────┘
37/// offset  0             Byte 0             7    0              Byte 1            7
38///
39///         length = 10 bits, offset = 0
40/// ```
41///
42/// The same bitmask with length 10 and offset 3 would be represented using 2
43/// bytes like this:
44///
45/// ```text
46///       ┌─────────────────────────────────┐    ┌─────────────────────────────────┐
47///       │┌───┬───┬───┬───┬───┬───┬───┬───┐│    │┌───┬───┬───┬───┬───┬───┬───┬───┐│
48///       ││ ? │ ? │ ? │ 1 │ 0 │ 1 │ 1 │ 0 ││    ││ 0 │ 1 │ 1 │ 1 │ 0 │ ? │ ? │ ? ││
49///       │└───┴───┴───┴───┴───┴───┴───┴───┘│    │└───┴───┴───┴───┴───┴───┴───┴───┘│
50/// bit   └─────────────────────────────────┘    └─────────────────────────────────┘
51/// offset 0             Byte 0             7    0              Byte 1            7
52///
53///        length = 10 bits, offset = 3
54/// ```
55///
56/// Note that the bits marked `?` are not logically part of the mask and may
57/// contain either `0` or `1`
58///
59/// # Bitwise Operations
60///
61/// `BooleanBuffer` implements the standard bitwise traits for creating a new
62/// buffer ([`BitAnd`], [`BitOr`], [`BitXor`], [`Not`]) as well as the assign variants
63/// for updating an existing buffer in place when possible ([`BitAndAssign`],
64/// [`BitOrAssign`], [`BitXorAssign`]).
65///
66/// ```
67/// # use arrow_buffer::BooleanBuffer;
68/// let mut left = BooleanBuffer::from(&[true, false, true, true] as &[bool]);
69/// let right = BooleanBuffer::from(&[true, true, false, true] as &[bool]);
70///
71/// // Create a new buffer by applying bitwise AND
72/// let anded = &left & &right;
73/// assert_eq!(anded, BooleanBuffer::from(&[true, false, false, true] as &[bool]));
74///
75/// // Update `left` in place by applying bitwise AND in place
76/// left &= &right;
77/// assert_eq!(left, BooleanBuffer::from(&[true, false, false, true] as &[bool]));
78/// ```
79///
80/// # See Also
81/// * [`BooleanBufferBuilder`] for building [`BooleanBuffer`] instances
82/// * [`Self::set_bit_counter`] for counting the set bits in many ranges of one buffer
83/// * [`NullBuffer`] for representing null values in Arrow arrays
84///
85/// [`NullBuffer`]: crate::NullBuffer
86#[derive(Debug, Clone, Eq)]
87pub struct BooleanBuffer {
88    /// Underlying buffer (byte aligned)
89    buffer: Buffer,
90    /// Offset in bits (not bytes)
91    bit_offset: usize,
92    /// Length in bits (not bytes)
93    bit_len: usize,
94}
95
96impl PartialEq for BooleanBuffer {
97    fn eq(&self, other: &Self) -> bool {
98        if self.bit_len != other.bit_len {
99            return false;
100        }
101
102        let lhs = self.bit_chunks().iter_padded();
103        let rhs = other.bit_chunks().iter_padded();
104        lhs.zip(rhs).all(|(a, b)| a == b)
105    }
106}
107
108impl BooleanBuffer {
109    /// Create a new [`BooleanBuffer`] from a [`Buffer`], `bit_offset` offset and `bit_len` length
110    ///
111    /// # Panics
112    ///
113    /// This method will panic if `buffer` is not large enough
114    pub fn new(buffer: Buffer, bit_offset: usize, bit_len: usize) -> Self {
115        let total_len = bit_offset.saturating_add(bit_len);
116        let buffer_len = buffer.len();
117        let buffer_bit_len = buffer_len.saturating_mul(8);
118        assert!(
119            total_len <= buffer_bit_len,
120            "buffer not large enough (bit_offset: {bit_offset}, bit_len: {bit_len}, buffer_len: {buffer_len})"
121        );
122        Self {
123            buffer,
124            bit_offset,
125            bit_len,
126        }
127    }
128
129    /// Create a new [`BooleanBuffer`] of `length` bits (not bytes) where all values are `true`
130    pub fn new_set(length: usize) -> Self {
131        let mut builder = BooleanBufferBuilder::new(length);
132        builder.append_n(length, true);
133        builder.finish()
134    }
135
136    /// Create a new [`BooleanBuffer`] of `length` bits (not bytes) where all values are `false`
137    pub fn new_unset(length: usize) -> Self {
138        let buffer = MutableBuffer::new_null(length).into_buffer();
139        Self {
140            buffer,
141            bit_offset: 0,
142            bit_len: length,
143        }
144    }
145
146    /// Invokes `f` with indexes `0..len` collecting the boolean results into a new `BooleanBuffer`
147    pub fn collect_bool<F: FnMut(usize) -> bool>(len: usize, f: F) -> Self {
148        let buffer = MutableBuffer::collect_bool(len, f);
149        Self::new(buffer.into(), 0, len)
150    }
151
152    /// Create a new [`BooleanBuffer`] by copying the relevant bits from an
153    /// input buffer.
154    ///
155    /// # Notes:
156    /// * The new `BooleanBuffer` may have non zero offset
157    ///   and/or padding bits outside the logical range.
158    ///
159    /// # Example: Create a new [`BooleanBuffer`] copying a bit slice from in input slice
160    /// ```
161    /// # use arrow_buffer::BooleanBuffer;
162    /// let input = [0b11001100u8, 0b10111010u8];
163    /// // // Copy bits 4..16 from input
164    /// let result = BooleanBuffer::from_bits(&input, 4, 12);
165    /// // output is 12 bits long starting from bit offset 4
166    /// assert_eq!(result.len(), 12);
167    /// assert_eq!(result.offset(), 4);
168    /// // the expected 12 bits are 0b101110101100 (bits 4..16 of the input)
169    /// let expected_bits = [false, false, true, true, false, true, false, true, true, true, false, true];
170    /// for (i, v) in expected_bits.into_iter().enumerate() {
171    ///    assert_eq!(result.value(i), v);
172    /// }
173    /// // However, underlying buffer has (ignored) bits set outside the requested range
174    /// assert_eq!(result.values(), &[0b11001100u8, 0b10111010, 0, 0, 0, 0, 0, 0]);
175    /// ```
176    pub fn from_bits(src: impl AsRef<[u8]>, offset_in_bits: usize, len_in_bits: usize) -> Self {
177        Self::from_bitwise_unary_op(src, offset_in_bits, len_in_bits, |a| a)
178    }
179
180    /// Create a new [`BooleanBuffer`] by applying the bitwise operation to `op`
181    /// to an input buffer.
182    ///
183    /// This function is faster than applying the operation bit by bit as
184    /// it processes input buffers in chunks of 64 bits (8 bytes) at a time
185    ///
186    /// # Notes:
187    /// * `op` takes a single `u64` inputs and produces one `u64` output.
188    /// * `op` must only apply bitwise operations
189    ///   on the relevant bits; the input `u64` may contain irrelevant bits
190    ///   and may be processed differently on different endian architectures.
191    /// * `op` may be called with input bits outside the requested range
192    /// * Returned `BooleanBuffer` may have non zero offset
193    /// * Returned `BooleanBuffer` may have bits set outside the requested range
194    ///
195    /// # See Also
196    /// - [`BooleanBuffer::from_bitwise_binary_op`] to create a new buffer from a binary operation
197    /// - [`apply_bitwise_unary_op`](bit_util::apply_bitwise_unary_op) for in-place unary bitwise operations
198    ///
199    /// # Example: Create new [`BooleanBuffer`] from bitwise `NOT`
200    /// ```
201    /// # use arrow_buffer::BooleanBuffer;
202    /// let input = [0b11001100u8, 0b10111010u8]; // 2 bytes = 16 bits
203    /// // NOT of bits 4..16
204    /// let result = BooleanBuffer::from_bitwise_unary_op(
205    ///  &input, 4, 12, |a| !a
206    /// );
207    /// // output is 12 bits long starting from bit offset 4
208    /// assert_eq!(result.len(), 12);
209    /// assert_eq!(result.offset(), 4);
210    /// // the expected 12 bits are 0b001100110101, (NOT of the requested bits)
211    /// let expected_bits = [true, true, false, false, true, false, true, false, false, false, true, false];
212    /// for (i, v) in expected_bits.into_iter().enumerate() {
213    ///     assert_eq!(result.value(i), v);
214    /// }
215    /// // However, underlying buffer has (ignored) bits set outside the requested range
216    /// let expected = [0b00110011u8, 0b01000101u8, 255, 255, 255, 255, 255, 255];
217    /// assert_eq!(result.values(), &expected);
218    /// ```
219    pub fn from_bitwise_unary_op<F>(
220        src: impl AsRef<[u8]>,
221        offset_in_bits: usize,
222        len_in_bits: usize,
223        mut op: F,
224    ) -> Self
225    where
226        F: FnMut(u64) -> u64,
227    {
228        let end = offset_in_bits + len_in_bits;
229        // Align start and end to 64 bit (8 byte) boundaries if possible to allow using the
230        // optimized code path as much as possible.
231        let aligned_offset = offset_in_bits & !63;
232        let aligned_end_bytes = bit_util::ceil(end, 64) * 8;
233        let src_len = src.as_ref().len();
234        let slice_end = aligned_end_bytes.min(src_len);
235
236        let aligned_start = &src.as_ref()[aligned_offset / 8..slice_end];
237
238        let (prefix, aligned_u64s, suffix) = unsafe { aligned_start.as_ref().align_to::<u64>() };
239        match (prefix, suffix) {
240            ([], []) => {
241                // the buffer is word (64 bit) aligned, so use optimized Vec code.
242                let result_u64s: Vec<u64> = aligned_u64s.iter().map(|l| op(*l)).collect();
243                return BooleanBuffer::new(result_u64s.into(), offset_in_bits % 64, len_in_bits);
244            }
245            ([], suffix) => {
246                let suffix = read_u64(suffix);
247                let result_u64s: Vec<u64> = aligned_u64s
248                    .iter()
249                    .copied()
250                    .chain(std::iter::once(suffix))
251                    .map(&mut op)
252                    .collect();
253                return BooleanBuffer::new(result_u64s.into(), offset_in_bits % 64, len_in_bits);
254            }
255            _ => {}
256        }
257
258        // align to byte boundaries
259        // Use unaligned code path, handle remainder bytes
260        let (chunks, remainder) = aligned_start.as_chunks::<8>();
261        let iter = chunks.iter().map(|c| u64::from_le_bytes(*c));
262        let vec_u64s: Vec<u64> = if remainder.is_empty() {
263            iter.map(&mut op).collect()
264        } else {
265            iter.chain(Some(read_u64(remainder))).map(&mut op).collect()
266        };
267
268        BooleanBuffer::new(vec_u64s.into(), offset_in_bits % 64, len_in_bits)
269    }
270
271    /// Create a new [`BooleanBuffer`] by applying the bitwise operation `op` to
272    /// the relevant bits from two input buffers.
273    ///
274    /// This function is faster than applying the operation bit by bit as
275    /// it processes input buffers in chunks of 64 bits (8 bytes) at a time
276    ///
277    /// # Notes:
278    /// * `op` takes two `u64` inputs and produces one `u64` output.
279    /// * `op` must only apply bitwise operations
280    ///   on the relevant bits; the input `u64` values may contain irrelevant bits
281    ///   and may be processed differently on different endian architectures.
282    /// * `op` may be called with input bits outside the requested range.
283    /// * Returned `BooleanBuffer` may have non zero offset
284    /// * Returned `BooleanBuffer` may have bits set outside the requested range
285    ///
286    /// # See Also
287    /// - [`BooleanBuffer::from_bitwise_unary_op`] for unary operations on a single input buffer.
288    /// - [`apply_bitwise_binary_op`](bit_util::apply_bitwise_binary_op) for in-place binary bitwise operations
289    ///
290    /// # Example: Create new [`BooleanBuffer`] from bitwise `AND` of two [`Buffer`]s
291    /// ```
292    /// # use arrow_buffer::{Buffer, BooleanBuffer};
293    /// let left = Buffer::from(vec![0b11001100u8, 0b10111010u8]); // 2 bytes = 16 bits
294    /// let right = Buffer::from(vec![0b10101010u8, 0b11011100u8, 0b11110000u8]); // 3 bytes = 24 bits
295    /// // AND of the first 12 bits
296    /// let result = BooleanBuffer::from_bitwise_binary_op(
297    ///   &left, 0, &right, 0, 12, |a, b| a & b
298    /// );
299    /// assert_eq!(result.len(), 12);
300    /// for i in 0..12 {
301    ///     assert_eq!(result.value(i), left.as_slice()[i / 8] >> (i % 8) & 1 == 1
302    ///         && right.as_slice()[i / 8] >> (i % 8) & 1 == 1);
303    /// }
304    /// ```
305    ///
306    /// # Example: Create new [`BooleanBuffer`] from bitwise `OR` of two byte slices
307    /// ```
308    /// # use arrow_buffer::{BooleanBuffer, bit_util};
309    /// let left = [0b11001100u8, 0b10111010u8];
310    /// let right = [0b10101010u8, 0b11011100u8];
311    /// // OR of bits 4..16 from left and bits 0..12 from right
312    /// let result = BooleanBuffer::from_bitwise_binary_op(
313    ///  &left, 4, &right, 0, 12, |a, b| a | b
314    /// );
315    /// assert_eq!(result.len(), 12);
316    /// for i in 0..12 {
317    ///     let l = bit_util::get_bit(&left, 4 + i);
318    ///     let r = bit_util::get_bit(&right, i);
319    ///     assert_eq!(result.value(i), l | r);
320    /// }
321    /// ```
322    pub fn from_bitwise_binary_op<F>(
323        left: impl AsRef<[u8]>,
324        left_offset_in_bits: usize,
325        right: impl AsRef<[u8]>,
326        right_offset_in_bits: usize,
327        len_in_bits: usize,
328        mut op: F,
329    ) -> Self
330    where
331        F: FnMut(u64, u64) -> u64,
332    {
333        let left = left.as_ref();
334        let right = right.as_ref();
335
336        // When both offsets share the same sub-64-bit alignment, we can
337        // align both to 64-bit boundaries and zip u64s directly,
338        // avoiding BitChunks bit-shifting entirely.
339        if left_offset_in_bits % 64 == right_offset_in_bits % 64 {
340            let bit_offset = left_offset_in_bits % 64;
341            let left_end = left_offset_in_bits + len_in_bits;
342            let right_end = right_offset_in_bits + len_in_bits;
343
344            let left_aligned = left_offset_in_bits & !63;
345            let right_aligned = right_offset_in_bits & !63;
346
347            let left_end_bytes = (bit_util::ceil(left_end, 64) * 8).min(left.len());
348            let right_end_bytes = (bit_util::ceil(right_end, 64) * 8).min(right.len());
349
350            let left_slice = &left[left_aligned / 8..left_end_bytes];
351            let right_slice = &right[right_aligned / 8..right_end_bytes];
352
353            let (lp, left_u64s, ls) = unsafe { left_slice.align_to::<u64>() };
354            let (rp, right_u64s, rs) = unsafe { right_slice.align_to::<u64>() };
355
356            match (lp, ls, rp, rs) {
357                ([], [], [], []) => {
358                    let result_u64s: Vec<u64> = left_u64s
359                        .iter()
360                        .zip(right_u64s.iter())
361                        .map(|(l, r)| op(*l, *r))
362                        .collect();
363                    return BooleanBuffer::new(result_u64s.into(), bit_offset, len_in_bits);
364                }
365                ([], left_suf, [], right_suf) => {
366                    let left_iter = left_u64s
367                        .iter()
368                        .copied()
369                        .chain((!left_suf.is_empty()).then(|| read_u64(left_suf)));
370                    let right_iter = right_u64s
371                        .iter()
372                        .copied()
373                        .chain((!right_suf.is_empty()).then(|| read_u64(right_suf)));
374                    let result_u64s: Vec<u64> =
375                        left_iter.zip(right_iter).map(|(l, r)| op(l, r)).collect();
376                    return BooleanBuffer::new(result_u64s.into(), bit_offset, len_in_bits);
377                }
378                _ => {}
379            }
380
381            // Memory not u64-aligned, use chunks_exact fallback
382            let (left_chunks, left_rem) = left_slice.as_chunks::<8>();
383            let (right_chunks, right_rem) = right_slice.as_chunks::<8>();
384
385            let left_iter = left_chunks.iter().map(|c| u64::from_le_bytes(*c));
386            let right_iter = right_chunks.iter().map(|c| u64::from_le_bytes(*c));
387
388            let result_u64s: Vec<u64> = if left_rem.is_empty() && right_rem.is_empty() {
389                left_iter.zip(right_iter).map(|(l, r)| op(l, r)).collect()
390            } else {
391                left_iter
392                    .chain(Some(read_u64(left_rem)))
393                    .zip(right_iter.chain(Some(read_u64(right_rem))))
394                    .map(|(l, r)| op(l, r))
395                    .collect()
396            };
397            return BooleanBuffer::new(result_u64s.into(), bit_offset, len_in_bits);
398        }
399
400        // Different sub-64-bit alignments: bit-shifting unavoidable
401        let left_chunks = BitChunks::new(left, left_offset_in_bits, len_in_bits);
402        let right_chunks = BitChunks::new(right, right_offset_in_bits, len_in_bits);
403
404        let chunks = left_chunks
405            .iter()
406            .zip(right_chunks.iter())
407            .map(|(left, right)| op(left, right));
408        // Soundness: `BitChunks` is a `BitChunks` trusted length iterator which
409        // correctly reports its upper bound
410        let mut buffer = unsafe { MutableBuffer::from_trusted_len_iter(chunks) };
411
412        let remainder_bytes = bit_util::ceil(left_chunks.remainder_len(), 8);
413        let rem = op(left_chunks.remainder_bits(), right_chunks.remainder_bits());
414        // we are counting its starting from the least significant bit, to to_le_bytes should be correct
415        let rem = &rem.to_le_bytes()[0..remainder_bytes];
416        buffer.extend_from_slice(rem);
417
418        BooleanBuffer {
419            buffer: Buffer::from(buffer),
420            bit_offset: 0,
421            bit_len: len_in_bits,
422        }
423    }
424
425    /// Returns the number of set bits in this buffer
426    pub fn count_set_bits(&self) -> usize {
427        self.buffer
428            .count_set_bits_offset(self.bit_offset, self.bit_len)
429    }
430
431    /// Finds the position of the n-th set bit (1-based) starting from `start` index.
432    /// If fewer than `n` set bits are found, returns the length of the buffer.
433    pub fn find_nth_set_bit_position(&self, start: usize, n: usize) -> usize {
434        if n == 0 {
435            return start;
436        }
437
438        self.slice(start, self.bit_len - start)
439            .set_indices()
440            .nth(n - 1)
441            .map(|idx| start + idx + 1)
442            .unwrap_or(self.bit_len)
443    }
444
445    /// Returns a [`BitChunks`] instance which can be used to iterate over
446    /// this buffer's bits in `u64` chunks
447    #[inline]
448    pub fn bit_chunks(&self) -> BitChunks<'_> {
449        BitChunks::new(self.values(), self.bit_offset, self.bit_len)
450    }
451
452    /// Returns the offset of this [`BooleanBuffer`] in bits (not bytes)
453    #[inline]
454    pub fn offset(&self) -> usize {
455        self.bit_offset
456    }
457
458    /// Returns the length of this [`BooleanBuffer`] in bits (not bytes)
459    #[inline]
460    pub fn len(&self) -> usize {
461        self.bit_len
462    }
463
464    /// Returns true if this [`BooleanBuffer`] is empty
465    #[inline]
466    pub fn is_empty(&self) -> bool {
467        self.bit_len == 0
468    }
469
470    /// Free up unused memory.
471    pub fn shrink_to_fit(&mut self) {
472        // TODO(emilk): we could shrink even more in the case where we are a small sub-slice of the full buffer
473        self.buffer.shrink_to_fit();
474    }
475
476    /// Returns the boolean value at index `i`.
477    ///
478    /// # Panics
479    ///
480    /// Panics if `i >= self.len()`
481    #[inline]
482    pub fn value(&self, idx: usize) -> bool {
483        assert!(idx < self.bit_len);
484        unsafe { self.value_unchecked(idx) }
485    }
486
487    /// Returns the boolean value at index `i`.
488    ///
489    /// # Safety
490    /// This doesn't check bounds, the caller must ensure that index < self.len()
491    #[inline]
492    pub unsafe fn value_unchecked(&self, i: usize) -> bool {
493        unsafe { bit_util::get_bit_raw(self.buffer.as_ptr(), i + self.bit_offset) }
494    }
495
496    /// Returns the packed values of this [`BooleanBuffer`] not including any offset
497    #[inline]
498    pub fn values(&self) -> &[u8] {
499        &self.buffer
500    }
501
502    /// Slices this [`BooleanBuffer`] by the provided `offset` and `length`
503    ///
504    /// # Panics
505    ///
506    /// Panics if `offset + len > self.len()`
507    pub fn slice(&self, offset: usize, len: usize) -> Self {
508        assert!(
509            offset.saturating_add(len) <= self.bit_len,
510            "the length + offset of the sliced BooleanBuffer cannot exceed the existing length"
511        );
512        Self {
513            buffer: self.buffer.clone(),
514            bit_offset: self.bit_offset + offset,
515            bit_len: len,
516        }
517    }
518
519    /// Returns a new [`Buffer`] containing the sliced contents of this [`BooleanBuffer`]
520    ///
521    /// Equivalent to `self.buffer.bit_slice(self.offset, self.len)`
522    pub fn sliced(&self) -> Buffer {
523        self.buffer.bit_slice(self.bit_offset, self.bit_len)
524    }
525
526    /// Returns true if this [`BooleanBuffer`] is equal to `other`, using pointer comparisons
527    /// to determine buffer equality. This is cheaper than `PartialEq::eq` but may
528    /// return false when the arrays are logically equal
529    pub fn ptr_eq(&self, other: &Self) -> bool {
530        self.buffer.as_ptr() == other.buffer.as_ptr()
531            && self.bit_offset == other.bit_offset
532            && self.bit_len == other.bit_len
533    }
534
535    /// Returns the inner [`Buffer`]
536    ///
537    /// Note: this does not account for offset and length of this [`BooleanBuffer`]
538    #[inline]
539    pub fn inner(&self) -> &Buffer {
540        &self.buffer
541    }
542
543    /// Returns the inner [`Buffer`], consuming self
544    ///
545    /// Note: this does not account for offset and length of this [`BooleanBuffer`]
546    pub fn into_inner(self) -> Buffer {
547        self.buffer
548    }
549
550    /// Claim memory used by this buffer in the provided memory pool.
551    ///
552    /// See [`Buffer::claim`] for details.
553    #[cfg(feature = "pool")]
554    pub fn claim(&self, pool: &dyn crate::MemoryPool) {
555        self.buffer.claim(pool);
556    }
557
558    /// Apply a bitwise binary operation to `self`.
559    ///
560    /// If the underlying buffer is uniquely owned, reuses the allocation
561    /// and updates the bytes in place. If the underlying buffer is shared,
562    /// returns a newly allocated buffer.
563    ///
564    /// # API Notes
565    ///
566    /// If the buffer is reused, the result preserves the existing offset, which
567    /// may be non-zero.
568    fn bitwise_bin_op_assign<F>(&mut self, rhs: &BooleanBuffer, op: F)
569    where
570        F: FnMut(u64, u64) -> u64,
571    {
572        assert_eq!(self.bit_len, rhs.bit_len);
573        // Try to mutate in place if the buffer is uniquely owned
574        let buffer = std::mem::take(&mut self.buffer);
575        match buffer.into_mutable() {
576            Ok(mut buf) => {
577                bit_util::apply_bitwise_binary_op(
578                    &mut buf,
579                    self.bit_offset,
580                    &rhs.buffer,
581                    rhs.bit_offset,
582                    self.bit_len,
583                    op,
584                );
585                self.buffer = buf.into();
586            }
587            Err(buf) => {
588                self.buffer = buf;
589                *self = BooleanBuffer::from_bitwise_binary_op(
590                    self.values(),
591                    self.bit_offset,
592                    rhs.values(),
593                    rhs.bit_offset,
594                    self.bit_len,
595                    op,
596                );
597            }
598        }
599    }
600
601    /// Returns an iterator over the bits in this [`BooleanBuffer`]
602    pub fn iter(&self) -> BitIterator<'_> {
603        self.into_iter()
604    }
605
606    /// Returns an [`UnalignedBitChunk`] over this buffer's values.
607    fn unaligned_bit_chunks(&self) -> UnalignedBitChunk<'_> {
608        UnalignedBitChunk::new(self.values(), self.offset(), self.len())
609    }
610
611    /// Returns an iterator over the set bit positions in this [`BooleanBuffer`]
612    pub fn set_indices(&self) -> BitIndexIterator<'_> {
613        BitIndexIterator::new(self.values(), self.bit_offset, self.bit_len)
614    }
615
616    /// Returns a `u32` iterator over set bit positions without any usize->u32 conversion
617    pub fn set_indices_u32(&self) -> BitIndexU32Iterator<'_> {
618        BitIndexU32Iterator::new(self.values(), self.bit_offset, self.bit_len)
619    }
620
621    /// Returns a [`BitSliceIterator`] yielding contiguous ranges of set bits
622    pub fn set_slices(&self) -> BitSliceIterator<'_> {
623        BitSliceIterator::new(self.values(), self.bit_offset, self.bit_len)
624    }
625
626    /// Returns a [`SetBitCounter`] that counts the set bits in ranges of this
627    /// [`BooleanBuffer`]
628    ///
629    /// ```
630    /// # use arrow_buffer::BooleanBuffer;
631    /// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]);
632    /// let mut counter = bits.set_bit_counter();
633    /// assert_eq!(counter.count_range(0..2), 1);
634    /// assert_eq!(counter.count_range(2..4), 2);
635    /// ```
636    pub fn set_bit_counter(&self) -> SetBitCounter<'_> {
637        SetBitCounter::new(self.values(), self.bit_offset, self.bit_len)
638    }
639
640    /// Block size for chunked fold operations in [`Self::has_true`] and [`Self::has_false`].
641    /// Using `chunks_exact` with this size lets the compiler fully unroll the inner
642    /// fold (no inner branch/loop), enabling short-circuit exits every N chunks.
643    const CHUNK_FOLD_BLOCK_SIZE: usize = 16;
644
645    /// Returns whether there is at least one `true` value in this buffer.
646    ///
647    /// This is more efficient than `count_set_bits() > 0` because it can short-circuit
648    /// as soon as a `true` value is found, without counting all set bits.
649    ///
650    /// Returns `false` for empty buffer.
651    pub fn has_true(&self) -> bool {
652        let bit_chunks = self.unaligned_bit_chunks();
653        let chunks = bit_chunks.chunks();
654        let (exact, remainder) = chunks.as_chunks::<{ Self::CHUNK_FOLD_BLOCK_SIZE }>();
655        let found = bit_chunks.prefix().unwrap_or(0) != 0
656            || exact
657                .iter()
658                .any(|block| block.iter().fold(0u64, |acc, &c| acc | c) != 0);
659        found || remainder.iter().any(|&c| c != 0) || bit_chunks.suffix().unwrap_or(0) != 0
660    }
661
662    /// Returns whether there is at least one `false` value in this buffer.
663    ///
664    /// This is more efficient than `len() > count_set_bits()` because it can short-circuit
665    /// as soon as a `false` value is found, without counting all set bits.
666    ///
667    /// Returns `false` for empty buffer.
668    pub fn has_false(&self) -> bool {
669        let bit_chunks = self.unaligned_bit_chunks();
670        // UnalignedBitChunk zeros padding bits; fill them with 1s so
671        // they don't appear as false values.
672        let lead_mask = !((1u64 << bit_chunks.lead_padding()) - 1);
673        let trail_mask = if bit_chunks.trailing_padding() == 0 {
674            u64::MAX
675        } else {
676            (1u64 << (64 - bit_chunks.trailing_padding())) - 1
677        };
678        let (prefix_fill, suffix_fill) = match (bit_chunks.prefix(), bit_chunks.suffix()) {
679            (Some(_), Some(_)) => (!lead_mask, !trail_mask),
680            (Some(_), None) => (!lead_mask | !trail_mask, 0),
681            (None, Some(_)) => (0, !trail_mask),
682            (None, None) => (0, 0),
683        };
684        let chunks = bit_chunks.chunks();
685        let (exact, remainder) = chunks.as_chunks::<{ Self::CHUNK_FOLD_BLOCK_SIZE }>();
686        let found = bit_chunks
687            .prefix()
688            .is_some_and(|v| (v | prefix_fill) != u64::MAX)
689            || exact
690                .iter()
691                .any(|block| block.iter().fold(u64::MAX, |acc, &c| acc & c) != u64::MAX);
692        found
693            || remainder.iter().any(|&c| c != u64::MAX)
694            || bit_chunks
695                .suffix()
696                .is_some_and(|v| (v | suffix_fill) != u64::MAX)
697    }
698}
699
700impl Not for &BooleanBuffer {
701    type Output = BooleanBuffer;
702
703    fn not(self) -> Self::Output {
704        BooleanBuffer::from_bitwise_unary_op(&self.buffer, self.bit_offset, self.bit_len, |a| !a)
705    }
706}
707
708impl BitAnd<&BooleanBuffer> for &BooleanBuffer {
709    type Output = BooleanBuffer;
710
711    fn bitand(self, rhs: &BooleanBuffer) -> Self::Output {
712        assert_eq!(self.bit_len, rhs.bit_len);
713        BooleanBuffer {
714            buffer: buffer_bin_and(
715                &self.buffer,
716                self.bit_offset,
717                &rhs.buffer,
718                rhs.bit_offset,
719                self.bit_len,
720            ),
721            bit_offset: 0,
722            bit_len: self.bit_len,
723        }
724    }
725}
726
727impl BitOr<&BooleanBuffer> for &BooleanBuffer {
728    type Output = BooleanBuffer;
729
730    fn bitor(self, rhs: &BooleanBuffer) -> Self::Output {
731        assert_eq!(self.bit_len, rhs.bit_len);
732        BooleanBuffer {
733            buffer: buffer_bin_or(
734                &self.buffer,
735                self.bit_offset,
736                &rhs.buffer,
737                rhs.bit_offset,
738                self.bit_len,
739            ),
740            bit_offset: 0,
741            bit_len: self.bit_len,
742        }
743    }
744}
745
746impl BitXor<&BooleanBuffer> for &BooleanBuffer {
747    type Output = BooleanBuffer;
748
749    fn bitxor(self, rhs: &BooleanBuffer) -> Self::Output {
750        assert_eq!(self.bit_len, rhs.bit_len);
751        BooleanBuffer {
752            buffer: buffer_bin_xor(
753                &self.buffer,
754                self.bit_offset,
755                &rhs.buffer,
756                rhs.bit_offset,
757                self.bit_len,
758            ),
759            bit_offset: 0,
760            bit_len: self.bit_len,
761        }
762    }
763}
764
765impl BitAndAssign<&BooleanBuffer> for BooleanBuffer {
766    fn bitand_assign(&mut self, rhs: &BooleanBuffer) {
767        self.bitwise_bin_op_assign(rhs, |a, b| a & b);
768    }
769}
770
771impl BitOrAssign<&BooleanBuffer> for BooleanBuffer {
772    fn bitor_assign(&mut self, rhs: &BooleanBuffer) {
773        self.bitwise_bin_op_assign(rhs, |a, b| a | b);
774    }
775}
776
777impl BitXorAssign<&BooleanBuffer> for BooleanBuffer {
778    fn bitxor_assign(&mut self, rhs: &BooleanBuffer) {
779        self.bitwise_bin_op_assign(rhs, |a, b| a ^ b);
780    }
781}
782
783impl<'a> IntoIterator for &'a BooleanBuffer {
784    type Item = bool;
785    type IntoIter = BitIterator<'a>;
786
787    fn into_iter(self) -> Self::IntoIter {
788        BitIterator::new(self.values(), self.bit_offset, self.bit_len)
789    }
790}
791
792impl From<&[bool]> for BooleanBuffer {
793    fn from(value: &[bool]) -> Self {
794        let mut builder = BooleanBufferBuilder::new(value.len());
795        builder.append_slice(value);
796        builder.finish()
797    }
798}
799
800impl From<Vec<bool>> for BooleanBuffer {
801    fn from(value: Vec<bool>) -> Self {
802        value.as_slice().into()
803    }
804}
805
806impl FromIterator<bool> for BooleanBuffer {
807    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
808        let iter = iter.into_iter();
809        let (hint, _) = iter.size_hint();
810        let mut builder = BooleanBufferBuilder::new(hint);
811        iter.for_each(|b| builder.append(b));
812        builder.finish()
813    }
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819
820    #[test]
821    fn test_boolean_new() {
822        let bytes = &[0, 1, 2, 3, 4];
823        let buf = Buffer::from(bytes);
824        let offset = 0;
825        let len = 24;
826
827        let boolean_buf = BooleanBuffer::new(buf.clone(), offset, len);
828        assert_eq!(bytes, boolean_buf.values());
829        assert_eq!(offset, boolean_buf.offset());
830        assert_eq!(len, boolean_buf.len());
831
832        assert_eq!(2, boolean_buf.count_set_bits());
833        assert_eq!(&buf, boolean_buf.inner());
834        assert_eq!(buf, boolean_buf.clone().into_inner());
835
836        assert!(!boolean_buf.is_empty())
837    }
838
839    #[test]
840    fn test_boolean_data_equality() {
841        let boolean_buf1 = BooleanBuffer::new(Buffer::from(&[0, 1, 4, 3, 5]), 0, 32);
842        let boolean_buf2 = BooleanBuffer::new(Buffer::from(&[0, 1, 4, 3, 5]), 0, 32);
843        assert_eq!(boolean_buf1, boolean_buf2);
844
845        // slice with same offset and same length should still preserve equality
846        let boolean_buf3 = boolean_buf1.slice(8, 16);
847        assert_ne!(boolean_buf1, boolean_buf3);
848        let boolean_buf4 = boolean_buf1.slice(0, 32);
849        assert_eq!(boolean_buf1, boolean_buf4);
850
851        // unequal because of different elements
852        let boolean_buf2 = BooleanBuffer::new(Buffer::from(&[0, 0, 2, 3, 4]), 0, 32);
853        assert_ne!(boolean_buf1, boolean_buf2);
854
855        // unequal because of different length
856        let boolean_buf2 = BooleanBuffer::new(Buffer::from(&[0, 1, 4, 3, 5]), 0, 24);
857        assert_ne!(boolean_buf1, boolean_buf2);
858
859        // ptr_eq
860        assert!(boolean_buf1.ptr_eq(&boolean_buf1));
861        assert!(boolean_buf2.ptr_eq(&boolean_buf2));
862        assert!(!boolean_buf1.ptr_eq(&boolean_buf2));
863    }
864
865    #[test]
866    fn test_boolean_slice() {
867        let bytes = &[0, 3, 2, 6, 2];
868        let boolean_buf1 = BooleanBuffer::new(Buffer::from(bytes), 0, 32);
869        let boolean_buf2 = BooleanBuffer::new(Buffer::from(bytes), 0, 32);
870
871        let boolean_slice1 = boolean_buf1.slice(16, 16);
872        let boolean_slice2 = boolean_buf2.slice(0, 16);
873        assert_eq!(boolean_slice1.values(), boolean_slice2.values());
874
875        assert_eq!(bytes, boolean_slice1.values());
876        assert_eq!(16, boolean_slice1.bit_offset);
877        assert_eq!(16, boolean_slice1.bit_len);
878
879        assert_eq!(bytes, boolean_slice2.values());
880        assert_eq!(0, boolean_slice2.bit_offset);
881        assert_eq!(16, boolean_slice2.bit_len);
882    }
883
884    #[test]
885    fn test_boolean_bitand() {
886        let offset = 0;
887        let len = 40;
888
889        let buf1 = Buffer::from(&[0, 1, 1, 0, 0]);
890        let boolean_buf1 = &BooleanBuffer::new(buf1, offset, len);
891
892        let buf2 = Buffer::from(&[0, 1, 1, 1, 0]);
893        let boolean_buf2 = &BooleanBuffer::new(buf2, offset, len);
894
895        let expected = BooleanBuffer::new(Buffer::from(&[0, 1, 1, 0, 0]), offset, len);
896        assert_eq!(boolean_buf1 & boolean_buf2, expected);
897    }
898
899    #[test]
900    fn test_boolean_bitor() {
901        let offset = 0;
902        let len = 40;
903
904        let buf1 = Buffer::from(&[0, 1, 1, 0, 0]);
905        let boolean_buf1 = &BooleanBuffer::new(buf1, offset, len);
906
907        let buf2 = Buffer::from(&[0, 1, 1, 1, 0]);
908        let boolean_buf2 = &BooleanBuffer::new(buf2, offset, len);
909
910        let expected = BooleanBuffer::new(Buffer::from(&[0, 1, 1, 1, 0]), offset, len);
911        assert_eq!(boolean_buf1 | boolean_buf2, expected);
912    }
913
914    #[test]
915    fn test_boolean_bitxor() {
916        let offset = 0;
917        let len = 40;
918
919        let buf1 = Buffer::from(&[0, 1, 1, 0, 0]);
920        let boolean_buf1 = &BooleanBuffer::new(buf1, offset, len);
921
922        let buf2 = Buffer::from(&[0, 1, 1, 1, 0]);
923        let boolean_buf2 = &BooleanBuffer::new(buf2, offset, len);
924
925        let expected = BooleanBuffer::new(Buffer::from(&[0, 0, 0, 1, 0]), offset, len);
926        assert_eq!(boolean_buf1 ^ boolean_buf2, expected);
927    }
928
929    #[test]
930    fn test_boolean_bitand_assign_shared_and_unshared() {
931        let rhs = BooleanBuffer::from(&[true, true, false, true, false, true][..]);
932        let original = BooleanBuffer::from(&[true, false, true, true, true, false][..]);
933
934        let mut unshared = BooleanBuffer::from(&[true, false, true, true, true, false][..]);
935        unshared &= &rhs;
936
937        let mut shared = original.clone();
938        let _shared_owner = shared.clone();
939        shared &= &rhs;
940
941        let expected = &original & &rhs;
942        assert_eq!(unshared, expected);
943        assert_eq!(shared, expected);
944    }
945
946    #[test]
947    fn test_boolean_bitor_assign() {
948        let rhs = BooleanBuffer::from(&[true, true, false, true, false, true][..]);
949        let original = BooleanBuffer::from(&[true, false, true, true, true, false][..]);
950
951        let mut actual = original.clone();
952        actual |= &rhs;
953
954        let expected = &original | &rhs;
955        assert_eq!(actual, expected);
956    }
957
958    #[test]
959    fn test_boolean_bitxor_assign() {
960        let rhs = BooleanBuffer::from(&[true, true, false, true, false, true][..]);
961        let original = BooleanBuffer::from(&[true, false, true, true, true, false][..]);
962
963        let mut actual = original.clone();
964        actual ^= &rhs;
965
966        let expected = &original ^ &rhs;
967        assert_eq!(actual, expected);
968    }
969
970    #[test]
971    fn test_boolean_not() {
972        let offset = 0;
973        let len = 40;
974
975        let buf = Buffer::from(&[0, 1, 1, 0, 0]);
976        let boolean_buf = &BooleanBuffer::new(buf, offset, len);
977
978        let expected = BooleanBuffer::new(Buffer::from(&[255, 254, 254, 255, 255]), offset, len);
979        assert_eq!(!boolean_buf, expected);
980
981        // Demonstrate that Non-zero offsets are preserved
982        let sliced = boolean_buf.slice(3, 20);
983        let result = !&sliced;
984        assert_eq!(result.offset(), 3);
985        assert_eq!(result.len(), sliced.len());
986        for i in 0..sliced.len() {
987            assert_eq!(result.value(i), !sliced.value(i));
988        }
989    }
990
991    #[test]
992    fn test_boolean_from_slice_bool() {
993        let v = [true, false, false];
994        let buf = BooleanBuffer::from(&v[..]);
995        assert_eq!(buf.offset(), 0);
996        assert_eq!(buf.len(), 3);
997        assert_eq!(buf.values().len(), 1);
998        assert!(buf.value(0));
999    }
1000
1001    #[test]
1002    fn test_from_bitwise_unary_op() {
1003        // Use 1024 boolean values so that at least some of the tests cover multiple u64 chunks and
1004        // perfect alignment
1005        let input_bools = (0..1024)
1006            .map(|_| rand::random::<bool>())
1007            .collect::<Vec<bool>>();
1008        let input_buffer = BooleanBuffer::from(&input_bools[..]);
1009
1010        // Note ensure we test offsets over 100 to cover multiple u64 chunks
1011        for offset in 0..1024 {
1012            let result = BooleanBuffer::from_bitwise_unary_op(
1013                input_buffer.values(),
1014                offset,
1015                input_buffer.len() - offset,
1016                |a| !a,
1017            );
1018            let expected = input_bools[offset..]
1019                .iter()
1020                .map(|b| !*b)
1021                .collect::<BooleanBuffer>();
1022            assert_eq!(result, expected);
1023        }
1024
1025        // Also test when the input doesn't cover the entire buffer
1026        for offset in 0..512 {
1027            let len = 512 - offset; // fixed length less than total
1028            let result =
1029                BooleanBuffer::from_bitwise_unary_op(input_buffer.values(), offset, len, |a| !a);
1030            let expected = input_bools[offset..]
1031                .iter()
1032                .take(len)
1033                .map(|b| !*b)
1034                .collect::<BooleanBuffer>();
1035            assert_eq!(result, expected);
1036        }
1037    }
1038
1039    #[test]
1040    fn test_from_bitwise_unary_op_unaligned_fallback() {
1041        // Deterministic affine sequence over u8: b[i] = 37*i + 11 (mod 256).
1042        // This yields a non-trivial mix of bits (prefix: 11, 48, 85, 122, 159, 196, 233, 14, ...)
1043        // so unary bit operations are exercised on varied input patterns.
1044        let bytes = (0..80)
1045            .map(|i| (i as u8).wrapping_mul(37).wrapping_add(11))
1046            .collect::<Vec<_>>();
1047        let base = bytes.as_ptr() as usize;
1048        let shift = (0..8).find(|s| !(base + s).is_multiple_of(8)).unwrap();
1049        let misaligned = &bytes[shift..];
1050
1051        // Case 1: fallback path with `remainder.is_empty() == true`
1052        let src = &misaligned[..24];
1053        let offset = 7;
1054        let len = 96;
1055        let result = BooleanBuffer::from_bitwise_unary_op(src, offset, len, |a| !a);
1056        let expected = (0..len)
1057            .map(|i| !bit_util::get_bit(src, offset + i))
1058            .collect::<BooleanBuffer>();
1059        assert_eq!(result, expected);
1060        assert_eq!(result.offset(), offset % 64);
1061
1062        // Case 2: fallback path with `remainder.is_empty() == false`
1063        let src = &misaligned[..13];
1064        let offset = 3;
1065        let len = 100;
1066        let result = BooleanBuffer::from_bitwise_unary_op(src, offset, len, |a| !a);
1067        let expected = (0..len)
1068            .map(|i| !bit_util::get_bit(src, offset + i))
1069            .collect::<BooleanBuffer>();
1070        assert_eq!(result, expected);
1071        assert_eq!(result.offset(), offset % 64);
1072    }
1073
1074    #[test]
1075    fn test_from_bitwise_binary_op() {
1076        // pick random boolean inputs
1077        let input_bools_left = (0..1024)
1078            .map(|_| rand::random::<bool>())
1079            .collect::<Vec<bool>>();
1080        let input_bools_right = (0..1024)
1081            .map(|_| rand::random::<bool>())
1082            .collect::<Vec<bool>>();
1083        let input_buffer_left = BooleanBuffer::from(&input_bools_left[..]);
1084        let input_buffer_right = BooleanBuffer::from(&input_bools_right[..]);
1085
1086        #[cfg(miri)] // Takes too long otherwise
1087        let left_offsets = [0, 1, 7, 8, 63, 64, 65];
1088        #[cfg(not(miri))]
1089        let left_offsets = 0..200;
1090
1091        for left_offset in left_offsets {
1092            for right_offset in [0, 4, 5, 17, 33, 24, 45, 64, 65, 100, 200] {
1093                for len_offset in [0, 1, 44, 100, 256, 300, 512] {
1094                    let len = 1024 - len_offset - left_offset.max(right_offset); // ensure we don't go out of bounds
1095                    // compute with AND
1096                    let result = BooleanBuffer::from_bitwise_binary_op(
1097                        input_buffer_left.values(),
1098                        left_offset,
1099                        input_buffer_right.values(),
1100                        right_offset,
1101                        len,
1102                        |a, b| a & b,
1103                    );
1104                    // compute directly from bools
1105                    let expected = input_bools_left[left_offset..]
1106                        .iter()
1107                        .zip(&input_bools_right[right_offset..])
1108                        .take(len)
1109                        .map(|(a, b)| *a & *b)
1110                        .collect::<BooleanBuffer>();
1111                    assert_eq!(result, expected);
1112                }
1113            }
1114        }
1115    }
1116
1117    #[test]
1118    fn test_from_bitwise_binary_op_same_mod_64_unaligned_fallback() {
1119        // Exercise the shared-alignment fast path when both inputs are misaligned in memory,
1120        // forcing the chunks_exact fallback instead of align_to::<u64>().
1121        let left_bytes = [
1122            0,           // dropped so `&left_bytes[1..]` is not u64-aligned in memory
1123            0b1101_0010, // logical left bits start at bit 3 of this byte
1124            0b0110_1101,
1125            0b1010_0111,
1126            0b0001_1110,
1127            0b1110_0001,
1128            0b0101_1010,
1129            0b1001_0110,
1130            0b0011_1100,
1131            0b1011_0001,
1132            0b0100_1110,
1133            0b1100_0011,
1134            0b0111_1000,
1135        ];
1136        let right_bytes = [
1137            0,           // dropped so `&right_bytes[1..]` is not u64-aligned in memory
1138            0b1010_1100, // logical right bits start at bit 67 == bit 3 of the second 64-bit block
1139            0b0101_0011,
1140            0b1111_0000,
1141            0b0011_1010,
1142            0b1000_1111,
1143            0b0110_0101,
1144            0b1101_1000,
1145            0b0001_0111,
1146            0b1110_0100,
1147            0b0010_1101,
1148            0b1001_1010,
1149            0b0111_0001,
1150        ];
1151
1152        let left = &left_bytes[1..];
1153        let right = &right_bytes[1..];
1154
1155        let left_offset = 3;
1156        let right_offset = 67; // same mod 64 as left_offset, so this takes the shared-alignment path
1157        let len = 24; // leaves a partial trailing chunk, so this covers the non-empty remainder branch
1158
1159        let result = BooleanBuffer::from_bitwise_binary_op(
1160            left,
1161            left_offset,
1162            right,
1163            right_offset,
1164            len,
1165            |a, b| a & b,
1166        );
1167        let expected = (0..len)
1168            .map(|i| {
1169                bit_util::get_bit(left, left_offset + i)
1170                    & bit_util::get_bit(right, right_offset + i)
1171            })
1172            .collect::<BooleanBuffer>();
1173
1174        assert_eq!(result, expected);
1175        assert_eq!(result.offset(), left_offset % 64);
1176    }
1177
1178    #[test]
1179    fn test_from_bitwise_binary_op_same_mod_64_unaligned_fallback_no_remainder() {
1180        // Force the chunks_exact fallback with an exact 8-byte chunk so both remainders are empty.
1181        let left_bytes = [
1182            0,           // dropped so `&left_bytes[1..]` is not u64-aligned in memory
1183            0b1010_1100, // logical left bits start at bit 3 of this byte
1184            0b0110_1001,
1185            0b1101_0011,
1186            0b0001_1110,
1187            0b1110_0101,
1188            0b0101_1000,
1189            0b1001_0111,
1190            0b0011_1101,
1191        ];
1192        let right_bytes = [
1193            0,           // dropped so `&right_bytes[1..]` is not u64-aligned in memory
1194            0b0111_0010, // logical right bits start at bit 67 == bit 3 of the second 64-bit block
1195            0b1010_1001,
1196            0b0101_1110,
1197            0b1100_0011,
1198            0b0011_1011,
1199            0b1000_1110,
1200            0b1111_0001,
1201            0b0100_1101,
1202            0b1011_0110,
1203            0b0001_1011,
1204            0b1101_0100,
1205            0b0110_0011,
1206            0b1001_1110,
1207            0b0010_1001,
1208            0b1110_0110,
1209            0b0101_0001,
1210        ];
1211
1212        let left = &left_bytes[1..];
1213        let right = &right_bytes[1..];
1214
1215        let left_offset = 3;
1216        let right_offset = 67; // same mod 64 as left_offset, so this takes the shared-alignment path
1217        let len = 61; // 3 + 61 = 64, so the aligned slices are exactly one 8-byte chunk with empty remainders
1218
1219        let result = BooleanBuffer::from_bitwise_binary_op(
1220            left,
1221            left_offset,
1222            right,
1223            right_offset,
1224            len,
1225            |a, b| a | b,
1226        );
1227        let expected = (0..len)
1228            .map(|i| {
1229                bit_util::get_bit(left, left_offset + i)
1230                    | bit_util::get_bit(right, right_offset + i)
1231            })
1232            .collect::<BooleanBuffer>();
1233
1234        assert_eq!(result, expected);
1235        assert_eq!(result.offset(), left_offset % 64);
1236    }
1237
1238    #[test]
1239    fn test_extend_trusted_len_sets_byte_len() {
1240        // Ensures extend_trusted_len keeps the underlying byte length in sync with bit length.
1241        let mut builder = BooleanBufferBuilder::new(0);
1242        let bools: Vec<_> = (0..10).map(|i| i % 2 == 0).collect();
1243        unsafe { builder.extend_trusted_len(bools.into_iter()) };
1244        assert_eq!(builder.as_slice().len(), bit_util::ceil(builder.len(), 8));
1245    }
1246
1247    #[test]
1248    fn test_extend_trusted_len_then_append() {
1249        // Exercises append after extend_trusted_len to validate byte length and values.
1250        let mut builder = BooleanBufferBuilder::new(0);
1251        let bools: Vec<_> = (0..9).map(|i| i % 3 == 0).collect();
1252        unsafe { builder.extend_trusted_len(bools.clone().into_iter()) };
1253        builder.append(true);
1254        assert_eq!(builder.as_slice().len(), bit_util::ceil(builder.len(), 8));
1255        let finished = builder.finish();
1256        for (i, v) in bools.into_iter().chain(std::iter::once(true)).enumerate() {
1257            assert_eq!(finished.value(i), v, "at index {i}");
1258        }
1259    }
1260
1261    #[test]
1262    fn test_find_nth_set_bit_position() {
1263        let bools = vec![true, false, true, true, false, true];
1264        let buffer = BooleanBuffer::from(bools);
1265
1266        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 1), 1);
1267        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 2), 3);
1268        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 3), 4);
1269        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 4), 6);
1270        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 5), 6);
1271
1272        assert_eq!(buffer.clone().find_nth_set_bit_position(1, 1), 3);
1273        assert_eq!(buffer.clone().find_nth_set_bit_position(3, 1), 4);
1274        assert_eq!(buffer.clone().find_nth_set_bit_position(3, 2), 6);
1275    }
1276
1277    #[test]
1278    fn test_find_nth_set_bit_position_large() {
1279        let mut bools = vec![false; 1000];
1280        bools[100] = true;
1281        bools[500] = true;
1282        bools[999] = true;
1283        let buffer = BooleanBuffer::from(bools);
1284
1285        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 1), 101);
1286        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 2), 501);
1287        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 3), 1000);
1288        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 4), 1000);
1289
1290        assert_eq!(buffer.clone().find_nth_set_bit_position(101, 1), 501);
1291    }
1292
1293    #[test]
1294    fn test_find_nth_set_bit_position_sliced() {
1295        let bools = vec![false, true, false, true, true, false, true]; // [F, T, F, T, T, F, T]
1296        let buffer = BooleanBuffer::from(bools);
1297        let slice = buffer.slice(1, 6); // [T, F, T, T, F, T]
1298
1299        assert_eq!(slice.len(), 6);
1300        // Logical indices: 0, 1, 2, 3, 4, 5
1301        // Logical values: T, F, T, T, F, T
1302
1303        assert_eq!(slice.clone().find_nth_set_bit_position(0, 1), 1);
1304        assert_eq!(slice.clone().find_nth_set_bit_position(0, 2), 3);
1305        assert_eq!(slice.clone().find_nth_set_bit_position(0, 3), 4);
1306        assert_eq!(slice.clone().find_nth_set_bit_position(0, 4), 6);
1307    }
1308
1309    #[test]
1310    fn test_find_nth_set_bit_position_all_set() {
1311        let buffer = BooleanBuffer::new_set(100);
1312        for i in 1..=100 {
1313            assert_eq!(buffer.clone().find_nth_set_bit_position(0, i), i);
1314        }
1315        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 101), 100);
1316    }
1317
1318    #[test]
1319    fn test_find_nth_set_bit_position_none_set() {
1320        let buffer = BooleanBuffer::new_unset(100);
1321        assert_eq!(buffer.clone().find_nth_set_bit_position(0, 1), 100);
1322    }
1323
1324    #[test]
1325    fn test_has_true_has_false_all_true() {
1326        let arr = BooleanBuffer::from(vec![true, true, true]);
1327        assert!(arr.has_true());
1328        assert!(!arr.has_false());
1329    }
1330
1331    #[test]
1332    fn test_has_true_has_false_all_false() {
1333        let arr = BooleanBuffer::from(vec![false, false, false]);
1334        assert!(!arr.has_true());
1335        assert!(arr.has_false());
1336    }
1337
1338    #[test]
1339    fn test_has_true_has_false_mixed() {
1340        let arr = BooleanBuffer::from(vec![true, false, true]);
1341        assert!(arr.has_true());
1342        assert!(arr.has_false());
1343    }
1344
1345    #[test]
1346    fn test_has_true_has_false_empty() {
1347        let arr = BooleanBuffer::from(Vec::<bool>::new());
1348        assert!(!arr.has_true());
1349        assert!(!arr.has_false());
1350    }
1351
1352    #[test]
1353    fn test_has_false_aligned_suffix_all_true() {
1354        let arr = BooleanBuffer::from(vec![true; 129]);
1355        assert!(arr.has_true());
1356        assert!(!arr.has_false());
1357    }
1358
1359    #[test]
1360    fn test_has_false_non_aligned_all_true() {
1361        // 65 elements: exercises the remainder path in has_false
1362        let arr = BooleanBuffer::from(vec![true; 65]);
1363        assert!(arr.has_true());
1364        assert!(!arr.has_false());
1365    }
1366
1367    #[test]
1368    fn test_has_false_non_aligned_last_false() {
1369        // 64 trues + 1 false: remainder path should find the false
1370        let mut values = vec![true; 64];
1371        values.push(false);
1372        let arr = BooleanBuffer::from(values);
1373        assert!(arr.has_true());
1374        assert!(arr.has_false());
1375    }
1376
1377    #[test]
1378    fn test_has_false_exact_64_all_true() {
1379        // Exactly 64 elements, no remainder
1380        let arr = BooleanBuffer::from(vec![true; 64]);
1381        assert!(arr.has_true());
1382        assert!(!arr.has_false());
1383    }
1384
1385    #[test]
1386    fn test_has_true_has_false_unaligned_slices() {
1387        let cases = [
1388            (1, 129, true, false),
1389            (3, 130, true, false),
1390            (5, 65, true, false),
1391            (7, 64, true, false),
1392        ];
1393
1394        let base = BooleanBuffer::from(vec![true; 300]);
1395
1396        for (offset, len, expected_has_true, expected_has_false) in cases {
1397            let arr = base.slice(offset, len);
1398            assert_eq!(
1399                arr.has_true(),
1400                expected_has_true,
1401                "offset={offset} len={len}"
1402            );
1403            assert_eq!(
1404                arr.has_false(),
1405                expected_has_false,
1406                "offset={offset} len={len}"
1407            );
1408        }
1409    }
1410
1411    #[test]
1412    fn test_has_true_has_false_exact_multiples_of_64() {
1413        let cases = [
1414            (64, true, false),
1415            (128, true, false),
1416            (192, true, false),
1417            (256, true, false),
1418        ];
1419
1420        for (len, expected_has_true, expected_has_false) in cases {
1421            let arr = BooleanBuffer::from(vec![true; len]);
1422            assert_eq!(arr.has_true(), expected_has_true, "len={len}");
1423            assert_eq!(arr.has_false(), expected_has_false, "len={len}");
1424        }
1425    }
1426}