1use std::fmt;
21use std::ops::Deref;
22
23use chrono;
24use serde::de::{self, Deserialize, Deserializer, Visitor};
25
26#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
29pub struct DateTime(pub chrono::DateTime<chrono::Utc>);
30
31impl fmt::Debug for DateTime {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 self.0.fmt(f)
34 }
35}
36
37impl fmt::Display for DateTime {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 self.0.fmt(f)
40 }
41}
42
43impl Deref for DateTime {
44 type Target = chrono::DateTime<chrono::Utc>;
45
46 fn deref(&self) -> &Self::Target {
47 &self.0
48 }
49}
50
51impl<'de> Deserialize<'de> for DateTime {
52 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53 where
54 D: Deserializer<'de>,
55 {
56 struct DateTimeVisitor;
57
58 impl<'de> Visitor<'de> for DateTimeVisitor {
59 type Value = DateTime;
60
61 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 write!(f, "date time string or seconds since unix epoch")
63 }
64
65 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
66 where
67 E: de::Error,
68 {
69 Ok(DateTime(
70 v.parse().map_err(|e| E::custom(format!("{}", e)))?,
71 ))
72 }
73
74 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
75 where
76 E: de::Error,
77 {
78 use chrono::offset::LocalResult;
79 use chrono::TimeZone;
80
81 match chrono::Utc.timestamp_opt(v, 0) {
82 LocalResult::None => Err(E::custom(format!(
83 "value is not a legal timestamp: {}",
84 v
85 ))),
86 LocalResult::Ambiguous(min, max) => {
87 Err(E::custom(format!(
88 "value is an ambiguous timestamp: \
89 {}, could be either of {}, {}",
90 v, min, max
91 )))
92 }
93 LocalResult::Single(datetime) => Ok(DateTime(datetime)),
94 }
95 }
96
97 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
98 where
99 E: de::Error,
100 {
101 self.visit_i64(v as i64)
102 }
103 }
104
105 if deserializer.is_human_readable() {
106 deserializer.deserialize_any(DateTimeVisitor)
107 } else {
108 deserializer.deserialize_i64(DateTimeVisitor)
109 }
110 }
111}