github_types/
datetime.rs

1// Copyright (c) 2019 Jason White
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20use std::fmt;
21use std::ops::Deref;
22
23use chrono;
24use serde::de::{self, Deserialize, Deserializer, Visitor};
25
26/// A UTC datetime that can be deserialized as either a string or unix
27/// timestamp.
28#[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}