| 1 | |
| 2 | |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use time::{ |
| 6 | OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description, |
| 7 | }; |
| 8 | |
| 9 | const FORMAT: &[FormatItem<'static>] = |
| 10 | format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z"); |
| 11 | |
| 12 | fn format_stamp(at: OffsetDateTime) -> String { |
| 13 | |
| 14 | at.format(FORMAT).unwrap_or_default() |
| 15 | } |
| 16 | |
| 17 | |
| 18 | pub fn now_stamp() -> String { |
| 19 | format_stamp(OffsetDateTime::now_utc()) |
| 20 | } |
| 21 | |
| 22 | |
| 23 | |
| 24 | pub 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 | |
| 30 | |
| 31 | pub 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 | |
| 37 | |
| 38 | pub 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)] |
| 44 | mod 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 | } |