Skip to main content

vpf_runner/
time.rs

1//! Time: the clock a run reads and waits on, and the times a plan writes as deadlines.
2
3use std::thread;
4use std::time::Duration;
5
6use jiff::{SignedDuration, Timestamp};
7
8/// The clock a run reads, and waits on until a step's time comes.
9pub trait Clock {
10    /// Now.
11    fn now(&self) -> Timestamp;
12
13    /// Waits until `at`.
14    fn wait_until(&mut self, at: Timestamp);
15}
16
17/// The computer's own clock.
18#[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/// A time as a plan writes it: a date and time, or a wait from some moment.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Moment {
39    /// A date and time.
40    At(Timestamp),
41    /// A wait.
42    Wait(SignedDuration),
43}
44
45impl Moment {
46    /// Reads a deadline: a date and time with its offset, or a duration in weeks, or days and a time.
47    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    /// When it is, a wait counted from `from`.
57    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
65/// `P2W`, or `P` with days and a time such as `P1DT12H`, `PT30M` or `PT45S`.
66fn 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
93/// `12H30M` as `[(12, 'H'), (30, 'M')]`.
94fn 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
108/// A time as the person reads it, where the runner runs.
109pub 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}