use std::ops::{Add, Sub, Mul};
#[derive(Clone, PartialEq, Eq, Debug, Copy)]
pub struct Duration {
seconds: i64,
milliseconds: i16,
}
impl Duration {
pub fn zero() -> Self {
Self { seconds: 0, milliseconds: 0 }
}
pub fn of(seconds: i64) -> Self {
Self { seconds, milliseconds: 0 }
}
pub fn of_ms(seconds: i64, milliseconds: i16) -> Self {
assert!(milliseconds >= 0 && milliseconds <= 999); Self { seconds, milliseconds }
}
pub fn lengths(&self) -> (i64, i16) {
(self.seconds, self.milliseconds)
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Add<Duration> for Duration {
type Output = Self;
fn add(self, rhs: Self) -> Self {
let ms = self.milliseconds + rhs.milliseconds;
if ms >= 1000 {
Self::of_ms(self.seconds + rhs.seconds + 1, ms - 1000)
}
else {
Self::of_ms(self.seconds + rhs.seconds, ms)
}
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Sub<Duration> for Duration {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
let ms = self.milliseconds - rhs.milliseconds;
if ms < 0 {
Self::of_ms(self.seconds - rhs.seconds - 1, ms + 1000)
}
else {
Self::of_ms(self.seconds - rhs.seconds, ms)
}
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Mul<i64> for Duration {
type Output = Self;
fn mul(self, amount: i64) -> Self {
let ms = self.milliseconds as i64 * amount;
Self::of_ms(self.seconds * amount + ms / 1000, (ms % 1000) as i16)
}
}