use core::{
borrow::Borrow,
fmt::{self, Display, Formatter},
ops::Deref,
};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct U22(u32);
impl Display for U22 {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl U22 {
pub const MAX: u32 = !(u32::MAX << 22);
pub const fn from_u32(n: u32) -> Result<Self, U22FromU32Error> {
if n > Self::MAX {
Err(U22FromU32Error(n))
} else {
Ok(Self(n))
}
}
pub const unsafe fn from_u32_unchecked(n: u32) -> Self {
Self(n)
}
pub const fn as_u32(self) -> u32 {
self.0
}
}
impl TryFrom<u32> for U22 {
type Error = U22FromU32Error;
fn try_from(n: u32) -> Result<Self, Self::Error> {
Self::from_u32(n)
}
}
impl From<U22> for u32 {
fn from(u22: U22) -> Self {
u22.0
}
}
impl AsRef<u32> for U22 {
fn as_ref(&self) -> &u32 {
&self.0
}
}
impl Borrow<u32> for U22 {
fn borrow(&self) -> &u32 {
&self.0
}
}
impl Deref for U22 {
type Target = u32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct U22FromU32Error(
pub u32,
);
impl Display for U22FromU32Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{} exceeds U22::MAX", self.0)
}
}