Skip to main content

mln_engine/storage/
chrono.rs

1// Durations and the monotonic clock are std::time's `Duration` and
2// mln_style::time's `Instant`; this module has the wall-clock `Timestamp`.
3
4/// A wall-clock time: a signed count of seconds since the Unix epoch.
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
6pub struct Timestamp(i64);
7
8impl Timestamp {
9    #[must_use]
10    pub const fn from_secs(secs: i64) -> Self {
11        Timestamp(secs)
12    }
13
14    #[must_use]
15    pub const fn secs_since_epoch(self) -> i64 {
16        self.0
17    }
18}
19
20/// Returns the current wall-clock time, truncated toward zero to whole
21/// seconds.
22#[must_use]
23pub fn now() -> Timestamp {
24    let secs = match mln_style::time::SystemTime::now().duration_since(mln_style::time::UNIX_EPOCH) {
25        Ok(d) => d.as_secs() as i64,
26        Err(e) => -(e.duration().as_secs() as i64),
27    };
28    Timestamp(secs)
29}
30
31// Wall-clock formatting and parsing (src/mln/util/chrono.cpp; added by glfw).
32
33/// `gmtime_r` fields for `rfc1123`: (weekday 0 = Sunday, mday, month 0-11,
34/// year, hour, minute, second).
35#[cfg(any(test, not(target_family = "wasm")))]
36fn gmtime(secs: i64) -> (usize, i64, usize, i64, i64, i64, i64) {
37    let days = secs.div_euclid(86400);
38    let rem = secs.rem_euclid(86400);
39    let (hour, min, sec) = (rem / 3600, (rem % 3600) / 60, rem % 60);
40    // 1970-01-01 was a Thursday.
41    let wday = (days + 4).rem_euclid(7) as usize;
42    // Civil from days (Howard Hinnant's algorithm).
43    let z = days + 719_468;
44    let era = z.div_euclid(146_097);
45    let doe = z.rem_euclid(146_097);
46    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
47    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
48    let mp = (5 * doy + 2) / 153;
49    let mday = doy - (153 * mp + 2) / 5 + 1;
50    let month = if mp < 10 { mp + 3 } else { mp - 9 };
51    let year = yoe + era * 400 + i64::from(month <= 2);
52    (wday, mday, (month - 1) as usize, year, hour, min, sec)
53}
54
55/// Formats `timestamp` as an RFC 1123 date, e.g. "Sun, 06 Nov 1994 08:49:37
56/// GMT". Unlike `httpdate::fmt_http_date`, which panics outside the years
57/// 1970 to 9999, it formats any timestamp, such as a cached response's
58/// modification date.
59#[cfg(any(test, not(target_family = "wasm")))]
60#[must_use]
61pub(crate) fn rfc1123(timestamp: Timestamp) -> String {
62    const WEEK: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
63    const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
64    let (wday, mday, month, year, hour, min, sec) = gmtime(timestamp.secs_since_epoch());
65    format!("{}, {:02} {} {:4} {:02}:{:02}:{:02} GMT", WEEK[wday], mday, MONTHS[month], year, hour, min, sec)
66}
67
68/// Formats `timestamp` as an ISO 8601 date in UTC, e.g. "1994-11-06
69/// 08:49:37".
70#[must_use]
71#[cfg(test)]
72pub(crate) fn iso8601(timestamp: Timestamp) -> String {
73    let (_, mday, month, year, hour, min, sec) = gmtime(timestamp.secs_since_epoch());
74    format!("{year:04}-{:02}-{mday:02} {hour:02}:{min:02}:{sec:02}", month + 1)
75}
76
77/// An HTTP date (`Expires`, `Last-Modified`, `Retry-After`, ...) in any of
78/// the three formats RFC 9110 ยง5.6.7 has recipients accept: IMF-fixdate
79/// ("Sun, 06 Nov 1994 08:49:37 GMT"), RFC 850 and asctime. `None` when it is
80/// none of them or falls outside the years 1970 to 9999.
81#[must_use]
82pub(crate) fn parse_http_date(date: &str) -> Option<Timestamp> {
83    let since_epoch = httpdate::parse_http_date(date).ok()?.duration_since(std::time::UNIX_EPOCH).ok()?;
84    Some(Timestamp::from_secs(i64::try_from(since_epoch.as_secs()).ok()?))
85}
86
87#[must_use]
88pub(crate) fn parse_timestamp_i32(timestamp: i32) -> Timestamp {
89    Timestamp::from_secs(i64::from(timestamp))
90}
91
92#[cfg(test)]
93mod wall_clock_tests {
94    use super::*;
95
96    #[test]
97    fn rfc1123_format() {
98        // test/util/timestamp... the C++ formats with gmtime_r + snprintf.
99        assert_eq!(rfc1123(Timestamp::from_secs(784_111_777)), "Sun, 06 Nov 1994 08:49:37 GMT");
100        assert_eq!(rfc1123(Timestamp::from_secs(0)), "Thu, 01 Jan 1970 00:00:00 GMT");
101        assert_eq!(rfc1123(Timestamp::from_secs(951_782_400)), "Tue, 29 Feb 2000 00:00:00 GMT");
102        assert_eq!(
103            parse_http_date(&rfc1123(Timestamp::from_secs(1_445_412_480))),
104            Some(Timestamp::from_secs(1_445_412_480))
105        );
106    }
107
108    #[test]
109    fn http_dates() {
110        let date = Some(Timestamp::from_secs(784_111_777));
111        assert_eq!(parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT"), date);
112        assert_eq!(parse_http_date("Sunday, 06-Nov-94 08:49:37 GMT"), date);
113        assert_eq!(parse_http_date("Sun Nov  6 08:49:37 1994"), date);
114        assert_eq!(parse_http_date("Fri, 01 Jan 2100 00:00:00 GMT"), Some(Timestamp::from_secs(4_102_444_800)));
115        assert_eq!(parse_http_date("Thu, 01 Jan 1960 00:00:00 GMT"), None);
116        assert_eq!(parse_http_date("Sun, 06 Nov 1994 08:49:37 +0100"), None);
117        assert_eq!(parse_http_date("0"), None);
118        assert_eq!(parse_http_date(""), None);
119    }
120
121    #[test]
122    fn iso8601_format() {
123        assert_eq!(iso8601(Timestamp::from_secs(784_111_777)), "1994-11-06 08:49:37");
124        assert_eq!(iso8601(Timestamp::from_secs(0)), "1970-01-01 00:00:00");
125        assert_eq!(iso8601(Timestamp::from_secs(951_782_400)), "2000-02-29 00:00:00");
126    }
127}