1use std::thread;
4use std::time::Duration;
5
6use jiff::{SignedDuration, Timestamp};
7
8pub trait Clock {
10 fn now(&self) -> Timestamp;
12
13 fn wait_until(&mut self, at: Timestamp);
15}
16
17#[derive(Clone, Copy, Debug, Default)]
19pub struct SystemClock;
20
21impl Clock for SystemClock {
22 fn now(&self) -> Timestamp {
23 Timestamp::now()
24 }
25
26 fn wait_until(&mut self, at: Timestamp) {
27 while let Ok(left) = Duration::try_from(at.duration_since(Timestamp::now())) {
28 if left.is_zero() {
29 break;
30 }
31 thread::sleep(left.min(Duration::from_secs(30)));
32 }
33 }
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Moment {
39 At(Timestamp),
41 Wait(SignedDuration),
43}
44
45impl Moment {
46 pub fn read(text: &str) -> Option<Self> {
48 let text = text.trim();
49 if text.starts_with('P') {
50 duration(text).map(Self::Wait)
51 } else {
52 text.parse().ok().map(Self::At)
53 }
54 }
55
56 pub fn from(self, from: Timestamp) -> Timestamp {
58 match self {
59 Self::At(at) => at,
60 Self::Wait(wait) => from.saturating_add(wait).unwrap_or(Timestamp::MAX),
61 }
62 }
63}
64
65fn duration(text: &str) -> Option<SignedDuration> {
67 let rest = text.strip_prefix('P')?;
68 let (days, time) = match rest.split_once('T') {
69 Some((days, time)) => (days, Some(time)),
70 None => (rest, None),
71 };
72 let mut seconds: i64 = 0;
73 for (number, unit) in parts(days)? {
74 seconds += number.checked_mul(match unit {
75 'W' => 7 * 86_400,
76 'D' => 86_400,
77 _ => return None,
78 })?;
79 }
80 if let Some(time) = time {
81 for (number, unit) in parts(time)? {
82 seconds += number.checked_mul(match unit {
83 'H' => 3_600,
84 'M' => 60,
85 'S' => 1,
86 _ => return None,
87 })?;
88 }
89 }
90 (seconds > 0).then(|| SignedDuration::from_secs(seconds))
91}
92
93fn parts(text: &str) -> Option<Vec<(i64, char)>> {
95 let mut found = Vec::new();
96 let mut number = String::new();
97 for character in text.chars() {
98 if character.is_ascii_digit() {
99 number.push(character);
100 } else {
101 found.push((number.parse().ok()?, character));
102 number.clear();
103 }
104 }
105 number.is_empty().then_some(found)
106}
107
108pub fn words(at: Timestamp) -> String {
110 at.to_zoned(jiff::tz::TimeZone::system())
111 .strftime("%Y-%m-%d %H:%M (%:z)")
112 .to_string()
113}
114
115#[cfg(test)]
116mod tests {
117 use jiff::SignedDuration;
118
119 use super::Moment;
120
121 #[test]
122 fn deadlines_are_read_as_dates_or_waits() {
123 let hours = |hours| Some(Moment::Wait(SignedDuration::from_hours(hours)));
124 assert_eq!(Moment::read("P7D"), hours(7 * 24));
125 assert_eq!(Moment::read("P2W"), hours(14 * 24));
126 assert_eq!(Moment::read("PT48H"), hours(48));
127 assert_eq!(Moment::read("P1DT12H"), hours(36));
128 assert_eq!(
129 Moment::read("PT1H30M45S"),
130 Some(Moment::Wait(SignedDuration::from_secs(5445)))
131 );
132 assert_eq!(
133 Moment::read("2027-03-20T07:00-03:00"),
134 Some(Moment::At("2027-03-20T10:00:00Z".parse().expect("a time")))
135 );
136 for wrong in [
137 "P",
138 "PT",
139 "P0D",
140 "P1Y",
141 "P1M",
142 "PT1D",
143 "P1H",
144 "2027-02-30T10:00Z",
145 "soon",
146 ] {
147 assert_eq!(Moment::read(wrong), None, "{wrong}");
148 }
149 }
150}