1use core::fmt;
21use core::str::FromStr;
22
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24
25#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
38#[serde(transparent)]
39pub struct Duration(u64);
40
41impl Duration {
42 pub const ZERO: Self = Self(0);
44
45 pub const MAX: Self = Self(u64::MAX);
51
52 #[must_use]
54 pub const fn from_millis(millis: u64) -> Self {
55 Self(millis)
56 }
57
58 #[must_use]
60 pub const fn from_secs(secs: u64) -> Self {
61 Self(secs.saturating_mul(1_000))
62 }
63
64 #[must_use]
66 pub const fn as_millis(self) -> u64 {
67 self.0
68 }
69
70 #[must_use]
72 #[allow(clippy::cast_precision_loss)] pub const fn as_secs_f64(self) -> f64 {
74 self.0 as f64 / 1_000.0
75 }
76
77 #[must_use]
79 pub const fn is_zero(self) -> bool {
80 self.0 == 0
81 }
82
83 #[must_use]
85 pub const fn checked_add(self, other: Self) -> Option<Self> {
86 match self.0.checked_add(other.0) {
87 Some(v) => Some(Self(v)),
88 None => None,
89 }
90 }
91
92 #[must_use]
94 pub const fn checked_sub(self, other: Self) -> Option<Self> {
95 match self.0.checked_sub(other.0) {
96 Some(v) => Some(Self(v)),
97 None => None,
98 }
99 }
100}
101
102impl fmt::Debug for Duration {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 write!(f, "{}ms", self.0)
105 }
106}
107
108impl fmt::Display for Duration {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 write!(f, "{} ms", self.0)
111 }
112}
113
114impl From<Duration> for core::time::Duration {
115 fn from(d: Duration) -> Self {
116 Self::from_millis(d.0)
117 }
118}
119
120impl TryFrom<core::time::Duration> for Duration {
121 type Error = TimeOutOfRange;
122 fn try_from(d: core::time::Duration) -> Result<Self, Self::Error> {
123 u64::try_from(d.as_millis())
124 .map(Self)
125 .map_err(|_| TimeOutOfRange)
126 }
127}
128
129#[cfg(feature = "schemars")]
130impl schemars::JsonSchema for Duration {
131 fn schema_name() -> alloc::borrow::Cow<'static, str> {
132 "Duration".into()
133 }
134 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
135 schemars::json_schema!({ "type": "integer", "minimum": 0 })
136 }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
141#[error("the value is outside the range this time type can represent")]
142pub struct TimeOutOfRange;
143
144#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
168pub struct Timestamp {
169 secs: i64,
170 nanos: u32,
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
175pub enum InvalidTimestamp {
176 #[error("not an RFC 3339 date-time")]
178 Malformed,
179 #[error("the {field} field of the date-time is out of range")]
181 FieldOutOfRange {
182 field: &'static str,
184 },
185 #[error("the date-time is outside the representable range")]
187 OutOfRange,
188}
189
190impl Timestamp {
191 pub const UNIX_EPOCH: Self = Self { secs: 0, nanos: 0 };
193
194 #[must_use]
198 pub const fn from_unix(secs: i64, nanos: u32) -> Self {
199 let extra = (nanos / 1_000_000_000) as i64;
200 Self {
201 secs: secs.saturating_add(extra),
202 nanos: nanos % 1_000_000_000,
203 }
204 }
205
206 #[must_use]
208 pub const fn from_unix_millis(millis: i64) -> Self {
209 let secs = millis.div_euclid(1_000);
210 let rem = millis.rem_euclid(1_000);
211 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] Self {
213 secs,
214 nanos: (rem as u32) * 1_000_000,
215 }
216 }
217
218 #[must_use]
220 pub const fn unix_secs(self) -> i64 {
221 self.secs
222 }
223
224 #[must_use]
226 pub const fn subsec_nanos(self) -> u32 {
227 self.nanos
228 }
229
230 #[must_use]
232 pub const fn unix_millis(self) -> Option<i64> {
233 match self.secs.checked_mul(1_000) {
234 Some(ms) => ms.checked_add((self.nanos / 1_000_000) as i64),
235 None => None,
236 }
237 }
238
239 #[cfg(feature = "std")]
245 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
246 #[must_use]
247 pub fn now() -> Self {
248 let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
249 match d {
250 Ok(d) => {
251 let secs = i64::try_from(d.as_secs()).unwrap_or(i64::MAX);
252 Self::from_unix(secs, d.subsec_nanos())
253 }
254 Err(e) => {
256 let d = e.duration();
257 let secs = i64::try_from(d.as_secs()).unwrap_or(i64::MAX);
258 Self::from_unix(-secs, 0)
259 }
260 }
261 }
262
263 #[must_use]
265 #[allow(clippy::cast_possible_wrap)] pub const fn checked_add(self, d: Duration) -> Option<Self> {
267 let ms = d.as_millis();
268 let add_secs = (ms / 1_000) as i64;
269 let add_nanos = ((ms % 1_000) as u32) * 1_000_000;
270 let mut nanos = self.nanos + add_nanos;
271 let mut carry = 0i64;
272 if nanos >= 1_000_000_000 {
273 nanos -= 1_000_000_000;
274 carry = 1;
275 }
276 match self.secs.checked_add(add_secs) {
277 Some(s) => match s.checked_add(carry) {
278 Some(s) => Some(Self { secs: s, nanos }),
279 None => None,
280 },
281 None => None,
282 }
283 }
284
285 #[must_use]
287 #[allow(clippy::cast_possible_wrap)] pub const fn checked_sub(self, d: Duration) -> Option<Self> {
289 let ms = d.as_millis();
290 let sub_secs = (ms / 1_000) as i64;
291 let sub_nanos = ((ms % 1_000) as u32) * 1_000_000;
292 let (nanos, borrow) = if self.nanos >= sub_nanos {
293 (self.nanos - sub_nanos, 0i64)
294 } else {
295 (self.nanos + 1_000_000_000 - sub_nanos, 1i64)
296 };
297 match self.secs.checked_sub(sub_secs) {
298 Some(s) => match s.checked_sub(borrow) {
299 Some(s) => Some(Self { secs: s, nanos }),
300 None => None,
301 },
302 None => None,
303 }
304 }
305
306 #[must_use]
312 #[allow(clippy::cast_sign_loss)] pub const fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
314 let Some(secs) = self.secs.checked_sub(earlier.secs) else {
315 return None;
316 };
317 let (secs, nanos) = if self.nanos >= earlier.nanos {
318 (secs, self.nanos - earlier.nanos)
319 } else {
320 let Some(borrowed) = secs.checked_sub(1) else {
321 return None;
322 };
323 (borrowed, self.nanos + 1_000_000_000 - earlier.nanos)
324 };
325 if secs < 0 {
326 return None;
327 }
328 match (secs as u64).checked_mul(1_000) {
329 Some(ms) => match ms.checked_add((nanos / 1_000_000) as u64) {
330 Some(total) => Some(Duration::from_millis(total)),
331 None => None,
332 },
333 None => None,
334 }
335 }
336
337 #[must_use]
339 pub const fn saturating_duration_since(self, earlier: Self) -> Duration {
340 match self.checked_duration_since(earlier) {
341 Some(d) => d,
342 None => Duration::ZERO,
343 }
344 }
345
346 pub fn parse(s: &str) -> Result<Self, InvalidTimestamp> {
348 parse_rfc3339(s)
349 }
350
351 #[must_use]
353 pub const fn to_civil_utc(self) -> (i64, u32, u32, u32, u32, u32) {
354 let days = self.secs.div_euclid(86_400);
355 let sod = self.secs.rem_euclid(86_400);
356 let (y, m, d) = civil_from_days(days);
357 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] (
359 y,
360 m,
361 d,
362 (sod / 3_600) as u32,
363 ((sod % 3_600) / 60) as u32,
364 (sod % 60) as u32,
365 )
366 }
367}
368
369impl fmt::Display for Timestamp {
370 #[allow(clippy::many_single_char_names)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372 let (y, mo, d, h, mi, s) = self.to_civil_utc();
373 if (0..=9999).contains(&y) {
374 write!(f, "{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}")?;
375 } else {
376 write!(f, "{y:+}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}")?;
379 }
380 let n = self.nanos;
381 if n != 0 {
382 if n.is_multiple_of(1_000_000) {
383 write!(f, ".{:03}", n / 1_000_000)?;
384 } else if n.is_multiple_of(1_000) {
385 write!(f, ".{:06}", n / 1_000)?;
386 } else {
387 write!(f, ".{n:09}")?;
388 }
389 }
390 f.write_str("Z")
391 }
392}
393
394impl fmt::Debug for Timestamp {
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 write!(f, "Timestamp({self})")
397 }
398}
399
400impl FromStr for Timestamp {
401 type Err = InvalidTimestamp;
402 fn from_str(s: &str) -> Result<Self, Self::Err> {
403 parse_rfc3339(s)
404 }
405}
406
407impl Serialize for Timestamp {
408 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
409 use alloc::string::ToString;
410 serializer.serialize_str(&self.to_string())
411 }
412}
413
414impl<'de> Deserialize<'de> for Timestamp {
415 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
416 struct Visitor;
417 impl serde::de::Visitor<'_> for Visitor {
418 type Value = Timestamp;
419 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420 f.write_str("an RFC 3339 date-time")
421 }
422 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Timestamp, E> {
423 parse_rfc3339(v).map_err(E::custom)
424 }
425 }
426 deserializer.deserialize_str(Visitor)
427 }
428}
429
430#[cfg(feature = "schemars")]
431impl schemars::JsonSchema for Timestamp {
432 fn schema_name() -> alloc::borrow::Cow<'static, str> {
433 "DateTimeStamp".into()
434 }
435 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
436 schemars::json_schema!({ "type": "string", "format": "date-time" })
437 }
438}
439
440fn digits(bytes: &[u8], from: usize, len: usize) -> Result<u64, InvalidTimestamp> {
445 let slice = bytes
446 .get(from..from + len)
447 .ok_or(InvalidTimestamp::Malformed)?;
448 let mut acc = 0u64;
449 for &b in slice {
450 if !b.is_ascii_digit() {
451 return Err(InvalidTimestamp::Malformed);
452 }
453 acc = acc * 10 + u64::from(b - b'0');
454 }
455 Ok(acc)
456}
457
458#[allow(
459 clippy::cast_possible_truncation,
460 clippy::cast_possible_wrap,
461 clippy::many_single_char_names
462)]
463fn parse_rfc3339(s: &str) -> Result<Timestamp, InvalidTimestamp> {
464 let b = s.as_bytes();
465 if b.len() < 20 {
467 return Err(InvalidTimestamp::Malformed);
468 }
469 let year = digits(b, 0, 4)? as i64;
470 if b.get(4) != Some(&b'-') {
471 return Err(InvalidTimestamp::Malformed);
472 }
473 let month = digits(b, 5, 2)? as u32;
474 if b.get(7) != Some(&b'-') {
475 return Err(InvalidTimestamp::Malformed);
476 }
477 let day = digits(b, 8, 2)? as u32;
478 match b.get(10) {
479 Some(&b'T' | &b't' | &b' ') => {}
480 _ => return Err(InvalidTimestamp::Malformed),
481 }
482 let hour = digits(b, 11, 2)? as u32;
483 if b.get(13) != Some(&b':') {
484 return Err(InvalidTimestamp::Malformed);
485 }
486 let minute = digits(b, 14, 2)? as u32;
487 if b.get(16) != Some(&b':') {
488 return Err(InvalidTimestamp::Malformed);
489 }
490 let second = digits(b, 17, 2)? as u32;
491
492 let mut i = 19;
493 let mut nanos = 0u32;
494 if b.get(i) == Some(&b'.') || b.get(i) == Some(&b',') {
495 i += 1;
496 let start = i;
497 while b.get(i).is_some_and(u8::is_ascii_digit) {
498 i += 1;
499 }
500 if i == start {
501 return Err(InvalidTimestamp::Malformed);
502 }
503 let mut scale = 100_000_000u32;
505 for &d in b.get(start..i).unwrap_or(&[]).iter().take(9) {
506 nanos += u32::from(d - b'0') * scale;
507 scale /= 10;
508 }
509 }
510
511 let offset_secs: i64 = match b.get(i) {
512 Some(&b'Z' | &b'z') => {
513 i += 1;
514 0
515 }
516 Some(&sign @ (b'+' | b'-')) => {
517 let oh = digits(b, i + 1, 2)? as i64;
518 if b.get(i + 3) != Some(&b':') {
519 return Err(InvalidTimestamp::Malformed);
520 }
521 let om = digits(b, i + 4, 2)? as i64;
522 if oh > 23 || om > 59 {
523 return Err(InvalidTimestamp::FieldOutOfRange { field: "offset" });
524 }
525 i += 6;
526 let magnitude = oh * 3_600 + om * 60;
527 if sign == b'-' { -magnitude } else { magnitude }
528 }
529 _ => return Err(InvalidTimestamp::Malformed),
530 };
531 if i != b.len() {
532 return Err(InvalidTimestamp::Malformed);
533 }
534
535 if !(1..=12).contains(&month) {
536 return Err(InvalidTimestamp::FieldOutOfRange { field: "month" });
537 }
538 if day < 1 || day > days_in_month(year, month) {
539 return Err(InvalidTimestamp::FieldOutOfRange { field: "day" });
540 }
541 if hour > 23 {
542 return Err(InvalidTimestamp::FieldOutOfRange { field: "hour" });
543 }
544 if minute > 59 {
545 return Err(InvalidTimestamp::FieldOutOfRange { field: "minute" });
546 }
547 if second > 60 {
550 return Err(InvalidTimestamp::FieldOutOfRange { field: "second" });
551 }
552 let second = second.min(59);
553
554 let days = days_from_civil(year, month, day);
555 let secs = days
556 .checked_mul(86_400)
557 .and_then(|s| {
558 s.checked_add(i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second))
559 })
560 .and_then(|s| s.checked_sub(offset_secs))
561 .ok_or(InvalidTimestamp::OutOfRange)?;
562 Ok(Timestamp { secs, nanos })
563}
564
565const fn is_leap(y: i64) -> bool {
566 (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
567}
568
569const fn days_in_month(y: i64, m: u32) -> u32 {
570 match m {
571 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
572 4 | 6 | 9 | 11 => 30,
573 2 if is_leap(y) => 29,
574 2 => 28,
575 _ => 0,
576 }
577}
578
579#[allow(clippy::many_single_char_names)]
584const fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
585 let y = if m <= 2 { y - 1 } else { y };
586 let era = if y >= 0 { y } else { y - 399 } / 400;
587 let yoe = y - era * 400; let mp = if m > 2 { m - 3 } else { m + 9 } as i64; let doy = (153 * mp + 2) / 5 + d as i64 - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146_097 + doe - 719_468
592}
593
594#[allow(
596 clippy::many_single_char_names,
597 clippy::cast_possible_truncation,
598 clippy::cast_sign_loss
599)]
600const fn civil_from_days(z: i64) -> (i64, u32, u32) {
601 let z = z + 719_468;
602 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
603 let doe = z - era * 146_097; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let y = yoe + era * 400;
606 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = (doy - (153 * mp + 2) / 5 + 1) as u32; let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; (if m <= 2 { y + 1 } else { y }, m, d)
611}
612
613#[cfg(feature = "jiff")]
618#[cfg_attr(docsrs, doc(cfg(feature = "jiff")))]
619mod jiff_conv {
620 use super::{TimeOutOfRange, Timestamp};
621
622 impl From<Timestamp> for jiff::Timestamp {
623 fn from(t: Timestamp) -> Self {
624 #[allow(clippy::cast_possible_wrap)]
625 Self::new(t.unix_secs(), t.subsec_nanos() as i32).unwrap_or(Self::UNIX_EPOCH)
626 }
627 }
628
629 impl TryFrom<jiff::Timestamp> for Timestamp {
630 type Error = TimeOutOfRange;
631 fn try_from(t: jiff::Timestamp) -> Result<Self, Self::Error> {
632 let nanos = u32::try_from(t.subsec_nanosecond()).map_err(|_| TimeOutOfRange)?;
633 Ok(Self::from_unix(t.as_second(), nanos))
634 }
635 }
636}
637
638#[cfg(feature = "time")]
639#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
640mod time_conv {
641 use super::{TimeOutOfRange, Timestamp};
642
643 impl TryFrom<Timestamp> for time::OffsetDateTime {
644 type Error = TimeOutOfRange;
645 fn try_from(t: Timestamp) -> Result<Self, Self::Error> {
646 let nanos = i128::from(t.unix_secs()) * 1_000_000_000 + i128::from(t.subsec_nanos());
647 Self::from_unix_timestamp_nanos(nanos).map_err(|_| TimeOutOfRange)
648 }
649 }
650
651 impl From<time::OffsetDateTime> for Timestamp {
652 fn from(t: time::OffsetDateTime) -> Self {
653 Self::from_unix(t.unix_timestamp(), t.nanosecond())
654 }
655 }
656}
657
658#[cfg(feature = "chrono")]
659#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
660mod chrono_conv {
661 use super::{TimeOutOfRange, Timestamp};
662
663 impl TryFrom<Timestamp> for chrono::DateTime<chrono::Utc> {
664 type Error = TimeOutOfRange;
665 fn try_from(t: Timestamp) -> Result<Self, Self::Error> {
666 Self::from_timestamp(t.unix_secs(), t.subsec_nanos()).ok_or(TimeOutOfRange)
667 }
668 }
669
670 impl From<chrono::DateTime<chrono::Utc>> for Timestamp {
671 fn from(t: chrono::DateTime<chrono::Utc>) -> Self {
672 Self::from_unix(t.timestamp(), t.timestamp_subsec_nanos().min(999_999_999))
673 }
674 }
675}
676
677#[cfg(test)]
678mod tests {
679 use super::*;
680 use alloc::string::ToString;
681
682 #[test]
683 fn every_arithmetic_operation_is_total_at_the_extremes() {
684 let hi = Timestamp::from_unix(i64::MAX, 999_999_999);
689 let lo = Timestamp::from_unix(i64::MIN, 0);
690
691 assert_eq!(
692 hi.checked_duration_since(lo),
693 None,
694 "gap overflows i64 secs"
695 );
696 assert_eq!(lo.checked_duration_since(hi), None, "not after");
697 assert_eq!(hi.saturating_duration_since(lo), Duration::ZERO);
698 assert_eq!(lo.saturating_duration_since(hi), Duration::ZERO);
699
700 let floor = Timestamp::from_unix(i64::MIN, 0);
703 let just_above = Timestamp::from_unix(i64::MIN, 500);
704 assert_eq!(floor.checked_duration_since(just_above), None);
705
706 assert_eq!(hi.checked_add(Duration::from_millis(1)), None);
707 assert_eq!(lo.checked_sub(Duration::from_millis(1_000)), None);
708
709 let a = Timestamp::from_unix(1_000, 0);
711 let b = Timestamp::from_unix(1_002, 500_000_000);
712 assert_eq!(
713 b.checked_duration_since(a),
714 Some(Duration::from_millis(2_500))
715 );
716 }
717
718 #[test]
719 fn parses_every_timestamp_in_the_official_examples() {
720 for s in [
722 "2019-08-24T14:15:22Z",
723 "2024-08-24T14:15:22Z",
724 "2024-08-24T15:00:00Z",
725 "2024-12-25T14:15:22Z",
726 "2024-08-24T14:00:00Z",
727 ] {
728 let t = Timestamp::parse(s).unwrap();
729 assert_eq!(t.to_string(), s, "{s} should round-trip");
730 }
731 }
732
733 #[test]
734 fn accepts_the_rfc3339_spellings_a_peer_may_use() {
735 let canonical = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
736 for s in [
737 "2019-08-24t14:15:22z",
738 "2019-08-24 14:15:22Z",
739 "2019-08-24T14:15:22+00:00",
740 "2019-08-24T16:15:22+02:00",
741 "2019-08-24T11:15:22-03:00",
742 "2019-08-24T14:15:22.000Z",
743 "2019-08-24T14:15:22.000000000Z",
744 ] {
745 assert_eq!(Timestamp::parse(s).unwrap(), canonical, "{s}");
746 }
747 }
748
749 #[test]
750 fn fractional_digits_are_preserved_and_minimised() {
751 for (input, expected) in [
752 ("2019-08-24T14:15:22.5Z", "2019-08-24T14:15:22.500Z"),
753 ("2019-08-24T14:15:22.123Z", "2019-08-24T14:15:22.123Z"),
754 ("2019-08-24T14:15:22.123456Z", "2019-08-24T14:15:22.123456Z"),
755 (
756 "2019-08-24T14:15:22.123456789Z",
757 "2019-08-24T14:15:22.123456789Z",
758 ),
759 (
761 "2019-08-24T14:15:22.1234567891Z",
762 "2019-08-24T14:15:22.123456789Z",
763 ),
764 ("2019-08-24T14:15:22.000Z", "2019-08-24T14:15:22Z"),
765 ] {
766 assert_eq!(Timestamp::parse(input).unwrap().to_string(), expected);
767 }
768 }
769
770 #[test]
771 fn rejects_what_is_not_a_date_time() {
772 for s in [
773 "",
774 "2019-08-24",
775 "2019-08-24T14:15:22", "2019-13-24T14:15:22Z", "2019-02-30T14:15:22Z", "2019-08-24T25:15:22Z", "2019-08-24T14:60:22Z", "2019-08-24T14:15:61Z", "2019-08-24T14:15:22Zjunk", "2019-08-24T14:15:22.Z", "2019-08-24T14:15:22+0200", "2019-08-24T14:15:22+24:00", ] {
786 assert!(Timestamp::parse(s).is_err(), "{s:?} should be rejected");
787 }
788 }
789
790 #[test]
791 fn leap_second_collapses_onto_fifty_nine() {
792 let t = Timestamp::parse("2016-12-31T23:59:60Z").unwrap();
794 assert_eq!(t.to_string(), "2016-12-31T23:59:59Z");
795 }
796
797 #[test]
798 fn far_dates_survive_because_the_representation_is_not_nanoseconds() {
799 let t = Timestamp::parse("3000-01-01T00:00:00Z").unwrap();
802 assert_eq!(t.to_string(), "3000-01-01T00:00:00Z");
803 let t = Timestamp::parse("1900-01-01T00:00:00Z").unwrap();
804 assert_eq!(t.to_string(), "1900-01-01T00:00:00Z");
805 let t = Timestamp::parse("0001-01-01T00:00:00Z").unwrap();
806 assert_eq!(t.to_string(), "0001-01-01T00:00:00Z");
807 let t = Timestamp::parse("9999-12-31T23:59:59Z").unwrap();
808 assert_eq!(t.to_string(), "9999-12-31T23:59:59Z");
809 }
810
811 #[test]
812 fn civil_conversions_are_inverse_over_four_centuries() {
813 let mut days = days_from_civil(1800, 1, 1);
815 let end = days_from_civil(2200, 1, 1);
816 while days < end {
817 let (y, m, d) = civil_from_days(days);
818 assert_eq!(days_from_civil(y, m, d), days, "{y}-{m}-{d}");
819 days += 1;
820 }
821 }
822
823 #[test]
824 fn arithmetic_is_checked() {
825 let t = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
826 let hour = Duration::from_secs(3_600);
827 assert_eq!(
828 t.checked_add(hour).unwrap().to_string(),
829 "2019-08-24T15:15:22Z"
830 );
831 assert_eq!(
832 t.checked_sub(hour).unwrap().to_string(),
833 "2019-08-24T13:15:22Z"
834 );
835 assert_eq!(
836 t.checked_add(hour).unwrap().checked_duration_since(t),
837 Some(hour)
838 );
839 assert_eq!(t.checked_duration_since(t.checked_add(hour).unwrap()), None);
840 assert_eq!(
841 t.saturating_duration_since(t.checked_add(hour).unwrap()),
842 Duration::ZERO
843 );
844 }
845
846 #[test]
847 fn sub_second_arithmetic_carries() {
848 let t = Timestamp::parse("2019-08-24T14:15:22.900Z").unwrap();
849 assert_eq!(
850 t.checked_add(Duration::from_millis(200))
851 .unwrap()
852 .to_string(),
853 "2019-08-24T14:15:23.100Z"
854 );
855 let t = Timestamp::parse("2019-08-24T14:15:22.100Z").unwrap();
856 assert_eq!(
857 t.checked_sub(Duration::from_millis(200))
858 .unwrap()
859 .to_string(),
860 "2019-08-24T14:15:21.900Z"
861 );
862 }
863
864 #[test]
865 fn ordering_is_chronological() {
866 let a = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
867 let b = Timestamp::parse("2019-08-24T14:15:22.001Z").unwrap();
868 let c = Timestamp::parse("2019-08-24T14:15:23Z").unwrap();
869 assert!(a < b && b < c);
870 }
871
872 #[test]
873 fn json_is_a_bare_string() {
874 let t = Timestamp::parse("2019-08-24T14:15:22Z").unwrap();
875 assert_eq!(
876 serde_json::to_string(&t).unwrap(),
877 "\"2019-08-24T14:15:22Z\""
878 );
879 assert_eq!(
880 serde_json::from_str::<Timestamp>("\"2019-08-24T14:15:22Z\"").unwrap(),
881 t
882 );
883 assert!(serde_json::from_str::<Timestamp>("\"nope\"").is_err());
884 }
885
886 #[test]
887 fn duration_is_milliseconds_on_the_wire() {
888 let d = Duration::from_millis(3_600_000);
889 assert_eq!(serde_json::to_string(&d).unwrap(), "3600000");
890 assert_eq!(
891 serde_json::from_str::<Duration>("0").unwrap(),
892 Duration::ZERO
893 );
894 assert!(serde_json::from_str::<Duration>("-1").is_err());
896 }
897
898 #[test]
899 fn size_is_what_we_promised() {
900 assert_eq!(core::mem::size_of::<Timestamp>(), 16);
901 assert_eq!(core::mem::size_of::<Duration>(), 8);
902 }
903}