//! UTC stamps for storage. Format: RFC 3339, 9 fractional digits, `Z` suffix, always 30 characters, //! so that text order is time order. Local calendar handling lives in `zones.rs`. use std::time::Duration; use time::{ OffsetDateTime, SignedDuration, format_description::FormatItem, format_description::well_known::Rfc3339, macros::format_description, }; const FORMAT: &[FormatItem<'static>] = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z"); /// Formats `at` as a stamp. The format only uses fields that always render, so this cannot fail. pub fn format_stamp(at: OffsetDateTime) -> String { at.to_offset(time::UtcOffset::UTC) .format(FORMAT) .unwrap_or_default() } /// Current time as a stamp. pub fn now_stamp() -> String { format_stamp(OffsetDateTime::now_utc()) } /// 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) } /// Parses an RFC 3339 time (any offset, any fraction length) and re-formats it as a stamp. `None` when /// the text does not parse. This brings directory times into the stored form so text comparison works. pub fn normalize_stamp(raw: &str) -> Option { OffsetDateTime::parse(raw.trim(), &Rfc3339) .ok() .map(format_stamp) } /// 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 the time `before` ago. Text order is time order, so `deleted_at >= stamp_before(d)` is /// "deleted within the last `d`". 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::*; use time::macros::datetime; #[test] fn normalize_brings_rfc3339_into_stamp_form() { assert_eq!( normalize_stamp("2026-10-28T12:00:00+03:00").as_deref(), Some("2026-10-28T09:00:00.000000000Z") ); assert_eq!( normalize_stamp("2026-10-28T09:00:00.5Z").as_deref(), Some("2026-10-28T09:00:00.500000000Z") ); assert_eq!(normalize_stamp(""), None); assert_eq!(normalize_stamp("yesterday"), None); } #[test] fn stamp_is_fixed_width_utc_with_nine_digits() { let s = format_stamp(datetime!(2026-10-28 09:05:00.5 UTC)); assert_eq!(s, "2026-10-28T09:05:00.500000000Z"); assert_eq!(s.len(), 30); assert_eq!(now_stamp().len(), 30); assert!(stamp_after(Duration::from_secs(60)) > now_stamp()); } }