use crate::{error, polyfill};
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct BitLength<T = usize>(T);
pub(crate) trait FromUsizeBytes: Sized {
fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified>;
}
impl FromUsizeBytes for BitLength<usize> {
#[inline]
fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified> {
let bits = bytes.checked_shl(3).ok_or(error::Unspecified)?;
Ok(Self(bits))
}
}
impl FromUsizeBytes for BitLength<u64> {
#[inline]
fn from_usize_bytes(bytes: usize) -> Result<Self, error::Unspecified> {
let bytes = polyfill::u64_from_usize(bytes);
let bits = bytes.checked_shl(3).ok_or(error::Unspecified)?;
Ok(Self(bits))
}
}
impl<T: Copy> BitLength<T> {
#[inline]
pub fn as_bits(self) -> T {
self.0
}
}
impl BitLength<usize> {
#[inline]
pub const fn from_usize_bits(bits: usize) -> Self {
Self(bits)
}
#[cfg(feature = "alloc")]
#[inline]
pub(crate) fn half_rounded_up(&self) -> Self {
let round_up = self.0 & 1;
Self((self.0 / 2) + round_up)
}
#[cfg(any(target_arch = "aarch64", 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(crate) fn try_sub_1(self) -> Result<Self, error::Unspecified> {
let sum = self.0.checked_sub(1).ok_or(error::Unspecified)?;
Ok(Self(sum))
}
}