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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(core_intrinsics))]
use core::ops::{Deref, DerefMut};
use core::time::Duration;
#[cfg(feature = "std")]
use std::time::SystemTime;
use time::{OffsetDateTime, PrimitiveDateTime, UtcOffset};
#[macro_use]
mod macros;
mod format;
mod parse;
mod ts_str;
use ts_str::{Full, FullMicroseconds, FullNanoseconds, FullOffset, Short};
pub use ts_str::TimestampStr;
pub mod formats {
pub use crate::ts_str::{Full, FullMicroseconds, FullNanoseconds, FullOffset, Short};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Timestamp(PrimitiveDateTime);
use core::fmt;
impl fmt::Display for Timestamp {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.format())
}
}
#[cfg(feature = "std")]
impl From<SystemTime> for Timestamp {
fn from(ts: SystemTime) -> Self {
Timestamp(match ts.duration_since(SystemTime::UNIX_EPOCH) {
Ok(dur) => Self::PRIMITIVE_UNIX_EPOCH + dur,
Err(err) => Self::PRIMITIVE_UNIX_EPOCH - err.duration(),
})
}
}
impl From<OffsetDateTime> for Timestamp {
fn from(ts: OffsetDateTime) -> Self {
let utc_datetime = ts.to_offset(UtcOffset::UTC);
let date = utc_datetime.date();
let time = utc_datetime.time();
Timestamp(PrimitiveDateTime::new(date, time))
}
}
impl From<PrimitiveDateTime> for Timestamp {
#[inline]
fn from(ts: PrimitiveDateTime) -> Self {
Timestamp(ts)
}
}
#[cfg(feature = "std")]
impl Timestamp {
#[inline]
pub fn now_utc() -> Self {
SystemTime::now().into()
}
}
impl Timestamp {
const PRIMITIVE_UNIX_EPOCH: PrimitiveDateTime = time::macros::datetime!(1970 - 01 - 01 00:00);
pub const UNIX_EPOCH: Self = Timestamp(Self::PRIMITIVE_UNIX_EPOCH);
pub fn from_unix_timestamp(seconds: i64) -> Self {
if seconds < 0 {
Self::UNIX_EPOCH - Duration::from_secs(-seconds as u64)
} else {
Self::UNIX_EPOCH + Duration::from_secs(seconds as u64)
}
}
pub fn from_unix_timestamp_ms(milliseconds: i64) -> Self {
if milliseconds < 0 {
Self::UNIX_EPOCH - Duration::from_millis(-milliseconds as u64)
} else {
Self::UNIX_EPOCH + Duration::from_millis(milliseconds as u64)
}
}
pub fn to_unix_timestamp_ms(self) -> i64 {
const UNIX_EPOCH_JULIAN_DAY: i64 = time::macros::date!(1970 - 01 - 01).to_julian_day() as i64;
let day = self.to_julian_day() as i64 - UNIX_EPOCH_JULIAN_DAY;
let (hour, minute, second, ms) = self.as_hms_milli();
let hours = day * 24 + hour as i64;
let minutes = hours * 60 + minute as i64;
let seconds = minutes * 60 + second as i64;
let millis = seconds * 1000 + ms as i64;
millis
}
pub fn format(&self) -> TimestampStr<Full> {
format::format_iso8601(self.0, UtcOffset::UTC)
}
pub fn format_short(&self) -> TimestampStr<Short> {
format::format_iso8601(self.0, UtcOffset::UTC)
}
pub fn format_with_offset(&self, offset: UtcOffset) -> TimestampStr<FullOffset> {
format::format_iso8601(self.0, offset)
}
pub fn format_nanoseconds(&self) -> TimestampStr<FullNanoseconds> {
format::format_iso8601(self.0, UtcOffset::UTC)
}
pub fn format_microseconds(&self) -> TimestampStr<FullMicroseconds> {
format::format_iso8601(self.0, UtcOffset::UTC)
}
#[inline]
pub fn parse(ts: &str) -> Option<Self> {
parse::parse_iso8601(ts).map(Timestamp)
}
pub const fn assume_offset(self, offset: UtcOffset) -> time::OffsetDateTime {
self.0.assume_offset(offset)
}
}
impl Deref for Timestamp {
type Target = PrimitiveDateTime;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Timestamp {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
use core::ops::{Add, Sub};
impl<T> Add<T> for Timestamp
where
PrimitiveDateTime: Add<T, Output = PrimitiveDateTime>,
{
type Output = Self;
#[inline]
fn add(self, rhs: T) -> Self::Output {
Timestamp(self.0 + rhs)
}
}
impl<T> Sub<T> for Timestamp
where
PrimitiveDateTime: Sub<T, Output = PrimitiveDateTime>,
{
type Output = Self;
#[inline]
fn sub(self, rhs: T) -> Self::Output {
Timestamp(self.0 - rhs)
}
}
#[cfg(feature = "serde")]
mod serde_impl {
#[cfg(feature = "bson")]
use serde::de::MapAccess;
use serde::de::{Deserialize, Deserializer, Error, Visitor};
use serde::ser::{Serialize, Serializer};
use super::Timestamp;
impl Serialize for Timestamp {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
self.format().serialize(serializer)
} else {
self.to_unix_timestamp_ms().serialize(serializer)
}
}
}
impl<'de> Deserialize<'de> for Timestamp {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use core::fmt;
struct TsVisitor;
impl<'de> Visitor<'de> for TsVisitor {
type Value = Timestamp;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("an ISO8601 Timestamp")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
match Timestamp::parse(v) {
Some(ts) => Ok(ts),
None => Err(E::custom("Invalid Format")),
}
}
#[cfg(feature = "bson")]
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
#[derive(serde::Deserialize, Debug)]
#[serde(untagged)]
enum StringOrNumberLong {
Str(Timestamp),
Num {
#[serde(rename = "$numberLong")]
num: String,
},
}
let (key, v) = access
.next_entry::<String, StringOrNumberLong>()?
.ok_or_else(|| M::Error::custom("Map Is Empty"))?;
if key == "$date" {
Ok(match v {
StringOrNumberLong::Str(ts) => ts,
StringOrNumberLong::Num { num } => Timestamp::from_unix_timestamp_ms(
num.parse::<i64>()
.map_err(|_| M::Error::custom("Invalid Number"))?,
),
})
} else {
Err(M::Error::custom("Expected only key `$date` in map"))
}
}
#[inline]
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Timestamp::from_unix_timestamp_ms(v))
}
#[inline]
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Timestamp::UNIX_EPOCH + std::time::Duration::from_millis(v))
}
}
deserializer.deserialize_any(TsVisitor)
}
}
}
#[cfg(feature = "pg")]
mod pg_impl {
use postgres_types::{accepts, to_sql_checked, FromSql, IsNull, ToSql, Type};
use time::PrimitiveDateTime;
use super::Timestamp;
impl ToSql for Timestamp {
#[inline]
fn to_sql(
&self,
ty: &Type,
out: &mut bytes::BytesMut,
) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>>
where
Self: Sized,
{
self.0.to_sql(ty, out)
}
accepts!(TIMESTAMP, TIMESTAMPTZ);
to_sql_checked!();
}
impl<'a> FromSql<'a> for Timestamp {
#[inline]
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
PrimitiveDateTime::from_sql(ty, raw).map(Timestamp)
}
accepts!(TIMESTAMP, TIMESTAMPTZ);
}
}
#[cfg(feature = "schema")]
mod schema_impl {
use schemars::_serde_json::json;
use schemars::schema::{InstanceType, Metadata, Schema, SchemaObject, SingleOrVec};
use schemars::JsonSchema;
use super::Timestamp;
impl JsonSchema for Timestamp {
fn schema_name() -> String {
"ISO8601 Timestamp".to_owned()
}
fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> Schema {
Schema::Object(SchemaObject {
metadata: Some(Box::new(Metadata {
description: Some("ISO8601 formatted timestamp".to_owned()),
examples: vec![json!("1970-01-01T00:00:00Z")],
..Default::default()
})),
format: Some("date-time".to_owned()),
instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
..Default::default()
})
}
}
}