1 // Copyright 2016 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 use crate::error;
16 
17 #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
18 pub struct BitLength(usize);
19 
20 // Lengths measured in bits, where all arithmetic is guaranteed not to
21 // overflow.
22 impl BitLength {
23     #[inline]
from_usize_bits(bits: usize) -> Self24     pub const fn from_usize_bits(bits: usize) -> Self {
25         Self(bits)
26     }
27 
28     #[inline]
from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified>29     pub fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified> {
30         let bits = bytes.checked_mul(8).ok_or(error::Unspecified)?;
31         Ok(Self::from_usize_bits(bits))
32     }
33 
34     #[cfg(feature = "alloc")]
35     #[inline]
half_rounded_up(&self) -> Self36     pub fn half_rounded_up(&self) -> Self {
37         let round_up = self.0 & 1;
38         Self((self.0 / 2) + round_up)
39     }
40 
41     #[inline]
as_usize_bits(&self) -> usize42     pub fn as_usize_bits(&self) -> usize {
43         self.0
44     }
45 
46     #[cfg(feature = "alloc")]
47     #[inline]
as_usize_bytes_rounded_up(&self) -> usize48     pub fn as_usize_bytes_rounded_up(&self) -> usize {
49         // Equivalent to (self.0 + 7) / 8, except with no potential for
50         // overflow and without branches.
51 
52         // Branchless round_up = if self.0 & 0b111 != 0 { 1 } else { 0 };
53         let round_up = ((self.0 >> 2) | (self.0 >> 1) | self.0) & 1;
54 
55         (self.0 / 8) + round_up
56     }
57 
58     #[cfg(feature = "alloc")]
59     #[inline]
try_sub_1(self) -> Result<BitLength, error::Unspecified>60     pub fn try_sub_1(self) -> Result<BitLength, error::Unspecified> {
61         let sum = self.0.checked_sub(1).ok_or(error::Unspecified)?;
62         Ok(BitLength(sum))
63     }
64 }
65