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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use chrono::{DateTime, NaiveDateTime, Utc};
use newtype_ops::newtype_ops;
use serde::{Deserialize, Serialize};
use std::{fmt, ops::Div};
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)]
pub struct EpochTime(u64);
impl EpochTime {
pub fn now() -> EpochTime {
EpochTime(Utc::now().timestamp() as u64)
}
pub fn as_u64(self) -> u64 {
self.0
}
pub fn increase(self, seconds: u64) -> EpochTime {
let num = seconds.checked_add(self.0);
let value = match num {
Some(v) => v,
_ => panic!("u64 overlfow in timestamp"),
};
EpochTime(value)
}
pub fn checked_sub(self, other: EpochTime) -> Option<EpochTime> {
match self.0.checked_sub(other.0) {
None => None,
Some(v) => Some(EpochTime(v)),
}
}
}
impl Default for EpochTime {
fn default() -> Self {
EpochTime(Utc::now().timestamp() as u64)
}
}
newtype_ops! { [EpochTime] {add sub} {:=} Self Self }
newtype_ops! { [EpochTime] {add sub} {:=} &Self &Self }
newtype_ops! { [EpochTime] {add sub} {:=} Self &Self }
newtype_ops! { [EpochTime] {mul div rem} {:=} Self u64 }
impl Div for EpochTime {
type Output = u64;
fn div(self, rhs: Self) -> Self::Output {
self.0 / rhs.0
}
}
impl fmt::Display for EpochTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<u64> for EpochTime {
fn from(value: u64) -> Self {
EpochTime(value)
}
}
impl From<DateTime<Utc>> for EpochTime {
fn from(value: DateTime<Utc>) -> Self {
EpochTime(value.timestamp() as u64)
}
}
impl From<EpochTime> for DateTime<Utc> {
fn from(value: EpochTime) -> Self {
DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(value.0 as i64, 0), Utc)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn add_epoch_time() {
assert_eq!(EpochTime::from(1_000) + EpochTime::from(8_000), EpochTime::from(9_000));
assert_eq!(&EpochTime::from(15) + &EpochTime::from(5), EpochTime::from(20));
}
}