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
use chrono::Utc;
use extended_primitives::Buffer;
use handshake_encoding::{Decodable, DecodingError, Encodable};
use std::cmp;
use std::ops;
#[derive(Copy, Debug, Clone, Default, Eq, Ord)]
pub struct Time(u64);
impl Time {
pub fn new() -> Self {
Default::default()
}
pub fn now() -> Self {
Time(Utc::now().timestamp() as u64)
}
pub fn to_seconds(self) -> u64 {
self.0
}
}
impl From<u64> for Time {
fn from(time: u64) -> Self {
Time(time)
}
}
impl<T> ops::Add<T> for Time
where
T: Into<Time>,
{
type Output = Self;
fn add(self, other: T) -> Self {
Self(self.0 + other.into().0)
}
}
impl<T> ops::Sub<T> for Time
where
T: Into<Time>,
{
type Output = Self;
fn sub(self, other: T) -> Self {
Self(self.0 - other.into().0)
}
}
impl cmp::PartialEq<u64> for Time {
fn eq(&self, other: &u64) -> bool {
&self.0 == other
}
}
impl cmp::PartialEq for Time {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl cmp::PartialOrd<u64> for Time {
fn partial_cmp(&self, other: &u64) -> Option<cmp::Ordering> {
Some(self.0.cmp(other))
}
}
impl cmp::PartialOrd for Time {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.0.cmp(&other.0))
}
}
impl Encodable for Time {
fn size(&self) -> usize {
8
}
fn encode(&self) -> Buffer {
let mut buffer = Buffer::new();
buffer.write_u64(self.0);
buffer
}
}
impl Decodable for Time {
type Err = DecodingError;
fn decode(buffer: &mut Buffer) -> Result<Self, Self::Err> {
let inner = buffer.read_u64()?;
Ok(Self(inner))
}
}