1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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 {
    /// Checked add
    /// return None if overflow
    pub fn checked_add(self, rhs: Self) -> Option<Self> {
        self.0.checked_add(rhs.0).map(TimeInNs)
    }

    /// Checked sub
    /// return None if overflow
    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)
    }
}