//! UTC timestamps. Format: RFC 3339, 9 fractional digits, `Z` suffix. 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() } /// Current time as an RFC 3339 UTC string with 9 fractional digits and a `Z` suffix. pub fn now_stamp() -> String { format_stamp(OffsetDateTime::now_utc()) } /// The stamp for `now + after`, in the same format as [`now_stamp`]. /// Saturates at the maximum 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 for `now - before`, in the same format as [`now_stamp`]. /// Saturates at the minimum 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)) } /// The stamp for `now - ago`, in the same format as [`now_stamp`]. Saturates at the minimum /// representable time instead of panicking. pub fn stamp_ago(ago: Duration) -> String { let delta = SignedDuration::try_from(ago).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 now_stamp_has_nine_digits_and_z() { let s = now_stamp(); assert!(is_valid_stamp(&s), "bad stamp: {s}"); } #[test] fn stamps_sort_lexicographically_in_time_order() { let a = now_stamp(); let b = stamp_after(Duration::from_secs(3600)); assert!(is_valid_stamp(&b), "bad stamp: {b}"); assert!(a < b); let c = stamp_after(Duration::from_secs(7200)); assert!(b < c); } #[test] fn stamp_after_saturates_instead_of_panicking() { let s = stamp_after(Duration::MAX); assert!(s.ends_with('Z')); } }