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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#![deny(missing_docs)]
#[allow(missing_docs)]
mod error;
#[cfg(feature = "chrono")]
mod human;
#[cfg(feature = "chrono")]
pub use human::*;
use core::ops::{Add, Sub};
use serde::{Deserialize, Serialize};
use std::convert::{TryFrom, TryInto};
pub use crate::error::{TimestampError, TimestampResult};
#[cfg(feature = "chrono")]
pub(crate) use chrono_ext::*;
#[cfg(feature = "chrono")]
mod chrono_ext;
pub const MM: i64 = 1_000_000;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(not(feature = "chrono"), derive(Debug))]
pub struct Timestamp(
pub i64,
);
impl<D: Into<core::time::Duration>> Add<D> for Timestamp {
type Output = TimestampResult<Timestamp>;
fn add(self, rhs: D) -> Self::Output {
self.checked_add(&rhs.into())
.ok_or(TimestampError::Overflow)
}
}
impl<D: Into<core::time::Duration>> Add<D> for &Timestamp {
type Output = TimestampResult<Timestamp>;
fn add(self, rhs: D) -> Self::Output {
self.to_owned() + rhs
}
}
impl<D: Into<core::time::Duration>> Sub<D> for Timestamp {
type Output = TimestampResult<Timestamp>;
fn sub(self, rhs: D) -> Self::Output {
self.checked_sub(&rhs.into())
.ok_or(TimestampError::Overflow)
}
}
impl<D: Into<core::time::Duration>> Sub<D> for &Timestamp {
type Output = TimestampResult<Timestamp>;
fn sub(self, rhs: D) -> Self::Output {
self.to_owned() - rhs
}
}
impl Timestamp {
pub const ZERO: Timestamp = Timestamp(0);
pub const MIN: Timestamp = Timestamp(i64::MIN);
pub const MAX: Timestamp = Timestamp(i64::MAX);
pub const HOLOCHAIN_EPOCH: Timestamp = Timestamp(1640995200000000);
pub fn max() -> Timestamp {
Timestamp(i64::MAX)
}
pub fn from_micros(micros: i64) -> Self {
Self(micros)
}
pub fn as_micros(&self) -> i64 {
self.0
}
pub fn as_millis(&self) -> i64 {
self.0 / 1000
}
pub fn as_seconds_and_nanos(&self) -> (i64, u32) {
let secs = self.0 / MM;
let nsecs = (self.0 % 1_000_000) * 1000;
(secs, nsecs as u32)
}
pub fn checked_add(&self, rhs: &core::time::Duration) -> Option<Timestamp> {
let micros = rhs.as_micros();
if micros <= i64::MAX as u128 {
Some(Self(self.0.checked_add(micros as i64)?))
} else {
None
}
}
pub fn checked_sub(&self, rhs: &core::time::Duration) -> Option<Timestamp> {
let micros = rhs.as_micros();
if micros <= i64::MAX as u128 {
Some(Self(self.0.checked_sub(micros as i64)?))
} else {
None
}
}
pub fn saturating_add(&self, rhs: &core::time::Duration) -> Timestamp {
self.checked_add(rhs).unwrap_or(Self::MAX)
}
pub fn saturating_sub(&self, rhs: &core::time::Duration) -> Timestamp {
self.checked_sub(rhs).unwrap_or(Self::MIN)
}
pub fn saturating_from_dur(duration: &core::time::Duration) -> Self {
Timestamp(std::cmp::min(duration.as_micros(), i64::MAX as u128) as i64)
}
pub fn into_sql_lossy(self) -> Self {
Self(i64::clamp(self.0, -62167219200 * MM, 106751991167 * MM))
}
}
impl TryFrom<core::time::Duration> for Timestamp {
type Error = error::TimestampError;
fn try_from(value: core::time::Duration) -> Result<Self, Self::Error> {
Ok(Timestamp(
value
.as_micros()
.try_into()
.map_err(|_| error::TimestampError::Overflow)?,
))
}
}
#[cfg(feature = "rusqlite")]
impl rusqlite::ToSql for Timestamp {
fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput> {
Ok(rusqlite::types::ToSqlOutput::Owned(
self.into_sql_lossy().0.into(),
))
}
}
#[cfg(feature = "rusqlite")]
impl rusqlite::types::FromSql for Timestamp {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
match value {
rusqlite::types::ValueRef::Integer(i) => Ok(Self::from_micros(i)),
_ => Err(rusqlite::types::FromSqlError::InvalidType),
}
}
}
#[cfg(test)]
mod tests {
use std::convert::TryInto;
use super::*;
const TEST_TS: &'static str = "2020-05-05T19:16:04.266431Z";
#[test]
fn timestamp_distance() {
let t1 = Timestamp(i64::MAX); let d1: TimestampResult<chrono::DateTime<chrono::Utc>> = t1.try_into();
assert_eq!(d1, Err(TimestampError::Overflow));
let t2 = Timestamp(0) + core::time::Duration::new(0, 1000);
assert_eq!(t2, Ok(Timestamp(1)));
}
#[test]
fn micros_roundtrip() {
for t in [Timestamp(1234567890), Timestamp(987654321)] {
let micros = t.clone().into_sql_lossy().as_micros();
let r = Timestamp::from_micros(micros);
assert_eq!(t.0, r.0);
assert_eq!(t, r);
}
}
#[test]
fn test_timestamp_serialization() {
use holochain_serialized_bytes::prelude::*;
let t: Timestamp = TEST_TS.try_into().unwrap();
let (secs, nsecs) = t.as_seconds_and_nanos();
assert_eq!(secs, 1588706164);
assert_eq!(nsecs, 266431000);
assert_eq!(TEST_TS, &t.to_string());
#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes)]
struct S(Timestamp);
let s = S(t);
let sb = SerializedBytes::try_from(s).unwrap();
let s: S = sb.try_into().unwrap();
let t = s.0;
assert_eq!(TEST_TS, &t.to_string());
}
}