Skip to main content

vortex_buffer/bit/
buf.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::convert::Infallible;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::fmt::Result as FmtResult;
8use std::ops::BitAnd;
9use std::ops::BitOr;
10use std::ops::BitXor;
11use std::ops::Not;
12use std::ops::RangeBounds;
13
14use crate::Alignment;
15use crate::BitBufferMeta;
16use crate::BitBufferMut;
17use crate::Buffer;
18use crate::BufferAllocatorRef;
19use crate::BufferMut;
20use crate::ByteBuffer;
21use crate::bit::BitChunks;
22use crate::bit::BitIndexIterator;
23use crate::bit::BitIterator;
24use crate::bit::BitSliceIterator;
25use crate::bit::UnalignedBitChunk;
26use crate::bit::collect_bool_word;
27use crate::bit::count_ones::count_ones;
28use crate::bit::get_bit_unchecked;
29use crate::bit::ops::bitwise_binary_op;
30use crate::bit::ops::bitwise_binary_op_both_owned;
31use crate::bit::ops::bitwise_binary_op_lhs_owned;
32use crate::bit::ops::bitwise_unary_op;
33use crate::bit::ops::bitwise_unary_op_copy;
34use crate::bit::select::bit_select;
35use crate::bit::select::bit_select_unset;
36
37/// An immutable bitset stored as a packed byte buffer.
38#[derive(Debug, Clone, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub struct BitBuffer {
41    buffer: ByteBuffer,
42    /// Represents the offset of the bit buffer into the first byte.
43    ///
44    /// This is always less than 8 (for when the bit buffer is not aligned to a byte).
45    offset: usize,
46    len: usize,
47}
48
49const LIMIT_LEN: usize = 16;
50impl Display for BitBuffer {
51    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
52        let limit = f.precision().unwrap_or(LIMIT_LEN);
53        let buf: Vec<bool> = self.into_iter().take(limit).collect();
54        f.debug_struct("BitBuffer")
55            .field("len", &self.len)
56            .field("buffer", &buf)
57            .finish()
58    }
59}
60
61impl PartialEq for BitBuffer {
62    fn eq(&self, other: &Self) -> bool {
63        if self.len != other.len {
64            return false;
65        }
66
67        if self.len == 0 {
68            return true;
69        }
70
71        // Fast path: both byte-aligned and same length — direct byte comparison.
72        if self.offset == 0 && other.offset == 0 {
73            let full_bytes = self.len / 8;
74            let self_bytes = &self.buffer.as_slice()[..full_bytes];
75            let other_bytes = &other.buffer.as_slice()[..full_bytes];
76            if self_bytes != other_bytes {
77                return false;
78            }
79            // Compare remaining bits in the last partial byte.
80            let rem = self.len % 8;
81            if rem != 0 {
82                let mask = (1u8 << rem) - 1;
83                let a = self.buffer.as_slice()[full_bytes] & mask;
84                let b = other.buffer.as_slice()[full_bytes] & mask;
85                return a == b;
86            }
87            return true;
88        }
89
90        self.chunks()
91            .iter_padded()
92            .zip(other.chunks().iter_padded())
93            .all(|(a, b)| a == b)
94    }
95}
96
97impl BitBuffer {
98    /// Create a new `BoolBuffer` backed by a [`ByteBuffer`] with `len` bits in view.
99    ///
100    /// Panics if the buffer is not large enough to hold `len` bits.
101    #[inline]
102    pub fn new(buffer: ByteBuffer, len: usize) -> Self {
103        assert!(
104            buffer.len() * 8 >= len,
105            "provided ByteBuffer not large enough to back BoolBuffer with len {len}"
106        );
107
108        // BitBuffers make no assumptions on byte alignment, so we strip any alignment.
109        let buffer = buffer.aligned(Alignment::none());
110
111        Self {
112            buffer,
113            len,
114            offset: 0,
115        }
116    }
117
118    /// Create a new `BoolBuffer` backed by a [`ByteBuffer`] with `len` bits in view, starting at
119    /// the given `offset` (in bits).
120    ///
121    /// Panics if the buffer is not large enough to hold `len` bits after the offset.
122    #[inline]
123    pub fn new_with_offset(buffer: ByteBuffer, len: usize, offset: usize) -> Self {
124        assert!(
125            len.saturating_add(offset) <= buffer.len().saturating_mul(8),
126            "provided ByteBuffer (len={}) not large enough to back BoolBuffer with offset {offset} len {len}",
127            buffer.len()
128        );
129
130        // BitBuffers make no assumptions on byte alignment, so we strip any alignment.
131        let buffer = buffer.aligned(Alignment::none());
132
133        // Slice the buffer to ensure the offset is within the first byte
134        let byte_offset = offset / 8;
135        let offset = offset % 8;
136        let buffer = if byte_offset != 0 {
137            buffer.slice(byte_offset..)
138        } else {
139            buffer
140        };
141
142        Self {
143            buffer,
144            offset,
145            len,
146        }
147    }
148
149    /// Create a new `BoolBuffer` of length `len` where all bits are set (true).
150    #[inline]
151    pub fn new_set(len: usize) -> Self {
152        Self::new_set_in(len, BufferAllocatorRef::statically_allocated())
153    }
154
155    /// Create a set bit buffer with the provided allocator.
156    #[inline]
157    pub fn new_set_in(len: usize, allocator: BufferAllocatorRef) -> Self {
158        let words = len.div_ceil(8);
159        let buffer = Buffer::full_in(0xFF, words, allocator);
160
161        Self {
162            buffer,
163            len,
164            offset: 0,
165        }
166    }
167
168    /// Create a new `BoolBuffer` of length `len` where all bits are unset (false).
169    #[inline]
170    pub fn new_unset(len: usize) -> Self {
171        Self::new_unset_in(len, BufferAllocatorRef::statically_allocated())
172    }
173
174    /// Create an unset bit buffer with the provided allocator.
175    #[inline]
176    pub fn new_unset_in(len: usize, allocator: BufferAllocatorRef) -> Self {
177        let words = len.div_ceil(8);
178        let buffer = Buffer::zeroed_in(words, allocator);
179
180        Self {
181            buffer,
182            len,
183            offset: 0,
184        }
185    }
186
187    /// Create a bit buffer of `len` with `indices` set as true.
188    pub fn from_indices(len: usize, indices: impl IntoIterator<Item = usize>) -> BitBuffer {
189        BitBufferMut::from_indices(len, indices).freeze()
190    }
191
192    /// Create a new empty `BitBuffer`.
193    #[inline]
194    pub fn empty() -> Self {
195        Self::new_set(0)
196    }
197
198    /// Create a new `BitBuffer` of length `len` where all bits are set to `value`.
199    #[inline]
200    pub fn full(value: bool, len: usize) -> Self {
201        Self::full_in(value, len, BufferAllocatorRef::statically_allocated())
202    }
203
204    /// Create a full bit buffer with the provided allocator.
205    #[inline]
206    pub fn full_in(value: bool, len: usize, allocator: BufferAllocatorRef) -> Self {
207        if value {
208            Self::new_set_in(len, allocator)
209        } else {
210            Self::new_unset_in(len, allocator)
211        }
212    }
213
214    /// Collects `len` Boolean values from `f` into a packed [`BitBuffer`].
215    ///
216    /// Calls `f` exactly once for each index in `0..len`, in order.
217    ///
218    /// # Code generation
219    ///
220    /// `collect_bool_words` calls `collect_bool_words_inline`, which selects a `pack_bool_word_*`
221    /// kernel at compile time and passes it to `collect_bool_words_with`. That shared word loop
222    /// materializes each full 64-value chunk as a byte-per-value `[bool; 64]`, then passes it to the
223    /// selected kernel. For simple predicates, LLVM vectorizes the loop and removes the physical
224    /// stack array. On AVX-512, it still combines the comparison masks, expands the result into 64
225    /// `0` or `1` bytes with `vpbroadcastq` and `vmovdqu8`, then recreates the mask with `vptestmb`.
226    /// [LLVM issue #219235](https://github.com/llvm/llvm-project/issues/219235) tracks replacing
227    /// that round trip with a direct `kmovq` store. The conversion is per chunk. This method does
228    /// not create a full-column byte buffer.
229    ///
230    /// # Performance
231    ///
232    /// `collect_bool_words_inline` and `collect_bool_words_with` can inline into the caller, so LLVM
233    /// sees `f`, the fill loop, and the packing kernel together. A retained bounds check inside `f`
234    /// can prevent vectorization. A caller that proves `len <= values.len()` can use
235    /// `unsafe { *values.get_unchecked(i) }` because this method only passes indices in `0..len`.
236    ///
237    /// Use this method for general predicates. Use [`Self::collect_bool_multiversioned`] only for
238    /// the specialized predicates described there.
239    #[inline]
240    pub fn collect_bool<F: FnMut(usize) -> bool>(len: usize, f: F) -> Self {
241        BitBufferMut::collect_bool(len, f).freeze()
242    }
243
244    /// Collects predicate results with the provided allocator.
245    #[inline]
246    pub fn collect_bool_in<F: FnMut(usize) -> bool>(
247        len: usize,
248        f: F,
249        allocator: BufferAllocatorRef,
250    ) -> Self {
251        BitBufferMut::collect_bool_in(len, f, allocator).freeze()
252    }
253
254    /// Collects Boolean values with a fill-and-pack loop selected for the current CPU.
255    ///
256    /// This has the same callback contract as [`Self::collect_bool`]. On x86-64,
257    /// `collect_bool_words_multiversioned` selects `collect_bool_words_avx512`,
258    /// `collect_bool_words_avx2`, or `collect_bool_words_inline` at runtime. Each wider version is a
259    /// `#[target_feature]` function, so Rust cannot inline it into a caller compiled without those
260    /// features.
261    ///
262    /// Use this method only for a small, bounds-check-free predicate whose wider loop has been
263    /// benchmarked. Use [`Self::collect_bool`] for general predicates.
264    #[inline]
265    pub fn collect_bool_multiversioned<F: FnMut(usize) -> bool>(len: usize, f: F) -> Self {
266        Self::collect_bool_multiversioned_in(len, f, BufferAllocatorRef::statically_allocated())
267    }
268
269    /// Collects multiversioned predicate results with the provided allocator.
270    #[inline]
271    pub fn collect_bool_multiversioned_in<F: FnMut(usize) -> bool>(
272        len: usize,
273        f: F,
274        allocator: BufferAllocatorRef,
275    ) -> Self {
276        BitBufferMut::collect_bool_multiversioned_in(len, f, allocator).freeze()
277    }
278
279    /// Maps over each bit in this buffer, calling `f(index, bit_value)` and collecting results.
280    ///
281    /// This is more efficient than `collect_bool` when you need to read the current bit value,
282    /// as it unpacks each u64 chunk only once rather than doing random access for each bit.
283    pub fn map_cmp<F>(&self, mut f: F) -> Self
284    where
285        F: FnMut(usize, bool) -> bool,
286    {
287        let len = self.len;
288        let mut buffer: BufferMut<u64> = BufferMut::with_capacity(len.div_ceil(64));
289
290        let chunks_count = len / 64;
291        let remainder = len % 64;
292        let chunks = self.chunks();
293
294        for (chunk_idx, src_chunk) in chunks.iter().enumerate() {
295            let packed = collect_bool_word(64, |bit_idx| {
296                let i = bit_idx + chunk_idx * 64;
297                let bit_value = (src_chunk >> bit_idx) & 1 == 1;
298                f(i, bit_value)
299            });
300
301            // SAFETY: Already allocated sufficient capacity
302            unsafe { buffer.push_unchecked(packed) }
303        }
304
305        if remainder != 0 {
306            let src_chunk = chunks.remainder_bits();
307            let packed = collect_bool_word(remainder, |bit_idx| {
308                let i = bit_idx + chunks_count * 64;
309                let bit_value = (src_chunk >> bit_idx) & 1 == 1;
310                f(i, bit_value)
311            });
312
313            // SAFETY: Already allocated sufficient capacity
314            unsafe { buffer.push_unchecked(packed) }
315        }
316
317        let mut bytes = buffer.into_byte_buffer();
318        bytes.truncate(len.div_ceil(8));
319
320        Self {
321            buffer: bytes.freeze(),
322            offset: 0,
323            len,
324        }
325    }
326
327    /// Clear all bits in the buffer, preserving existing capacity.
328    #[inline]
329    pub fn clear(&mut self) {
330        self.buffer.clear();
331        self.len = 0;
332        self.offset = 0;
333    }
334
335    /// Get the logical length of this `BoolBuffer`.
336    ///
337    /// This may differ from the physical length of the backing buffer, for example if it was
338    /// created using the `new_with_offset` constructor, or if it was sliced.
339    #[inline]
340    pub fn len(&self) -> usize {
341        self.len
342    }
343
344    /// Returns `true` if the `BoolBuffer` is empty.
345    #[inline]
346    pub fn is_empty(&self) -> bool {
347        self.len() == 0
348    }
349
350    /// Offset of the start of the buffer in bits.
351    #[allow(clippy::inline_always)]
352    #[inline(always)]
353    pub fn offset(&self) -> usize {
354        self.offset
355    }
356
357    /// Get a reference to the underlying buffer.
358    #[allow(clippy::inline_always)]
359    #[inline(always)]
360    pub fn inner(&self) -> &ByteBuffer {
361        &self.buffer
362    }
363
364    /// Return the backing bytes for this bit buffer when its logical offset is byte-aligned.
365    ///
366    /// The returned slice contains exactly `self.len().div_ceil(8)` bytes. Bits past the logical
367    /// length in the final byte are outside the buffer's logical range and should be ignored by
368    /// callers.
369    #[inline]
370    pub fn byte_aligned_bytes(&self) -> Option<&[u8]> {
371        if !self.offset.is_multiple_of(8) {
372            return None;
373        }
374
375        let n_bytes = self.len.div_ceil(8);
376        let start = self.offset / 8;
377        let end = start + n_bytes;
378        Some(&self.buffer.as_slice()[start..end])
379    }
380
381    /// Retrieve the value at the given index.
382    ///
383    /// Panics if the index is out of bounds.
384    ///
385    /// Please note for repeatedly calling this function, please prefer [`crate::get_bit`].
386    #[inline]
387    pub fn value(&self, index: usize) -> bool {
388        assert!(index < self.len);
389        unsafe { self.value_unchecked(index) }
390    }
391
392    /// Retrieve the value at the given index without bounds checking
393    ///
394    /// # SAFETY
395    /// Caller must ensure that index is within the range of the buffer
396    #[inline]
397    pub unsafe fn value_unchecked(&self, index: usize) -> bool {
398        unsafe { get_bit_unchecked(self.buffer.as_ptr(), index + self.offset) }
399    }
400
401    /// Create a new zero-copy slice of this BoolBuffer that begins at the `start` index and extends
402    /// for `len` bits.
403    ///
404    /// Panics if the slice would extend beyond the end of the buffer.
405    #[inline]
406    pub fn slice(&self, range: impl RangeBounds<usize>) -> Self {
407        let (byte_offset, meta) = BitBufferMeta::new(self.offset, self.len).slice(range);
408
409        // Trim whole bytes off the front directly rather than going through `new_with_offset`,
410        // which would slice (and re-clone) the clone we'd have to pass it.
411        let buffer = if byte_offset != 0 {
412            self.buffer.slice_unaligned(byte_offset..)
413        } else {
414            self.buffer.clone().aligned(Alignment::none())
415        };
416
417        Self {
418            buffer,
419            offset: meta.offset(),
420            len: meta.len(),
421        }
422    }
423
424    /// Slice any full bytes from the buffer, leaving the offset < 8.
425    pub fn shrink_offset(self) -> Self {
426        let word_start = self.offset / 8;
427        let word_end = (self.offset + self.len).div_ceil(8);
428
429        let buffer = self.buffer.slice(word_start..word_end);
430
431        let bit_offset = self.offset % 8;
432        let len = self.len;
433        BitBuffer::new_with_offset(buffer, len, bit_offset)
434    }
435
436    /// Access chunks of the buffer aligned to 8 byte boundary as [prefix, \<full chunks\>, suffix]
437    #[inline]
438    pub fn unaligned_chunks(&self) -> UnalignedBitChunk<'_> {
439        UnalignedBitChunk::new(self.buffer.as_slice(), self.offset, self.len)
440    }
441
442    /// Access chunks of the underlying buffer as 8 byte chunks with a final trailer
443    ///
444    /// If you're performing operations on a single buffer, prefer [BitBuffer::unaligned_chunks]
445    #[inline]
446    pub fn chunks(&self) -> BitChunks<'_> {
447        BitChunks::new(self.buffer.as_slice(), self.offset, self.len)
448    }
449
450    /// Get the number of set bits in the buffer.
451    #[inline]
452    pub fn true_count(&self) -> usize {
453        count_ones(self.buffer.as_slice(), self.offset, self.len)
454    }
455
456    /// Get the number of set bits in the bit range `[start, end)`.
457    ///
458    /// Unlike `self.slice(start..end).true_count()`, this counts directly over the
459    /// existing backing buffer without allocating or cloning a new [`BitBuffer`],
460    /// making it cheap to call repeatedly over many small ranges.
461    ///
462    /// Panics if `start > end` or `end > len`.
463    #[inline]
464    pub fn count_range(&self, start: usize, end: usize) -> usize {
465        assert!(start <= end, "start {start} exceeds end {end}");
466        assert!(end <= self.len, "end {end} exceeds len {}", self.len);
467        count_ones(self.buffer.as_slice(), self.offset + start, end - start)
468    }
469
470    /// Returns the position of the `nth` set bit (0-indexed).
471    ///
472    /// This is the "select" operation on a bitmap: given a rank `nth`, find
473    /// which logical bit position holds that rank.
474    ///
475    /// Returns `None` if `nth` is greater than or equal to the number of set bits.
476    #[inline]
477    pub fn select(&self, nth: usize) -> Option<usize> {
478        bit_select(self.buffer.as_slice(), self.offset, self.len, nth)
479    }
480
481    /// Returns the position of the `nth` unset bit (0-indexed).
482    ///
483    /// This is the "select0" operation, the counterpart of [`Self::select`] for unset bits:
484    /// given a rank `nth` among the unset bits, find which logical bit position holds it.
485    ///
486    /// Returns `None` if `nth` is greater than or equal to the number of unset bits.
487    #[inline]
488    pub fn select_unset(&self, nth: usize) -> Option<usize> {
489        bit_select_unset(self.buffer.as_slice(), self.offset, self.len, nth)
490    }
491
492    /// Returns the index of the last set bit, or `None` if every bit is unset.
493    ///
494    /// This scans from the end a word at a time, avoiding the full forward scan required by
495    /// [`Self::select`] when selecting the final set bit.
496    #[inline]
497    pub fn last_set_index(&self) -> Option<usize> {
498        let chunks = self.unaligned_chunks();
499        let lead = chunks.lead_padding();
500        let prefix_words = usize::from(chunks.prefix().is_some());
501
502        if let Some(word) = chunks.suffix()
503            && word != 0
504        {
505            let word_index = prefix_words + chunks.chunks().len();
506            return Some(word_index * 64 + 63 - word.leading_zeros() as usize - lead);
507        }
508
509        for (index, &word) in chunks.chunks().iter().enumerate().rev() {
510            if word != 0 {
511                let word_index = prefix_words + index;
512                return Some(word_index * 64 + 63 - word.leading_zeros() as usize - lead);
513            }
514        }
515
516        chunks.prefix().filter(|word| *word != 0).map(|word| {
517            debug_assert!(word.trailing_zeros() as usize >= lead);
518            63 - word.leading_zeros() as usize - lead
519        })
520    }
521
522    /// Get the number of unset bits in the buffer.
523    #[inline]
524    pub fn false_count(&self) -> usize {
525        self.len - self.true_count()
526    }
527
528    /// Iterator over bits in the buffer
529    #[inline]
530    pub fn iter(&self) -> BitIterator<'_> {
531        BitIterator::new(self.buffer.as_slice(), self.offset, self.len)
532    }
533
534    /// Iterator over set indices of the underlying buffer
535    #[inline]
536    pub fn set_indices(&self) -> BitIndexIterator<'_> {
537        BitIndexIterator::new(self.buffer.as_slice(), self.offset, self.len)
538    }
539
540    /// Iterator over set slices of the underlying buffer
541    #[inline]
542    pub fn set_slices(&self) -> BitSliceIterator<'_> {
543        BitSliceIterator::new(self.buffer.as_slice(), self.offset, self.len)
544    }
545
546    /// Invoke `f(index)` for every set bit, in ascending order, processing a `u64`
547    /// word at a time.
548    ///
549    /// This is the fast way to "do something for each set bit": it skips all-zero
550    /// words, fast-paths all-one words, and walks the remaining bits with
551    /// `trailing_zeros`. Prefer it over `for i in 0..len { if buf.value(i) { f(i) } }`
552    /// (which pays a branch per element) and over collecting [`Self::set_indices`]
553    /// (whose per-`next` iterator state does not inline as well).
554    #[inline]
555    pub fn for_each_set_index<F: FnMut(usize)>(&self, mut f: F) {
556        let Ok(()) = self.try_for_each_set_index(|index| {
557            f(index);
558            Ok::<_, Infallible>(())
559        });
560    }
561
562    /// Fallible variant of [`for_each_set_index`](Self::for_each_set_index).
563    ///
564    /// Stops and returns the first error from `f`.
565    #[inline]
566    pub fn try_for_each_set_index<E, F>(&self, f: F) -> Result<(), E>
567    where
568        F: FnMut(usize) -> Result<(), E>,
569    {
570        self.try_for_each_index::<false, E, F>(f)
571    }
572
573    /// Invoke `f(index)` for every unset bit, in ascending order, processing a `u64` word at a
574    /// time.
575    ///
576    /// This is the counterpart of [`for_each_set_index`](Self::for_each_set_index) for unset bits.
577    #[inline]
578    pub fn for_each_unset_index<F: FnMut(usize)>(&self, mut f: F) {
579        let Ok(()) = self.try_for_each_index::<true, _, _>(|index| {
580            f(index);
581            Ok::<_, Infallible>(())
582        });
583    }
584
585    /// The scan behind [`try_for_each_set_index`](Self::try_for_each_set_index). With `UNSET`,
586    /// each word is inverted as it is read, so the same scan visits the unset bits instead.
587    #[inline]
588    fn try_for_each_index<const UNSET: bool, E, F>(&self, mut f: F) -> Result<(), E>
589    where
590        F: FnMut(usize) -> Result<(), E>,
591    {
592        let mut base = 0usize;
593        for word in self.chunks().iter_padded() {
594            let word = if UNSET {
595                // The last word is zero padded past `len`. Setting the padding before inverting
596                // keeps it from being visited.
597                let held = self.len - base;
598                let padding = if held < 64 { u64::MAX << held } else { 0 };
599                !(word | padding)
600            } else {
601                word
602            };
603            if word == u64::MAX {
604                for k in 0..64 {
605                    f(base + k)?;
606                }
607            } else {
608                let mut w = word;
609                while w != 0 {
610                    f(base + w.trailing_zeros() as usize)?;
611                    w &= w - 1;
612                }
613            }
614            base += 64;
615        }
616
617        Ok(())
618    }
619
620    /// Created a new BitBuffer with offset reset to 0
621    pub fn sliced(&self) -> Self {
622        if self.offset.is_multiple_of(8) {
623            return Self::new(
624                self.buffer
625                    .slice(self.offset / 8..(self.offset + self.len).div_ceil(8)),
626                self.len,
627            );
628        }
629
630        // Allocate directly rather than clone + identity op which would fail try_into_mut.
631        bitwise_unary_op_copy(self, |a| a)
632    }
633}
634
635// Conversions
636
637impl BitBuffer {
638    /// Returns the offset, len and underlying buffer.
639    #[inline]
640    pub fn into_inner(self) -> (usize, usize, ByteBuffer) {
641        (self.offset, self.len, self.buffer)
642    }
643
644    /// Attempt to convert this `BitBuffer` into a mutable version.
645    #[inline]
646    pub fn try_into_mut(self) -> Result<BitBufferMut, Self> {
647        match self.buffer.try_into_mut() {
648            Ok(buffer) => Ok(BitBufferMut::from_buffer(buffer, self.offset, self.len)),
649            Err(buffer) => Err(BitBuffer::new_with_offset(buffer, self.len, self.offset)),
650        }
651    }
652}
653
654impl From<&[bool]> for BitBuffer {
655    fn from(value: &[bool]) -> Self {
656        BitBufferMut::from(value).freeze()
657    }
658}
659
660impl From<Vec<bool>> for BitBuffer {
661    fn from(value: Vec<bool>) -> Self {
662        BitBufferMut::from(value).freeze()
663    }
664}
665
666impl FromIterator<bool> for BitBuffer {
667    #[inline]
668    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
669        BitBufferMut::from_iter(iter).freeze()
670    }
671}
672
673impl BitOr for BitBuffer {
674    type Output = Self;
675
676    #[inline]
677    fn bitor(self, rhs: Self) -> Self::Output {
678        bitwise_binary_op_both_owned(self, rhs, |a, b| a | b)
679    }
680}
681
682impl BitOr for &BitBuffer {
683    type Output = BitBuffer;
684
685    #[inline]
686    fn bitor(self, rhs: Self) -> Self::Output {
687        bitwise_binary_op(self, rhs, |a, b| a | b)
688    }
689}
690
691impl BitOr<&BitBuffer> for BitBuffer {
692    type Output = BitBuffer;
693
694    #[inline]
695    fn bitor(self, rhs: &BitBuffer) -> Self::Output {
696        bitwise_binary_op_lhs_owned(self, rhs, |a, b| a | b)
697    }
698}
699
700impl BitAnd for &BitBuffer {
701    type Output = BitBuffer;
702
703    #[inline]
704    fn bitand(self, rhs: Self) -> Self::Output {
705        bitwise_binary_op(self, rhs, |a, b| a & b)
706    }
707}
708
709impl BitAnd<BitBuffer> for &BitBuffer {
710    type Output = BitBuffer;
711
712    #[inline]
713    fn bitand(self, rhs: BitBuffer) -> Self::Output {
714        self.bitand(&rhs)
715    }
716}
717
718impl BitAnd<&BitBuffer> for BitBuffer {
719    type Output = BitBuffer;
720
721    #[inline]
722    fn bitand(self, rhs: &BitBuffer) -> Self::Output {
723        bitwise_binary_op_lhs_owned(self, rhs, |a, b| a & b)
724    }
725}
726
727impl BitAnd<BitBuffer> for BitBuffer {
728    type Output = BitBuffer;
729
730    #[inline]
731    fn bitand(self, rhs: BitBuffer) -> Self::Output {
732        bitwise_binary_op_both_owned(self, rhs, |a, b| a & b)
733    }
734}
735
736impl Not for &BitBuffer {
737    type Output = BitBuffer;
738
739    #[inline]
740    fn not(self) -> Self::Output {
741        // Allocate directly rather than clone+try_into_mut, which always fails
742        // since the clone shares the Arc with the original reference.
743        bitwise_unary_op_copy(self, |a| !a)
744    }
745}
746
747impl Not for BitBuffer {
748    type Output = BitBuffer;
749
750    #[inline]
751    fn not(self) -> Self::Output {
752        bitwise_unary_op(self, |a| !a)
753    }
754}
755
756impl BitXor for &BitBuffer {
757    type Output = BitBuffer;
758
759    #[inline]
760    fn bitxor(self, rhs: Self) -> Self::Output {
761        bitwise_binary_op(self, rhs, |a, b| a ^ b)
762    }
763}
764
765impl BitXor<&BitBuffer> for BitBuffer {
766    type Output = BitBuffer;
767
768    #[inline]
769    fn bitxor(self, rhs: &BitBuffer) -> Self::Output {
770        bitwise_binary_op_lhs_owned(self, rhs, |a, b| a ^ b)
771    }
772}
773
774impl BitBuffer {
775    /// Create a new BitBuffer by performing a bitwise AND NOT operation between two BitBuffers.
776    ///
777    /// This operation is sufficiently common that we provide a dedicated method for it avoid
778    /// making two passes over the data.
779    pub fn bitand_not(&self, rhs: &BitBuffer) -> BitBuffer {
780        bitwise_binary_op(self, rhs, |a, b| a & !b)
781    }
782
783    /// Owned variant of [`bitand_not`](Self::bitand_not) that can mutate in-place when possible.
784    pub fn into_bitand_not(self, rhs: &BitBuffer) -> BitBuffer {
785        bitwise_binary_op_lhs_owned(self, rhs, |a, b| a & !b)
786    }
787
788    /// Iterate through bits in a buffer.
789    ///
790    /// # Arguments
791    ///
792    /// * `f` - Callback function taking (bit_index, is_set)
793    ///
794    /// # Panics
795    ///
796    /// Panics if the range is outside valid bounds of the buffer.
797    #[inline]
798    pub fn iter_bits<F>(&self, mut f: F)
799    where
800        F: FnMut(usize, bool),
801    {
802        let total_bits = self.len;
803        if total_bits == 0 {
804            return;
805        }
806
807        // Process in 64-bit chunks for better ILP and fewer loop iterations.
808        let chunks = self.chunks();
809        let chunks_count = total_bits / 64;
810        let remainder = total_bits % 64;
811
812        for (chunk_idx, chunk) in chunks.iter().enumerate() {
813            let base = chunk_idx * 64;
814            for bit_idx in 0..64 {
815                f(base + bit_idx, (chunk >> bit_idx) & 1 == 1);
816            }
817        }
818
819        if remainder != 0 {
820            let rem_chunk = chunks.remainder_bits();
821            let base = chunks_count * 64;
822            for bit_idx in 0..remainder {
823                f(base + bit_idx, (rem_chunk >> bit_idx) & 1 == 1);
824            }
825        }
826    }
827}
828
829impl<'a> IntoIterator for &'a BitBuffer {
830    type Item = bool;
831    type IntoIter = BitIterator<'a>;
832
833    fn into_iter(self) -> Self::IntoIter {
834        self.iter()
835    }
836}
837
838#[cfg(test)]
839mod tests {
840    use rand::RngExt;
841    use rand::SeedableRng;
842    use rand::rngs::StdRng;
843    use rstest::rstest;
844    use vortex_error::VortexResult;
845
846    use crate::ByteBuffer;
847    use crate::bit::BitBuffer;
848    use crate::buffer;
849
850    #[test]
851    fn test_bool() {
852        // Create a new Buffer<u64> of length 1024 where the 8th bit is set.
853        let buffer: ByteBuffer = buffer![1 << 7; 1024];
854        let bools = BitBuffer::new(buffer, 1024 * 8);
855
856        // sanity checks
857        assert_eq!(bools.len(), 1024 * 8);
858        assert!(!bools.is_empty());
859        assert_eq!(bools.true_count(), 1024);
860        assert_eq!(bools.false_count(), 1024 * 7);
861
862        // Check all the values
863        for word in 0..1024 {
864            for bit in 0..8 {
865                if bit == 7 {
866                    assert!(bools.value(word * 8 + bit));
867                } else {
868                    assert!(!bools.value(word * 8 + bit));
869                }
870            }
871        }
872
873        // Slice the buffer to create a new subset view.
874        let sliced = bools.slice(64..72);
875
876        // sanity checks
877        assert_eq!(sliced.len(), 8);
878        assert!(!sliced.is_empty());
879        assert_eq!(sliced.true_count(), 1);
880        assert_eq!(sliced.false_count(), 7);
881
882        // Check all of the values like before
883        for bit in 0..8 {
884            if bit == 7 {
885                assert!(sliced.value(bit));
886            } else {
887                assert!(!sliced.value(bit));
888            }
889        }
890    }
891
892    #[test]
893    fn test_padded_equaltiy() {
894        let buf1 = BitBuffer::new_set(64); // All bits set.
895        let buf2 = BitBuffer::collect_bool(64, |x| x < 32); // First half set, other half unset.
896
897        for i in 0..32 {
898            assert_eq!(buf1.value(i), buf2.value(i), "Bit {} should be the same", i);
899        }
900
901        for i in 32..64 {
902            assert_ne!(buf1.value(i), buf2.value(i), "Bit {} should differ", i);
903        }
904
905        assert_eq!(
906            buf1.slice(0..32),
907            buf2.slice(0..32),
908            "Buffer slices with same bits should be equal (`PartialEq` needs `iter_padded()`)"
909        );
910        assert_ne!(
911            buf1.slice(32..64),
912            buf2.slice(32..64),
913            "Buffer slices with different bits should not be equal (`PartialEq` needs `iter_padded()`)"
914        );
915    }
916
917    #[test]
918    fn test_slice_offset_calculation() {
919        let buf = BitBuffer::collect_bool(16, |_| true);
920        let sliced = buf.slice(10..16);
921        assert_eq!(sliced.len(), 6);
922        // Ensure the offset is modulo 8
923        assert_eq!(sliced.offset(), 2);
924    }
925
926    #[test]
927    fn test_byte_aligned_bytes() {
928        let bytes: ByteBuffer = buffer![0b1010_0101u8, 0b0000_0011];
929        let buf = BitBuffer::new(bytes.clone(), 10);
930        assert_eq!(buf.byte_aligned_bytes(), Some(bytes.as_slice()));
931
932        let byte_sliced = buf.slice(8..10);
933        assert_eq!(byte_sliced.byte_aligned_bytes(), Some(&[0b0000_0011][..]));
934
935        let bit_sliced = buf.slice(1..9);
936        assert!(bit_sliced.byte_aligned_bytes().is_none());
937    }
938
939    #[test]
940    fn test_from_indices_dense_crosses_words() {
941        let len = 130;
942        let indices = (0..len).filter(|idx| idx % 3 != 1);
943        let buf = BitBuffer::from_indices(len, indices);
944
945        assert_eq!(buf.len(), len);
946        for idx in 0..len {
947            assert_eq!(buf.value(idx), idx % 3 != 1, "mismatch at {idx}");
948        }
949    }
950
951    #[test]
952    #[should_panic(expected = "index 5 exceeds len 5")]
953    fn test_from_indices_out_of_bounds() {
954        BitBuffer::from_indices(5, [0, 5]);
955    }
956
957    #[rstest]
958    #[case(0, 0, None)]
959    #[case(3, 7, None)]
960    #[case(0, 1, Some(0))]
961    #[case(8, 64, Some(63))]
962    #[case(13, 65, Some(0))]
963    #[case(13, 65, Some(64))]
964    #[case(67, 151, Some(97))]
965    #[case(67, 151, Some(150))]
966    fn last_set_index_handles_offsets_and_padding(
967        #[case] offset: usize,
968        #[case] len: usize,
969        #[case] expected: Option<usize>,
970    ) {
971        let backing = BitBuffer::from_iter(
972            std::iter::repeat_n(true, offset)
973                .chain((0..len).map(|index| Some(index) == expected))
974                .chain(std::iter::repeat_n(true, 7)),
975        );
976        let buffer = BitBuffer::new_with_offset(backing.inner().clone(), len, offset);
977
978        assert_eq!(buffer.last_set_index(), expected);
979    }
980
981    #[rstest]
982    #[case(5)]
983    #[case(8)]
984    #[case(10)]
985    #[case(13)]
986    #[case(16)]
987    #[case(23)]
988    #[case(100)]
989    fn test_iter_bits(#[case] len: usize) {
990        let buf = BitBuffer::collect_bool(len, |i| i % 2 == 0);
991
992        let mut collected = Vec::new();
993        buf.iter_bits(|idx, is_set| {
994            collected.push((idx, is_set));
995        });
996
997        let expected: Vec<_> = (0..len).map(|idx| (idx, idx % 2 == 0)).collect();
998        assert_eq!(collected, expected);
999    }
1000
1001    #[rstest]
1002    #[case(3, 5)]
1003    #[case(3, 8)]
1004    #[case(5, 10)]
1005    #[case(2, 16)]
1006    #[case(8, 16)]
1007    #[case(9, 16)]
1008    #[case(17, 16)]
1009    fn test_iter_bits_with_offset(#[case] offset: usize, #[case] len: usize) {
1010        let total_bits = offset + len;
1011        let buf = BitBuffer::collect_bool(total_bits, |i| i % 2 == 0);
1012        let buf_with_offset = BitBuffer::new_with_offset(buf.inner().clone(), len, offset);
1013
1014        let mut collected = Vec::new();
1015        buf_with_offset.iter_bits(|idx, is_set| {
1016            collected.push((idx, is_set));
1017        });
1018
1019        let expected: Vec<_> = (0..len)
1020            .map(|idx| (idx, (offset + idx).is_multiple_of(2)))
1021            .collect();
1022        assert_eq!(collected, expected);
1023    }
1024
1025    #[rstest]
1026    #[case(8, 10)]
1027    #[case(9, 7)]
1028    #[case(16, 8)]
1029    #[case(17, 10)]
1030    fn test_iter_bits_catches_wrong_byte_offset(#[case] offset: usize, #[case] len: usize) {
1031        let total_bits = offset + len;
1032        // Alternating pattern to catch byte offset errors: Bits are set for even indexed bytes.
1033        let buf = BitBuffer::collect_bool(total_bits, |i| (i / 8) % 2 == 0);
1034
1035        let buf_with_offset = BitBuffer::new_with_offset(buf.inner().clone(), len, offset);
1036
1037        let mut collected = Vec::new();
1038        buf_with_offset.iter_bits(|idx, is_set| {
1039            collected.push((idx, is_set));
1040        });
1041
1042        let expected: Vec<_> = (0..len)
1043            .map(|idx| (idx, ((offset + idx) / 8).is_multiple_of(2)))
1044            .collect();
1045        assert_eq!(collected, expected);
1046    }
1047
1048    #[rstest]
1049    #[case(5)]
1050    #[case(8)]
1051    #[case(10)]
1052    #[case(64)]
1053    #[case(65)]
1054    #[case(100)]
1055    #[case(128)]
1056    fn test_map_cmp_identity(#[case] len: usize) {
1057        // map_cmp with identity function should return the same buffer
1058        let buf = BitBuffer::collect_bool(len, |i| i % 3 == 0);
1059        let mapped = buf.map_cmp(|_idx, bit| bit);
1060
1061        assert_eq!(buf.len(), mapped.len());
1062        for i in 0..len {
1063            assert_eq!(buf.value(i), mapped.value(i), "Mismatch at index {}", i);
1064        }
1065    }
1066
1067    #[rstest]
1068    #[case(5)]
1069    #[case(8)]
1070    #[case(64)]
1071    #[case(65)]
1072    #[case(100)]
1073    fn test_map_cmp_negate(#[case] len: usize) {
1074        // map_cmp negating all bits
1075        let buf = BitBuffer::collect_bool(len, |i| i % 2 == 0);
1076        let mapped = buf.map_cmp(|_idx, bit| !bit);
1077
1078        assert_eq!(buf.len(), mapped.len());
1079        for i in 0..len {
1080            assert_eq!(!buf.value(i), mapped.value(i), "Mismatch at index {}", i);
1081        }
1082    }
1083
1084    #[rstest]
1085    #[case(0, 0)]
1086    #[case(0, 64)]
1087    #[case(5, 70)]
1088    #[case(64, 130)]
1089    #[case(0, 200)]
1090    fn test_count_range(#[case] start: usize, #[case] end: usize) {
1091        let len = 200;
1092        let buf = BitBuffer::collect_bool(len, |i| i % 3 == 0);
1093        let expected = (start..end).filter(|i| i % 3 == 0).count();
1094        assert_eq!(buf.count_range(start, end), expected);
1095        // Must agree with slicing then counting.
1096        assert_eq!(
1097            buf.count_range(start, end),
1098            buf.slice(start..end).true_count()
1099        );
1100    }
1101
1102    #[rstest]
1103    #[case(3)]
1104    #[case(7)]
1105    fn test_count_range_with_offset(#[case] offset: usize) {
1106        let len = 150;
1107        let buf = BitBuffer::collect_bool(offset + len, |i| i % 2 == 0);
1108        let view = BitBuffer::new_with_offset(buf.inner().clone(), len, offset);
1109        for (start, end) in [(0, len), (10, 100), (1, 2), (63, 129)] {
1110            let expected = (offset + start..offset + end)
1111                .filter(|i| i % 2 == 0)
1112                .count();
1113            assert_eq!(view.count_range(start, end), expected, "[{start}, {end})");
1114        }
1115    }
1116
1117    #[rstest]
1118    #[case(0)]
1119    #[case(1)]
1120    #[case(63)]
1121    #[case(64)]
1122    #[case(65)]
1123    #[case(200)]
1124    #[case(1000)]
1125    fn test_set_index_visitors_match_set_indices(#[case] len: usize) {
1126        let buf = BitBuffer::collect_bool(len, |i| i % 5 == 0 || i % 7 == 0);
1127        let expected: Vec<usize> = buf.set_indices().collect();
1128
1129        let mut got = Vec::new();
1130        buf.for_each_set_index(|i| got.push(i));
1131        assert_eq!(got, expected);
1132
1133        let mut fallible_got = Vec::new();
1134        let result = buf.try_for_each_set_index(|i| {
1135            fallible_got.push(i);
1136            Ok::<(), ()>(())
1137        });
1138        assert_eq!(result, Ok(()));
1139        assert_eq!(fallible_got, expected);
1140    }
1141
1142    #[rstest]
1143    #[case(3, 200)]
1144    #[case(7, 130)]
1145    fn test_for_each_set_index_with_offset(#[case] offset: usize, #[case] len: usize) {
1146        let base = BitBuffer::collect_bool(offset + len, |i| i % 3 == 0);
1147        let view = BitBuffer::new_with_offset(base.inner().clone(), len, offset);
1148        let expected: Vec<usize> = view.set_indices().collect();
1149        let mut got = Vec::new();
1150        view.for_each_set_index(|i| got.push(i));
1151        assert_eq!(got, expected);
1152    }
1153
1154    #[test]
1155    fn test_for_each_set_index_all_set() {
1156        let buf = BitBuffer::new_set(130);
1157        let mut got = Vec::new();
1158        buf.for_each_set_index(|i| got.push(i));
1159        assert_eq!(got, (0..130).collect::<Vec<_>>());
1160    }
1161
1162    #[test]
1163    fn test_try_for_each_set_index_stops_on_error() {
1164        for (buffer, stop) in [
1165            (BitBuffer::new_set(130), 65),
1166            (BitBuffer::collect_bool(130, |i| i % 3 == 0), 66),
1167        ] {
1168            let mut visited = Vec::new();
1169            let result = buffer.try_for_each_set_index(|index| {
1170                visited.push(index);
1171                if index == stop {
1172                    return Err(index);
1173                }
1174
1175                Ok(())
1176            });
1177
1178            assert_eq!(result, Err(stop));
1179            assert_eq!(
1180                visited,
1181                buffer
1182                    .set_indices()
1183                    .take_while(|&i| i <= stop)
1184                    .collect::<Vec<_>>()
1185            );
1186        }
1187    }
1188
1189    #[rstest]
1190    #[case(0)]
1191    #[case(1)]
1192    #[case(63)]
1193    #[case(64)]
1194    #[case(65)]
1195    #[case(128)]
1196    #[case(200)]
1197    fn test_for_each_unset_index_agrees_with_naive(#[case] len: usize) -> VortexResult<()> {
1198        let mut rng = StdRng::seed_from_u64(u64::try_from(len)?);
1199        let random: BitBuffer = (0..len).map(|_| rng.random_bool(0.5)).collect();
1200        // The same kind of bits, starting 3 bits into their buffer.
1201        let offset: BitBuffer = (0..len + 3).map(|_| rng.random_bool(0.5)).collect();
1202        for bits in [
1203            random,
1204            offset.slice(3..),
1205            BitBuffer::new_set(len),
1206            BitBuffer::new_unset(len),
1207        ] {
1208            let expected: Vec<usize> = bits
1209                .iter()
1210                .enumerate()
1211                .filter_map(|(index, set)| (!set).then_some(index))
1212                .collect();
1213            let mut found = Vec::new();
1214            bits.for_each_unset_index(|index| found.push(index));
1215            assert_eq!(found, expected);
1216        }
1217        Ok(())
1218    }
1219
1220    #[test]
1221    fn test_map_cmp_conditional() {
1222        // map_cmp with conditional logic based on index and bit value
1223        let len = 100;
1224        let buf = BitBuffer::collect_bool(len, |i| i % 2 == 0);
1225
1226        // Only keep bits that are set AND at even index divisible by 4
1227        let mapped = buf.map_cmp(|idx, bit| bit && idx % 4 == 0);
1228
1229        for i in 0..len {
1230            let expected = (i % 2 == 0) && (i % 4 == 0);
1231            assert_eq!(mapped.value(i), expected, "Mismatch at index {}", i);
1232        }
1233    }
1234
1235    #[rstest]
1236    #[case(0, 200)]
1237    #[case(3, 197)]
1238    #[case(13, 600)]
1239    fn test_select_unset_sliced(#[case] start: usize, #[case] len: usize) {
1240        let buf = BitBuffer::collect_bool(start + len, |i| i % 3 == 0 || i % 7 == 0);
1241        let sliced = buf.slice(start..start + len);
1242        let expected: Vec<usize> = sliced
1243            .iter()
1244            .enumerate()
1245            .filter_map(|(index, set)| (!set).then_some(index))
1246            .collect();
1247
1248        for (nth, &index) in expected.iter().enumerate() {
1249            assert_eq!(
1250                sliced.select_unset(nth),
1251                Some(index),
1252                "start={start} nth={nth}"
1253            );
1254        }
1255        assert_eq!(sliced.select_unset(expected.len()), None);
1256    }
1257}