Skip to main content

vortex_buffer/bit/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Packed bitmaps that can be used to store boolean values.
5//!
6//! This module provides a wrapper on top of the `Buffer` type to store mutable and immutable
7//! bitsets. The bitsets are stored in little-endian order, meaning that the least significant bit
8//! of the first byte is the first bit in the bitset.
9#[cfg(feature = "arrow")]
10mod arrow;
11mod buf;
12mod buf_mut;
13mod count_ones;
14mod index_iterator;
15mod macros;
16mod meta;
17mod ops;
18mod pack;
19mod select;
20mod take;
21mod view;
22
23pub use arrow_buffer::bit_chunk_iterator::BitChunkIterator;
24pub use arrow_buffer::bit_chunk_iterator::BitChunks;
25pub use arrow_buffer::bit_chunk_iterator::UnalignedBitChunk;
26pub use arrow_buffer::bit_chunk_iterator::UnalignedBitChunkIterator;
27pub use arrow_buffer::bit_iterator::BitIterator;
28pub use arrow_buffer::bit_iterator::BitSliceIterator;
29pub use buf::*;
30pub use buf_mut::*;
31pub use index_iterator::BitIndexIterator;
32pub use meta::*;
33pub use pack::*;
34pub use take::*;
35pub use view::*;
36
37/// Packs up to 64 boolean values into a little-endian `u64` word.
38///
39/// This is [`collect_bool_words`] for a single word: a full 64-bit word is materialized as a
40/// `[bool; 64]` and packed with the baseline SIMD byte→bit instruction of the target; shorter
41/// lengths fall back to the bit-at-a-time [`collect_bool_word_scalar`] loop.
42#[inline]
43pub fn collect_bool_word<F>(len: usize, f: F) -> u64
44where
45    F: FnMut(usize) -> bool,
46{
47    assert!(len <= 64, "cannot pack {len} bits into a u64 word");
48
49    let mut word = [0u64; 1];
50    collect_bool_words_inline(&mut word, len, f);
51    word[0]
52}
53
54/// Pack `len` boolean values returned by `f` into the prefix of `words`, LSB-first,
55/// 64 bits per `u64`. `words` must have capacity for at least `len.div_ceil(64)` entries.
56///
57/// `f` is invoked exactly once per index, in ascending order `0..len`.
58///
59/// Writes via `=` (not `|=`), so the destination need not be zero-initialised.
60///
61/// The word loop packs with the baseline SIMD kernel of the target (SSE2 on x86-64, NEON on
62/// aarch64), which inlines fully into the caller together with the predicate and the
63/// `[bool; 64]` materialization — wider kernels would sit behind a non-inlinable
64/// `#[target_feature]` boundary that deoptimizes expensive predicates. See
65/// [`BitBuffer::collect_bool`] for the performance note on
66/// avoiding bounds checks in `f`.
67///
68/// Prefer this entry point for every predicate; only switch to
69/// [`collect_bool_words_multiversioned`] after carefully checking that your specific `f`
70/// meets its contract.
71#[inline]
72pub fn collect_bool_words<F>(words: &mut [u64], len: usize, f: F)
73where
74    F: FnMut(usize) -> bool,
75{
76    let num_words = len.div_ceil(64);
77    assert!(
78        words.len() >= num_words,
79        "words slice has {} entries, need at least {num_words}",
80        words.len(),
81    );
82
83    collect_bool_words_inline(words, len, f)
84}
85
86/// Read up to 8 bytes as a little-endian `u64`, zero-padding the high bytes when fewer than 8
87/// bytes are supplied.
88///
89/// This preserves Vortex's least-significant-bit-first bitmap numbering on little- and big-endian
90/// targets. For a full 8-byte slice it lowers to a single word load.
91#[inline]
92pub fn read_u64_le(bytes: &[u8]) -> u64 {
93    debug_assert!(bytes.len() <= 8);
94    let mut buf = [0u8; 8];
95    buf[..bytes.len()].copy_from_slice(bytes);
96    u64::from_le_bytes(buf)
97}
98
99/// Splice a packed word `w` (whose bits above the highest valid bit are zero) into
100/// `words` at the given bit position.
101///
102/// The destination word at `bit_offset / 64` is OR'd, preserving any bits below
103/// `bit_offset % 64`. When `w` has high bits that spill into the next word, those
104/// bits are *assigned* (not OR'd) — so callers must ensure that next slot is zero
105/// (e.g. via `BufferMut::zeroed`).
106///
107/// `words.len()` need only cover the slots `w` actually writes to: skipping the
108/// spillover when its bits are all zero means a tail that fits entirely in the
109/// leading word never touches `words[dest_word + 1]`.
110#[inline]
111pub fn splice_word_at_bit(words: &mut [u64], bit_offset: usize, word: u64) {
112    let dest_word = bit_offset / 64;
113    let bit_in_word = bit_offset % 64;
114    words[dest_word] |= word << bit_in_word;
115    if bit_in_word != 0 {
116        let high = word >> (64 - bit_in_word);
117        if high != 0 {
118            words[dest_word + 1] = high;
119        }
120    }
121}
122
123/// Pack `len` boolean values returned by `f` into `words` starting at bit position
124/// `bit_offset`, LSB-first.
125///
126/// Composes [`collect_bool_word`] (pack up to 64 bools into a u64) with
127/// [`splice_word_at_bit`] (merge the packed word into the destination via shift-OR).
128///
129/// `words` must have at least `(bit_offset + len).div_ceil(64)` entries; see
130/// [`splice_word_at_bit`] for zero-init requirements on words above the cursor.
131#[inline]
132pub fn pack_bools_into_words<F>(words: &mut [u64], bit_offset: usize, len: usize, mut f: F)
133where
134    F: FnMut(usize) -> bool,
135{
136    if len == 0 {
137        return;
138    }
139    let num_words = (bit_offset + len).div_ceil(64);
140    assert!(
141        words.len() >= num_words,
142        "words slice has {} entries, need at least {num_words}",
143        words.len(),
144    );
145
146    let mut done = 0;
147    while len - done >= 64 {
148        let word = collect_bool_word(64, |bit| f(done + bit));
149        splice_word_at_bit(words, bit_offset + done, word);
150        done += 64;
151    }
152    let tail = len - done;
153    if tail > 0 {
154        let word = collect_bool_word(tail, |bit| f(done + bit));
155        splice_word_at_bit(words, bit_offset + done, word);
156    }
157}
158
159/// Get the bit value at `index` out of `buf`.
160///
161/// # Panics
162///
163/// Panics if `index` is not between 0 and length of `buf * 8`.
164#[allow(clippy::inline_always)]
165#[inline(always)]
166pub fn get_bit(buf: &[u8], index: usize) -> bool {
167    buf[index / 8] & (1 << (index % 8)) != 0
168}
169
170/// Get the bit value at `index` out of `buf` without bounds checking.
171///
172/// # Safety
173///
174/// `index` must be between 0 and length of `buf * 8`.
175#[allow(clippy::inline_always)]
176#[inline(always)]
177pub unsafe fn get_bit_unchecked(buf: *const u8, index: usize) -> bool {
178    (unsafe { *buf.add(index / 8) } & (1 << (index % 8))) != 0
179}
180
181/// Set the bit value at `index` in `buf` without bounds checking.
182///
183/// # Safety
184///
185/// `index` must be between 0 and length of `buf * 8`.
186#[allow(clippy::inline_always)]
187#[inline(always)]
188pub unsafe fn set_bit_unchecked(buf: *mut u8, index: usize) {
189    unsafe { *buf.add(index / 8) |= 1 << (index % 8) };
190}
191
192/// Unset the bit value at `index` in `buf` without bounds checking.
193///
194/// # Safety
195///
196/// `index` must be between 0 and length of `buf * 8`.
197#[allow(clippy::inline_always)]
198#[inline(always)]
199pub unsafe fn unset_bit_unchecked(buf: *mut u8, index: usize) {
200    unsafe { *buf.add(index / 8) &= !(1 << (index % 8)) };
201}
202
203#[cfg(test)]
204mod tests {
205    use super::collect_bool_word;
206    use super::pack_bools_into_words;
207    use super::read_u64_le;
208
209    #[test]
210    fn collect_bool_word_packs_lsb_first() {
211        let word = collect_bool_word(5, |idx| idx.is_multiple_of(2));
212        assert_eq!(word, 0b10101);
213    }
214
215    #[test]
216    fn collect_bool_word_empty() {
217        assert_eq!(collect_bool_word(0, |_| true), 0);
218    }
219
220    #[test]
221    fn read_u64_le_zero_pads_tail() {
222        assert_eq!(read_u64_le(&[0x34, 0x12]), 0x1234);
223        assert_eq!(read_u64_le(&[0xff; 8]), u64::MAX);
224    }
225
226    #[test]
227    #[should_panic(expected = "cannot pack 65 bits into a u64 word")]
228    fn collect_bool_word_rejects_too_many_bits() {
229        let _ = collect_bool_word(65, |_| true);
230    }
231
232    fn pack(bit_offset: usize, len: usize, f: impl Fn(usize) -> bool) -> Vec<bool> {
233        let num_words = (bit_offset + len).div_ceil(64);
234        let mut words = vec![0u64; num_words];
235        pack_bools_into_words(&mut words, bit_offset, len, &f);
236        (0..bit_offset + len)
237            .map(|i| (words[i / 64] >> (i % 64)) & 1 == 1)
238            .collect()
239    }
240
241    #[test]
242    fn pack_bools_aligned_multi_word_with_tail() {
243        let bits = pack(0, 130, |i| i.is_multiple_of(3));
244        for i in 0..130 {
245            assert_eq!(bits[i], i.is_multiple_of(3), "bit {i}");
246        }
247    }
248
249    #[test]
250    fn pack_bools_unaligned_crossing_words() {
251        let bits = pack(40, 200, |i| i.is_multiple_of(7));
252        assert!(bits[..40].iter().all(|&b| !b));
253        for i in 0..200 {
254            assert_eq!(bits[40 + i], i.is_multiple_of(7), "bit {}", 40 + i);
255        }
256    }
257
258    #[test]
259    fn pack_bools_preserves_low_bits_of_leading_word() {
260        let mut words = vec![0u64; 2];
261        words[0] = 0b11111;
262        pack_bools_into_words(&mut words, 5, 70, |_| true);
263        for i in 0..5 {
264            assert_eq!((words[0] >> i) & 1, 1, "preserved bit {i}");
265        }
266        for i in 5..75 {
267            assert_eq!((words[i / 64] >> (i % 64)) & 1, 1, "extended bit {i}");
268        }
269    }
270}