Skip to main content

vortex_buffer/bit/
view.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::ops::Bound;
5use std::ops::RangeBounds;
6
7use crate::BitBuffer;
8use crate::BitBufferMeta;
9use crate::BitBufferMut;
10use crate::ByteBuffer;
11use crate::bit::BitChunks;
12use crate::bit::BitIndexIterator;
13use crate::bit::BitIterator;
14use crate::bit::BitSliceIterator;
15use crate::bit::UnalignedBitChunk;
16use crate::bit::buf_mut::fill_bits;
17use crate::bit::count_ones::count_ones;
18use crate::bit::get_bit_unchecked;
19use crate::bit::select::bit_select;
20use crate::bit::set_bit_unchecked;
21use crate::bit::unset_bit_unchecked;
22
23/// Resolve `start..end` bounds against a logical length, panicking on invalid ranges.
24#[inline]
25fn resolve_range(range: impl RangeBounds<usize>, len: usize) -> (usize, usize) {
26    let start = match range.start_bound() {
27        Bound::Included(&s) => s,
28        Bound::Excluded(&s) => s + 1,
29        Bound::Unbounded => 0,
30    };
31    let end = match range.end_bound() {
32        Bound::Included(&e) => e + 1,
33        Bound::Excluded(&e) => e,
34        Bound::Unbounded => len,
35    };
36
37    assert!(start <= end);
38    assert!(start <= len);
39    assert!(end <= len);
40    (start, end)
41}
42
43/// Normalize a byte slice and bit offset so that the returned offset is `< 8`.
44#[inline]
45fn normalize(buffer: &[u8], offset: usize) -> (&[u8], usize) {
46    let byte_offset = offset / 8;
47    (&buffer[byte_offset..], offset % 8)
48}
49
50/// An immutable, borrowed view over a packed bitset.
51///
52/// This is the borrowing analogue of [`BitBuffer`]: it stores a byte slice together with a bit
53/// `offset` (always `< 8`) and a logical bit `len`, without owning or reference-counting the
54/// backing allocation. Use it to read a bitset without cloning the underlying [`ByteBuffer`].
55#[derive(Debug, Clone, Copy)]
56pub struct BitBufferView<'a> {
57    buffer: &'a [u8],
58    offset: usize,
59    len: usize,
60}
61
62impl<'a> BitBufferView<'a> {
63    /// Create a new view over `buffer` with `len` bits, starting at bit zero.
64    ///
65    /// Panics if the buffer is not large enough to hold `len` bits.
66    #[inline]
67    pub fn new(buffer: &'a [u8], len: usize) -> Self {
68        Self::new_with_offset(buffer, len, 0)
69    }
70
71    /// Create a new view over `buffer` with `len` bits, starting at the given bit `offset`.
72    ///
73    /// Panics if the buffer is not large enough to hold `len` bits after the offset.
74    #[inline]
75    pub fn new_with_offset(buffer: &'a [u8], len: usize, offset: usize) -> Self {
76        assert!(
77            len.saturating_add(offset) <= buffer.len().saturating_mul(8),
78            "provided slice (len={}) not large enough to back BitBufferView with offset {offset} len {len}",
79            buffer.len()
80        );
81
82        let (buffer, offset) = normalize(buffer, offset);
83        Self {
84            buffer,
85            offset,
86            len,
87        }
88    }
89
90    /// Create a new view over `buffer` described by `meta`.
91    #[inline]
92    pub fn from_meta(buffer: &'a [u8], meta: BitBufferMeta) -> Self {
93        Self::new_with_offset(buffer, meta.len(), meta.offset())
94    }
95
96    /// Returns the [`BitBufferMeta`] (offset and length) describing this view.
97    #[inline]
98    pub fn meta(&self) -> BitBufferMeta {
99        BitBufferMeta::new(self.offset, self.len)
100    }
101
102    /// Get the logical length of this view in bits.
103    #[inline]
104    pub fn len(&self) -> usize {
105        self.len
106    }
107
108    /// Returns `true` if the view is empty.
109    #[inline]
110    pub fn is_empty(&self) -> bool {
111        self.len == 0
112    }
113
114    /// Offset of the start of the view in bits. Always `< 8`.
115    #[allow(clippy::inline_always)]
116    #[inline(always)]
117    pub fn offset(&self) -> usize {
118        self.offset
119    }
120
121    /// Get a reference to the underlying byte slice.
122    #[allow(clippy::inline_always)]
123    #[inline(always)]
124    pub fn inner(&self) -> &'a [u8] {
125        self.buffer
126    }
127
128    /// Retrieve the value at the given index.
129    ///
130    /// Panics if the index is out of bounds.
131    #[inline]
132    pub fn value(&self, index: usize) -> bool {
133        assert!(index < self.len);
134        // SAFETY: checked by assertion
135        unsafe { self.value_unchecked(index) }
136    }
137
138    /// Retrieve the value at the given index without bounds checking.
139    ///
140    /// # Safety
141    ///
142    /// Caller must ensure that `index` is within the range of the view.
143    #[inline]
144    pub unsafe fn value_unchecked(&self, index: usize) -> bool {
145        unsafe { get_bit_unchecked(self.buffer.as_ptr(), index + self.offset) }
146    }
147
148    /// Create a new view over the range `[start, end)` of this view.
149    ///
150    /// Panics if the slice would extend beyond the end of the view.
151    #[inline]
152    pub fn slice(&self, range: impl RangeBounds<usize>) -> BitBufferView<'a> {
153        let (start, end) = resolve_range(range, self.len);
154        BitBufferView::new_with_offset(self.buffer, end - start, self.offset + start)
155    }
156
157    /// Access chunks of the buffer aligned to an 8 byte boundary as
158    /// `[prefix, <full chunks>, suffix]`.
159    #[inline]
160    pub fn unaligned_chunks(&self) -> UnalignedBitChunk<'a> {
161        UnalignedBitChunk::new(self.buffer, self.offset, self.len)
162    }
163
164    /// Access chunks of the underlying buffer as 8 byte chunks with a final trailer.
165    #[inline]
166    pub fn chunks(&self) -> BitChunks<'a> {
167        BitChunks::new(self.buffer, self.offset, self.len)
168    }
169
170    /// Get the number of set bits in the view.
171    #[inline]
172    pub fn true_count(&self) -> usize {
173        count_ones(self.buffer, self.offset, self.len)
174    }
175
176    /// Get the number of unset bits in the view.
177    #[inline]
178    pub fn false_count(&self) -> usize {
179        self.len - self.true_count()
180    }
181
182    /// Returns the position of the `nth` set bit (0-indexed), or `None` if out of range.
183    #[inline]
184    pub fn select(&self, nth: usize) -> Option<usize> {
185        bit_select(self.buffer, self.offset, self.len, nth)
186    }
187
188    /// Iterator over bits in the view.
189    #[inline]
190    pub fn iter(&self) -> BitIterator<'a> {
191        BitIterator::new(self.buffer, self.offset, self.len)
192    }
193
194    /// Iterator over set indices of the underlying buffer.
195    #[inline]
196    pub fn set_indices(&self) -> BitIndexIterator<'a> {
197        BitIndexIterator::new(self.buffer, self.offset, self.len)
198    }
199
200    /// Iterator over set slices of the underlying buffer.
201    #[inline]
202    pub fn set_slices(&self) -> BitSliceIterator<'a> {
203        BitSliceIterator::new(self.buffer, self.offset, self.len)
204    }
205
206    /// Copy this view into an owned [`BitBuffer`].
207    pub fn to_bit_buffer(&self) -> BitBuffer {
208        let bytes = (self.offset + self.len).div_ceil(8);
209        BitBuffer::new_with_offset(
210            ByteBuffer::copy_from(&self.buffer[..bytes]),
211            self.len,
212            self.offset,
213        )
214    }
215}
216
217impl<'a> From<&'a BitBuffer> for BitBufferView<'a> {
218    #[inline]
219    fn from(buffer: &'a BitBuffer) -> Self {
220        buffer.as_view()
221    }
222}
223
224impl<'a> IntoIterator for BitBufferView<'a> {
225    type Item = bool;
226    type IntoIter = BitIterator<'a>;
227
228    fn into_iter(self) -> Self::IntoIter {
229        self.iter()
230    }
231}
232
233impl PartialEq for BitBufferView<'_> {
234    fn eq(&self, other: &Self) -> bool {
235        if self.len != other.len {
236            return false;
237        }
238
239        self.chunks()
240            .iter_padded()
241            .zip(other.chunks().iter_padded())
242            .all(|(a, b)| a == b)
243    }
244}
245
246impl Eq for BitBufferView<'_> {}
247
248/// A mutable, borrowed view over a packed bitset.
249///
250/// This is the borrowing analogue of [`BitBufferMut`]: it stores a mutable byte slice together
251/// with a bit `offset` (always `< 8`) and a logical bit `len`. Unlike [`BitBufferMut`] it cannot
252/// grow or reallocate, so it only supports in-place reads and writes (such as
253/// [`set`](Self::set), [`unset`](Self::unset), and [`fill_range`](Self::fill_range)).
254#[derive(Debug)]
255pub struct BitBufferMutView<'a> {
256    buffer: &'a mut [u8],
257    offset: usize,
258    len: usize,
259}
260
261impl<'a> BitBufferMutView<'a> {
262    /// Create a new mutable view over `buffer` with `len` bits, starting at bit zero.
263    ///
264    /// Panics if the buffer is not large enough to hold `len` bits.
265    #[inline]
266    pub fn new(buffer: &'a mut [u8], len: usize) -> Self {
267        Self::new_with_offset(buffer, len, 0)
268    }
269
270    /// Create a new mutable view over `buffer` with `len` bits, starting at bit `offset`.
271    ///
272    /// Panics if the buffer is not large enough to hold `len` bits after the offset.
273    #[inline]
274    pub fn new_with_offset(buffer: &'a mut [u8], len: usize, offset: usize) -> Self {
275        assert!(
276            len.saturating_add(offset) <= buffer.len().saturating_mul(8),
277            "provided slice (len={}) not large enough to back BitBufferMutView with offset {offset} len {len}",
278            buffer.len()
279        );
280
281        let byte_offset = offset / 8;
282        let offset = offset % 8;
283        Self {
284            buffer: &mut buffer[byte_offset..],
285            offset,
286            len,
287        }
288    }
289
290    /// Borrow this mutable view as an immutable [`BitBufferView`].
291    #[inline]
292    pub fn as_view(&self) -> BitBufferView<'_> {
293        BitBufferView {
294            buffer: self.buffer,
295            offset: self.offset,
296            len: self.len,
297        }
298    }
299
300    /// Get the logical length of this view in bits.
301    #[inline]
302    pub fn len(&self) -> usize {
303        self.len
304    }
305
306    /// Returns `true` if the view is empty.
307    #[inline]
308    pub fn is_empty(&self) -> bool {
309        self.len == 0
310    }
311
312    /// Offset of the start of the view in bits. Always `< 8`.
313    #[allow(clippy::inline_always)]
314    #[inline(always)]
315    pub fn offset(&self) -> usize {
316        self.offset
317    }
318
319    /// Get the underlying bytes as a slice.
320    #[inline]
321    pub fn as_slice(&self) -> &[u8] {
322        self.buffer
323    }
324
325    /// Get the underlying bytes as a mutable slice.
326    #[inline]
327    pub fn as_mut_slice(&mut self) -> &mut [u8] {
328        self.buffer
329    }
330
331    /// Retrieve the value at the given index.
332    ///
333    /// Panics if the index is out of bounds.
334    #[inline]
335    pub fn value(&self, index: usize) -> bool {
336        assert!(index < self.len);
337        // SAFETY: checked by assertion
338        unsafe { self.value_unchecked(index) }
339    }
340
341    /// Retrieve the value at the given index without bounds checking.
342    ///
343    /// # Safety
344    ///
345    /// Caller must ensure that `index` is within the range of the view.
346    #[inline]
347    pub unsafe fn value_unchecked(&self, index: usize) -> bool {
348        unsafe { get_bit_unchecked(self.buffer.as_ptr(), index + self.offset) }
349    }
350
351    /// Get the number of set bits in the view.
352    #[inline]
353    pub fn true_count(&self) -> usize {
354        self.as_view().true_count()
355    }
356
357    /// Get the number of unset bits in the view.
358    #[inline]
359    pub fn false_count(&self) -> usize {
360        self.as_view().false_count()
361    }
362
363    /// Iterator over bits in the view.
364    #[inline]
365    pub fn iter(&self) -> BitIterator<'_> {
366        self.as_view().iter()
367    }
368
369    /// Set the bit at `index` to the given boolean value.
370    ///
371    /// Panics if `index` exceeds the view length.
372    #[inline]
373    pub fn set_to(&mut self, index: usize, value: bool) {
374        if value {
375            self.set(index);
376        } else {
377            self.unset(index);
378        }
379    }
380
381    /// Set the bit at `index` to the given boolean value without bounds checking.
382    ///
383    /// # Safety
384    ///
385    /// Caller must ensure that `index` is within the range of the view.
386    #[inline]
387    pub unsafe fn set_to_unchecked(&mut self, index: usize, value: bool) {
388        if value {
389            // SAFETY: checked by caller
390            unsafe { self.set_unchecked(index) }
391        } else {
392            // SAFETY: checked by caller
393            unsafe { self.unset_unchecked(index) }
394        }
395    }
396
397    /// Set the bit at `index` to `true`.
398    ///
399    /// Panics if `index` exceeds the view length.
400    #[inline]
401    pub fn set(&mut self, index: usize) {
402        assert!(index < self.len, "index {index} exceeds len {}", self.len);
403        // SAFETY: checked by assertion
404        unsafe { self.set_unchecked(index) };
405    }
406
407    /// Set the bit at `index` to `false`.
408    ///
409    /// Panics if `index` exceeds the view length.
410    #[inline]
411    pub fn unset(&mut self, index: usize) {
412        assert!(index < self.len, "index {index} exceeds len {}", self.len);
413        // SAFETY: checked by assertion
414        unsafe { self.unset_unchecked(index) };
415    }
416
417    /// Set the bit at `index` to `true` without bounds checking.
418    ///
419    /// # Safety
420    ///
421    /// Caller must ensure that `index` is within the range of the view.
422    #[inline]
423    pub unsafe fn set_unchecked(&mut self, index: usize) {
424        // SAFETY: checked by caller
425        unsafe { set_bit_unchecked(self.buffer.as_mut_ptr(), self.offset + index) }
426    }
427
428    /// Set the bit at `index` to `false` without bounds checking.
429    ///
430    /// # Safety
431    ///
432    /// Caller must ensure that `index` is within the range of the view.
433    #[inline]
434    pub unsafe fn unset_unchecked(&mut self, index: usize) {
435        // SAFETY: checked by caller
436        unsafe { unset_bit_unchecked(self.buffer.as_mut_ptr(), self.offset + index) }
437    }
438
439    /// Sets all bits in the range `[start, end)` to `value`.
440    ///
441    /// Panics if `end > self.len()` or `start > end`.
442    #[allow(clippy::inline_always)]
443    #[inline(always)]
444    pub fn fill_range(&mut self, start: usize, end: usize, value: bool) {
445        assert!(end <= self.len, "end {end} exceeds len {}", self.len);
446        assert!(start <= end, "start {start} exceeds end {end}");
447        // SAFETY: assertions guarantee start <= end <= self.len.
448        unsafe { self.fill_range_unchecked(start, end, value) }
449    }
450
451    /// Sets all bits in the range `[start, end)` to `value` without bounds checking.
452    ///
453    /// # Safety
454    ///
455    /// Caller must ensure that `start <= end <= self.len()`.
456    #[allow(clippy::inline_always)]
457    #[inline(always)]
458    pub unsafe fn fill_range_unchecked(&mut self, start: usize, end: usize, value: bool) {
459        fill_bits(self.buffer, self.offset + start, self.offset + end, value);
460    }
461
462    /// Copy this view into an owned [`BitBuffer`].
463    pub fn to_bit_buffer(&self) -> BitBuffer {
464        self.as_view().to_bit_buffer()
465    }
466}
467
468impl BitBuffer {
469    /// Borrow this buffer as a [`BitBufferView`] without cloning the backing allocation.
470    #[inline]
471    pub fn as_view(&self) -> BitBufferView<'_> {
472        BitBufferView {
473            buffer: self.inner().as_slice(),
474            offset: self.offset(),
475            len: self.len(),
476        }
477    }
478}
479
480impl BitBufferMut {
481    /// Borrow this buffer as an immutable [`BitBufferView`].
482    #[inline]
483    pub fn as_view(&self) -> BitBufferView<'_> {
484        BitBufferView {
485            buffer: self.as_slice(),
486            offset: self.offset(),
487            len: self.len(),
488        }
489    }
490
491    /// Borrow this buffer as a [`BitBufferMutView`].
492    #[inline]
493    pub fn as_mut_view(&mut self) -> BitBufferMutView<'_> {
494        let offset = self.offset();
495        let len = self.len();
496        BitBufferMutView {
497            buffer: self.as_mut_slice(),
498            offset,
499            len,
500        }
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use crate::BitBuffer;
507    use crate::BitBufferMut;
508    use crate::bitbuffer;
509
510    #[test]
511    fn view_reads_match_buffer() {
512        let buffer = bitbuffer![true, false, true, true, false, true, false, false];
513        let view = buffer.as_view();
514
515        assert_eq!(view.len(), buffer.len());
516        assert_eq!(view.true_count(), buffer.true_count());
517        assert_eq!(view.false_count(), buffer.false_count());
518        for i in 0..buffer.len() {
519            assert_eq!(view.value(i), buffer.value(i));
520        }
521        assert_eq!(
522            view.iter().collect::<Vec<_>>(),
523            buffer.iter().collect::<Vec<_>>()
524        );
525    }
526
527    #[test]
528    fn view_slice_preserves_offset() {
529        let buffer = BitBuffer::collect_bool(20, |i| i % 3 == 0);
530        let view = buffer.as_view().slice(5..17);
531        let expected = BitBuffer::from_iter([
532            false, true, false, false, true, false, false, true, false, false, true, false,
533        ]);
534
535        assert_eq!(view.offset(), 5);
536        assert_eq!(view.len(), 12);
537        assert_eq!(view.true_count(), 4);
538        assert_eq!(view.to_bit_buffer(), expected);
539    }
540
541    #[test]
542    fn view_offset_buffer() {
543        let buffer = BitBuffer::new_set(64).slice(3..40);
544        let view = buffer.as_view();
545        assert_eq!(view.offset(), buffer.offset());
546        assert_eq!(view.len(), buffer.len());
547        assert_eq!(view.to_bit_buffer(), buffer);
548    }
549
550    #[test]
551    fn mut_view_set_unset() {
552        let mut buffer = BitBufferMut::new_unset(16);
553        {
554            let mut view = buffer.as_mut_view();
555            view.set(0);
556            view.set(15);
557            view.set_to(7, true);
558            view.fill_range(2, 5, true);
559            assert!(view.value(0));
560            assert_eq!(view.true_count(), 6);
561            view.unset(0);
562        }
563        let frozen = buffer.freeze();
564        assert!(!frozen.value(0));
565        assert!(frozen.value(2));
566        assert!(frozen.value(4));
567        assert!(frozen.value(7));
568        assert!(frozen.value(15));
569        assert_eq!(frozen.true_count(), 5);
570    }
571
572    #[test]
573    fn mut_view_with_offset() {
574        let mut buffer = BitBufferMut::from_buffer(crate::buffer_mut![0u8; 4], 3, 20);
575        {
576            let mut view = buffer.as_mut_view();
577            assert_eq!(view.offset(), 3);
578            view.fill_range(0, 20, true);
579        }
580        let frozen = buffer.freeze();
581        assert_eq!(frozen.true_count(), 20);
582    }
583}