1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::error;
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
pub struct BitLength(usize);
impl BitLength {
#[inline]
pub const fn from_usize_bits(bits: usize) -> Self {
Self(bits)
}
#[inline]
pub fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified> {
let bits = bytes.checked_mul(8).ok_or(error::Unspecified)?;
Ok(Self::from_usize_bits(bits))
}
#[cfg(feature = "alloc")]
#[inline]
pub fn half_rounded_up(&self) -> Self {
let round_up = self.0 & 1;
Self((self.0 / 2) + round_up)
}
#[inline]
pub fn as_usize_bits(&self) -> usize {
self.0
}
#[cfg(feature = "alloc")]
#[inline]
pub fn as_usize_bytes_rounded_up(&self) -> usize {
let round_up = ((self.0 >> 2) | (self.0 >> 1) | self.0) & 1;
(self.0 / 8) + round_up
}
#[cfg(feature = "alloc")]
#[inline]
pub fn try_sub_1(self) -> Result<BitLength, error::Unspecified> {
let sum = self.0.checked_sub(1).ok_or(error::Unspecified)?;
Ok(BitLength(sum))
}
}