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
17use crate::{error, polyfill};
18
19/// The length of something, in bits.
20///
21/// This can represent a bit length that isn't a whole number of bytes.
22#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
23#[repr(transparent)]
24pub struct BitLength<T = usize>(T);
25
26pub(crate) trait FromUsizeBytes: Sized {
27 /// Constructs a `BitLength` from the given length in bytes.
28 ///
29 /// Fails if `bytes * 8` is too large for a `T`.
30 fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified>;
31}
32
33impl FromUsizeBytes for BitLength<usize> {
34 #[inline]
35 fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified> {
36 let bits: usize = bytes.checked_shl(3).ok_or(err:error::Unspecified)?;
37 Ok(Self(bits))
38 }
39}
40
41impl FromUsizeBytes for BitLength<u64> {
42 #[inline]
43 fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified> {
44 let bytes: u64 = polyfill::u64_from_usize(bytes);
45 let bits: u64 = bytes.checked_shl(3).ok_or(err:error::Unspecified)?;
46 Ok(Self(bits))
47 }
48}
49
50impl<T: Copy> BitLength<T> {
51 /// The number of bits this bit length represents, as a `usize`.
52 #[inline]
53 pub fn as_bits(self) -> T {
54 self.0
55 }
56}
57
58// Lengths measured in bits, where all arithmetic is guaranteed not to
59// overflow.
60impl BitLength<usize> {
61 /// Constructs a `BitLength` from the given length in bits.
62 #[inline]
63 pub const fn from_usize_bits(bits: usize) -> Self {
64 Self(bits)
65 }
66
67 #[cfg(feature = "alloc")]
68 #[inline]
69 pub(crate) fn half_rounded_up(&self) -> Self {
70 let round_up = self.0 & 1;
71 Self((self.0 / 2) + round_up)
72 }
73
74 /// The bit length, rounded up to a whole number of bytes.
75 #[cfg(any(target_arch = "aarch64", feature = "alloc"))]
76 #[inline]
77 pub fn as_usize_bytes_rounded_up(&self) -> usize {
78 // Equivalent to (self.0 + 7) / 8, except with no potential for
79 // overflow and without branches.
80
81 // Branchless round_up = if self.0 & 0b111 != 0 { 1 } else { 0 };
82 let round_up = ((self.0 >> 2) | (self.0 >> 1) | self.0) & 1;
83
84 (self.0 / 8) + round_up
85 }
86
87 #[cfg(feature = "alloc")]
88 #[inline]
89 pub(crate) fn try_sub_1(self) -> Result<Self, error::Unspecified> {
90 let sum = self.0.checked_sub(1).ok_or(error::Unspecified)?;
91 Ok(Self(sum))
92 }
93}
94