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).
35fn gmtime(secs: i64) -> (usize, i64, usize, i64, i64, i64, i64) {
36    let days = secs.div_euclid(86400);
37    let rem = secs.rem_euclid(86400);
38    let (hour, min, sec) = (rem / 3600, (rem % 3600) / 60, rem % 60);
39    // 1970-01-01 was a Thursday.
40    let wday = (days + 4).rem_euclid(7) as usize;
41    // Civil from days (Howard Hinnant's algorithm).
42    let z = days + 719_468;
43    let era = z.div_euclid(146_097);
44    let doe = z.rem_euclid(146_097);
45    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
46    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
47    let mp = (5 * doy + 2) / 153;
48    let mday = doy - (153 * mp + 2) / 5 + 1;
49    let month = if mp < 10 { mp + 3 } else { mp - 9 };
50    let year = yoe + era * 400 + i64::from(month <= 2);
51    (wday, mday, (month - 1) as usize, year, hour, min, sec)
52}
53
54/// Formats `timestamp` as an RFC 1123 date, e.g. "Sun, 06 Nov 1994 08:49:37
55/// GMT". Unlike `httpdate::fmt_http_date`, which panics outside the years
56/// 1970 to 9999, it formats any timestamp, such as a cached response's
57/// modification date.
58#[must_use]
59pub fn rfc1123(timestamp: Timestamp) -> String {
60    const WEEK: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
61    const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
62    let (wday, mday, month, year, hour, min, sec) = gmtime(timestamp.secs_since_epoch());
63    format!("{}, {:02} {} {:4} {:02}:{:02}:{:02} GMT", WEEK[wday], mday, MONTHS[month], year, hour, min, sec)
64}
65
66/// Formats `timestamp` as an ISO 8601 date in UTC, e.g. "1994-11-06
67/// 08:49:37".
68#[must_use]
69pub fn iso8601(timestamp: Timestamp) -> String {
70    let (_, mday, month, year, hour, min, sec) = gmtime(timestamp.secs_since_epoch());
71    format!("{year:04}-{:02}-{mday:02} {hour:02}:{min:02}:{sec:02}", month + 1)
72}
73
74/// An HTTP date (`Expires`, `Last-Modified`, `Retry-After`, ...) in any of
75/// the three formats RFC 9110 ยง5.6.7 has recipients accept: IMF-fixdate
76/// ("Sun, 06 Nov 1994 08:49:37 GMT"), RFC 850 and asctime. `None` when it is
77/// none of them or falls outside the years 1970 to 9999.
78#[must_use]
79pub fn parse_http_date(date: &str) -> Option<Timestamp> {
80    let since_epoch = httpdate::parse_http_date(date).ok()?.duration_since(std::time::UNIX_EPOCH).ok()?;
81    Some(Timestamp::from_secs(i64::try_from(since_epoch.as_secs()).ok()?))
82}
83
84#[must_use]
85pub fn parse_timestamp_i32(timestamp: i32) -> Timestamp {
86    Timestamp::from_secs(i64::from(timestamp))
87}
88
89#[cfg(test)]
90mod wall_clock_tests {
91    use super::*;
92
93    #[test]
94    fn rfc1123_format() {
95        // test/util/timestamp... the C++ formats with gmtime_r + snprintf.
96        assert_eq!(rfc1123(Timestamp::from_secs(784_111_777)), "Sun, 06 Nov 1994 08:49:37 GMT");
97        assert_eq!(rfc1123(Timestamp::from_secs(0)), "Thu, 01 Jan 1970 00:00:00 GMT");
98        assert_eq!(rfc1123(Timestamp::from_secs(951_782_400)), "Tue, 29 Feb 2000 00:00:00 GMT");
99        assert_eq!(
100            parse_http_date(&rfc1123(Timestamp::from_secs(1_445_412_480))),
101            Some(Timestamp::from_secs(1_445_412_480))
102        );
103    }
104
105    #[test]
106    fn http_dates() {
107        let date = Some(Timestamp::from_secs(784_111_777));
108        assert_eq!(parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT"), date);
109        assert_eq!(parse_http_date("Sunday, 06-Nov-94 08:49:37 GMT"), date);
110        assert_eq!(parse_http_date("Sun Nov  6 08:49:37 1994"), date);
111        assert_eq!(parse_http_date("Fri, 01 Jan 2100 00:00:00 GMT"), Some(Timestamp::from_secs(4_102_444_800)));
112        assert_eq!(parse_http_date("Thu, 01 Jan 1960 00:00:00 GMT"), None);
113        assert_eq!(parse_http_date("Sun, 06 Nov 1994 08:49:37 +0100"), None);
114        assert_eq!(parse_http_date("0"), None);
115        assert_eq!(parse_http_date(""), None);
116    }
117
118    #[test]
119    fn iso8601_format() {
120        assert_eq!(iso8601(Timestamp::from_secs(784_111_777)), "1994-11-06 08:49:37");
121        assert_eq!(iso8601(Timestamp::from_secs(0)), "1970-01-01 00:00:00");
122        assert_eq!(iso8601(Timestamp::from_secs(951_782_400)), "2000-02-29 00:00:00");
123    }
124}