//! Five-field cron lines for `on { schedule "…" }` (oxygenflow#24): //! minute, hour, day of month, month, day of week (0 or 7 is Sunday), each //! `*`, a number, a range `a-b`, a list `a,b`, or any of those `/step`. //! The hub checks each minute which lines are due. /// A parsed line: the values each field allows. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Cron { minute: Vec, hour: Vec, day: Vec, month: Vec, weekday: Vec, /// Both day fields restricted: either may match, as cron has it. either_day: bool, } fn field(text: &str, lo: u32, hi: u32) -> Option<(Vec, bool)> { let mut allowed = vec![false; hi as usize + 1]; let star = text == "*"; for part in text.split(',') { let (range, step) = match part.split_once('/') { Some((r, s)) => (r, s.parse::().ok().filter(|s| *s > 0)?), None => (part, 1), }; let (a, b) = if range == "*" { (lo, hi) } else if let Some((a, b)) = range.split_once('-') { (a.parse().ok()?, b.parse().ok()?) } else { let a: u32 = range.parse().ok()?; // `5/15` is from 5 to the end, every 15. (a, if part.contains('/') { hi } else { a }) }; if a < lo || b > hi || a > b { return None; } let mut v = a; while v <= b { allowed[v as usize] = true; v += step; } } Some((allowed, star)) } impl Cron { pub fn parse(line: &str) -> Option { let f: Vec<&str> = line.split_whitespace().collect(); let [m, h, d, mo, w] = f.as_slice() else { return None }; let (minute, _) = field(m, 0, 59)?; let (hour, _) = field(h, 0, 23)?; let (day, day_star) = field(d, 1, 31)?; let (month, _) = field(mo, 1, 12)?; let (mut weekday, week_star) = field(w, 0, 7)?; if weekday[7] { weekday[0] = true; } Some(Cron { minute, hour, day, month, weekday, either_day: !day_star && !week_star }) } /// Whether the line is due at this minute (UTC): `weekday` 0 is Sunday. pub fn matches(&self, minute: u32, hour: u32, day: u32, month: u32, weekday: u32) -> bool { let get = |v: &Vec, i: u32| v.get(i as usize).copied().unwrap_or(false); let (d, w) = (get(&self.day, day), get(&self.weekday, weekday % 7)); let days = if self.either_day { d || w } else { d && w }; get(&self.minute, minute) && get(&self.hour, hour) && get(&self.month, month) && days } } #[cfg(test)] mod tests { use super::Cron; #[test] fn lines_parse_and_match_as_cron_does() { let nightly = Cron::parse("0 3 * * *").unwrap(); assert!(nightly.matches(0, 3, 15, 6, 2)); assert!(!nightly.matches(1, 3, 15, 6, 2)); let quarter = Cron::parse("*/15 9-17 * * 1-5").unwrap(); assert!(quarter.matches(45, 17, 2, 10, 5)); assert!(!quarter.matches(50, 17, 2, 10, 5)); assert!(!quarter.matches(0, 12, 3, 10, 6), "Saturday"); let sunday = Cron::parse("30 4 * * 7").unwrap(); assert!(sunday.matches(30, 4, 4, 10, 0)); let either = Cron::parse("0 0 1 * 1").unwrap(); assert!(either.matches(0, 0, 1, 10, 3) && either.matches(0, 0, 5, 10, 1), "the 1st or a Monday"); for bad in ["", "* * * *", "60 * * * *", "* 24 * * *", "* * 0 * *", "*/0 * * * *", "a * * * *", "5-1 * * * *"] { assert!(Cron::parse(bad).is_none(), "{bad:?}"); } } }