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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

//! DateTime type for representing Smithy timestamps.

use num_integer::div_mod_floor;
use num_integer::Integer;
use std::convert::TryFrom;
use std::error::Error as StdError;
use std::fmt;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

mod format;
pub use self::format::DateTimeFormatError;
pub use self::format::DateTimeParseError;

const MILLIS_PER_SECOND: i64 = 1000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const NANOS_PER_SECOND: i128 = 1_000_000_000;
const NANOS_PER_SECOND_U32: u32 = 1_000_000_000;

/* ANCHOR: date_time */

/// DateTime in time.
///
/// DateTime in time represented as seconds and sub-second nanos since
/// the Unix epoch (January 1, 1970 at midnight UTC/GMT).
///
/// This type can be converted to/from the standard library's [`SystemTime`](std::time::SystemTime):
/// ```rust
/// # fn doc_fn() -> Result<(), aws_smithy_types::date_time::ConversionError> {
/// # use aws_smithy_types::date_time::DateTime;
/// # use std::time::SystemTime;
/// use std::convert::TryFrom;
///
/// let the_millennium_as_system_time = SystemTime::try_from(DateTime::from_secs(946_713_600))?;
/// let now_as_date_time = DateTime::from(SystemTime::now());
/// # Ok(())
/// # }
/// ```
///
/// The [`aws-smithy-types-convert`](https://crates.io/crates/aws-smithy-types-convert) crate
/// can be used for conversions to/from other libraries, such as
/// [`time`](https://crates.io/crates/time) or [`chrono`](https://crates.io/crates/chrono).
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DateTime {
    seconds: i64,
    subsecond_nanos: u32,
}

/* ANCHOR_END: date_time */

impl DateTime {
    /// Creates a `DateTime` from a number of seconds since the Unix epoch.
    pub fn from_secs(epoch_seconds: i64) -> Self {
        DateTime {
            seconds: epoch_seconds,
            subsecond_nanos: 0,
        }
    }

    /// Creates a `DateTime` from a number of milliseconds since the Unix epoch.
    pub fn from_millis(epoch_millis: i64) -> DateTime {
        let (seconds, millis) = div_mod_floor(epoch_millis, MILLIS_PER_SECOND);
        DateTime::from_secs_and_nanos(seconds, millis as u32 * NANOS_PER_MILLI)
    }

    /// Creates a `DateTime` from a number of nanoseconds since the Unix epoch.
    pub fn from_nanos(epoch_nanos: i128) -> Result<Self, ConversionError> {
        let (seconds, subsecond_nanos) = epoch_nanos.div_mod_floor(&NANOS_PER_SECOND);
        let seconds = i64::try_from(seconds).map_err(|_| {
            ConversionError("given epoch nanos are too large to fit into a DateTime")
        })?;
        let subsecond_nanos = subsecond_nanos as u32; // safe cast because of the modulus
        Ok(DateTime {
            seconds,
            subsecond_nanos,
        })
    }

    /// Returns the number of nanoseconds since the Unix epoch that this `DateTime` represents.
    pub fn as_nanos(&self) -> i128 {
        let seconds = self.seconds as i128 * NANOS_PER_SECOND;
        if seconds < 0 {
            let adjusted_nanos = self.subsecond_nanos as i128 - NANOS_PER_SECOND;
            seconds + NANOS_PER_SECOND + adjusted_nanos
        } else {
            seconds + self.subsecond_nanos as i128
        }
    }

    /// Creates a `DateTime` from a number of seconds and a fractional second since the Unix epoch.
    ///
    /// # Example
    /// ```
    /// # use aws_smithy_types::DateTime;
    /// assert_eq!(
    ///     DateTime::from_secs_and_nanos(1, 500_000_000u32),
    ///     DateTime::from_fractional_secs(1, 0.5),
    /// );
    /// ```
    pub fn from_fractional_secs(epoch_seconds: i64, fraction: f64) -> Self {
        let subsecond_nanos = (fraction * 1_000_000_000_f64) as u32;
        DateTime::from_secs_and_nanos(epoch_seconds, subsecond_nanos)
    }

    /// Creates a `DateTime` from a number of seconds and sub-second nanos since the Unix epoch.
    ///
    /// # Example
    /// ```
    /// # use aws_smithy_types::DateTime;
    /// assert_eq!(
    ///     DateTime::from_fractional_secs(1, 0.5),
    ///     DateTime::from_secs_and_nanos(1, 500_000_000u32),
    /// );
    /// ```
    pub fn from_secs_and_nanos(seconds: i64, subsecond_nanos: u32) -> Self {
        if subsecond_nanos >= 1_000_000_000 {
            panic!("{} is > 1_000_000_000", subsecond_nanos)
        }
        DateTime {
            seconds,
            subsecond_nanos,
        }
    }

    /// Returns the `DateTime` value as an `f64` representing the seconds since the Unix epoch.
    ///
    /// _Note: This conversion will lose precision due to the nature of floating point numbers._
    pub fn as_secs_f64(&self) -> f64 {
        self.seconds as f64 + self.subsecond_nanos as f64 / 1_000_000_000_f64
    }

    /// Creates a `DateTime` from an `f64` representing the number of seconds since the Unix epoch.
    ///
    /// # Example
    /// ```
    /// # use aws_smithy_types::DateTime;
    /// assert_eq!(
    ///     DateTime::from_fractional_secs(1, 0.5),
    ///     DateTime::from_secs_f64(1.5),
    /// );
    /// ```
    pub fn from_secs_f64(epoch_seconds: f64) -> Self {
        let seconds = epoch_seconds.floor() as i64;
        let rem = epoch_seconds - epoch_seconds.floor();
        DateTime::from_fractional_secs(seconds, rem)
    }

    /// Parses a `DateTime` from a string using the given `format`.
    pub fn from_str(s: &str, format: Format) -> Result<Self, DateTimeParseError> {
        match format {
            Format::DateTime => format::rfc3339::parse(s),
            Format::HttpDate => format::http_date::parse(s),
            Format::EpochSeconds => format::epoch_seconds::parse(s),
        }
    }

    /// Returns true if sub-second nanos is greater than zero.
    pub fn has_subsec_nanos(&self) -> bool {
        self.subsecond_nanos != 0
    }

    /// Returns the epoch seconds component of the `DateTime`.
    ///
    /// _Note: this does not include the sub-second nanos._
    pub fn secs(&self) -> i64 {
        self.seconds
    }

    /// Returns the sub-second nanos component of the `DateTime`.
    ///
    /// _Note: this does not include the number of seconds since the epoch._
    pub fn subsec_nanos(&self) -> u32 {
        self.subsecond_nanos
    }

    /// Converts the `DateTime` to the number of milliseconds since the Unix epoch.
    ///
    /// This is fallible since `DateTime` holds more precision than an `i64`, and will
    /// return a `ConversionError` for `DateTime` values that can't be converted.
    pub fn to_millis(self) -> Result<i64, ConversionError> {
        let subsec_millis =
            Integer::div_floor(&i64::from(self.subsecond_nanos), &(NANOS_PER_MILLI as i64));
        if self.seconds < 0 {
            self.seconds
                .checked_add(1)
                .and_then(|seconds| seconds.checked_mul(MILLIS_PER_SECOND))
                .and_then(|millis| millis.checked_sub(1000 - subsec_millis))
        } else {
            self.seconds
                .checked_mul(MILLIS_PER_SECOND)
                .and_then(|millis| millis.checked_add(subsec_millis))
        }
        .ok_or(ConversionError(
            "DateTime value too large to fit into i64 epoch millis",
        ))
    }

    /// Read 1 date of `format` from `s`, expecting either `delim` or EOF
    ///
    /// Enable parsing multiple dates from the same string
    pub fn read(s: &str, format: Format, delim: char) -> Result<(Self, &str), DateTimeParseError> {
        let (inst, next) = match format {
            Format::DateTime => format::rfc3339::read(s)?,
            Format::HttpDate => format::http_date::read(s)?,
            Format::EpochSeconds => {
                let split_point = s.find(delim).unwrap_or_else(|| s.len());
                let (s, rest) = s.split_at(split_point);
                (Self::from_str(s, format)?, rest)
            }
        };
        if next.is_empty() {
            Ok((inst, next))
        } else if next.starts_with(delim) {
            Ok((inst, &next[1..]))
        } else {
            Err(DateTimeParseError::Invalid(
                "didn't find expected delimiter".into(),
            ))
        }
    }

    /// Formats the `DateTime` to a string using the given `format`.
    ///
    /// Returns an error if the given `DateTime` cannot be represented by the desired format.
    pub fn fmt(&self, format: Format) -> Result<String, DateTimeFormatError> {
        match format {
            Format::DateTime => format::rfc3339::format(self),
            Format::EpochSeconds => Ok(format::epoch_seconds::format(self)),
            Format::HttpDate => format::http_date::format(self),
        }
    }
}

/// Tries to convert a [`DateTime`] into a [`SystemTime`].
///
/// This can fail if the the `DateTime` value is larger or smaller than what the `SystemTime`
/// can represent on the operating system it's compiled for. On Linux, for example, it will only
/// fail on `Instant::from_secs(i64::MIN)` (with any nanoseconds value). On Windows, however,
/// Rust's standard library uses a smaller precision type for `SystemTime`, and it will fail
/// conversion for a much larger range of date-times. This is only an issue if dealing with
/// date-times beyond several thousands of years from now.
impl TryFrom<DateTime> for SystemTime {
    type Error = ConversionError;

    fn try_from(date_time: DateTime) -> Result<Self, Self::Error> {
        if date_time.secs() < 0 {
            let mut secs = date_time.secs().unsigned_abs();
            let mut nanos = date_time.subsec_nanos();
            if date_time.has_subsec_nanos() {
                // This is safe because we just went from a negative number to a positive and are subtracting
                secs -= 1;
                // This is safe because nanos are < 999,999,999
                nanos = NANOS_PER_SECOND_U32 - nanos;
            }
            UNIX_EPOCH
                .checked_sub(Duration::new(secs, nanos))
                .ok_or(ConversionError(
                    "overflow occurred when subtracting duration from UNIX_EPOCH",
                ))
        } else {
            UNIX_EPOCH
                .checked_add(Duration::new(
                    date_time.secs().unsigned_abs(),
                    date_time.subsec_nanos(),
                ))
                .ok_or(ConversionError(
                    "overflow occurred when adding duration to UNIX_EPOCH",
                ))
        }
    }
}

impl From<SystemTime> for DateTime {
    fn from(time: SystemTime) -> Self {
        if time < UNIX_EPOCH {
            let duration = UNIX_EPOCH.duration_since(time).expect("time < UNIX_EPOCH");
            let mut secs = -(duration.as_secs() as i128);
            let mut nanos = duration.subsec_nanos() as i128;
            if nanos != 0 {
                secs -= 1;
                nanos = NANOS_PER_SECOND - nanos;
            }
            DateTime::from_nanos(secs * NANOS_PER_SECOND + nanos)
                .expect("SystemTime has same precision as DateTime")
        } else {
            let duration = time.duration_since(UNIX_EPOCH).expect("UNIX_EPOCH <= time");
            DateTime::from_secs_and_nanos(
                i64::try_from(duration.as_secs())
                    .expect("SystemTime has same precision as DateTime"),
                duration.subsec_nanos(),
            )
        }
    }
}

/// Failure to convert a `DateTime` to or from another type.
#[derive(Debug)]
#[non_exhaustive]
pub struct ConversionError(&'static str);

impl StdError for ConversionError {}

impl fmt::Display for ConversionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Formats for representing a `DateTime` in the Smithy protocols.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Format {
    /// RFC-3339 Date Time.
    DateTime,
    /// Date format used by the HTTP `Date` header, specified in RFC-7231.
    HttpDate,
    /// Number of seconds since the Unix epoch formatted as a floating point.
    EpochSeconds,
}

#[cfg(test)]
mod test {
    use crate::date_time::Format;
    use crate::DateTime;
    use std::convert::TryFrom;
    use std::time::SystemTime;
    use time::format_description::well_known::Rfc3339;
    use time::OffsetDateTime;

    #[test]
    fn test_fmt() {
        let date_time = DateTime::from_secs(1576540098);
        assert_eq!(
            date_time.fmt(Format::DateTime).unwrap(),
            "2019-12-16T23:48:18Z"
        );
        assert_eq!(date_time.fmt(Format::EpochSeconds).unwrap(), "1576540098");
        assert_eq!(
            date_time.fmt(Format::HttpDate).unwrap(),
            "Mon, 16 Dec 2019 23:48:18 GMT"
        );

        let date_time = DateTime::from_fractional_secs(1576540098, 0.52);
        assert_eq!(
            date_time.fmt(Format::DateTime).unwrap(),
            "2019-12-16T23:48:18.52Z"
        );
        assert_eq!(
            date_time.fmt(Format::EpochSeconds).unwrap(),
            "1576540098.52"
        );
        assert_eq!(
            date_time.fmt(Format::HttpDate).unwrap(),
            "Mon, 16 Dec 2019 23:48:18.52 GMT"
        );
    }

    #[test]
    fn test_fmt_zero_seconds() {
        let date_time = DateTime::from_secs(1576540080);
        assert_eq!(
            date_time.fmt(Format::DateTime).unwrap(),
            "2019-12-16T23:48:00Z"
        );
        assert_eq!(date_time.fmt(Format::EpochSeconds).unwrap(), "1576540080");
        assert_eq!(
            date_time.fmt(Format::HttpDate).unwrap(),
            "Mon, 16 Dec 2019 23:48:00 GMT"
        );
    }

    #[test]
    fn test_read_single_http_date() {
        let s = "Mon, 16 Dec 2019 23:48:18 GMT";
        let (_, next) = DateTime::read(s, Format::HttpDate, ',').expect("valid");
        assert_eq!(next, "");
    }

    #[test]
    fn test_read_single_float() {
        let s = "1576540098.52";
        let (_, next) = DateTime::read(s, Format::EpochSeconds, ',').expect("valid");
        assert_eq!(next, "");
    }

    #[test]
    fn test_read_many_float() {
        let s = "1576540098.52,1576540098.53";
        let (_, next) = DateTime::read(s, Format::EpochSeconds, ',').expect("valid");
        assert_eq!(next, "1576540098.53");
    }

    #[test]
    fn test_ready_many_http_date() {
        let s = "Mon, 16 Dec 2019 23:48:18 GMT,Tue, 17 Dec 2019 23:48:18 GMT";
        let (_, next) = DateTime::read(s, Format::HttpDate, ',').expect("valid");
        assert_eq!(next, "Tue, 17 Dec 2019 23:48:18 GMT");
    }

    #[derive(Debug)]
    struct EpochMillisTestCase {
        rfc3339: &'static str,
        epoch_millis: i64,
        epoch_seconds: i64,
        epoch_subsec_nanos: u32,
    }

    // These test case values were generated from the following Kotlin JVM code:
    // ```kotlin
    // val date_time = DateTime.ofEpochMilli(<epoch milli value>);
    // println(DateTimeFormatter.ISO_DATE_TIME.format(date_time.atOffset(ZoneOffset.UTC)))
    // println(date_time.epochSecond)
    // println(date_time.nano)
    // ```
    const EPOCH_MILLIS_TEST_CASES: &[EpochMillisTestCase] = &[
        EpochMillisTestCase {
            rfc3339: "2021-07-30T21:20:04.123Z",
            epoch_millis: 1627680004123,
            epoch_seconds: 1627680004,
            epoch_subsec_nanos: 123000000,
        },
        EpochMillisTestCase {
            rfc3339: "1918-06-04T02:39:55.877Z",
            epoch_millis: -1627680004123,
            epoch_seconds: -1627680005,
            epoch_subsec_nanos: 877000000,
        },
        EpochMillisTestCase {
            rfc3339: "+292278994-08-17T07:12:55.807Z",
            epoch_millis: i64::MAX,
            epoch_seconds: 9223372036854775,
            epoch_subsec_nanos: 807000000,
        },
        EpochMillisTestCase {
            rfc3339: "-292275055-05-16T16:47:04.192Z",
            epoch_millis: i64::MIN,
            epoch_seconds: -9223372036854776,
            epoch_subsec_nanos: 192000000,
        },
    ];

    #[test]
    fn to_millis() {
        for test_case in EPOCH_MILLIS_TEST_CASES {
            println!("Test case: {:?}", test_case);
            let date_time = DateTime::from_secs_and_nanos(
                test_case.epoch_seconds,
                test_case.epoch_subsec_nanos,
            );
            assert_eq!(test_case.epoch_seconds, date_time.secs());
            assert_eq!(test_case.epoch_subsec_nanos, date_time.subsec_nanos());
            assert_eq!(test_case.epoch_millis, date_time.to_millis().unwrap());
        }

        assert!(DateTime::from_secs_and_nanos(i64::MAX, 0)
            .to_millis()
            .is_err());
    }

    #[test]
    fn from_millis() {
        for test_case in EPOCH_MILLIS_TEST_CASES {
            println!("Test case: {:?}", test_case);
            let date_time = DateTime::from_millis(test_case.epoch_millis);
            assert_eq!(test_case.epoch_seconds, date_time.secs());
            assert_eq!(test_case.epoch_subsec_nanos, date_time.subsec_nanos());
        }
    }

    #[test]
    fn to_from_millis_round_trip() {
        for millis in &[0, 1627680004123, -1627680004123, i64::MAX, i64::MIN] {
            assert_eq!(*millis, DateTime::from_millis(*millis).to_millis().unwrap());
        }
    }

    #[test]
    fn as_nanos() {
        assert_eq!(
            -9_223_372_036_854_775_807_000_000_001_i128,
            DateTime::from_secs_and_nanos(i64::MIN, 999_999_999).as_nanos()
        );
        assert_eq!(
            -10_876_543_211,
            DateTime::from_secs_and_nanos(-11, 123_456_789).as_nanos()
        );
        assert_eq!(0, DateTime::from_secs_and_nanos(0, 0).as_nanos());
        assert_eq!(
            11_123_456_789,
            DateTime::from_secs_and_nanos(11, 123_456_789).as_nanos()
        );
        assert_eq!(
            9_223_372_036_854_775_807_999_999_999_i128,
            DateTime::from_secs_and_nanos(i64::MAX, 999_999_999).as_nanos()
        );
    }

    #[test]
    fn from_nanos() {
        assert_eq!(
            DateTime::from_secs_and_nanos(i64::MIN, 999_999_999),
            DateTime::from_nanos(-9_223_372_036_854_775_807_000_000_001_i128).unwrap(),
        );
        assert_eq!(
            DateTime::from_secs_and_nanos(-11, 123_456_789),
            DateTime::from_nanos(-10_876_543_211).unwrap(),
        );
        assert_eq!(
            DateTime::from_secs_and_nanos(0, 0),
            DateTime::from_nanos(0).unwrap(),
        );
        assert_eq!(
            DateTime::from_secs_and_nanos(11, 123_456_789),
            DateTime::from_nanos(11_123_456_789).unwrap(),
        );
        assert_eq!(
            DateTime::from_secs_and_nanos(i64::MAX, 999_999_999),
            DateTime::from_nanos(9_223_372_036_854_775_807_999_999_999_i128).unwrap(),
        );
        assert!(DateTime::from_nanos(-10_000_000_000_000_000_000_999_999_999_i128).is_err());
        assert!(DateTime::from_nanos(10_000_000_000_000_000_000_999_999_999_i128).is_err());
    }

    #[test]
    fn system_time_conversions() {
        // Check agreement
        let date_time = DateTime::from_str("1000-01-02T01:23:10.123Z", Format::DateTime).unwrap();
        let off_date_time = OffsetDateTime::parse("1000-01-02T01:23:10.123Z", &Rfc3339).unwrap();
        assert_eq!(
            SystemTime::from(off_date_time),
            SystemTime::try_from(date_time).unwrap()
        );

        let date_time = DateTime::from_str("2039-10-31T23:23:10.456Z", Format::DateTime).unwrap();
        let off_date_time = OffsetDateTime::parse("2039-10-31T23:23:10.456Z", &Rfc3339).unwrap();
        assert_eq!(
            SystemTime::from(off_date_time),
            SystemTime::try_from(date_time).unwrap()
        );
    }
}