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