Skip to main content

marathon_core/
duration.rs

1//! Parsing of how long to stay awake: `2h`, `1h30m`, `90` (minutes),
2//! `until 17:30`, `5:30pm`, `forever`.
3
4use std::fmt;
5use std::time::Duration;
6
7use jiff::civil::Time;
8use jiff::{Timestamp, tz::TimeZone};
9
10/// When a session should end, as the user wrote it.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Until {
13    /// No end time.
14    Indefinite,
15    /// A fixed length from now.
16    For(Duration),
17    /// The next time the local clock shows this time.
18    At(Time),
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct ParseError(String);
23
24impl fmt::Display for ParseError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        f.write_str(&self.0)
27    }
28}
29
30impl std::error::Error for ParseError {}
31
32fn err(input: &str) -> ParseError {
33    ParseError(format!(
34        "can't read {input:?} as a duration; try 2h, 45m, 1h30m, 90 (minutes), 17:30, 5:30pm or forever"
35    ))
36}
37
38impl Until {
39    /// Parses a duration or clock time. A bare number means minutes.
40    pub fn parse(input: &str) -> Result<Self, ParseError> {
41        let s = input.trim().to_ascii_lowercase();
42        let s = s
43            .strip_prefix("until")
44            .or_else(|| s.strip_prefix('@'))
45            .map(str::trim)
46            .unwrap_or(&s);
47        match s {
48            "" => return Err(err(input)),
49            "forever" | "indefinitely" | "indefinite" | "inf" => return Ok(Until::Indefinite),
50            _ => {}
51        }
52        if let Some(t) = parse_clock(s) {
53            return Ok(Until::At(t));
54        }
55        if let Ok(minutes) = s.parse::<u64>() {
56            return positive(Duration::from_secs(minutes.saturating_mul(60)), input);
57        }
58        parse_units(s)
59            .ok_or_else(|| err(input))
60            .and_then(|d| positive(d, input))
61    }
62
63    /// Resolves to a wall-clock deadline, or `None` for no end time.
64    /// A clock time already past today means tomorrow.
65    pub fn resolve(self, now: Timestamp, tz: &TimeZone) -> Option<Timestamp> {
66        match self {
67            Until::Indefinite => None,
68            Until::For(d) => Some(now.saturating_add(d).unwrap_or(Timestamp::MAX)),
69            Until::At(t) => {
70                let today = tz.to_datetime(now).date();
71                let at = tz.to_timestamp(today.to_datetime(t)).ok()?;
72                if at > now {
73                    return Some(at);
74                }
75                tz.to_timestamp(today.tomorrow().ok()?.to_datetime(t)).ok()
76            }
77        }
78    }
79}
80
81/// Ten years: longer than anyone means, and keeps deadlines meaningful.
82const MAX_SECS: f64 = 315_360_000.0;
83
84fn positive(d: Duration, input: &str) -> Result<Until, ParseError> {
85    if d.as_secs_f64() > MAX_SECS {
86        Err(ParseError(format!(
87            "{input:?} is too long; the most is 10 years"
88        )))
89    } else if d.is_zero() {
90        Err(ParseError(format!(
91            "{input:?} is zero; give a length above zero"
92        )))
93    } else {
94        Ok(Until::For(d))
95    }
96}
97
98/// `1h30m`, `2h`, `45m`, `30s`, `1d`, `1.5h`, with optional spaces.
99fn parse_units(s: &str) -> Option<Duration> {
100    let mut total = 0f64;
101    let mut rest = s;
102    while !rest.is_empty() {
103        let num_len = rest
104            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
105            .unwrap_or(rest.len());
106        if num_len == 0 {
107            return None;
108        }
109        let n: f64 = rest[..num_len].parse().ok()?;
110        rest = rest[num_len..].trim_start();
111        let unit_len = rest
112            .find(|c: char| !c.is_ascii_alphabetic())
113            .unwrap_or(rest.len());
114        let secs = match &rest[..unit_len] {
115            "s" | "sec" | "secs" | "second" | "seconds" => 1.0,
116            "m" | "min" | "mins" | "minute" | "minutes" => 60.0,
117            "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0,
118            "d" | "day" | "days" => 86400.0,
119            _ => return None,
120        };
121        total += n * secs;
122        rest = rest[unit_len..].trim_start();
123    }
124    (total.is_finite() && total <= MAX_SECS).then(|| Duration::from_secs_f64(total))
125}
126
127/// `17:30`, `5:30pm`, `5pm`, `5 pm`, `12am`.
128fn parse_clock(s: &str) -> Option<Time> {
129    let (body, pm) = match s.strip_suffix("pm").or_else(|| s.strip_suffix("p")) {
130        Some(b) => (b.trim(), Some(true)),
131        None => match s.strip_suffix("am").or_else(|| s.strip_suffix("a")) {
132            Some(b) => (b.trim(), Some(false)),
133            None => (s, None),
134        },
135    };
136    let (h, m) = match body.split_once(':') {
137        Some((h, m)) if m.len() == 2 => (h.parse::<i8>().ok()?, m.parse::<i8>().ok()?),
138        None if pm.is_some() => (body.parse::<i8>().ok()?, 0),
139        _ => return None,
140    };
141    let hour = match pm {
142        None => h,
143        Some(_) if !(1..=12).contains(&h) => return None,
144        Some(true) => h % 12 + 12,
145        Some(false) => h % 12,
146    };
147    Time::new(hour, m, 0, 0).ok()
148}
149
150/// A deadline as a local 24-hour clock time, e.g. `17:30`.
151pub fn format_clock(at: Timestamp, tz: &TimeZone) -> String {
152    format_time(tz.to_datetime(at).time())
153}
154
155/// A time of day on the 24-hour clock, e.g. `09:00`.
156pub fn format_time(t: jiff::civil::Time) -> String {
157    t.strftime("%H:%M").to_string()
158}
159
160/// Short human form of what is left: `2h 05m`, `14m`, `45s`.
161/// Minutes round up, like the menu bar countdown, so `on 2m` reads "2m".
162pub fn format_remaining(d: Duration) -> String {
163    let secs = d.as_secs();
164    if secs < 60 {
165        return format!("{secs}s");
166    }
167    let minutes = secs.div_ceil(60);
168    let (h, m) = (minutes / 60, minutes % 60);
169    if h > 0 {
170        format!("{h}h {m:02}m")
171    } else {
172        format!("{m}m")
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    fn min(m: u64) -> Until {
181        Until::For(Duration::from_secs(m * 60))
182    }
183
184    #[test]
185    fn parses_lengths() {
186        assert_eq!(Until::parse("2h").unwrap(), min(120));
187        assert_eq!(Until::parse("1h30m").unwrap(), min(90));
188        assert_eq!(Until::parse("1h 30m").unwrap(), min(90));
189        assert_eq!(Until::parse("90").unwrap(), min(90));
190        assert_eq!(Until::parse("1.5h").unwrap(), min(90));
191        assert_eq!(Until::parse("45 minutes").unwrap(), min(45));
192        assert_eq!(Until::parse("1d").unwrap(), min(1440));
193        assert_eq!(
194            Until::parse("30s").unwrap(),
195            Until::For(Duration::from_secs(30))
196        );
197        assert_eq!(Until::parse("Forever").unwrap(), Until::Indefinite);
198    }
199
200    #[test]
201    fn parses_clock_times() {
202        let t = |h, m| Until::At(Time::new(h, m, 0, 0).unwrap());
203        assert_eq!(Until::parse("17:30").unwrap(), t(17, 30));
204        assert_eq!(Until::parse("until 17:30").unwrap(), t(17, 30));
205        assert_eq!(Until::parse("@9:05").unwrap(), t(9, 5));
206        assert_eq!(Until::parse("5:30pm").unwrap(), t(17, 30));
207        assert_eq!(Until::parse("5 PM").unwrap(), t(17, 0));
208        assert_eq!(Until::parse("12am").unwrap(), t(0, 0));
209        assert_eq!(Until::parse("12pm").unwrap(), t(12, 0));
210    }
211
212    #[test]
213    fn rejects_nonsense() {
214        for bad in [
215            "",
216            "0",
217            "0m",
218            "h",
219            "2x",
220            "25:00",
221            "13pm",
222            "1:5",
223            "-5m",
224            "1e400h",
225            "99999999999d",
226        ] {
227            assert!(Until::parse(bad).is_err(), "{bad:?} should fail");
228        }
229    }
230
231    #[test]
232    fn clock_time_rolls_to_tomorrow() {
233        let tz = TimeZone::UTC;
234        let now: Timestamp = "2026-12-03T18:00:00Z".parse().unwrap();
235        let later = Until::parse("19:00").unwrap().resolve(now, &tz).unwrap();
236        assert_eq!(later, "2026-12-03T19:00:00Z".parse().unwrap());
237        let earlier = Until::parse("17:00").unwrap().resolve(now, &tz).unwrap();
238        assert_eq!(earlier, "2026-12-04T17:00:00Z".parse().unwrap());
239        let same = Until::parse("18:00").unwrap().resolve(now, &tz).unwrap();
240        assert_eq!(same, "2026-12-04T18:00:00Z".parse().unwrap());
241    }
242
243    #[test]
244    fn clock_time_respects_zone() {
245        let tz = TimeZone::get("America/Los_Angeles").unwrap();
246        let now: Timestamp = "2026-12-03T21:00:00Z".parse().unwrap(); // 13:00 PST
247        let at = Until::parse("5pm").unwrap().resolve(now, &tz).unwrap();
248        assert_eq!(at, "2026-12-04T01:00:00Z".parse().unwrap());
249    }
250
251    #[test]
252    fn formats_remaining() {
253        assert_eq!(format_remaining(Duration::from_secs(7500)), "2h 05m");
254        assert_eq!(format_remaining(Duration::from_secs(840)), "14m");
255        assert_eq!(format_remaining(Duration::from_secs(45)), "45s");
256        assert_eq!(format_remaining(Duration::from_secs(119)), "2m");
257        assert_eq!(format_remaining(Duration::from_secs(3599)), "1h 00m");
258    }
259}