Skip to main content

bit_buf/
buf.rs

1use crate::{Storage, StorageMut};
2
3/// The main structure
4///
5/// Keeps track of the data storage and a cursor for automatic operations
6#[derive(Debug)]
7pub struct BitBuf<S> {
8  data: S,
9  pos: usize,
10}
11
12impl<S> BitBuf<S> {
13  /// Construct from provided data storage
14  pub const fn from(data: S) -> Self {
15    Self { data, pos: 0 }
16  }
17
18  /// Get the underlying bytes from the storage
19  #[inline(always)]
20  pub fn bytes(&self) -> &[u8]
21  where
22    S: Storage,
23  {
24    self.data.as_bytes()
25  }
26
27  /// Get the underlying bytes from the storage
28  #[inline(always)]
29  pub fn bytes_mut(&mut self) -> &mut [u8]
30  where
31    S: StorageMut,
32  {
33    self.data.as_bytes_mut()
34  }
35
36  /// Advance the internal cursor for automatic operations
37  ///
38  /// <div class="warning">
39  ///
40  /// This does not enforce that the cursor stay within storage bounds
41  ///
42  /// </div>
43  #[inline(always)]
44  pub fn advance(&mut self, bits: usize) -> &mut Self {
45    self.pos += bits;
46    self
47  }
48
49  /// Set the internal cursor for automatic operations
50  ///
51  /// <div class="warning">
52  ///
53  /// This does not enforce that the cursor stay within storage bounds
54  ///
55  /// </div>
56  #[inline(always)]
57  pub fn seek(&mut self, offset: usize) -> &mut Self {
58    self.pos = offset;
59    self
60  }
61
62  /// Checks if the internal cursor for automatic operations is aligned on the start of a byte
63  ///
64  /// <div class="warning">
65  ///
66  /// This does not care whether the cursor is outside storage bounds
67  ///
68  /// </div>
69  #[inline(always)]
70  pub fn is_aligned(&self) -> bool {
71    self.pos.is_multiple_of(8)
72  }
73}