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