forge
ExploreLog in

Tahinli/forge

public
0 watching
★ 0
2.7 KiB
1//! UTC timestamps. Format: RFC 3339, 9 fractional digits, `Z` suffix.
2
3use std::time::Duration;
4
5use time::{
6 OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description,
7};
8
9const FORMAT: &[FormatItem<'static>] =
10 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");
11
12fn format_stamp(at: OffsetDateTime) -> String {
13 // The format description only uses fields that always format, so this cannot fail.
14 at.format(FORMAT).unwrap_or_default()
15}
16
17/// Current time as an RFC 3339 UTC string with 9 fractional digits and a `Z` suffix.
18pub fn now_stamp() -> String {
19 format_stamp(OffsetDateTime::now_utc())
20}
21
22/// The stamp for `now + after`, in the same format as [`now_stamp`].
23/// Saturates at the maximum 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 for `now - before`, in the same format as [`now_stamp`].
30/// Saturates at the minimum representable time instead of panicking.
31pub fn stamp_before(before: Duration) -> String {
32 let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX);
33 format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))
34}
35
36/// The stamp for `now - ago`, in the same format as [`now_stamp`]. Saturates at the minimum
37/// representable time instead of panicking.
38pub fn stamp_ago(ago: Duration) -> String {
39 let delta = SignedDuration::try_from(ago).unwrap_or(SignedDuration::MAX);
40 format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 fn is_valid_stamp(s: &str) -> bool {
48 let b = s.as_bytes();
49 b.len() == 30
50 && b[4] == b'-'
51 && b[7] == b'-'
52 && b[10] == b'T'
53 && b[13] == b':'
54 && b[16] == b':'
55 && b[19] == b'.'
56 && b[29] == b'Z'
57 && b[20..29].iter().all(u8::is_ascii_digit)
58 }
59
60 #[test]
61 fn now_stamp_has_nine_digits_and_z() {
62 let s = now_stamp();
63 assert!(is_valid_stamp(&s), "bad stamp: {s}");
64 }
65
66 #[test]
67 fn stamps_sort_lexicographically_in_time_order() {
68 let a = now_stamp();
69 let b = stamp_after(Duration::from_secs(3600));
70 assert!(is_valid_stamp(&b), "bad stamp: {b}");
71 assert!(a < b);
72 let c = stamp_after(Duration::from_secs(7200));
73 assert!(b < c);
74 }
75
76 #[test]
77 fn stamp_after_saturates_instead_of_panicking() {
78 let s = stamp_after(Duration::MAX);
79 assert!(s.ends_with('Z'));
80 }
81}