1use core::{fmt, str::FromStr};
4
5use serde::{
6 Deserialize, Deserializer, Serialize, Serializer,
7 de::{Error as DeError, Visitor},
8};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct Timestamp {
36 unix_micros: i64,
37}
38
39const MICROS_PER_SECOND: i64 = 1_000_000;
40const SECONDS_PER_DAY: i64 = 86_400;
41
42impl Timestamp {
43 #[must_use]
47 pub const fn from_unix_micros(unix_micros: i64) -> Self {
48 Self { unix_micros }
49 }
50
51 #[must_use]
57 pub const fn from_unix_millis(unix_millis: i64) -> Option<Self> {
58 match unix_millis.checked_mul(1_000) {
59 Some(unix_micros) => Some(Self { unix_micros }),
60 None => None,
61 }
62 }
63
64 #[must_use]
70 pub const fn from_unix_secs(unix_secs: i64) -> Option<Self> {
71 match unix_secs.checked_mul(MICROS_PER_SECOND) {
72 Some(unix_micros) => Some(Self { unix_micros }),
73 None => None,
74 }
75 }
76
77 #[must_use]
85 pub fn now() -> Self {
86 let since_epoch = std::time::SystemTime::now()
87 .duration_since(std::time::UNIX_EPOCH)
88 .expect("system clock is set before the Unix epoch");
89 Self {
90 unix_micros: i64::try_from(since_epoch.as_micros())
91 .expect("system clock is too far in the future"),
92 }
93 }
94
95 #[must_use]
99 pub const fn as_unix_micros(self) -> i64 {
100 self.unix_micros
101 }
102
103 #[must_use]
108 pub const fn as_unix_millis(self) -> i64 {
109 self.unix_micros.div_euclid(1_000)
110 }
111
112 #[must_use]
119 pub const fn as_unix_secs(self) -> i64 {
120 self.unix_micros.div_euclid(MICROS_PER_SECOND)
121 }
122
123 pub fn parse(input: &str) -> Result<Self, ParseTimestampError> {
136 parse(input.as_bytes(), false).ok_or(ParseTimestampError(()))
137 }
138
139 pub(crate) fn parse_assume_utc(input: &str) -> Result<Self, ParseTimestampError> {
142 parse(input.as_bytes(), true).ok_or(ParseTimestampError(()))
143 }
144}
145
146impl FromStr for Timestamp {
147 type Err = ParseTimestampError;
148
149 fn from_str(s: &str) -> Result<Self, Self::Err> {
150 Self::parse(s)
151 }
152}
153
154impl fmt::Display for Timestamp {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 let days = self
158 .unix_micros
159 .div_euclid(SECONDS_PER_DAY * MICROS_PER_SECOND);
160 let micros_of_day = self
161 .unix_micros
162 .rem_euclid(SECONDS_PER_DAY * MICROS_PER_SECOND);
163 let (year, month, day) = civil_from_days(days);
164 let seconds_of_day = micros_of_day / MICROS_PER_SECOND;
165 let micros = micros_of_day % MICROS_PER_SECOND;
166 write!(
167 f,
168 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}+00:00",
169 seconds_of_day / 3_600,
170 seconds_of_day / 60 % 60,
171 seconds_of_day % 60,
172 )
173 }
174}
175
176#[derive(Clone, Debug, PartialEq, Eq)]
180pub struct ParseTimestampError(());
181
182impl fmt::Display for ParseTimestampError {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 f.write_str("invalid ISO 8601 timestamp")
185 }
186}
187
188impl core::error::Error for ParseTimestampError {}
189
190impl Serialize for Timestamp {
191 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
192 serializer.collect_str(self)
193 }
194}
195
196impl<'de> Deserialize<'de> for Timestamp {
197 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
198 struct TimestampVisitor;
199
200 impl Visitor<'_> for TimestampVisitor {
201 type Value = Timestamp;
202
203 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 f.write_str("an ISO 8601 timestamp string")
205 }
206
207 fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
208 Timestamp::parse(value).map_err(E::custom)
209 }
210 }
211
212 deserializer.deserialize_str(TimestampVisitor)
213 }
214}
215
216fn digits(input: &[u8], at: usize, len: usize) -> Option<i64> {
218 let slice = input.get(at..at + len)?;
219 let mut value = 0_i64;
220 for &byte in slice {
221 if !byte.is_ascii_digit() {
222 return None;
223 }
224 value = value * 10 + i64::from(byte - b'0');
225 }
226 Some(value)
227}
228
229fn expect(input: &[u8], at: usize, byte: u8) -> Option<()> {
230 (input.get(at) == Some(&byte)).then_some(())
231}
232
233fn parse(input: &[u8], assume_utc: bool) -> Option<Timestamp> {
234 let year = digits(input, 0, 4)?;
236 expect(input, 4, b'-')?;
237 let month = digits(input, 5, 2)?;
238 expect(input, 7, b'-')?;
239 let day = digits(input, 8, 2)?;
240 if !matches!(input.get(10), Some(b'T' | b't' | b' ')) {
241 return None;
242 }
243 let hour = digits(input, 11, 2)?;
244 expect(input, 13, b':')?;
245 let minute = digits(input, 14, 2)?;
246 expect(input, 16, b':')?;
247 let second = digits(input, 17, 2)?;
248
249 if !(1..=12).contains(&month)
250 || day < 1
251 || day > days_in_month(year, month)
252 || hour > 23
253 || minute > 59
254 || second > 59
255 {
256 return None;
257 }
258
259 let mut at = 19;
261 let mut micros = 0_i64;
262 if input.get(at) == Some(&b'.') {
263 at += 1;
264 let start = at;
265 while let Some(byte) = input.get(at).filter(|byte| byte.is_ascii_digit()) {
266 if at - start < 6 {
267 micros = micros * 10 + i64::from(byte - b'0');
268 }
269 at += 1;
270 }
271 let len = at - start;
272 if len == 0 || len > 9 {
273 return None;
274 }
275 for _ in len..6 {
276 micros *= 10;
277 }
278 }
279
280 let offset_seconds = match input.get(at) {
282 None if assume_utc => 0,
283 Some(b'Z' | b'z') => {
284 at += 1;
285 0
286 }
287 Some(sign @ (b'+' | b'-')) => {
288 let offset_hour = digits(input, at + 1, 2)?;
289 expect(input, at + 3, b':')?;
290 let offset_minute = digits(input, at + 4, 2)?;
291 if offset_hour > 23 || offset_minute > 59 {
292 return None;
293 }
294 at += 6;
295 let offset = offset_hour * 3_600 + offset_minute * 60;
296 if *sign == b'+' { offset } else { -offset }
297 }
298 _ => return None,
299 };
300 if at != input.len() {
301 return None;
302 }
303
304 let days = days_from_civil(year, month, day);
305 let seconds = days * SECONDS_PER_DAY + hour * 3_600 + minute * 60 + second - offset_seconds;
306 Some(Timestamp::from_unix_micros(
307 seconds * MICROS_PER_SECOND + micros,
308 ))
309}
310
311const fn is_leap_year(year: i64) -> bool {
312 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
313}
314
315const fn days_in_month(year: i64, month: i64) -> i64 {
316 match month {
317 2 if is_leap_year(year) => 29,
318 2 => 28,
319 4 | 6 | 9 | 11 => 30,
320 _ => 31,
321 }
322}
323
324const fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
328 let year = if month <= 2 { year - 1 } else { year };
329 let era = year.div_euclid(400);
330 let year_of_era = year - era * 400;
331 let month_index = (month + 9) % 12; let day_of_year = (153 * month_index + 2) / 5 + day - 1;
333 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
334 era * 146_097 + day_of_era - 719_468
335}
336
337const fn civil_from_days(days: i64) -> (i64, i64, i64) {
339 let days = days + 719_468;
340 let era = days.div_euclid(146_097);
341 let day_of_era = days - era * 146_097;
342 let year_of_era =
343 (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
344 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
345 let month_index = (5 * day_of_year + 2) / 153;
346 let day = day_of_year - (153 * month_index + 2) / 5 + 1;
347 let month = if month_index < 10 {
348 month_index + 3
349 } else {
350 month_index - 9
351 };
352 let year = year_of_era + era * 400 + if month <= 2 { 1 } else { 0 };
353 (year, month, day)
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 #[test]
361 fn parse_discord_formats() {
362 let with_fraction: Timestamp = "2017-07-11T17:27:07.299000+00:00".parse().unwrap();
363 assert_eq!(with_fraction.as_unix_millis(), 1_499_794_027_299);
364
365 let without_fraction: Timestamp = "2017-07-11T17:27:07+00:00".parse().unwrap();
366 assert_eq!(without_fraction.as_unix_secs(), 1_499_794_027);
367
368 let zulu: Timestamp = "2017-07-11T17:27:07.299Z".parse().unwrap();
369 assert_eq!(zulu, with_fraction);
370 }
371
372 #[test]
373 fn nanosecond_fraction_is_truncated() {
374 let ts: Timestamp = "1970-01-01T00:00:00.123456789Z".parse().unwrap();
375 assert_eq!(ts.as_unix_micros(), 123_456);
376 }
377
378 #[test]
379 fn display_round_trip() {
380 for input in [
381 "1970-01-01T00:00:00.000000+00:00",
382 "2000-02-29T23:59:59.999999+00:00",
383 "2026-11-10T19:42:07.123000+00:00",
384 "1969-12-31T23:59:59.500000+00:00",
385 ] {
386 let ts: Timestamp = input.parse().unwrap();
387 assert_eq!(ts.to_string(), input);
388 }
389 }
390
391 #[test]
392 fn negative_offset() {
393 let ts: Timestamp = "2021-01-01T00:00:00-05:30".parse().unwrap();
394 assert_eq!(ts.to_string(), "2021-01-01T05:30:00.000000+00:00");
395 }
396
397 #[test]
398 fn missing_offset_only_with_assume_utc() {
399 let input = "2024-10-18T14:42:53.064834";
400 assert!(input.parse::<Timestamp>().is_err());
401 let ts = Timestamp::parse_assume_utc(input).unwrap();
402 assert_eq!(ts, "2024-10-18T14:42:53.064834Z".parse().unwrap());
403 assert_eq!(
405 Timestamp::parse_assume_utc("2024-10-18T16:42:53.064834+02:00").unwrap(),
406 ts
407 );
408 assert!(Timestamp::parse_assume_utc("2024-10-18T14:42:53.").is_err());
409 assert!(Timestamp::parse_assume_utc("2024-10-18T14:42:53x").is_err());
410 }
411
412 #[test]
413 fn rejects_invalid() {
414 for input in [
415 "",
416 "2021-13-01T00:00:00Z",
417 "2021-02-29T00:00:00Z",
418 "2021-01-01T24:00:00Z",
419 "2021-01-01T00:00:00",
420 "2021-01-01T00:00:00.Z",
421 "2021-01-01T00:00:00.1234567890Z",
422 "2021-01-01T00:00:00+0000",
423 "2021-01-01T00:00:00Zjunk",
424 "2021-1-01T00:00:00Z",
425 ] {
426 assert!(
427 input.parse::<Timestamp>().is_err(),
428 "{input:?} should be rejected"
429 );
430 }
431 }
432
433 #[test]
434 fn civil_round_trip() {
435 for days in (-800_000..800_000).step_by(997) {
436 let (year, month, day) = civil_from_days(days);
437 assert_eq!(days_from_civil(year, month, day), days);
438 }
439 }
440}