bits_io/buf/
bits.rs

1use std::ops::{Deref, Range};
2
3use crate::prelude::*;
4use bitvec::{order::Msb0, view::BitView};
5use bytes::{Bytes, BytesMut};
6
7use super::util::bytes_needed;
8
9// TODO: Need to determine if advancing here needs to be reflected in the underlying Bytes
10// instances.  For BitsMut it's critical, since the starting point for writing is important for
11// certain operations.  I suspect that may be the same for reading, but need to look into
12// it/verify.
13
14/// A cheaply cloneable chunk of contiugous memory, built on top of `[bytes::Bytes`] but providing
15/// bit-level operations.  
16#[derive(Clone, Debug, Eq)]
17pub struct Bits {
18    pub(crate) inner: Bytes,
19    /// The start of this instance's view of the underlying storage
20    pub(crate) bit_start: usize,
21    /// How many bits, from bit_start, are part of this view
22    pub(crate) bit_len: usize,
23}
24
25impl Bits {
26    /// Creates a new empty [`Bits`] from an instance of [`Bytes`]
27    pub fn from_bytes(bytes: Bytes) -> Self {
28        let bit_len = bytes.len() * 8;
29        Self {
30            inner: bytes,
31            bit_start: 0,
32            bit_len,
33        }
34    }
35
36    pub fn from_static_bytes(bytes: &'static [u8]) -> Self {
37        let inner = Bytes::from_static(bytes);
38        let bit_len = inner.len() * 8;
39        Self {
40            inner,
41            bit_start: 0,
42            bit_len,
43        }
44    }
45
46    pub fn from_owner_bytes<T>(owner: T) -> Self
47    where
48        T: AsRef<[u8]> + Send + 'static,
49    {
50        let inner = Bytes::from_owner(owner);
51        let bit_len = inner.len() * 8;
52        Self {
53            inner,
54            bit_start: 0,
55            bit_len,
56        }
57    }
58
59    /// Creates a new [`Bits`] instance from the given `BitSlice` by copying it.
60    pub fn copy_from_bit_slice(bits: &BitSlice) -> Self {
61        let bytes_needed = bytes_needed(bits.len());
62        let mut bytes = BytesMut::with_capacity(bytes_needed);
63        bytes.resize(bytes_needed, 0);
64
65        let target = BitSlice::from_slice_mut(&mut bytes);
66        target[..bits.len()].clone_from_bitslice(bits);
67
68        Self {
69            inner: bytes.freeze(),
70            bit_start: 0,
71            bit_len: bits.len(),
72        }
73    }
74
75    /// Creates a new `Bits` instance from the given u8 slice by copying it.
76    pub fn copy_from_bytes(bytes: &[u8]) -> Self {
77        let mut target = BytesMut::with_capacity(bytes.len());
78        target.resize(bytes.len(), 0);
79        target.copy_from_slice(bytes);
80
81        Self {
82            inner: target.freeze(),
83            bit_start: 0,
84            bit_len: bytes.len() * 8,
85        }
86    }
87
88    /// Create a slice corresponding to the given range, which is given in bits.  The given range
89    /// is relative to the start of the buffer, not the current position.
90    pub fn slice_bits(&self, range: Range<usize>) -> Self {
91        assert!(
92            range.end <= self.bit_start + self.bit_len,
93            "Range beyond Bits length"
94        );
95        Self {
96            inner: self.inner.clone(),
97            bit_start: self.bit_start + range.start,
98            bit_len: range.end - range.start,
99        }
100    }
101
102    /// Create a slice corresponding to the given range, which is given in bytes.  The given range
103    /// is relative to the start of the buffer, not the current position.  Note that the 'start' of
104    /// this view may not correspond to a byte boundary on the underlying storage.
105    pub fn slice_bytes(&self, range: Range<usize>) -> Self {
106        assert!(
107            range.end * 8 <= self.bit_start + self.bit_len,
108            "Range beyond Bits length"
109        );
110        let bit_range_start = range.start * 8;
111        let bit_range_end = range.end * 8;
112        self.slice_bits(bit_range_start..bit_range_end)
113    }
114
115    /// Splits the bits into two at the given bit index.
116    ///
117    /// Afterwards self contains elements [at, len), and the returned Bits contains elements [0,
118    /// at).
119    pub fn split_to_bits(&mut self, at: usize) -> Self {
120        assert!(
121            at <= self.bit_len,
122            "split_to out of bounds: {:?} must be <= {:?}",
123            at,
124            self.len_bits()
125        );
126        let mut ret = self.clone();
127        self.inc_start_bits(at);
128        ret.bit_len = at;
129        ret
130    }
131
132    /// Splits the bits into two at the given byte index.  Note that this byte index is relative to
133    /// the start of this view, and may not fall on a byte boundary in the underlying storage.
134    ///
135    /// Afterwards self contains elements [at, len), and the returned Bits contains elements [0,
136    /// at).
137    pub fn split_to_bytes(&mut self, at: usize) -> Self {
138        self.split_to_bits(at * 8)
139    }
140
141    /// Splits the bits into two at the given index.
142    ///
143    /// Afterwards self contains elements [0, at), and the returned Bits contains elements [at,
144    /// len).
145    pub fn split_off_bits(&mut self, at: usize) -> Self {
146        assert!(
147            at <= self.bit_len,
148            "split_off out of bounds: {:?} must be <= {:?}",
149            at,
150            self.len_bits()
151        );
152        let mut ret = self.clone();
153        self.bit_len = at;
154        ret.inc_start_bits(at);
155        ret
156    }
157
158    /// Splits the bits into two at the given byte index.  Note that this byte index is relative to
159    /// the start of this view, and may not fall on a byte boundary in the underlying storage.
160    ///
161    /// Afterwards self contains elements [0, at), and the returned Bits contains elements [at,
162    /// len).
163    pub fn split_off_bytes(&mut self, at: usize) -> Self {
164        self.split_off_bits(at * 8)
165    }
166
167    /// Shortens the buffer, keeping the first len bits and dropping the rest.
168    ///
169    /// If len is greater than the buffer’s current length, this has no effect.
170    ///
171    /// The split_off method can emulate truncate, but this causes the excess bits to be returned
172    /// instead of dropped.
173    pub fn truncate_bits(&mut self, len: usize) {
174        if len < self.bit_len {
175            self.bit_len = len;
176        }
177    }
178
179    /// Shortens the buffer, keeping the first len bytes and dropping the rest.
180    ///
181    /// If len is greater than the buffer’s current length, this has no effect.
182    ///
183    /// The split_off method can emulate truncate, but this causes the excess bits to be returned
184    /// instead of dropped.
185    pub fn truncate_bytes(&mut self, len: usize) {
186        if len * 8 < self.bit_len {
187            self.bit_len = len * 8;
188        }
189    }
190
191    /// Clears the buffer, removing all data.
192    pub fn clear(&mut self) {
193        self.truncate_bits(0);
194    }
195
196    /// Returns the number of bits contained in this `Bits`
197    pub fn len_bits(&self) -> usize {
198        self.bit_len
199    }
200
201    /// Returns the number of _complete_ bytes contained in this `Bits`.  Note that this `Bits` may
202    /// contain a number of bits that does not evenly divide into bytes: this method returns the
203    /// number of _complete_ bytes, i.e. it does a truncating divide on the number of bits.
204    pub fn len_bytes(&self) -> usize {
205        self.bit_len / 8
206    }
207
208    /// Returns true if the `Bits` has a length of 0.
209    pub fn is_empty(&self) -> bool {
210        self.bit_len == 0
211    }
212
213    /// Move the start point of this view forward by `by` bits.
214    pub(crate) fn inc_start_bits(&mut self, by: usize) {
215        self.bit_len -= by;
216        self.bit_start += by;
217    }
218}
219
220impl PartialEq for Bits {
221    fn eq(&self, other: &Self) -> bool {
222        if self.byte_aligned() && other.byte_aligned() {
223            self.chunk_bytes() == other.chunk_bytes()
224        } else {
225            self.inner.view_bits::<Msb0>()[self.bit_start..self.bit_start + self.bit_len]
226                == other.inner.view_bits::<Msb0>()[other.bit_start..other.bit_start + other.bit_len]
227        }
228    }
229}
230
231impl Deref for Bits {
232    type Target = BitSlice;
233
234    fn deref(&self) -> &Self::Target {
235        BitSlice::from_slice(&self.inner)[self.bit_start..self.bit_start + self.bit_len].as_ref()
236    }
237}
238
239impl From<BitVec> for Bits {
240    fn from(bv: BitVec) -> Self {
241        // As far as I can tell, the bitvec crate does not give any way to get access to the
242        // underlying bytes _and_ give the offset at which the bitslice/bitvec starts (since it may
243        // not be at the beginning of that underlying storage).  This means we first need to
244        // 'left-align' the data that we get here, and the only way to do that is to copy the bits
245        // into a new bitvec.
246        let bit_len = bv.len();
247        let aligned: BitVec = bv.iter().by_vals().collect();
248        let bytes = aligned.into_vec();
249
250        Self {
251            inner: Bytes::from(bytes),
252            bit_start: 0,
253            bit_len,
254        }
255    }
256}
257
258impl From<&BitSlice> for Bits {
259    fn from(value: &BitSlice) -> Self {
260        Bits::from(value.to_bitvec())
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn test_copy_from_slice() {
270        // Mutable so we can alter it below to make sure a copy was made
271        let src = bits![mut 1, 0, 1, 1, 0, 1, 0, 0, 1, 1];
272
273        let bits = Bits::copy_from_bit_slice(src);
274
275        assert_eq!(bits.len_bits(), src.len());
276        assert_eq!(src, bits[..]);
277
278        // Ensure the data was copied (not shared)
279        src.set(0, false);
280
281        // Original `bits` should not be affected
282        assert!(bits[0]);
283    }
284
285    #[test]
286    fn test_from_bitslice() {
287        let slice = bits![1, 1, 0, 1, 1, 0];
288        let bits = Bits::from(slice);
289        assert_eq!(bits.len_bits(), 6);
290        assert_eq!(bits[..], bits![1, 1, 0, 1, 1, 0]);
291
292        // Now make sure a slice that came from a non-byte boundary still works
293        let unaligned_slice = &slice[2..];
294        let bits = Bits::from(unaligned_slice);
295        assert_eq!(bits.len_bits(), 4);
296        assert_eq!(bits[..], bits![0, 1, 1, 0]);
297    }
298
299    #[test]
300    fn test_slice() {
301        let bits = Bits::from_static_bytes(&[0b1010_1010, 0b1111_0000]);
302
303        let head = bits.slice_bits(0..4);
304        assert_eq!(head.len_bits(), 4);
305        assert_eq!(head[..], bits!(1, 0, 1, 0));
306
307        let mid = bits.slice_bits(4..12);
308        assert_eq!(mid.len_bits(), 8);
309        assert_eq!(mid[..], bits!(1, 0, 1, 0, 1, 1, 1, 1));
310
311        let tail = bits.slice_bits(12..16);
312        assert_eq!(tail.len_bits(), 4);
313        assert_eq!(tail[..], bits!(0, 0, 0, 0));
314
315        // A slice which overlaps two existing slices
316        let overlapping = bits.slice_bits(10..14);
317        assert_eq!(overlapping.len_bits(), 4);
318        assert_eq!(overlapping[..], bits!(1, 1, 0, 0));
319
320        // A slice taken from an existing slice who's starting point isn't at a byte boundary
321        let slice_of_slice = overlapping.slice_bits(0..2);
322        assert_eq!(slice_of_slice.len_bits(), 2);
323        assert_eq!(slice_of_slice[..], bits!(1, 1));
324    }
325
326    #[test]
327    fn test_slice_bytes() {
328        #[rustfmt::skip]
329        let bits = Bits::from_static_bytes(&[
330            0b1010_1010,
331            0b1100_1100,
332            0b1110_0011,
333            0b1111_0000,
334        ]);
335
336        let head = bits.slice_bytes(0..2);
337        assert_eq!(head.len_bits(), 16);
338        assert_eq!(
339            head[..],
340            bits!(1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0)
341        );
342
343        let mid = bits.slice_bytes(1..3);
344        assert_eq!(head.len_bits(), 16);
345        assert_eq!(
346            mid[..],
347            bits!(1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1)
348        );
349
350        // Grab a bitslice that starts at a non-byte boundary and make sure a byte slice from that
351        // works correctly
352        let bitslice = bits.slice_bits(4..32);
353        let byte_slice_from_bitslice = bitslice.slice_bytes(0..1);
354        assert_eq!(byte_slice_from_bitslice.len_bits(), 8);
355        assert_eq!(byte_slice_from_bitslice[..], bits!(1, 0, 1, 0, 1, 1, 0, 0));
356    }
357
358    #[test]
359    fn test_split_to() {
360        let mut bits = Bits::from_static_bytes(&[0b1010_1010, 0b1111_0000]);
361
362        let head = bits.split_to_bits(7);
363        assert_eq!(head.len_bits(), 7);
364        assert_eq!(bits.len_bits(), 9);
365        assert_eq!(head[..], bits!(1, 0, 1, 0, 1, 0, 1));
366        assert_eq!(bits[..], bits!(0, 1, 1, 1, 1, 0, 0, 0, 0));
367
368        // Split again from what was left over
369        let head = bits.split_to_bits(3);
370        assert_eq!(head.len_bits(), 3);
371        assert_eq!(bits.len_bits(), 6);
372        assert_eq!(head[..], bits!(0, 1, 1));
373        assert_eq!(bits[..], bits!(1, 1, 0, 0, 0, 0));
374    }
375
376    #[test]
377    fn test_split_to_bytes() {
378        #[rustfmt::skip]
379        let mut bits = Bits::from_static_bytes(&[
380            0b1010_1010,
381            0b1100_1100,
382            0b1110_0011,
383            0b1111_0000,
384        ]);
385
386        let head = bits.split_to_bytes(1);
387        assert_eq!(head.len_bits(), 8);
388        assert_eq!(bits.len_bits(), 24);
389        assert_eq!(head[..], bits!(1, 0, 1, 0, 1, 0, 1, 0));
390        assert_eq!(
391            bits[..],
392            bits!(1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0)
393        );
394
395        // Now split on a non-byte boundary
396        let _head = bits.split_to_bits(4);
397        // Then split_bytes on that and make sure it works
398        let head = bits.split_to_bytes(1);
399        assert_eq!(head.len_bits(), 8);
400        assert_eq!(bits.len_bits(), 12);
401        assert_eq!(head[..], bits!(1, 1, 0, 0, 1, 1, 1, 0));
402        assert_eq!(bits[..], bits!(0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0));
403    }
404
405    #[test]
406    fn test_split_off() {
407        let mut bits = Bits::from_static_bytes(&[0b1010_1010, 0b1111_0000]);
408
409        let tail = bits.split_off_bits(7);
410        assert_eq!(bits.len_bits(), 7);
411        assert_eq!(tail.len_bits(), 9);
412        assert_eq!(bits[..], bits!(1, 0, 1, 0, 1, 0, 1));
413        assert_eq!(tail[..], bits!(0, 1, 1, 1, 1, 0, 0, 0, 0));
414
415        // Split again from what was left over
416        let tail = bits.split_off_bits(3);
417        assert_eq!(bits.len_bits(), 3);
418        assert_eq!(tail.len_bits(), 4);
419        assert_eq!(bits[..], bits!(1, 0, 1));
420        assert_eq!(tail[..], bits!(0, 1, 0, 1));
421    }
422
423    #[test]
424    fn test_split_off_bytes() {
425        #[rustfmt::skip]
426        let mut bits = Bits::from_static_bytes(&[
427            0b1010_1010,
428            0b1100_1100,
429            0b1110_0011,
430            0b1111_0000,
431        ]);
432
433        let tail = bits.split_off_bytes(3);
434        // 'tail' is now bits [24, 32), 'bits' is [0, 24)
435        assert_eq!(bits.len_bits(), 24);
436        assert_eq!(tail.len_bits(), 8);
437        assert_eq!(
438            bits[..],
439            bits!(1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1)
440        );
441        assert_eq!(tail[..], bits!(1, 1, 1, 1, 0, 0, 0, 0));
442
443        // Now split on a non-byte boundary
444        let mut tail = bits.split_off_bits(6);
445        // 'tail' is now bits [6, 24), 'bits' is now [0, 6)
446        assert_eq!(bits.len_bits(), 6);
447        assert_eq!(bits[..], bits!(1, 0, 1, 0, 1, 0));
448
449        // Now split_off_bytes on 'tail' to make sure it works
450        let tail_tail = tail.split_off_bytes(1);
451        // 'tail_tail' is now bits [14, 24), 'tail' is [6, 14)
452        assert_eq!(tail_tail.len_bits(), 10);
453        assert_eq!(tail.len_bits(), 8);
454        assert_eq!(tail_tail[..], bits!(0, 0, 1, 1, 1, 0, 0, 0, 1, 1));
455        assert_eq!(tail[..], bits!(1, 0, 1, 1, 0, 0, 1, 1));
456    }
457
458    #[test]
459    fn test_truncate() {
460        #[rustfmt::skip]
461        let mut bits = Bits::from_static_bytes(&[
462            0b1010_1010,
463            0b1100_1100,
464            0b1110_0011,
465            0b1111_0000,
466        ]);
467
468        bits.truncate_bits(10);
469        assert_eq!(bits.len_bits(), 10);
470        assert_eq!(bits[..], bits![1, 0, 1, 0, 1, 0, 1, 0, 1, 1]);
471    }
472
473    #[test]
474    fn test_truncate_bytes() {
475        #[rustfmt::skip]
476        let mut bits = Bits::from_static_bytes(&[
477            0b1010_1010,
478            0b1100_1100,
479            0b1110_0011,
480            0b1111_0000,
481        ]);
482
483        bits.truncate_bytes(2);
484        assert_eq!(bits.len_bits(), 16);
485        assert_eq!(
486            bits[..],
487            bits![1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0]
488        );
489    }
490}