use core::fmt;
use core::num::NonZeroU64;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Millis(u64);
impl Millis {
pub const ZERO: Self = Self(0);
#[must_use]
pub const fn new(ms: u64) -> Self {
Self(ms)
}
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
#[must_use]
pub const fn saturating_add(self, other: Self) -> Self {
Self(self.0.saturating_add(other.0))
}
#[must_use]
pub const fn saturating_sub(self, other: Self) -> Self {
Self(self.0.saturating_sub(other.0))
}
#[must_use]
pub const fn max(self, other: Self) -> Self {
if self.0 >= other.0 {
self
} else {
other
}
}
#[must_use]
pub fn div_ceil_by(self, divisor: NonZeroU64) -> Self {
Self(self.0.div_ceil(divisor.get()))
}
#[must_use]
pub fn scaled(self, numerator: u64, denominator: NonZeroU64) -> Self {
let d = denominator.get() as u128;
let product = self.0 as u128 * numerator as u128;
#[allow(clippy::integer_division)]
let q = (product + d / 2) / d;
if q > u64::MAX as u128 {
Self(u64::MAX)
} else {
Self(q as u64)
}
}
}
impl fmt::Display for Millis {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}ms", self.0)
}
}
impl core::iter::Sum for Millis {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self::ZERO, Self::saturating_add)
}
}