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#[inline(always)]
162pub fn get_bit(buf: &[u8], index: usize) -> bool {
163    buf[index / 8] & (1 << (index % 8)) != 0
164}
165
166/// Get the bit value at `index` out of `buf` without bounds checking.
167///
168/// # Safety
169///
170/// `index` must be between 0 and length of `buf * 8`.
171#[inline(always)]
172pub unsafe fn get_bit_unchecked(buf: *const u8, index: usize) -> bool {
173    (unsafe { *buf.add(index / 8) } & (1 << (index % 8))) != 0
174}
175
176/// Set the bit value at `index` in `buf` without bounds checking.
177///
178/// # Safety
179///
180/// `index` must be between 0 and length of `buf * 8`.
181#[inline(always)]
182pub unsafe fn set_bit_unchecked(buf: *mut u8, index: usize) {
183    unsafe { *buf.add(index / 8) |= 1 << (index % 8) };
184}
185
186/// Unset the bit value at `index` in `buf` without bounds checking.
187///
188/// # Safety
189///
190/// `index` must be between 0 and length of `buf * 8`.
191#[inline(always)]
192pub unsafe fn unset_bit_unchecked(buf: *mut u8, index: usize) {
193    unsafe { *buf.add(index / 8) &= !(1 << (index % 8)) };
194}
195
196#[cfg(test)]
197mod tests {
198    use super::collect_bool_word;
199    use super::pack_bools_into_words;
200    use super::read_u64_le;
201
202    #[test]
203    fn collect_bool_word_packs_lsb_first() {
204        let word = collect_bool_word(5, |idx| idx.is_multiple_of(2));
205        assert_eq!(word, 0b10101);
206    }
207
208    #[test]
209    fn collect_bool_word_empty() {
210        assert_eq!(collect_bool_word(0, |_| true), 0);
211    }
212
213    #[test]
214    fn read_u64_le_zero_pads_tail() {
215        assert_eq!(read_u64_le(&[0x34, 0x12]), 0x1234);
216        assert_eq!(read_u64_le(&[0xff; 8]), u64::MAX);
217    }
218
219    #[test]
220    #[should_panic(expected = "cannot pack 65 bits into a u64 word")]
221    fn collect_bool_word_rejects_too_many_bits() {
222        let _ = collect_bool_word(65, |_| true);
223    }
224
225    fn pack(bit_offset: usize, len: usize, f: impl Fn(usize) -> bool) -> Vec<bool> {
226        let num_words = (bit_offset + len).div_ceil(64);
227        let mut words = vec![0u64; num_words];
228        pack_bools_into_words(&mut words, bit_offset, len, &f);
229        (0..bit_offset + len)
230            .map(|i| (words[i / 64] >> (i % 64)) & 1 == 1)
231            .collect()
232    }
233
234    #[test]
235    fn pack_bools_aligned_multi_word_with_tail() {
236        let bits = pack(0, 130, |i| i.is_multiple_of(3));
237        for i in 0..130 {
238            assert_eq!(bits[i], i.is_multiple_of(3), "bit {i}");
239        }
240    }
241
242    #[test]
243    fn pack_bools_unaligned_crossing_words() {
244        let bits = pack(40, 200, |i| i.is_multiple_of(7));
245        assert!(bits[..40].iter().all(|&b| !b));
246        for i in 0..200 {
247            assert_eq!(bits[40 + i], i.is_multiple_of(7), "bit {}", 40 + i);
248        }
249    }
250
251    #[test]
252    fn pack_bools_preserves_low_bits_of_leading_word() {
253        let mut words = vec![0u64; 2];
254        words[0] = 0b11111;
255        pack_bools_into_words(&mut words, 5, 70, |_| true);
256        for i in 0..5 {
257            assert_eq!((words[0] >> i) & 1, 1, "preserved bit {i}");
258        }
259        for i in 5..75 {
260            assert_eq!((words[i / 64] >> (i % 64)) & 1, 1, "extended bit {i}");
261        }
262    }
263}