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
//! Utilities for parsing and formatting RFC 3339 timestamps.
//!
//! The [`Timestamp`] newtype wraps `chrono::DateTime<Utc>` or `time::OffsetDateTime` if the `time`
//! feature is enabled.
//!
//! # Formatting
//! ```
//! # use serenity::model::id::GuildId;
//! # use serenity::model::Timestamp;
//! #
//! let timestamp: Timestamp = GuildId(175928847299117063).created_at();
//! assert_eq!(timestamp.unix_timestamp(), 1462015105);
//! assert_eq!(timestamp.to_string(), "2016-04-30T11:18:25.796Z");
//! ```
//!
//! # Parsing RFC 3339 string
//! ```
//! # use serenity::model::Timestamp;
//! #
//! let timestamp = Timestamp::parse("2016-04-30T11:18:25Z").unwrap();
//! let timestamp = Timestamp::parse("2016-04-30T11:18:25+00:00").unwrap();
//! let timestamp = Timestamp::parse("2016-04-30T11:18:25.796Z").unwrap();
//!
//! let timestamp: Timestamp = "2016-04-30T11:18:25Z".parse().unwrap();
//! let timestamp: Timestamp = "2016-04-30T11:18:25+00:00".parse().unwrap();
//! let timestamp: Timestamp = "2016-04-30T11:18:25.796Z".parse().unwrap();
//!
//! assert!(Timestamp::parse("2016-04-30T11:18:25").is_err());
//! assert!(Timestamp::parse("2016-04-30T11:18").is_err());
//! ```

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

/// Discord's epoch starts at "2015-01-01T00:00:00+00:00"
const DISCORD_EPOCH: u64 = 1_420_070_400_000;

cfg_if::cfg_if! {
    if #[cfg(all(feature = "chrono", not(feature = "time")))] {
        use chrono::{DateTime, NaiveDateTime, ParseError as InnerError, SecondsFormat, TimeZone, Utc};

        /// Representation of a Unix timestamp.
        ///
        /// The struct implements the `std::fmt::Display` trait to format the underlying type as
        /// an RFC 3339 date and string such as `2016-04-30T11:18:25.796Z`.
        ///
        /// ```
        /// # use serenity::model::id::GuildId;
        /// # use serenity::model::Timestamp;
        /// #
        /// let timestamp: Timestamp = GuildId(175928847299117063).created_at();
        /// assert_eq!(timestamp.unix_timestamp(), 1462015105);
        /// assert_eq!(timestamp.to_string(), "2016-04-30T11:18:25.796Z");
        /// ```
        #[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, Ord, PartialOrd)]
        #[serde(transparent)]
        pub struct Timestamp(DateTime<Utc>);

        impl Timestamp {
            pub(crate) fn from_discord_id(id: u64) -> Timestamp {
                Self(Utc.timestamp_millis(((id >> 22) + DISCORD_EPOCH) as i64))
            }

            /// Create a new `Timestamp` with the current date and time in UTC.
            #[must_use]
            pub fn now() -> Self {
                Self(Utc::now())
            }

            /// Create a new `Timestamp` from a UNIX timestamp.
            ///
            /// # Errors
            ///
            /// Returns `Err` if the value is invalid.
            pub fn from_unix_timestamp(secs: i64) -> Result<Self, InvalidTimestamp> {
                let dt = NaiveDateTime::from_timestamp_opt(secs, 0).ok_or(InvalidTimestamp)?;
                Ok(Self(DateTime::from_utc(dt, Utc)))
            }

            /// Returns the number of non-leap seconds since January 1, 1970 0:00:00 UTC
            #[must_use]
            pub fn unix_timestamp(&self) -> i64 {
                self.0.timestamp()
            }

            /// Parse a timestamp from an RFC 3339 date and time string.
            ///
            /// # Examples
            /// ```
            /// # use serenity::model::Timestamp;
            /// #
            /// let timestamp = Timestamp::parse("2016-04-30T11:18:25Z").unwrap();
            /// let timestamp = Timestamp::parse("2016-04-30T11:18:25+00:00").unwrap();
            /// let timestamp = Timestamp::parse("2016-04-30T11:18:25.796Z").unwrap();
            ///
            /// assert!(Timestamp::parse("2016-04-30T11:18:25").is_err());
            /// assert!(Timestamp::parse("2016-04-30T11:18").is_err());
            /// ```
            ///
            /// # Errors
            ///
            /// Returns `Err` if the string is not a valid RFC 3339 date and time string.
            pub fn parse(input: &str) -> Result<Timestamp, ParseError> {
                DateTime::parse_from_rfc3339(input).map(|d| Self(d.with_timezone(&Utc))).map_err(ParseError)
            }
        }

        impl fmt::Display for Timestamp {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                let s = self.0.to_rfc3339_opts(SecondsFormat::Millis, true);
                f.write_str(&s)
            }
        }
    } else {
        use dep_time::format_description::well_known::Rfc3339;
        use dep_time::serde::rfc3339;
        use dep_time::{Duration, OffsetDateTime};
        use dep_time::error::Parse as InnerError;

        /// Representation of a Unix timestamp.
        ///
        /// The struct implements the `std::fmt::Display` trait to format the underlying type as
        /// an RFC 3339 date and string such as `2016-04-30T11:18:25.796Z`.
        ///
        /// ```
        /// # use serenity::model::id::GuildId;
        /// # use serenity::model::Timestamp;
        /// #
        /// let timestamp: Timestamp = GuildId(175928847299117063).created_at();
        /// assert_eq!(timestamp.unix_timestamp(), 1462015105);
        /// assert_eq!(timestamp.to_string(), "2016-04-30T11:18:25.796Z");
        /// ```
        #[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, Ord, PartialOrd)]
        #[serde(transparent)]
        pub struct Timestamp(#[serde(with = "rfc3339")] OffsetDateTime);


        impl Timestamp {
            pub(crate) fn from_discord_id(id: u64) -> Timestamp {
                let ns = Duration::milliseconds(((id >> 22) + DISCORD_EPOCH) as i64).whole_nanoseconds();
                // This can't fail because of the bit shifting
                // `(u64::MAX >> 22) + DISCORD_EPOCH` = 5818116911103 = "Wed May 15 2154 07:35:11 GMT+0000"
                Self(OffsetDateTime::from_unix_timestamp_nanos(ns).expect("can't fail"))
            }

            /// Create a new `Timestamp` with the current date and time in UTC.
            #[must_use]
            pub fn now() -> Self {
                Self(OffsetDateTime::now_utc())
            }

            /// Create a new `Timestamp` from a UNIX timestamp.
            ///
            /// # Errors
            ///
            /// Returns `Err` if the value is invalid. The valid range of the value may vary depending on
            /// the feature flags enabled (`time` with `large-dates`).
            pub fn from_unix_timestamp(secs: i64) -> Result<Self, InvalidTimestamp> {
                let dt = OffsetDateTime::from_unix_timestamp(secs).map_err(|_| InvalidTimestamp)?;
                Ok(Self(dt))
            }

            /// Returns the number of non-leap seconds since January 1, 1970 0:00:00 UTC
            #[must_use]
            pub fn unix_timestamp(&self) -> i64 {
                self.0.unix_timestamp()
            }

            /// Parse a timestamp from an RFC 3339 date and time string.
            ///
            /// # Examples
            /// ```
            /// # use serenity::model::Timestamp;
            /// #
            /// let timestamp = Timestamp::parse("2016-04-30T11:18:25Z").unwrap();
            /// let timestamp = Timestamp::parse("2016-04-30T11:18:25+00:00").unwrap();
            /// let timestamp = Timestamp::parse("2016-04-30T11:18:25.796Z").unwrap();
            ///
            /// assert!(Timestamp::parse("2016-04-30T11:18:25").is_err());
            /// assert!(Timestamp::parse("2016-04-30T11:18").is_err());
            /// ```
            ///
            /// # Errors
            ///
            /// Returns `Err` if the string is not a valid RFC 3339 date and time string.
            pub fn parse(input: &str) -> Result<Timestamp, ParseError> {
                OffsetDateTime::parse(input, &Rfc3339).map(Self).map_err(ParseError)
            }
        }

        impl fmt::Display for Timestamp {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                let s = self.0.format(&Rfc3339).map_err(|_| fmt::Error)?;
                f.write_str(&s)
            }
        }
    }
}

cfg_if::cfg_if! {
    if #[cfg(feature = "time")] {
        impl std::ops::Deref for Timestamp {
            type Target = OffsetDateTime;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl From<OffsetDateTime> for Timestamp {
            fn from(dt: OffsetDateTime) -> Self {
                Self(dt)
            }
        }
    } else if #[cfg(feature = "chrono")] {
        impl std::ops::Deref for Timestamp {
            type Target = DateTime<Utc>;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl<Tz: TimeZone> From<DateTime<Tz>> for Timestamp {
            fn from(dt: DateTime<Tz>) -> Self {
                Self(dt.with_timezone(&Utc))
            }
        }
    }
}

#[derive(Debug)]
pub struct InvalidTimestamp;

impl std::error::Error for InvalidTimestamp {}

impl fmt::Display for InvalidTimestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("invalid UNIX timestamp value")
    }
}

/// Signifies the failure to parse the `Timestamp` from an RFC 3339 string.
#[derive(Debug)]
pub struct ParseError(InnerError);

impl std::error::Error for ParseError {}

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

impl FromStr for Timestamp {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Timestamp::parse(s)
    }
}

impl From<String> for Timestamp {
    /// Parses an RFC 3339 date and time string such as `2016-04-30T11:18:25.796Z`.
    ///
    /// Panics on invalid value.
    fn from(s: String) -> Self {
        #[allow(clippy::unwrap_used)]
        Timestamp::parse(&s).unwrap()
    }
}

impl<'a> From<&'a str> for Timestamp {
    /// Parses an RFC 3339 date and time string such as `2016-04-30T11:18:25.796Z`.
    ///
    /// Panics on invalid value.
    fn from(s: &'a str) -> Self {
        #[allow(clippy::unwrap_used)]
        Timestamp::parse(s).unwrap()
    }
}

impl From<&Timestamp> for Timestamp {
    fn from(ts: &Timestamp) -> Self {
        *ts
    }
}

#[cfg(test)]
mod tests {
    use super::Timestamp;

    #[test]
    fn from_unix_timestamp() {
        let timestamp = Timestamp::from_unix_timestamp(1462015105).unwrap();
        assert_eq!(timestamp.unix_timestamp(), 1462015105);
        if cfg!(all(feature = "chrono", not(feature = "time"))) {
            assert_eq!(timestamp.to_string(), "2016-04-30T11:18:25.000Z");
        } else {
            assert_eq!(timestamp.to_string(), "2016-04-30T11:18:25Z");
        }
    }
}