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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use crate::error::{Error, Kind};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::convert::{Infallible, TryFrom};
use std::fmt;
use std::ops::{Add, Sub};
use std::str::FromStr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tendermint_proto::google::protobuf::Timestamp;
use tendermint_proto::serializers::timestamp;
use tendermint_proto::Protobuf;
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "Timestamp", into = "Timestamp")]
pub struct Time(DateTime<Utc>);
impl Protobuf<Timestamp> for Time {}
impl TryFrom<Timestamp> for Time {
type Error = Infallible;
fn try_from(value: Timestamp) -> Result<Self, Self::Error> {
let prost_value = prost_types::Timestamp {
seconds: value.seconds,
nanos: value.nanos,
};
Ok(SystemTime::from(prost_value).into())
}
}
impl From<Time> for Timestamp {
fn from(value: Time) -> Self {
let prost_value = prost_types::Timestamp::from(value.to_system_time().unwrap());
Timestamp {
seconds: prost_value.seconds,
nanos: prost_value.nanos,
}
}
}
impl Time {
pub fn now() -> Self {
Time(Utc::now())
}
pub fn unix_epoch() -> Self {
UNIX_EPOCH.into()
}
pub fn duration_since(&self, other: Time) -> Result<Duration, Error> {
self.0
.signed_duration_since(other.0)
.to_std()
.map_err(|_| Kind::OutOfRange.into())
}
pub fn parse_from_rfc3339(s: &str) -> Result<Time, Error> {
Ok(Time(DateTime::parse_from_rfc3339(s)?.with_timezone(&Utc)))
}
pub fn to_rfc3339(&self) -> String {
timestamp::to_rfc3339_nanos(&self.0)
}
pub fn to_system_time(&self) -> Result<SystemTime, Error> {
let duration_since_epoch = self.duration_since(Self::unix_epoch())?;
Ok(UNIX_EPOCH + duration_since_epoch)
}
}
impl fmt::Display for Time {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_rfc3339())
}
}
impl FromStr for Time {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Time::parse_from_rfc3339(s)
}
}
impl From<DateTime<Utc>> for Time {
fn from(t: DateTime<Utc>) -> Time {
Time(t)
}
}
impl From<Time> for DateTime<Utc> {
fn from(t: Time) -> DateTime<Utc> {
t.0
}
}
impl From<SystemTime> for Time {
fn from(t: SystemTime) -> Time {
Time(t.into())
}
}
impl From<Time> for SystemTime {
fn from(t: Time) -> SystemTime {
t.to_system_time().unwrap()
}
}
impl Add<Duration> for Time {
type Output = Self;
fn add(self, rhs: Duration) -> Self::Output {
let st: SystemTime = self.into();
(st + rhs).into()
}
}
impl Sub<Duration> for Time {
type Output = Self;
fn sub(self, rhs: Duration) -> Self::Output {
let st: SystemTime = self.into();
(st - rhs).into()
}
}
pub trait ParseTimestamp {
fn parse_timestamp(&self) -> Result<Time, Error>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serde_roundtrip() {
const DATES: &[&str] = &[
"2020-09-14T16:33:54.21191421Z",
"2020-09-14T16:33:00Z",
"2020-09-14T16:33:00.1Z",
"2020-09-14T16:33:00.211914212Z",
"1970-01-01T00:00:00Z",
"2021-01-07T20:25:56.0455760Z",
"2021-01-07T20:25:57.039219Z",
"2021-01-07T20:25:58.03562100Z",
"2021-01-07T20:25:59.000955200Z",
"2021-01-07T20:26:04.0121030Z",
"2021-01-07T20:26:05.005096Z",
"2021-01-07T20:26:09.08488400Z",
"2021-01-07T20:26:11.0875340Z",
"2021-01-07T20:26:12.078268Z",
"2021-01-07T20:26:13.08074100Z",
"2021-01-07T20:26:15.079663000Z",
];
for input in DATES {
let initial_time: Time = input.parse().unwrap();
let encoded_time = serde_json::to_value(&initial_time).unwrap();
let decoded_time = serde_json::from_value(encoded_time.clone()).unwrap();
assert_eq!(initial_time, decoded_time);
}
}
}