1use crate::{error::InputTooLongError, polyfill};
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
23#[repr(transparent)]
24pub struct BitLength<T = usize>(T);
25
26pub(crate) trait FromByteLen<T>: Sized {
27 fn from_byte_len(bytes: T) -> Result<Self, InputTooLongError<T>>;
31}
32
33impl FromByteLen<usize> for BitLength<usize> {
34 #[inline]
35 fn from_byte_len(bytes: usize) -> Result<Self, InputTooLongError> {
36 match bytes.checked_mul(8) {
37 Some(bits) => Ok(Self(bits)),
38 None => Err(InputTooLongError::new(bytes)),
39 }
40 }
41}
42
43impl FromByteLen<u64> for BitLength<u64> {
44 #[inline]
45 fn from_byte_len(bytes: u64) -> Result<Self, InputTooLongError<u64>> {
46 match bytes.checked_mul(8) {
47 Some(bits) => Ok(Self(bits)),
48 None => Err(InputTooLongError::new(bytes)),
49 }
50 }
51}
52
53impl FromByteLen<usize> for BitLength<u64> {
54 #[inline]
55 fn from_byte_len(bytes: usize) -> Result<Self, InputTooLongError<usize>> {
56 match polyfill::u64_from_usize(bytes).checked_mul(8) {
57 Some(bits) => Ok(Self(bits)),
58 None => Err(InputTooLongError::new(bytes)),
59 }
60 }
61}
62
63impl<T> BitLength<T> {
64 #[inline]
66 pub const fn from_bits(bits: T) -> Self {
67 Self(bits)
68 }
69}
70
71impl<T: Copy> BitLength<T> {
72 #[inline]
74 pub fn as_bits(self) -> T {
75 self.0
76 }
77}
78
79impl BitLength<usize> {
82 #[cfg(feature = "alloc")]
83 #[inline]
84 pub(crate) fn half_rounded_up(&self) -> Self {
85 let round_up = self.0 & 1;
86 Self((self.0 / 2) + round_up)
87 }
88
89 #[inline]
91 pub const fn as_usize_bytes_rounded_up(&self) -> usize {
92 let round_up = ((self.0 >> 2) | (self.0 >> 1) | self.0) & 1;
97
98 (self.0 / 8) + round_up
99 }
100
101 #[cfg(feature = "alloc")]
102 #[inline]
103 pub(crate) fn try_sub_1(self) -> Result<Self, crate::error::Unspecified> {
104 let sum = self.0.checked_sub(1).ok_or(crate::error::Unspecified)?;
105 Ok(Self(sum))
106 }
107}
108
109impl BitLength<u64> {
110 pub fn to_be_bytes(self) -> [u8; 8] {
111 self.0.to_be_bytes()
112 }
113}
114
115#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
116impl From<BitLength<usize>> for BitLength<u64> {
117 fn from(BitLength(value): BitLength<usize>) -> Self {
118 BitLength(polyfill::u64_from_usize(value))
119 }
120}
121
122impl TryFrom<BitLength<u64>> for BitLength<core::num::NonZeroU64> {
123 type Error = <core::num::NonZeroU64 as TryFrom<u64>>::Error;
124
125 fn try_from(BitLength(value): BitLength<u64>) -> Result<Self, Self::Error> {
126 value.try_into().map(BitLength)
127 }
128}
129
130const _TEST_AS_USIZE_BYTES_ROUNDED_UP_EVEN: () =
131 assert!(BitLength::from_bits(8192).as_usize_bytes_rounded_up() == 8192 / 8);
132const _TEST_AS_USIZE_BYTES_ROUNDED_UP_ONE_BIT_HIGH: () =
133 assert!(BitLength::from_bits(8192 + 1).as_usize_bytes_rounded_up() == (8192 / 8) + 1);
134const _TEST_AS_USIZE_BYTES_ROUNDED_UP_SEVEN_BITS_HIGH: () =
135 assert!(BitLength::from_bits(8192 + 7).as_usize_bytes_rounded_up() == (8192 / 8) + 1);