Skip to main content

arrow_buffer/util/
bit_iterator.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
5//! Types for iterating over packed bitmasks
6
7use crate::bit_chunk_iterator::{
8    BitChunkIterator, BitChunks, UnalignedBitChunk, UnalignedBitChunkIterator,
9};
10use crate::bit_util::{ceil, get_bit_raw};
11use std::ops::Range;
12
13/// Iterator over the bits within a packed bitmask
14///
15/// To efficiently iterate over just the set bits see [`BitIndexIterator`] and [`BitSliceIterator`]
16#[derive(Clone)]
17pub struct BitIterator<'a> {
18    buffer: &'a [u8],
19    current_offset: usize,
20    end_offset: usize,
21}
22
23impl<'a> BitIterator<'a> {
24    /// Create a new [`BitIterator`] from the provided `buffer`,
25    /// and `offset` and `len` in bits
26    ///
27    /// # Panics
28    ///
29    /// Panics if `buffer` is too short for the provided offset and length
30    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
31        let end_offset = offset.checked_add(len).unwrap();
32        let required_len = ceil(end_offset, 8);
33        assert!(
34            buffer.len() >= required_len,
35            "BitIterator buffer too small, expected {required_len} got {}",
36            buffer.len()
37        );
38
39        Self {
40            buffer,
41            current_offset: offset,
42            end_offset,
43        }
44    }
45}
46
47impl Iterator for BitIterator<'_> {
48    type Item = bool;
49
50    #[inline]
51    fn next(&mut self) -> Option<Self::Item> {
52        if self.current_offset == self.end_offset {
53            return None;
54        }
55        // Safety:
56        // offsets in bounds
57        let v = unsafe { get_bit_raw(self.buffer.as_ptr(), self.current_offset) };
58        self.current_offset += 1;
59        Some(v)
60    }
61
62    fn size_hint(&self) -> (usize, Option<usize>) {
63        let remaining_bits = self.end_offset - self.current_offset;
64        (remaining_bits, Some(remaining_bits))
65    }
66
67    fn count(self) -> usize
68    where
69        Self: Sized,
70    {
71        self.len()
72    }
73
74    #[inline]
75    fn nth(&mut self, n: usize) -> Option<Self::Item> {
76        // Check if we can advance to the desired offset.
77        // When n is 0 it means we want the next() value
78        // and when n is 1 we want the next().next() value
79        // so adding n to the current offset and not n - 1
80        match self.current_offset.checked_add(n) {
81            // Yes, and still within bounds
82            Some(new_offset) if new_offset < self.end_offset => {
83                self.current_offset = new_offset;
84            }
85
86            // Either overflow or would exceed end_offset
87            _ => {
88                self.current_offset = self.end_offset;
89                return None;
90            }
91        }
92
93        self.next()
94    }
95
96    fn last(mut self) -> Option<Self::Item> {
97        // If already at the end, return None
98        if self.current_offset == self.end_offset {
99            return None;
100        }
101
102        // Go to the one before the last bit
103        self.current_offset = self.end_offset - 1;
104
105        // Return the last bit
106        self.next()
107    }
108
109    fn max(self) -> Option<Self::Item>
110    where
111        Self: Sized,
112        Self::Item: Ord,
113    {
114        if self.current_offset == self.end_offset {
115            return None;
116        }
117
118        // true is greater than false so we only need to check if there's any true bit
119        let mut bit_index_iter = BitIndexIterator::new(
120            self.buffer,
121            self.current_offset,
122            self.end_offset - self.current_offset,
123        );
124
125        if bit_index_iter.next().is_some() {
126            return Some(true);
127        }
128
129        // We know the iterator is not empty and there are no set bits so false is the max
130        Some(false)
131    }
132}
133
134impl ExactSizeIterator for BitIterator<'_> {}
135
136impl DoubleEndedIterator for BitIterator<'_> {
137    fn next_back(&mut self) -> Option<Self::Item> {
138        if self.current_offset == self.end_offset {
139            return None;
140        }
141        self.end_offset -= 1;
142        // Safety:
143        // offsets in bounds
144        let v = unsafe { get_bit_raw(self.buffer.as_ptr(), self.end_offset) };
145        Some(v)
146    }
147
148    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
149        // Check if we can advance to the desired offset.
150        // When n is 0 it means we want the next_back() value
151        // and when n is 1 we want the next_back().next_back() value
152        // so subtracting n to the current offset and not n - 1
153        match self.end_offset.checked_sub(n) {
154            // Yes, and still within bounds
155            Some(new_offset) if self.current_offset < new_offset => {
156                self.end_offset = new_offset;
157            }
158
159            // Either underflow or would exceed current_offset
160            _ => {
161                self.current_offset = self.end_offset;
162                return None;
163            }
164        }
165
166        self.next_back()
167    }
168}
169
170/// Iterator of contiguous ranges of set bits within a provided packed bitmask
171///
172/// Returns `(usize, usize)` each representing an interval where the corresponding
173/// bits in the provides mask are set
174///
175/// the first value is the start of the range (inclusive) and the second value is the end of the range (exclusive)
176///
177#[derive(Debug)]
178pub struct BitSliceIterator<'a> {
179    iter: UnalignedBitChunkIterator<'a>,
180    len: usize,
181    current_offset: i64,
182    current_chunk: u64,
183}
184
185impl<'a> BitSliceIterator<'a> {
186    /// Create a new [`BitSliceIterator`] from the provided `buffer`,
187    /// and `offset` and `len` in bits
188    #[inline]
189    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
190        let chunk = UnalignedBitChunk::new(buffer, offset, len);
191        let mut iter = chunk.iter();
192
193        let current_offset = -(chunk.lead_padding() as i64);
194        let current_chunk = iter.next().unwrap_or(0);
195
196        Self {
197            iter,
198            len,
199            current_offset,
200            current_chunk,
201        }
202    }
203
204    /// Returns `Some((chunk_offset, bit_offset))` for the next chunk that has at
205    /// least one bit set, or None if there is no such chunk.
206    ///
207    /// Where `chunk_offset` is the bit offset to the current `u64` chunk
208    /// and `bit_offset` is the offset of the first `1` bit in that chunk
209    #[inline]
210    fn advance_to_set_bit(&mut self) -> Option<(i64, u32)> {
211        loop {
212            if self.current_chunk != 0 {
213                // Find the index of the first 1
214                let bit_pos = self.current_chunk.trailing_zeros();
215                return Some((self.current_offset, bit_pos));
216            }
217
218            self.current_chunk = self.iter.next()?;
219            self.current_offset += 64;
220        }
221    }
222}
223
224impl Iterator for BitSliceIterator<'_> {
225    type Item = (usize, usize);
226
227    #[inline]
228    fn next(&mut self) -> Option<Self::Item> {
229        // Used as termination condition
230        if self.len == 0 {
231            return None;
232        }
233
234        let (start_chunk, start_bit) = self.advance_to_set_bit()?;
235
236        // Set bits up to start
237        self.current_chunk |= (1 << start_bit) - 1;
238
239        loop {
240            if self.current_chunk != u64::MAX {
241                // Find the index of the first 0
242                let end_bit = self.current_chunk.trailing_ones();
243
244                // Zero out up to end_bit
245                self.current_chunk &= !((1 << end_bit) - 1);
246
247                return Some((
248                    (start_chunk + start_bit as i64) as usize,
249                    (self.current_offset + end_bit as i64) as usize,
250                ));
251            }
252
253            match self.iter.next() {
254                Some(next) => {
255                    self.current_chunk = next;
256                    self.current_offset += 64;
257                }
258                None => {
259                    return Some((
260                        (start_chunk + start_bit as i64) as usize,
261                        std::mem::replace(&mut self.len, 0),
262                    ));
263                }
264            }
265        }
266    }
267}
268
269/// An iterator of `usize` whose index in a provided bitmask is true
270///
271/// This provides the best performance on most masks, apart from those which contain
272/// large runs and therefore favour [`BitSliceIterator`]
273#[derive(Debug)]
274pub struct BitIndexIterator<'a> {
275    current_chunk: u64,
276    chunk_offset: i64,
277    iter: UnalignedBitChunkIterator<'a>,
278}
279
280impl<'a> BitIndexIterator<'a> {
281    /// Create a new [`BitIndexIterator`] from the provide `buffer`,
282    /// and `offset` and `len` in bits
283    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
284        let chunks = UnalignedBitChunk::new(buffer, offset, len);
285        let mut iter = chunks.iter();
286
287        let current_chunk = iter.next().unwrap_or(0);
288        let chunk_offset = -(chunks.lead_padding() as i64);
289
290        Self {
291            current_chunk,
292            chunk_offset,
293            iter,
294        }
295    }
296}
297
298impl Iterator for BitIndexIterator<'_> {
299    type Item = usize;
300
301    #[inline(always)]
302    fn next(&mut self) -> Option<Self::Item> {
303        loop {
304            if self.current_chunk != 0 {
305                let bit_pos = self.current_chunk.trailing_zeros();
306                self.current_chunk &= self.current_chunk - 1;
307                return Some((self.chunk_offset + bit_pos as i64) as usize);
308            }
309
310            self.current_chunk = self.iter.next()?;
311            self.chunk_offset += 64;
312        }
313    }
314}
315
316/// An iterator of u32 whose index in a provided bitmask is true
317/// Respects arbitrary offsets and slice lead/trail padding exactly like BitIndexIterator
318#[derive(Debug)]
319pub struct BitIndexU32Iterator<'a> {
320    curr: u64,
321    chunk_offset: i64,
322    iter: UnalignedBitChunkIterator<'a>,
323}
324
325impl<'a> BitIndexU32Iterator<'a> {
326    /// Create a new [BitIndexU32Iterator] from the provided buffer,
327    /// offset and len in bits.
328    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
329        // Build the aligned chunks (including prefix/suffix masked)
330        let chunks = UnalignedBitChunk::new(buffer, offset, len);
331        let mut iter = chunks.iter();
332
333        // First 64-bit word (masked for lead padding), or 0 if empty
334        let curr = iter.next().unwrap_or(0);
335        // Negative lead padding ensures the first bit in curr maps to index 0
336        let chunk_offset = -(chunks.lead_padding() as i64);
337
338        Self {
339            curr,
340            chunk_offset,
341            iter,
342        }
343    }
344}
345
346impl Iterator for BitIndexU32Iterator<'_> {
347    type Item = u32;
348
349    #[inline(always)]
350    fn next(&mut self) -> Option<u32> {
351        loop {
352            if self.curr != 0 {
353                // Position of least-significant set bit
354                let tz = self.curr.trailing_zeros();
355                // Clear that bit
356                self.curr &= self.curr - 1;
357                // Return global index = chunk_offset + tz
358                return Some((self.chunk_offset + tz as i64) as u32);
359            }
360            // Advance to next 64-bit chunk
361            let next_chunk = self.iter.next()?;
362            // Move offset forward by 64 bits
363            self.chunk_offset += 64;
364            self.curr = next_chunk;
365        }
366    }
367}
368
369/// Counts the set bits in ranges of a packed bitmask
370///
371/// [`Self::count_range`] returns the number of set bits in a range, and
372/// [`Self::count_before`] the number before a position. A result depends only
373/// on the arguments, so calls can come in any order and repeat.
374///
375/// # Example
376/// ```
377/// # use arrow_buffer::BooleanBuffer;
378/// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]);
379/// let mut counter = bits.set_bit_counter();
380/// assert_eq!(counter.count_range(0..2), 1);
381/// assert_eq!(counter.count_range(2..4), 2);
382/// assert_eq!(counter.count_before(6), 4);
383/// // Calls can go back, and a repeated call returns the same count
384/// assert_eq!(counter.count_range(0..2), 1);
385/// ```
386///
387/// # Performance
388///
389/// The counter keeps the 64-bit word that holds the last position, and a call
390/// reads the words between that position and the new one. When positions do
391/// not decrease, as in a pass over the rows of a list, each word is read once,
392/// and a call within the current word costs a mask and a popcount. Calling
393/// [`Buffer::count_set_bits_offset`] for each range instead pays a setup cost on
394/// every call, which dominates for short ranges.
395///
396/// When positions jump across the bitmask, such as the rows of a list view in
397/// random order, a call reads every word it jumps over. Calling
398/// [`Buffer::count_set_bits_offset`] for each range is faster there.
399///
400/// # Example: Count the valid elements of each row of a list
401/// ```
402/// # use arrow_buffer::{BooleanBuffer, OffsetBuffer};
403/// // A list with rows of 3, 0, and 3 elements, and the validity of its elements
404/// let offsets = OffsetBuffer::<i32>::from_lengths([3, 0, 3]);
405/// let valid = BooleanBuffer::from(vec![true, false, true, true, false, true]);
406///
407/// // One counter for all rows. The rows are visited in order, so each word of
408/// // `valid` is read once.
409/// let mut counter = valid.set_bit_counter();
410/// // Each pair of adjacent offsets is the start and end of a row
411/// let valid_per_row: Vec<usize> = offsets
412///     .windows(2)
413///     .map(|w| counter.count_range(w[0] as usize..w[1] as usize))
414///     .collect();
415/// assert_eq!(valid_per_row, [2, 0, 2]);
416/// ```
417///
418/// [`Buffer::count_set_bits_offset`]: crate::Buffer::count_set_bits_offset
419#[derive(Debug)]
420pub struct SetBitCounter<'a> {
421    chunks: BitChunks<'a>,
422    /// Yields the words after `word`
423    iter: BitChunkIterator<'a>,
424    /// The bitmask's final partial word, zero padded
425    remainder: u64,
426    /// The word containing the most recent position
427    word: u64,
428    /// Position of the first bit of `word`
429    word_start: usize,
430    /// Set bits before `word_start`
431    count_before_word: usize,
432    len: usize,
433}
434
435impl<'a> SetBitCounter<'a> {
436    /// Create a new [`SetBitCounter`] from the provided `buffer`,
437    /// and `offset` and `len` in bits
438    ///
439    /// ```
440    /// # use arrow_buffer::bit_iterator::SetBitCounter;
441    /// // Bits 3..9 of the buffer are 1, 0, 1, 1, 0, 1
442    /// let mut counter = SetBitCounter::new(&[0b0110_1000, 0b0000_0001], 3, 6);
443    /// assert_eq!(counter.count_range(2..4), 2);
444    /// assert_eq!(counter.count_before(6), 4);
445    /// ```
446    ///
447    /// # Panics
448    ///
449    /// Panics if `buffer` is too short for the provided offset and length
450    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
451        let chunks = BitChunks::new(buffer, offset, len);
452        let mut counter = Self {
453            iter: chunks.iter(),
454            remainder: chunks.remainder_bits(),
455            chunks,
456            word: 0,
457            word_start: 0,
458            count_before_word: 0,
459            len,
460        };
461        counter.word = counter.next_word();
462        counter
463    }
464
465    #[inline]
466    fn next_word(&mut self) -> u64 {
467        self.iter.next().unwrap_or(self.remainder)
468    }
469
470    // Cold and out of line because callers that pass positions in order never
471    // call it, and inlining would copy it into every caller of the inlined
472    // `count_before`.
473    #[cold]
474    fn step_back(&mut self, end: usize) {
475        while end < self.word_start {
476            self.word_start -= 64;
477            // A word before the current one is never the remainder
478            self.word = self.chunks.chunk(self.word_start / 64);
479            self.count_before_word -= self.word.count_ones() as usize;
480        }
481        // Leave `iter` after `word`
482        self.iter = self.chunks.iter();
483        self.iter.nth(self.word_start / 64);
484    }
485
486    /// Returns the number of set bits before position `end`
487    ///
488    /// ```
489    /// # use arrow_buffer::BooleanBuffer;
490    /// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]);
491    /// let mut counter = bits.set_bit_counter();
492    /// assert_eq!(counter.count_before(0), 0);
493    /// assert_eq!(counter.count_before(3), 2);
494    /// assert_eq!(counter.count_before(6), 4);
495    /// ```
496    ///
497    /// # Panics
498    ///
499    /// Panics if `end` is greater than the length of the bitmask
500    #[inline]
501    pub fn count_before(&mut self, end: usize) -> usize {
502        assert!(
503            end <= self.len,
504            "position {end} out of bounds for length {}",
505            self.len
506        );
507        if end < self.word_start {
508            self.step_back(end);
509        }
510        while end - self.word_start >= 64 {
511            self.count_before_word += self.word.count_ones() as usize;
512            self.word = self.next_word();
513            self.word_start += 64;
514        }
515        let mask = (1u64 << (end - self.word_start)) - 1;
516        self.count_before_word + (self.word & mask).count_ones() as usize
517    }
518
519    /// Returns the number of set bits in `range`
520    ///
521    /// ```
522    /// # use arrow_buffer::BooleanBuffer;
523    /// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]);
524    /// let mut counter = bits.set_bit_counter();
525    /// assert_eq!(counter.count_range(0..2), 1);
526    /// assert_eq!(counter.count_range(2..2), 0);
527    /// assert_eq!(counter.count_range(2..4), 2);
528    /// ```
529    ///
530    /// # Panics
531    ///
532    /// Panics if `range.start` is greater than `range.end`, or if `range.end`
533    /// is greater than the length of the bitmask
534    #[inline]
535    pub fn count_range(&mut self, range: Range<usize>) -> usize {
536        assert!(
537            range.start <= range.end,
538            "range start {} is greater than end {}",
539            range.start,
540            range.end
541        );
542        let before = self.count_before(range.start);
543        self.count_before(range.end) - before
544    }
545}
546
547/// Calls the provided closure for each index in the provided null mask that is set,
548/// using an adaptive strategy based on the null count
549///
550/// Ideally this would be encapsulated in an [`Iterator`] that would determine the optimal
551/// strategy up front, and then yield indexes based on this.
552///
553/// Unfortunately, external iteration based on the resulting [`Iterator`] would match the strategy
554/// variant on each call to [`Iterator::next`], and LLVM generally cannot eliminate this.
555///
556/// One solution to this might be internal iteration, e.g. [`Iterator::try_fold`], however,
557/// it is currently [not possible] to override this for custom iterators in stable Rust.
558///
559/// As such this is the next best option
560///
561/// [not possible]: https://github.com/rust-lang/rust/issues/69595
562#[inline]
563pub fn try_for_each_valid_idx<E, F: FnMut(usize) -> Result<(), E>>(
564    len: usize,
565    offset: usize,
566    null_count: usize,
567    nulls: Option<&[u8]>,
568    f: F,
569) -> Result<(), E> {
570    let valid_count = len - null_count;
571
572    if valid_count == len {
573        (0..len).try_for_each(f)
574    } else if null_count != len {
575        BitIndexIterator::new(nulls.unwrap(), offset, len).try_for_each(f)
576    } else {
577        Ok(())
578    }
579}
580
581// Note: further tests located in arrow_select::filter module
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586    use crate::BooleanBuffer;
587    use rand::rngs::StdRng;
588    use rand::{RngExt, SeedableRng};
589    use std::fmt::Debug;
590    use std::iter::Copied;
591    use std::slice::Iter;
592
593    #[test]
594    fn test_bit_iterator_size_hint() {
595        let mut b = BitIterator::new(&[0b00000011], 0, 2);
596        assert_eq!(
597            b.size_hint(),
598            (2, Some(2)),
599            "Expected size_hint to be (2, Some(2))"
600        );
601
602        b.next();
603        assert_eq!(
604            b.size_hint(),
605            (1, Some(1)),
606            "Expected size_hint to be (1, Some(1)) after one bit consumed"
607        );
608
609        b.next();
610        assert_eq!(
611            b.size_hint(),
612            (0, Some(0)),
613            "Expected size_hint to be (0, Some(0)) after all bits consumed"
614        );
615    }
616
617    #[test]
618    fn test_bit_iterator() {
619        let mask = &[0b00010010, 0b00100011, 0b00000101, 0b00010001, 0b10010011];
620        let actual: Vec<_> = BitIterator::new(mask, 0, 5).collect();
621        assert_eq!(actual, &[false, true, false, false, true]);
622
623        let actual: Vec<_> = BitIterator::new(mask, 4, 5).collect();
624        assert_eq!(actual, &[true, false, false, false, true]);
625
626        let actual: Vec<_> = BitIterator::new(mask, 12, 14).collect();
627        assert_eq!(
628            actual,
629            &[
630                false, true, false, false, true, false, true, false, false, false, false, false,
631                true, false
632            ]
633        );
634
635        assert_eq!(BitIterator::new(mask, 0, 0).count(), 0);
636        assert_eq!(BitIterator::new(mask, 40, 0).count(), 0);
637    }
638
639    #[test]
640    #[should_panic(expected = "BitIterator buffer too small, expected 3 got 2")]
641    fn test_bit_iterator_bounds() {
642        let mask = &[223, 23];
643        BitIterator::new(mask, 17, 0);
644    }
645
646    #[test]
647    fn test_bit_index_u32_iterator_basic() {
648        let mask = &[0b00010010, 0b00100011];
649
650        let result: Vec<u32> = BitIndexU32Iterator::new(mask, 0, 16).collect();
651        let expected: Vec<u32> = BitIndexIterator::new(mask, 0, 16)
652            .map(|i| i as u32)
653            .collect();
654        assert_eq!(result, expected);
655
656        let result: Vec<u32> = BitIndexU32Iterator::new(mask, 4, 8).collect();
657        let expected: Vec<u32> = BitIndexIterator::new(mask, 4, 8)
658            .map(|i| i as u32)
659            .collect();
660        assert_eq!(result, expected);
661
662        let result: Vec<u32> = BitIndexU32Iterator::new(mask, 10, 4).collect();
663        let expected: Vec<u32> = BitIndexIterator::new(mask, 10, 4)
664            .map(|i| i as u32)
665            .collect();
666        assert_eq!(result, expected);
667
668        let result: Vec<u32> = BitIndexU32Iterator::new(mask, 0, 0).collect();
669        let expected: Vec<u32> = BitIndexIterator::new(mask, 0, 0)
670            .map(|i| i as u32)
671            .collect();
672        assert_eq!(result, expected);
673    }
674
675    #[test]
676    fn test_bit_index_u32_iterator_all_set() {
677        let mask = &[0xFF, 0xFF];
678        let result: Vec<u32> = BitIndexU32Iterator::new(mask, 0, 16).collect();
679        let expected: Vec<u32> = BitIndexIterator::new(mask, 0, 16)
680            .map(|i| i as u32)
681            .collect();
682        assert_eq!(result, expected);
683    }
684
685    #[test]
686    fn test_bit_index_u32_iterator_none_set() {
687        let mask = &[0x00, 0x00];
688        let result: Vec<u32> = BitIndexU32Iterator::new(mask, 0, 16).collect();
689        let expected: Vec<u32> = BitIndexIterator::new(mask, 0, 16)
690            .map(|i| i as u32)
691            .collect();
692        assert_eq!(result, expected);
693    }
694
695    #[test]
696    fn test_bit_index_u32_cross_chunk() {
697        let mut buf = vec![0u8; 16];
698        for bit in 60..68 {
699            let byte = (bit / 8) as usize;
700            let bit_in_byte = bit % 8;
701            buf[byte] |= 1 << bit_in_byte;
702        }
703        let offset = 58;
704        let len = 10;
705
706        let result: Vec<u32> = BitIndexU32Iterator::new(&buf, offset, len).collect();
707        let expected: Vec<u32> = BitIndexIterator::new(&buf, offset, len)
708            .map(|i| i as u32)
709            .collect();
710        assert_eq!(result, expected);
711    }
712
713    #[test]
714    fn test_bit_index_u32_unaligned_offset() {
715        let mask = &[0b0110_1100, 0b1010_0000];
716        let offset = 2;
717        let len = 12;
718
719        let result: Vec<u32> = BitIndexU32Iterator::new(mask, offset, len).collect();
720        let expected: Vec<u32> = BitIndexIterator::new(mask, offset, len)
721            .map(|i| i as u32)
722            .collect();
723        assert_eq!(result, expected);
724    }
725
726    #[test]
727    fn test_bit_index_u32_long_all_set() {
728        let len = 200;
729        let num_bytes = len / 8 + usize::from(len % 8 != 0);
730        let bytes = vec![0xFFu8; num_bytes];
731
732        let result: Vec<u32> = BitIndexU32Iterator::new(&bytes, 0, len).collect();
733        let expected: Vec<u32> = BitIndexIterator::new(&bytes, 0, len)
734            .map(|i| i as u32)
735            .collect();
736        assert_eq!(result, expected);
737    }
738
739    #[test]
740    fn test_bit_index_u32_none_set() {
741        let len = 50;
742        let num_bytes = len / 8 + usize::from(len % 8 != 0);
743        let bytes = vec![0u8; num_bytes];
744
745        let result: Vec<u32> = BitIndexU32Iterator::new(&bytes, 0, len).collect();
746        let expected: Vec<u32> = BitIndexIterator::new(&bytes, 0, len)
747            .map(|i| i as u32)
748            .collect();
749        assert_eq!(result, expected);
750    }
751
752    trait SharedBetweenBitIteratorAndSliceIter:
753        ExactSizeIterator<Item = bool> + DoubleEndedIterator<Item = bool>
754    {
755    }
756    impl<T: ?Sized + ExactSizeIterator<Item = bool> + DoubleEndedIterator<Item = bool>>
757        SharedBetweenBitIteratorAndSliceIter for T
758    {
759    }
760
761    fn get_bit_iterator_cases() -> impl Iterator<Item = (BooleanBuffer, Vec<bool>)> {
762        let mut rng = StdRng::seed_from_u64(42);
763
764        [0, 1, 6, 8, 100, 164]
765            .map(|len| {
766                let source = (0..len).map(|_| rng.random_bool(0.5)).collect::<Vec<_>>();
767
768                (BooleanBuffer::from(source.as_slice()), source)
769            })
770            .into_iter()
771    }
772
773    fn setup_and_assert(
774        setup_iters: impl Fn(&mut dyn SharedBetweenBitIteratorAndSliceIter),
775        assert_fn: impl Fn(BitIterator, Copied<Iter<bool>>),
776    ) {
777        for (boolean_buffer, source) in get_bit_iterator_cases() {
778            // Not using `boolean_buffer.iter()` in case the implementation change to not call BitIterator internally
779            // in which case the test would not test what it intends to test
780            let mut actual = BitIterator::new(boolean_buffer.values(), 0, boolean_buffer.len());
781            let mut expected = source.iter().copied();
782
783            setup_iters(&mut actual);
784            setup_iters(&mut expected);
785
786            assert_fn(actual, expected);
787        }
788    }
789
790    /// Trait representing an operation on a BitIterator
791    /// that can be compared against a slice iterator
792    trait BitIteratorOp {
793        /// What the operation returns (e.g. Option<bool> for last/max, usize for count, etc)
794        type Output: PartialEq + Debug;
795
796        /// The name of the operation, used for error messages
797        const NAME: &'static str;
798
799        /// Get the value of the operation for the provided iterator
800        /// This will be either a BitIterator or a slice iterator to make sure they produce the same result
801        fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(iter: T) -> Self::Output;
802    }
803
804    /// Helper function that will assert that the provided operation
805    /// produces the same result for both BitIterator and slice iterator
806    /// under various consumption patterns (e.g. some calls to next/next_back/consume_all/etc)
807    fn assert_bit_iterator_cases<O: BitIteratorOp>() {
808        setup_and_assert(
809            |_iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {},
810            |actual, expected| {
811                let current_iterator_values: Vec<bool> = expected.clone().collect();
812                assert_eq!(
813                    O::get_value(actual),
814                    O::get_value(expected),
815                    "Failed on op {} for new iter (left actual, right expected) ({current_iterator_values:?})",
816                    O::NAME
817                );
818            },
819        );
820
821        setup_and_assert(
822            |iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {
823                iter.next();
824            },
825            |actual, expected| {
826                let current_iterator_values: Vec<bool> = expected.clone().collect();
827
828                assert_eq!(
829                    O::get_value(actual),
830                    O::get_value(expected),
831                    "Failed on op {} for new iter after consuming 1 element from the start (left actual, right expected) ({current_iterator_values:?})",
832                    O::NAME
833                );
834            },
835        );
836
837        setup_and_assert(
838            |iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {
839                iter.next_back();
840            },
841            |actual, expected| {
842                let current_iterator_values: Vec<bool> = expected.clone().collect();
843
844                assert_eq!(
845                    O::get_value(actual),
846                    O::get_value(expected),
847                    "Failed on op {} for new iter after consuming 1 element from the end (left actual, right expected) ({current_iterator_values:?})",
848                    O::NAME
849                );
850            },
851        );
852
853        setup_and_assert(
854            |iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {
855                iter.next();
856                iter.next_back();
857            },
858            |actual, expected| {
859                let current_iterator_values: Vec<bool> = expected.clone().collect();
860
861                assert_eq!(
862                    O::get_value(actual),
863                    O::get_value(expected),
864                    "Failed on op {} for new iter after consuming 1 element from start and end (left actual, right expected) ({current_iterator_values:?})",
865                    O::NAME
866                );
867            },
868        );
869
870        setup_and_assert(
871            |iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {
872                while iter.len() > 1 {
873                    iter.next();
874                }
875            },
876            |actual, expected| {
877                let current_iterator_values: Vec<bool> = expected.clone().collect();
878
879                assert_eq!(
880                    O::get_value(actual),
881                    O::get_value(expected),
882                    "Failed on op {} for new iter after consuming all from the start but 1 (left actual, right expected) ({current_iterator_values:?})",
883                    O::NAME
884                );
885            },
886        );
887
888        setup_and_assert(
889            |iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {
890                while iter.len() > 1 {
891                    iter.next_back();
892                }
893            },
894            |actual, expected| {
895                let current_iterator_values: Vec<bool> = expected.clone().collect();
896
897                assert_eq!(
898                    O::get_value(actual),
899                    O::get_value(expected),
900                    "Failed on op {} for new iter after consuming all from the end but 1 (left actual, right expected) ({current_iterator_values:?})",
901                    O::NAME
902                );
903            },
904        );
905
906        setup_and_assert(
907            |iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {
908                while iter.next().is_some() {}
909            },
910            |actual, expected| {
911                let current_iterator_values: Vec<bool> = expected.clone().collect();
912
913                assert_eq!(
914                    O::get_value(actual),
915                    O::get_value(expected),
916                    "Failed on op {} for new iter after consuming all from the start (left actual, right expected) ({current_iterator_values:?})",
917                    O::NAME
918                );
919            },
920        );
921
922        setup_and_assert(
923            |iter: &mut dyn SharedBetweenBitIteratorAndSliceIter| {
924                while iter.next_back().is_some() {}
925            },
926            |actual, expected| {
927                let current_iterator_values: Vec<bool> = expected.clone().collect();
928
929                assert_eq!(
930                    O::get_value(actual),
931                    O::get_value(expected),
932                    "Failed on op {} for new iter after consuming all from the end (left actual, right expected) ({current_iterator_values:?})",
933                    O::NAME
934                );
935            },
936        );
937    }
938
939    #[test]
940    fn assert_bit_iterator_count() {
941        struct CountOp;
942
943        impl BitIteratorOp for CountOp {
944            type Output = usize;
945            const NAME: &'static str = "count";
946
947            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(iter: T) -> Self::Output {
948                iter.count()
949            }
950        }
951
952        assert_bit_iterator_cases::<CountOp>()
953    }
954
955    #[test]
956    fn assert_bit_iterator_last() {
957        struct LastOp;
958
959        impl BitIteratorOp for LastOp {
960            type Output = Option<bool>;
961            const NAME: &'static str = "last";
962
963            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(iter: T) -> Self::Output {
964                iter.last()
965            }
966        }
967
968        assert_bit_iterator_cases::<LastOp>()
969    }
970
971    #[test]
972    fn assert_bit_iterator_max() {
973        struct MaxOp;
974
975        impl BitIteratorOp for MaxOp {
976            type Output = Option<bool>;
977            const NAME: &'static str = "max";
978
979            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(iter: T) -> Self::Output {
980                iter.max()
981            }
982        }
983
984        assert_bit_iterator_cases::<MaxOp>()
985    }
986
987    #[test]
988    fn assert_bit_iterator_nth_0() {
989        struct NthOp<const BACK: bool>;
990
991        impl<const BACK: bool> BitIteratorOp for NthOp<BACK> {
992            type Output = Option<bool>;
993            const NAME: &'static str = if BACK { "nth_back(0)" } else { "nth(0)" };
994
995            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(mut iter: T) -> Self::Output {
996                if BACK { iter.nth_back(0) } else { iter.nth(0) }
997            }
998        }
999
1000        assert_bit_iterator_cases::<NthOp<false>>();
1001        assert_bit_iterator_cases::<NthOp<true>>();
1002    }
1003
1004    #[test]
1005    fn assert_bit_iterator_nth_1() {
1006        struct NthOp<const BACK: bool>;
1007
1008        impl<const BACK: bool> BitIteratorOp for NthOp<BACK> {
1009            type Output = Option<bool>;
1010            const NAME: &'static str = if BACK { "nth_back(1)" } else { "nth(1)" };
1011
1012            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(mut iter: T) -> Self::Output {
1013                if BACK { iter.nth_back(1) } else { iter.nth(1) }
1014            }
1015        }
1016
1017        assert_bit_iterator_cases::<NthOp<false>>();
1018        assert_bit_iterator_cases::<NthOp<true>>();
1019    }
1020
1021    #[test]
1022    fn assert_bit_iterator_nth_after_end() {
1023        struct NthOp<const BACK: bool>;
1024
1025        impl<const BACK: bool> BitIteratorOp for NthOp<BACK> {
1026            type Output = Option<bool>;
1027            const NAME: &'static str = if BACK {
1028                "nth_back(iter.len() + 1)"
1029            } else {
1030                "nth(iter.len() + 1)"
1031            };
1032
1033            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(mut iter: T) -> Self::Output {
1034                if BACK {
1035                    iter.nth_back(iter.len() + 1)
1036                } else {
1037                    iter.nth(iter.len() + 1)
1038                }
1039            }
1040        }
1041
1042        assert_bit_iterator_cases::<NthOp<false>>();
1043        assert_bit_iterator_cases::<NthOp<true>>();
1044    }
1045
1046    #[test]
1047    fn assert_bit_iterator_nth_len() {
1048        struct NthOp<const BACK: bool>;
1049
1050        impl<const BACK: bool> BitIteratorOp for NthOp<BACK> {
1051            type Output = Option<bool>;
1052            const NAME: &'static str = if BACK {
1053                "nth_back(iter.len())"
1054            } else {
1055                "nth(iter.len())"
1056            };
1057
1058            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(mut iter: T) -> Self::Output {
1059                if BACK {
1060                    iter.nth_back(iter.len())
1061                } else {
1062                    iter.nth(iter.len())
1063                }
1064            }
1065        }
1066
1067        assert_bit_iterator_cases::<NthOp<false>>();
1068        assert_bit_iterator_cases::<NthOp<true>>();
1069    }
1070
1071    #[test]
1072    fn assert_bit_iterator_nth_last() {
1073        struct NthOp<const BACK: bool>;
1074
1075        impl<const BACK: bool> BitIteratorOp for NthOp<BACK> {
1076            type Output = Option<bool>;
1077            const NAME: &'static str = if BACK {
1078                "nth_back(iter.len().saturating_sub(1))"
1079            } else {
1080                "nth(iter.len().saturating_sub(1))"
1081            };
1082
1083            fn get_value<T: SharedBetweenBitIteratorAndSliceIter>(mut iter: T) -> Self::Output {
1084                if BACK {
1085                    iter.nth_back(iter.len().saturating_sub(1))
1086                } else {
1087                    iter.nth(iter.len().saturating_sub(1))
1088                }
1089            }
1090        }
1091
1092        assert_bit_iterator_cases::<NthOp<false>>();
1093        assert_bit_iterator_cases::<NthOp<true>>();
1094    }
1095
1096    #[test]
1097    fn assert_bit_iterator_nth_and_reuse() {
1098        setup_and_assert(
1099            |_| {},
1100            |actual, expected| {
1101                {
1102                    let mut actual = actual.clone();
1103                    let mut expected = expected.clone();
1104                    for _ in 0..expected.len() {
1105                        #[expect(clippy::iter_nth_zero)]
1106                        let actual_val = actual.nth(0);
1107                        #[expect(clippy::iter_nth_zero)]
1108                        let expected_val = expected.nth(0);
1109                        assert_eq!(actual_val, expected_val, "Failed on nth(0)");
1110                    }
1111                }
1112
1113                {
1114                    let mut actual = actual.clone();
1115                    let mut expected = expected.clone();
1116                    for _ in 0..expected.len() {
1117                        let actual_val = actual.nth(1);
1118                        let expected_val = expected.nth(1);
1119                        assert_eq!(actual_val, expected_val, "Failed on nth(1)");
1120                    }
1121                }
1122
1123                {
1124                    let mut actual = actual.clone();
1125                    let mut expected = expected.clone();
1126                    for _ in 0..expected.len() {
1127                        let actual_val = actual.nth(2);
1128                        let expected_val = expected.nth(2);
1129                        assert_eq!(actual_val, expected_val, "Failed on nth(2)");
1130                    }
1131                }
1132            },
1133        );
1134    }
1135
1136    #[test]
1137    fn assert_bit_iterator_nth_back_and_reuse() {
1138        setup_and_assert(
1139            |_| {},
1140            |actual, expected| {
1141                {
1142                    let mut actual = actual.clone();
1143                    let mut expected = expected.clone();
1144                    for _ in 0..expected.len() {
1145                        let actual_val = actual.nth_back(0);
1146                        let expected_val = expected.nth_back(0);
1147                        assert_eq!(actual_val, expected_val, "Failed on nth_back(0)");
1148                    }
1149                }
1150
1151                {
1152                    let mut actual = actual.clone();
1153                    let mut expected = expected.clone();
1154                    for _ in 0..expected.len() {
1155                        let actual_val = actual.nth_back(1);
1156                        let expected_val = expected.nth_back(1);
1157                        assert_eq!(actual_val, expected_val, "Failed on nth_back(1)");
1158                    }
1159                }
1160
1161                {
1162                    let mut actual = actual.clone();
1163                    let mut expected = expected.clone();
1164                    for _ in 0..expected.len() {
1165                        let actual_val = actual.nth_back(2);
1166                        let expected_val = expected.nth_back(2);
1167                        assert_eq!(actual_val, expected_val, "Failed on nth_back(2)");
1168                    }
1169                }
1170            },
1171        );
1172    }
1173
1174    /// Sliced buffers covering empty, sub-word, exact-word, and multi-word
1175    /// lengths at byte-aligned and unaligned offsets, with their bits.
1176    fn set_bit_counter_cases() -> Vec<(BooleanBuffer, Vec<bool>)> {
1177        let mut rng = StdRng::seed_from_u64(42);
1178        let mut cases = vec![];
1179        for len in [0, 1, 63, 64, 65, 127, 128, 129, 300] {
1180            for offset in [0, 1, 7, 8, 63, 64, 67] {
1181                for density in [0.0, 0.5, 1.0] {
1182                    let bits = (0..offset + len)
1183                        .map(|_| rng.random_bool(density))
1184                        .collect::<Vec<_>>();
1185                    let buffer = BooleanBuffer::from(bits.as_slice()).slice(offset, len);
1186                    cases.push((buffer, bits[offset..].to_vec()));
1187                }
1188            }
1189        }
1190        cases
1191    }
1192
1193    fn count_set(bits: &[bool]) -> usize {
1194        bits.iter().filter(|&&b| b).count()
1195    }
1196
1197    #[test]
1198    fn test_set_bit_counter_every_position() {
1199        for (buffer, bits) in set_bit_counter_cases() {
1200            let mut counter = buffer.set_bit_counter();
1201            for end in 0..=bits.len() {
1202                assert_eq!(
1203                    counter.count_before(end),
1204                    count_set(&bits[..end]),
1205                    "offset {} len {} end {end}",
1206                    buffer.offset(),
1207                    buffer.len()
1208                );
1209            }
1210        }
1211    }
1212
1213    #[test]
1214    fn test_set_bit_counter_every_position_reversed() {
1215        for (buffer, bits) in set_bit_counter_cases() {
1216            let mut counter = buffer.set_bit_counter();
1217            for end in (0..=bits.len()).rev() {
1218                assert_eq!(
1219                    counter.count_before(end),
1220                    count_set(&bits[..end]),
1221                    "offset {} len {} end {end}",
1222                    buffer.offset(),
1223                    buffer.len()
1224                );
1225            }
1226        }
1227    }
1228
1229    #[test]
1230    fn test_set_bit_counter_shuffled_ranges() {
1231        let mut rng = StdRng::seed_from_u64(42);
1232        for (buffer, bits) in set_bit_counter_cases() {
1233            let len = bits.len();
1234            let mut counter = buffer.set_bit_counter();
1235            for _ in 0..100 {
1236                let start = rng.random_range(0..=len);
1237                let end = rng.random_range(start..=len);
1238                assert_eq!(
1239                    counter.count_range(start..end),
1240                    count_set(&bits[start..end]),
1241                    "offset {} len {len} range {start}..{end}",
1242                    buffer.offset()
1243                );
1244            }
1245        }
1246    }
1247
1248    #[test]
1249    fn test_set_bit_counter_ranges() {
1250        for (buffer, bits) in set_bit_counter_cases() {
1251            let len = bits.len();
1252            // Empty, contiguous, and gapped ranges, some spanning several words.
1253            let ranges = [
1254                (0, 0),
1255                (0, len / 3),
1256                (len / 3, len / 3),
1257                (len / 3, len / 2),
1258                (len / 2 + 1, len - len / 4),
1259                (len, len),
1260            ];
1261            let mut counter = buffer.set_bit_counter();
1262            for (start, end) in ranges {
1263                let (start, end) = (start.min(len), end.min(len));
1264                assert_eq!(
1265                    counter.count_range(start..end),
1266                    count_set(&bits[start..end]),
1267                    "offset {} len {len} range {start}..{end}",
1268                    buffer.offset()
1269                );
1270            }
1271        }
1272    }
1273
1274    #[test]
1275    fn test_set_bit_counter_decreasing_positions() {
1276        let bits = (0..300).map(|i| i % 3 != 0).collect::<Vec<_>>();
1277        let buffer = BooleanBuffer::from(bits.as_slice()).slice(5, 290);
1278        let bits = &bits[5..];
1279        let mut counter = buffer.set_bit_counter();
1280        // Back to an earlier word, back within the current word, then forward.
1281        for end in [290, 130, 10, 129, 128, 70, 64, 0, 200, 290] {
1282            assert_eq!(
1283                counter.count_before(end),
1284                count_set(&bits[..end]),
1285                "end {end}"
1286            );
1287        }
1288        assert_eq!(counter.count_range(10..20), count_set(&bits[10..20]));
1289    }
1290
1291    #[test]
1292    fn test_set_bit_counter_new() {
1293        // Bits 3..9 of 0b1011_0101, 0b0000_0001 are 0, 1, 1, 0, 1, 1.
1294        let mut counter = SetBitCounter::new(&[0b1011_0101, 0b0000_0001], 3, 6);
1295        assert_eq!(counter.count_before(0), 0);
1296        assert_eq!(counter.count_before(3), 2);
1297        assert_eq!(counter.count_before(6), 4);
1298    }
1299
1300    #[test]
1301    #[should_panic(expected = "position 4 out of bounds for length 3")]
1302    fn test_set_bit_counter_out_of_bounds() {
1303        let buffer = BooleanBuffer::from(&[true, false, true][..]);
1304        buffer.set_bit_counter().count_before(4);
1305    }
1306
1307    #[test]
1308    #[should_panic(expected = "position 1 out of bounds for length 0")]
1309    fn test_set_bit_counter_empty_out_of_bounds() {
1310        BooleanBuffer::new_unset(0)
1311            .set_bit_counter()
1312            .count_before(1);
1313    }
1314
1315    #[test]
1316    #[should_panic(expected = "range start 3 is greater than end 2")]
1317    #[expect(clippy::reversed_empty_ranges)]
1318    fn test_set_bit_counter_reversed_range() {
1319        let buffer = BooleanBuffer::new_set(10);
1320        buffer.set_bit_counter().count_range(3..2);
1321    }
1322
1323    #[test]
1324    #[should_panic(expected = "offset + len out of bounds")]
1325    fn test_set_bit_counter_new_buffer_too_short() {
1326        SetBitCounter::new(&[0xFF], 3, 6);
1327    }
1328}