use std::ops::{Add, AddAssign, Neg, Sub, SubAssign};
use super::{Duration, TICKS_PER_SECOND, try_rounded_ticks};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TimeOffset(i64);
impl TimeOffset {
pub const ZERO: Self = Self(0);
pub const fn from_ticks(ticks: i64) -> Self {
Self(ticks)
}
pub fn from_seconds(seconds: f64) -> Self {
Self::try_from_seconds(seconds).unwrap_or_else(|error| panic!("{}", error.message))
}
pub fn try_from_seconds(seconds: f64) -> Result<Self, crate::ValidationError> {
try_rounded_ticks(seconds * TICKS_PER_SECOND as f64).map(Self)
}
pub const fn ticks(self) -> i64 {
self.0
}
pub fn as_seconds(self) -> f64 {
self.0 as f64 / TICKS_PER_SECOND as f64
}
pub const fn is_negative(self) -> bool {
self.0 < 0
}
pub const fn magnitude(self) -> Duration {
Duration::from_ticks(self.0.unsigned_abs())
}
pub const fn to_duration(self) -> Option<Duration> {
if self.0 < 0 {
None
} else {
Some(Duration::from_ticks(self.0 as u64))
}
}
}
impl Add for TimeOffset {
type Output = Self;
fn add(self, other: Self) -> Self {
Self(
self.0
.checked_add(other.0)
.expect("offset addition overflow"),
)
}
}
impl Sub for TimeOffset {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self(
self.0
.checked_sub(other.0)
.expect("offset subtraction overflow"),
)
}
}
impl AddAssign for TimeOffset {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
impl SubAssign for TimeOffset {
fn sub_assign(&mut self, other: Self) {
*self = *self - other;
}
}
impl Neg for TimeOffset {
type Output = Self;
fn neg(self) -> Self {
Self(self.0.checked_neg().expect("offset negation overflow"))
}
}