• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //! Bit Lengths.
16 
17 use crate::error;
18 
19 /// A length of an integer value, measured in bits.
20 #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
21 pub struct BitLength(usize);
22 
23 impl BitLength {
24     /// Constructs a `BitLength` from `bits`, where bits is interpreted as a bit length.
25     #[inline]
from_usize_bits(bits: usize) -> Self26     pub const fn from_usize_bits(bits: usize) -> Self {
27         Self(bits)
28     }
29 
30     /// Constructs a `BitLength` from `bits`, where bits is interpreted as a byte length.
31     #[inline]
from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified>32     pub fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified> {
33         let bits = bytes.checked_mul(8).ok_or(error::Unspecified)?;
34         Ok(Self::from_usize_bits(bits))
35     }
36 
37     #[cfg(feature = "alloc")]
38     #[inline]
half_rounded_up(&self) -> Self39     pub(crate) fn half_rounded_up(&self) -> Self {
40         let round_up = self.0 & 1;
41         Self((self.0 / 2) + round_up)
42     }
43 
44     #[inline]
as_usize_bits(&self) -> usize45     pub(crate) fn as_usize_bits(&self) -> usize {
46         self.0
47     }
48 
49     #[cfg(feature = "alloc")]
50     #[inline]
as_usize_bytes_rounded_up(&self) -> usize51     pub(crate) const fn as_usize_bytes_rounded_up(&self) -> usize {
52         // Equivalent to (self.0 + 7) / 8, except with no potential for
53         // overflow and without branches.
54 
55         // Branchless round_up = if self.0 & 0b111 != 0 { 1 } else { 0 };
56         let round_up = ((self.0 >> 2) | (self.0 >> 1) | self.0) & 1;
57 
58         (self.0 / 8) + round_up
59     }
60 
61     #[cfg(feature = "alloc")]
62     #[inline]
try_sub_1(self) -> Result<Self, error::Unspecified>63     pub(crate) fn try_sub_1(self) -> Result<Self, error::Unspecified> {
64         let sum = self.0.checked_sub(1).ok_or(error::Unspecified)?;
65         Ok(Self(sum))
66     }
67 }
68