1use chrono::Utc;
2use extended_primitives::Buffer;
3use handshake_encoding::{Decodable, DecodingError, Encodable};
4use std::cmp;
5use std::ops;
6
7#[derive(Copy, Debug, Clone, Default, Eq, Ord)]
9pub struct Time(u64);
10
11impl Time {
13 pub fn new() -> Self {
15 Default::default()
16 }
17
18 pub fn now() -> Self {
19 Time(Utc::now().timestamp() as u64)
20 }
21
22 pub fn to_seconds(self) -> u64 {
23 self.0
24 }
25}
26
27impl From<u64> for Time {
28 fn from(time: u64) -> Self {
29 Time(time)
30 }
31}
32
33impl<T> ops::Add<T> for Time
35where
36 T: Into<Time>,
37{
38 type Output = Self;
39
40 fn add(self, other: T) -> Self {
41 Self(self.0 + other.into().0)
42 }
43}
44
45impl<T> ops::Sub<T> for Time
46where
47 T: Into<Time>,
48{
49 type Output = Self;
50
51 fn sub(self, other: T) -> Self {
52 Self(self.0 - other.into().0)
53 }
54}
55
56impl cmp::PartialEq<u64> for Time {
59 fn eq(&self, other: &u64) -> bool {
60 &self.0 == other
61 }
62}
63
64impl cmp::PartialEq for Time {
65 fn eq(&self, other: &Self) -> bool {
66 self.0 == other.0
67 }
68}
69
70impl cmp::PartialOrd<u64> for Time {
71 fn partial_cmp(&self, other: &u64) -> Option<cmp::Ordering> {
72 Some(self.0.cmp(other))
73 }
74}
75
76impl cmp::PartialOrd for Time {
77 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
78 Some(self.0.cmp(&other.0))
79 }
80}
81
82impl Encodable for Time {
85 fn size(&self) -> usize {
86 8
87 }
88
89 fn encode(&self) -> Buffer {
90 let mut buffer = Buffer::new();
91
92 buffer.write_u64(self.0);
93
94 buffer
95 }
96}
97
98impl Decodable for Time {
99 type Err = DecodingError;
100
101 fn decode(buffer: &mut Buffer) -> Result<Self, Self::Err> {
102 let inner = buffer.read_u64()?;
103
104 Ok(Self(inner))
105 }
106}