Skip to main content

vortex_buffer/bit/
index_iterator.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Lazy set-bit iteration with bulk skipping of empty bitmap words.
5
6use std::iter::FusedIterator;
7
8use arrow_buffer::ToByteSlice;
9use vortex_error::VortexExpect;
10
11use crate::bit::UnalignedBitChunk;
12
13/// Iterates the logical positions of set bits in a bitmap, in ascending order.
14///
15/// The iterator borrows its bitmap and skips empty word ranges without materializing indices.
16/// Word preparation uses Arrow's bitmap chunking implementation and currently supports
17/// little-endian targets.
18#[derive(Debug)]
19pub struct BitIndexIterator<'a> {
20    current_chunk: u64,
21    // The logical index of bit zero in `current_chunk`. Only the first word can have a
22    // negative base: its masked leading padding precedes the logical bitmap's start.
23    chunk_offset: i64,
24    // Native-endian words after `current_chunk`, excluding the masked suffix. Testing for
25    // zero is byte-order independent; a word is converted from little endian when loaded.
26    chunks: &'a [u64],
27    suffix: Option<u64>,
28    len: usize,
29}
30
31impl<'a> BitIndexIterator<'a> {
32    /// Creates an iterator over `len` bits in `buffer`, starting at bit `offset`.
33    ///
34    /// A nonempty range requires `buffer` to cover every bit in `offset..offset + len`.
35    ///
36    /// # Panics
37    ///
38    /// Panics if a nonempty range extends beyond `buffer`.
39    #[inline]
40    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
41        let unaligned = UnalignedBitChunk::new(buffer, offset, len);
42        let mut chunks = unaligned.chunks();
43        let mut suffix = unaligned.suffix().filter(|&word| word != 0);
44        let current_chunk = if let Some(prefix) = unaligned.prefix() {
45            prefix
46        } else if let Some((&first, rest)) = chunks.split_first() {
47            chunks = rest;
48            u64::from_le(first)
49        } else {
50            suffix.take().unwrap_or(0)
51        };
52
53        Self {
54            current_chunk,
55            chunk_offset: -(unaligned.lead_padding() as i64),
56            chunks,
57            suffix,
58            len,
59        }
60    }
61
62    /// Discards remaining indices below `index`, without consuming any later index.
63    ///
64    /// Seeking backward does not restore consumed indices. Seeking to or beyond the logical
65    /// bitmap length exhausts the iterator.
66    #[inline]
67    pub fn seek_to(&mut self, index: usize) {
68        if index >= self.len {
69            self.current_chunk = 0;
70            self.chunks = &[];
71            self.suffix = None;
72            return;
73        }
74
75        // The leading padding can put this intermediate just beyond usize::MAX on 32-bit
76        // targets, even though the resulting word index still fits usize.
77        let relative = index as i128 - i128::from(self.chunk_offset);
78        if relative < 0 {
79            return;
80        }
81
82        let skipped = usize::try_from(relative / 64).vortex_expect("bitmap word index fits usize");
83        if skipped != 0 {
84            if skipped <= self.chunks.len() {
85                self.current_chunk = u64::from_le(self.chunks[skipped - 1]);
86                self.chunks = &self.chunks[skipped..];
87            } else {
88                self.current_chunk = self.suffix.take().unwrap_or(0);
89                self.chunks = &[];
90            }
91            self.chunk_offset += skipped as i64 * 64;
92        }
93        self.current_chunk &= u64::MAX << (relative % 64);
94    }
95
96    #[inline]
97    fn advance_to_nonzero_word(&mut self) -> Option<()> {
98        if self.chunks.is_empty() && self.suffix.is_none() {
99            return None;
100        }
101
102        let skipped = first_nonzero_word(self.chunks);
103
104        if let Some(&word) = self.chunks.get(skipped) {
105            self.current_chunk = u64::from_le(word);
106            self.chunks = &self.chunks[skipped + 1..];
107            self.chunk_offset += (skipped as i64 + 1) * 64;
108            return Some(());
109        }
110
111        let skipped = self.chunks.len();
112        self.chunks = &[];
113        let suffix = self.suffix.take()?;
114        self.chunk_offset += (skipped as i64 + 1) * 64;
115        self.current_chunk = suffix;
116        Some(())
117    }
118}
119
120impl Iterator for BitIndexIterator<'_> {
121    type Item = usize;
122
123    #[allow(clippy::inline_always)]
124    #[inline(always)]
125    fn next(&mut self) -> Option<Self::Item> {
126        if self.current_chunk == 0 {
127            self.advance_to_nonzero_word()?;
128        }
129
130        let bit = self.current_chunk.trailing_zeros();
131        self.current_chunk &= self.current_chunk - 1;
132        #[expect(
133            clippy::cast_possible_truncation,
134            reason = "masked padding and tail bits keep the index within the usize bitmap length"
135        )]
136        let index = (self.chunk_offset + i64::from(bit)) as usize;
137        Some(index)
138    }
139}
140
141impl FusedIterator for BitIndexIterator<'_> {}
142
143// Byte-sized position candidates let a SIMD minimum both skip empty blocks and locate
144// the first occupied word, without a second search through the winning block.
145#[inline]
146fn first_nonzero_word(words: &[u64]) -> usize {
147    // Avoid a block reduction when the next unread word is already occupied.
148    let Some((&word, words)) = words.split_first() else {
149        return 0;
150    };
151    if word != 0 {
152        return 0;
153    }
154
155    let (blocks, tail) = words.as_chunks::<8>();
156    for (index, block) in blocks.iter().enumerate() {
157        let bytes = block.as_slice().to_byte_slice();
158        let mut first = 64_u8;
159        for byte in 0_u8..64 {
160            first = first.min(if bytes[usize::from(byte)] != 0 {
161                byte
162            } else {
163                64
164            });
165        }
166        if first < 64 {
167            return 1 + index * 8 + usize::from(first) / 8;
168        }
169    }
170    1 + blocks.len() * 8
171        + tail
172            .iter()
173            .position(|&word| word != 0)
174            .unwrap_or(tail.len())
175}
176
177#[cfg(test)]
178mod tests {
179    use crate::BitBuffer;
180    use crate::bit::BitIndexIterator;
181
182    #[test]
183    fn iterates_offset_bitmap_without_padding() {
184        let bytes = [0b1101_0011, 0b1110_1001];
185        let actual: Vec<_> = BitIndexIterator::new(&bytes, 3, 9).collect();
186        assert_eq!(actual, [1, 3, 4, 5, 8]);
187    }
188
189    #[test]
190    fn skips_empty_words_and_preserves_tail() {
191        let bits = BitBuffer::from_indices(1_027, [0, 641, 1_026]);
192        assert_eq!(bits.set_indices().collect::<Vec<_>>(), [0, 641, 1_026]);
193    }
194
195    #[test]
196    fn handles_empty_and_all_set_bitmaps() {
197        assert_eq!(BitIndexIterator::new(&[], 0, 0).next(), None);
198        assert_eq!(BitIndexIterator::new(&[0, 0], 0, 9).next(), None);
199        assert_eq!(
200            BitIndexIterator::new(&[0xff], 2, 4).collect::<Vec<_>>(),
201            [0, 1, 2, 3]
202        );
203    }
204
205    #[test]
206    fn seeks_forward_without_restoring_consumed_bits() {
207        let bits = BitBuffer::from_indices(300, [0, 5, 63, 64, 130, 299]);
208        let mut indices = bits.set_indices();
209        assert_eq!(indices.next(), Some(0));
210        indices.seek_to(5);
211        assert_eq!(indices.next(), Some(5));
212        indices.seek_to(1);
213        assert_eq!(indices.next(), Some(63));
214        indices.seek_to(65);
215        assert_eq!(indices.next(), Some(130));
216        indices.seek_to(299);
217        assert_eq!(indices.next(), Some(299));
218        assert_eq!(indices.next(), None);
219        indices.seek_to(0);
220        assert_eq!(indices.next(), None);
221    }
222
223    #[test]
224    fn seeks_offset_bitmaps_and_clamps_past_end() {
225        let bytes = [0xff; 16];
226        let mut indices = BitIndexIterator::new(&bytes, 5, 100);
227        indices.seek_to(63);
228        assert_eq!(indices.next(), Some(63));
229        indices.seek_to(99);
230        assert_eq!(indices.next(), Some(99));
231        indices.seek_to(usize::MAX);
232        assert_eq!(indices.next(), None);
233    }
234}