forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

time.rs68 lines, 2.3 KiBHistoryRawDownload
1//! UTC time stamps stored as text. The format is RFC 3339 with nine fractional digits and a `Z`
2//! suffix. Its width is fixed, so comparing stamps as text gives time order.
3
4use std::time::Duration;
5
6use time::{
7 OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description,
8};
9
10const FORMAT: &[FormatItem<'static>] =
11 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");
12
13fn format_stamp(at: OffsetDateTime) -> String {
14 // The format description only uses fields that always format, so this cannot fail.
15 at.format(FORMAT).unwrap_or_default()
16}
17
18/// The current time as a stamp.
19pub fn now_stamp() -> String {
20 format_stamp(OffsetDateTime::now_utc())
21}
22
23/// The stamp for `now + after`. Saturates at the largest representable time instead of panicking.
24pub fn stamp_after(after: Duration) -> String {
25 let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX);
26 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))
27}
28
29/// The stamp of a Unix time in whole seconds (an ID token's `iat`), or `None` when it is out of range.
30pub fn stamp_from_unix(secs: i64) -> Option<String> {
31 OffsetDateTime::from_unix_timestamp(secs)
32 .ok()
33 .map(format_stamp)
34}
35
36/// The stamp for `now - before`. Saturates at the smallest representable time instead of panicking.
37pub fn stamp_before(before: Duration) -> String {
38 let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX);
39 format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 fn is_valid_stamp(s: &str) -> bool {
47 let b = s.as_bytes();
48 b.len() == 30
49 && b[4] == b'-'
50 && b[7] == b'-'
51 && b[10] == b'T'
52 && b[13] == b':'
53 && b[16] == b':'
54 && b[19] == b'.'
55 && b[29] == b'Z'
56 && b[20..29].iter().all(u8::is_ascii_digit)
57 }
58
59 #[test]
60 fn stamps_have_fixed_width_and_sort_in_time_order() {
61 let now = now_stamp();
62 let later = stamp_after(Duration::from_secs(3600));
63 assert!(is_valid_stamp(&now), "bad stamp: {now}");
64 assert!(is_valid_stamp(&later), "bad stamp: {later}");
65 assert!(now < later);
66 assert!(stamp_before(Duration::from_secs(3600)) < now);
67 }
68}