use crate::calendar::{
CalendarError, Microsecond, Millisecond, NANOSECONDS_PER_MICROSECONDS,
NANOSECONDS_PER_MILLISECOND,
};
use core::hint;
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Nanosecond(u32);
impl Nanosecond {
pub const MAX: Self = Self(999_999_999);
pub const ZERO: Self = Self(0);
#[inline]
pub const fn from_num(num: u32) -> Result<Self, CalendarError> {
if num > 999_999_999 {
return Err(CalendarError::InvalidNanosecond { received: num });
}
Ok(Self(num))
}
#[inline]
pub const fn num(&self) -> u32 {
self.0
}
#[inline]
pub const fn to_ms(self) -> Millisecond {
match Millisecond::from_num((self.0 / NANOSECONDS_PER_MILLISECOND) as u16) {
Ok(elem) => elem,
Err(_err) => {
unsafe { hint::unreachable_unchecked() }
}
}
}
#[inline]
pub const fn to_us(self) -> Microsecond {
match Microsecond::from_num(self.0 / NANOSECONDS_PER_MICROSECONDS) {
Ok(elem) => elem,
Err(_err) => {
unsafe { hint::unreachable_unchecked() }
}
}
}
}
impl TryFrom<u32> for Nanosecond {
type Error = crate::Error;
#[inline]
fn try_from(from: u32) -> Result<Self, Self::Error> {
Ok(Self::from_num(from)?)
}
}