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
//! ISO8601 Timestamp
//!
//! This crate provides high-performance formatting and parsing routines for ISO8601 timestamps, primarily focused on UTC values but with support
//! for parsing (and automatically applying) UTC Offsets.
//!
//! The primary purpose of this is to keep the lightweight representation of timestamps within data structures, and only formatting it to
//! a string when needed via Serde.
//!
//! The [Timestamp] struct is only 12 bytes, while the formatted strings can be as large as 29 bytes,
//! and care is taken to avoid heap allocations when formatting.
//!
//! Example:
//! ```rust,ignore
//! use serde::{Serialize, Deserialize};
//! use smol_str::SmolStr; // stack-allocation for small strings
//! use iso8601_timestamp::Timestamp;
//!
//! #[derive(Debug, Clone, Serialize, Deserialize)]
//! pub struct Event {
//!     name: SmolStr,
//!     ts: Timestamp,
//!     value: i32,
//! }
//! ```
//! when serialized to JSON could result in:
//! ```json
//! {
//!     "name": "some_event",
//!     "ts": "2021-10-17T02:03:01Z",
//!     "value": 42
//! }
//! ```
//!
//! When serializing to non-human-readable formats, such as binary formats, the `Timestamp` will be written
//! as an `i64` representing milliseconds since the Unix Epoch. This way it only uses 8 bytes instead of 24.
//!
//! Similarly, when deserializing, it supports either an ISO8601 string or an `i64` representing a unix timestamp in milliseconds.
//!
//! ## Features
//!
//! * `std` (default)
//!     - Enables standard library features, such as getting the current time.
//!
//! * `serde` (default)
//!     - Enables serde implementations for `Timestamp` and `TimestampStr`
//!
//! * `verify`
//!     - Verifies numeric inputs when parsing and fails when non-numeric input is found.
//!     - When disabled, parsing ignores invalid input, possibly giving garbage timestamps.
//!
//! * `nightly`
//!     - Enables nightly-specific optimizations, but without it will fallback to workarounds to enable the same optimizations.
//!
//! * `pg`
//!     - Enables `ToSql`/`FromSql` implementations for `Timestamp` so it can be directly stored/fetched from a PostgreSQL database using `rust-postgres`
//!
//! * `schema`
//!     - Enables implementation for `JsonSchema` for generating a JSON schema on the fly using `schemars`.
//!
//! * `bson`
//!     - Enables `visit_map` implementation to handle deserialising BSON (MongoDB) DateTime format, `{ $date: string }`.

#![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;

/// Timestamp formats
pub mod formats {
    pub use crate::ts_str::{Full, FullMicroseconds, FullNanoseconds, FullOffset, Short};
}

/// UTC Timestamp with nanosecond precision, millisecond-precision when serialized to serde (JSON).
///
/// A `Deref`/`DerefMut` implementation is provided to gain access to the inner `PrimitiveDateTime` object.
#[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 {
    /// Get the current time, assuming UTC
    #[inline]
    pub fn now_utc() -> Self {
        SystemTime::now().into()
    }
}

impl Timestamp {
    const PRIMITIVE_UNIX_EPOCH: PrimitiveDateTime = time::macros::datetime!(1970 - 01 - 01 00:00);

    /// Unix Epoch -- 1970-01-01 Midnight
    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
    }

    /// Format timestamp to ISO8601 with full punctuation, see [Full](formats::Full) for more information.
    pub fn format(&self) -> TimestampStr<Full> {
        format::format_iso8601(self.0, UtcOffset::UTC)
    }

    /// Format timestamp to ISO8601 without most punctuation, see [Short](formats::Short) for more information.
    pub fn format_short(&self) -> TimestampStr<Short> {
        format::format_iso8601(self.0, UtcOffset::UTC)
    }

    /// Format timestamp to ISO8601 with arbitrary UTC offset. Any offset is formatted as `+HH:MM`,
    /// and no timezone conversions are done. It is interpreted literally.
    ///
    /// See [FullOffset](formats::FullOffset) for more information.
    pub fn format_with_offset(&self, offset: UtcOffset) -> TimestampStr<FullOffset> {
        format::format_iso8601(self.0, offset)
    }

    /// Format timestamp to ISO8601 with extended precision to nanoseconds, see [FullNanoseconds](formats::FullNanoseconds) for more information.
    pub fn format_nanoseconds(&self) -> TimestampStr<FullNanoseconds> {
        format::format_iso8601(self.0, UtcOffset::UTC)
    }

    /// Format timestamp to ISO8601 with extended precision to microseconds, see [FullMicroseconds](formats::FullMicroseconds) for more information.
    pub fn format_microseconds(&self) -> TimestampStr<FullMicroseconds> {
        format::format_iso8601(self.0, UtcOffset::UTC)
    }

    /// Parse to UTC timestamp from any ISO8601 string. Offsets are applied during parsing.
    #[inline]
    pub fn parse(ts: &str) -> Option<Self> {
        parse::parse_iso8601(ts).map(Timestamp)
    }

    /// Convert to `time::OffsetDateTime` with the given offset.
    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>,
                {
                    // In the MongoDB database, or generally with BSON, dates
                    // are serialised into `{ $date: string }` where `$date`
                    // is what we actually want.

                    // Though in some cases if the year is < 1970 or > 9999, it will be:
                    // `{ $date: { $numberLong: string } }` where `$numberLong` is a signed integer (as a string)

                    #[derive(serde::Deserialize, Debug)]
                    #[serde(untagged)]
                    enum StringOrNumberLong {
                        Str(Timestamp),
                        Num {
                            #[serde(rename = "$numberLong")]
                            num: String,
                        },
                    }

                    // Fish out the first entry we can find.
                    let (key, v) = access
                        .next_entry::<String, StringOrNumberLong>()?
                        .ok_or_else(|| M::Error::custom("Map Is Empty"))?;

                    // Match `$date` and only date.
                    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 {
                        // We don't expect anything else in the map in any case,
                        // but throw an error if we do encounter anything weird.
                        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()
            })
        }
    }
}