use core::{
convert::{TryFrom, TryInto},
fmt, ops,
};
use crate::utils::{Init, ZeroInit};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Duration {
micros: i32,
}
impl Init for Duration {
const INIT: Self = Self::ZERO;
}
unsafe impl ZeroInit for Duration {}
impl Default for Duration {
fn default() -> Self {
Self::INIT
}
}
impl Duration {
pub const ZERO: Self = Duration { micros: 0 };
pub const MAX: Self = Duration { micros: i32::MAX };
pub const MIN: Self = Duration { micros: i32::MIN };
#[inline]
pub const fn from_micros(micros: i32) -> Self {
Self { micros }
}
#[inline]
pub const fn from_millis(millis: i32) -> Self {
Self::from_micros(if let Some(x) = millis.checked_mul(1_000) {
x
} else {
panic!("duration overflow");
})
}
#[inline]
pub const fn from_secs(secs: i32) -> Self {
Self::from_micros(if let Some(x) = secs.checked_mul(1_000_000) {
x
} else {
panic!("duration overflow");
})
}
#[inline]
pub const fn as_micros(self) -> i32 {
self.micros
}
#[inline]
pub const fn as_millis(self) -> i32 {
self.micros / 1_000
}
#[inline]
pub const fn as_secs(self) -> i32 {
self.micros / 1_000_000
}
#[inline]
pub const fn as_secs_f64(self) -> f64 {
self.micros as f64 / 1_000_000.0
}
#[inline]
pub const fn as_secs_f32(self) -> f32 {
(self.micros / 1_000_000) as f32 + (self.micros % 1_000_000) as f32 / 1_000_000.0
}
#[inline]
pub const fn is_positive(self) -> bool {
self.micros.is_positive()
}
#[inline]
pub const fn is_negative(self) -> bool {
self.micros.is_negative()
}
#[inline]
pub const fn checked_mul(self, other: i32) -> Option<Self> {
if let Some(x) = self.micros.checked_mul(other) {
Some(Self::from_micros(x))
} else {
None
}
}
#[inline]
pub const fn checked_div(self, other: i32) -> Option<Self> {
if let Some(x) = self.micros.checked_div(other) {
Some(Self::from_micros(x))
} else {
None
}
}
#[inline]
pub const fn checked_abs(self) -> Option<Self> {
if let Some(x) = self.micros.checked_abs() {
Some(Self::from_micros(x))
} else {
None
}
}
#[inline]
pub const fn checked_add(self, other: Self) -> Option<Self> {
if let Some(x) = self.micros.checked_add(other.micros) {
Some(Self::from_micros(x))
} else {
None
}
}
#[inline]
pub const fn checked_sub(self, other: Self) -> Option<Self> {
if let Some(x) = self.micros.checked_sub(other.micros) {
Some(Self::from_micros(x))
} else {
None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TryFromDurationError(());
impl TryFrom<core::time::Duration> for Duration {
type Error = TryFromDurationError;
fn try_from(value: core::time::Duration) -> Result<Self, Self::Error> {
Ok(Self::from_micros(
value
.as_micros()
.try_into()
.map_err(|_| TryFromDurationError(()))?,
))
}
}
impl TryFrom<Duration> for core::time::Duration {
type Error = TryFromDurationError;
fn try_from(value: Duration) -> Result<Self, Self::Error> {
if value.micros < 0 {
Err(TryFromDurationError(()))
} else {
Ok(Self::from_micros(value.micros as u64))
}
}
}
impl fmt::Debug for Duration {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let abs_dur = core::time::Duration::from_micros((self.micros as i64).abs() as u64);
if self.micros < 0 {
write!(f, "-")?;
}
abs_dur.fmt(f)
}
}
impl ops::Add for Duration {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.checked_add(rhs)
.expect("overflow when adding durations")
}
}
impl ops::AddAssign for Duration {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs;
}
}
impl ops::Sub for Duration {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.checked_sub(rhs)
.expect("overflow when subtracting durations")
}
}
impl ops::SubAssign for Duration {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs;
}
}
impl ops::Mul<i32> for Duration {
type Output = Duration;
#[inline]
fn mul(self, rhs: i32) -> Self::Output {
self.checked_mul(rhs)
.expect("overflow when multiplying duration by scalar")
}
}
impl ops::Mul<Duration> for i32 {
type Output = Duration;
#[inline]
fn mul(self, rhs: Duration) -> Self::Output {
rhs.checked_mul(self)
.expect("overflow when multiplying duration by scalar")
}
}
impl ops::MulAssign<i32> for Duration {
#[inline]
fn mul_assign(&mut self, rhs: i32) {
*self = *self * rhs;
}
}
impl ops::Div<i32> for Duration {
type Output = Duration;
#[inline]
fn div(self, rhs: i32) -> Self::Output {
self.checked_div(rhs)
.expect("divide by zero or overflow when dividing duration by scalar")
}
}
impl ops::DivAssign<i32> for Duration {
#[inline]
fn div_assign(&mut self, rhs: i32) {
*self = *self / rhs;
}
}
impl core::iter::Sum for Duration {
fn sum<I: Iterator<Item = Duration>>(iter: I) -> Self {
iter.fold(Duration::ZERO, |x, y| {
x.checked_add(y)
.expect("overflow in iter::sum over durations")
})
}
}
impl<'a> core::iter::Sum<&'a Duration> for Duration {
fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Self {
iter.cloned().sum()
}
}
#[cfg(feature = "chrono")]
impl TryFrom<chrono::Duration> for Duration {
type Error = TryFromDurationError;
fn try_from(value: chrono::Duration) -> Result<Self, Self::Error> {
Ok(Self::from_micros(
value
.num_microseconds()
.and_then(|x| x.try_into().ok())
.ok_or(TryFromDurationError(()))?,
))
}
}
#[cfg(feature = "chrono")]
impl From<Duration> for chrono::Duration {
fn from(value: Duration) -> Self {
Self::microseconds(value.micros as i64)
}
}