//! UTC time stamps stored as text. The format is RFC 3339 with nine fractional digits and a `Z` //! suffix. Its width is fixed, so comparing stamps as text gives time order. use std::time::Duration; use time::{ OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description, }; const FORMAT: &[FormatItem<'static>] = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z"); fn format_stamp(at: OffsetDateTime) -> String { // The format description only uses fields that always format, so this cannot fail. at.format(FORMAT).unwrap_or_default() } /// The current time as a stamp. pub fn now_stamp() -> String { format_stamp(OffsetDateTime::now_utc()) } /// The stamp for `now + after`. Saturates at the largest representable time instead of panicking. pub fn stamp_after(after: Duration) -> String { let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX); format_stamp(OffsetDateTime::now_utc().saturating_add(delta)) } /// The stamp of a Unix time in whole seconds (an ID token's `iat`), or `None` when it is out of range. pub fn stamp_from_unix(secs: i64) -> Option { OffsetDateTime::from_unix_timestamp(secs) .ok() .map(format_stamp) } /// The stamp for `now - before`. Saturates at the smallest representable time instead of panicking. pub fn stamp_before(before: Duration) -> String { let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX); format_stamp(OffsetDateTime::now_utc().saturating_sub(delta)) } #[cfg(test)] mod tests { use super::*; fn is_valid_stamp(s: &str) -> bool { let b = s.as_bytes(); b.len() == 30 && b[4] == b'-' && b[7] == b'-' && b[10] == b'T' && b[13] == b':' && b[16] == b':' && b[19] == b'.' && b[29] == b'Z' && b[20..29].iter().all(u8::is_ascii_digit) } #[test] fn stamps_have_fixed_width_and_sort_in_time_order() { let now = now_stamp(); let later = stamp_after(Duration::from_secs(3600)); assert!(is_valid_stamp(&now), "bad stamp: {now}"); assert!(is_valid_stamp(&later), "bad stamp: {later}"); assert!(now < later); assert!(stamp_before(Duration::from_secs(3600)) < now); } }