use std::fmt::Display;
use std::ops::{Add, Sub};
#[cfg(feature = "canister")]
use candid::CandidType;
use serde::{Deserialize, Serialize};
#[derive(
Default, Serialize, Clone, Debug, Deserialize, Copy, Ord, PartialOrd, PartialEq, Eq, Hash,
)]
#[cfg_attr(feature = "canister", derive(CandidType))]
#[serde(transparent)]
pub struct TimeInNs(pub u64);
impl TimeInNs {
pub fn checked_add(self, rhs: Self) -> Option<Self> {
self.0.checked_add(rhs.0).map(TimeInNs)
}
pub fn checked_sub(self, rhs: Self) -> Option<Self> {
self.0.checked_sub(rhs.0).map(TimeInNs)
}
}
impl Add for TimeInNs {
type Output = TimeInNs;
fn add(self, rhs: Self) -> Self::Output {
TimeInNs(self.0 + rhs.0)
}
}
impl Sub for TimeInNs {
type Output = TimeInNs;
fn sub(self, rhs: Self) -> Self::Output {
TimeInNs(self.0 - rhs.0)
}
}
impl Display for TimeInNs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ns", self.0)
}
}
#[derive(Serialize, Clone, Debug, Deserialize, Copy, Ord, PartialOrd, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "canister", derive(CandidType))]
#[serde(transparent)]
pub struct TimeInSec(pub u64);
impl From<TimeInNs> for TimeInSec {
fn from(ns: TimeInNs) -> Self {
TimeInSec(ns.0 / 1_000_000_000)
}
}
impl From<TimeInSec> for TimeInNs {
fn from(sec: TimeInSec) -> Self {
TimeInNs(sec.0.checked_mul(1_000_000_000).expect("overflow"))
}
}
impl Display for TimeInSec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} s", self.0)
}
}