forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli4 hours ago363 commits

time.rs139 lines, 4.4 KiBHistoryRawDownload
1use std::time::Duration;
2
3use jiff::{Timestamp, tz::TimeZone};
4use time::{
5 OffsetDateTime, SignedDuration,
6 format_description::{FormatItem, well_known::Rfc3339},
7 macros::format_description,
8};
9
10const FORMAT: &[FormatItem<'static>] =
11 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");
12
13fn format_stamp(at: OffsetDateTime) -> String {
14 at.format(FORMAT).unwrap_or_default()
15}
16
17pub fn now_stamp() -> String {
18 format_stamp(OffsetDateTime::now_utc())
19}
20
21pub fn now_unix() -> i64 {
22 std::time::SystemTime::now()
23 .duration_since(std::time::UNIX_EPOCH)
24 .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0))
25}
26
27pub fn stamp_after(after: Duration) -> String {
28 let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX);
29 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))
30}
31
32pub fn stamp_ago(ago: Duration) -> String {
33 let delta = SignedDuration::try_from(ago).unwrap_or(SignedDuration::MAX);
34 format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))
35}
36
37pub fn stamp_from_unix(unix: i64) -> Option<String> {
38 OffsetDateTime::from_unix_timestamp(unix)
39 .ok()
40 .map(format_stamp)
41}
42
43pub fn stamp_to_unix(stamp: &str) -> Option<i64> {
44 OffsetDateTime::parse(stamp, &Rfc3339)
45 .ok()
46 .map(OffsetDateTime::unix_timestamp)
47}
48
49pub fn iso_time(unix: i64) -> String {
50 Timestamp::from_second(unix)
51 .map(|t| {
52 t.to_zoned_datetime(TimeZone::UTC)
53 .strftime("%Y-%m-%dT%H:%M:%SZ")
54 .to_string()
55 })
56 .unwrap_or_default()
57}
58
59pub fn civil_from_days(days: i64) -> (i64, i64, i64) {
60 let z = days + 719_468;
61 let era = z.div_euclid(146_097);
62 let doe = z.rem_euclid(146_097);
63 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
64 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
65 let mp = (5 * doy + 2) / 153;
66 let d = doy - (153 * mp + 2) / 5 + 1;
67 let m = if mp < 10 { mp + 3 } else { mp - 9 };
68 let y = yoe + era * 400 + i64::from(m <= 2);
69 (y, m, d)
70}
71
72pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
73 let y = if month <= 2 { year - 1 } else { year };
74 let era = y.div_euclid(400);
75 let yoe = y - era * 400;
76 let mp = (month + 9) % 12;
77 let doy = (153 * mp + 2) / 5 + day - 1;
78 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
79 era * 146_097 + doe - 719_468
80}
81
82const MIN_SLEEP: Duration = Duration::from_secs(1);
83
84pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration {
85 let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else {
86 return backstop;
87 };
88 let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO);
89 until.clamp(MIN_SLEEP, backstop)
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn sleep_stops_at_the_next_due_time_and_is_clamped() {
98 use time::macros::datetime;
99
100 let backstop = Duration::from_secs(900);
101 let now = datetime!(2026-10-15 12:00:00 UTC);
102 let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp");
103 assert_eq!(sleep_until(None, now, backstop), backstop);
104 let in_10s = stamp(now + SignedDuration::seconds(10));
105 assert_eq!(
106 sleep_until(Some(&in_10s), now, backstop),
107 Duration::from_secs(10)
108 );
109 let in_1h = stamp(now + SignedDuration::hours(1));
110 assert_eq!(sleep_until(Some(&in_1h), now, backstop), backstop);
111 let past = stamp(now - SignedDuration::seconds(5));
112 assert_eq!(sleep_until(Some(&past), now, backstop), MIN_SLEEP);
113 assert_eq!(sleep_until(Some("soon"), now, backstop), backstop);
114 }
115
116 fn is_valid_stamp(s: &str) -> bool {
117 let b = s.as_bytes();
118 b.len() == 30
119 && b[4] == b'-'
120 && b[7] == b'-'
121 && b[10] == b'T'
122 && b[13] == b':'
123 && b[16] == b':'
124 && b[19] == b'.'
125 && b[29] == b'Z'
126 && b[20..29].iter().all(u8::is_ascii_digit)
127 }
128
129 #[test]
130 fn stamps_sort_lexicographically_in_time_order() {
131 let a = now_stamp();
132 assert!(is_valid_stamp(&a), "bad stamp: {a}");
133 let b = stamp_after(Duration::from_secs(3600));
134 assert!(is_valid_stamp(&b), "bad stamp: {b}");
135 assert!(a < b);
136 let c = stamp_after(Duration::from_secs(7200));
137 assert!(b < c);
138 }
139}