Skip to main content

bit_buf/
lib.rs

1#![no_std]
2#![warn(missing_docs)]
3
4//! See <code>[BitBuf]::[from()][BitBuf::from]</code>, [`Storage`]/[`StorageMut`], and <code>[BitBuf]::{read,write}_*()</code>
5//!
6//! | Term | Definition |
7//! | - | - |
8//! | UB | [Undefined Behaviour](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) |
9//! | BE | [Big Endian](https://en.wikipedia.org/wiki/Endianness) |
10//! | LE | [Little Endian](https://en.wikipedia.org/wiki/Endianness) |
11//!
12//! Any usage of `pos`/`offset` implies bits rather than bytes
13
14#[cfg(test)]
15mod tests;
16
17mod buf;
18mod error;
19
20mod read;
21mod write;
22
23pub use buf::BitBuf;
24pub use error::Error;
25
26/// Returned from checked operations
27pub type Result<T> = core::result::Result<T, Error>;
28
29/// This trait must be implemented for types from which you wish to use `read_*` operations with
30pub trait Storage {
31  /// Get the bytes that represent this type
32  fn as_bytes(&self) -> &[u8];
33}
34
35/// This trait must be implemented for types from which you wish to use `write_*` operations with
36pub trait StorageMut: Storage {
37  /// Get the bytes that represent this type
38  fn as_bytes_mut(&mut self) -> &mut [u8];
39}
40
41impl<const N: usize> Storage for [u8; N] {
42  #[inline(always)]
43  fn as_bytes(&self) -> &[u8] {
44    self
45  }
46}
47
48impl<const N: usize> StorageMut for [u8; N] {
49  #[inline(always)]
50  fn as_bytes_mut(&mut self) -> &mut [u8] {
51    self
52  }
53}
54
55impl<const N: usize> Storage for &mut [u8; N] {
56  #[inline(always)]
57  fn as_bytes(&self) -> &[u8] {
58    *self
59  }
60}
61
62impl<const N: usize> StorageMut for &mut [u8; N] {
63  #[inline(always)]
64  fn as_bytes_mut(&mut self) -> &mut [u8] {
65    *self
66  }
67}
68
69impl Storage for &[u8] {
70  #[inline(always)]
71  fn as_bytes(&self) -> &[u8] {
72    self
73  }
74}
75
76impl Storage for &mut [u8] {
77  #[inline(always)]
78  fn as_bytes(&self) -> &[u8] {
79    self
80  }
81}
82
83impl StorageMut for &mut [u8] {
84  #[inline(always)]
85  fn as_bytes_mut(&mut self) -> &mut [u8] {
86    self
87  }
88}