const DAYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Window {
days: [bool; 7],
start: u16,
end: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LocalTime {
pub weekday: u8,
pub minute: u16,
}
impl LocalTime {
pub fn now() -> Self {
use chrono::{Datelike, Timelike};
let n = chrono::Local::now();
Self {
weekday: n.weekday().num_days_from_monday() as u8,
minute: (n.hour() * 60 + n.minute()) as u16,
}
}
}
fn day_index(s: &str) -> Result<usize, String> {
let l = s.trim().to_ascii_lowercase();
let short = l.get(..3).unwrap_or(&l);
DAYS.iter()
.position(|d| *d == short)
.ok_or_else(|| format!("{s:?} is not a day (mon..sun)"))
}
fn parse_hm(s: &str, allow_24: bool) -> Result<u16, String> {
let (h, m) = s
.trim()
.split_once(':')
.ok_or_else(|| format!("{s:?} is not HH:MM"))?;
let (h, m): (u16, u16) = (
h.parse().map_err(|_| format!("{s:?} is not HH:MM"))?,
m.parse().map_err(|_| format!("{s:?} is not HH:MM"))?,
);
let total = h * 60 + m;
if m > 59 || h > 24 || (h == 24 && m != 0) || (h == 24 && !allow_24) {
return Err(format!("{s:?} is not a time of day"));
}
Ok(total)
}
pub fn parse_window(spec: &str) -> Result<Window, String> {
let spec = spec.trim();
let (days_part, time_part) = match spec.rsplit_once(char::is_whitespace) {
Some((d, t)) => (Some(d.trim()), t),
None => (None, spec),
};
let mut days = [false; 7];
match days_part {
None | Some("daily") | Some("*") => days = [true; 7],
Some(list) => {
for item in list.split(',') {
match item.split_once('-') {
Some((a, b)) => {
let (a, b) = (day_index(a)?, day_index(b)?);
let mut i = a;
loop {
days[i] = true;
if i == b {
break;
}
i = (i + 1) % 7;
}
}
None => days[day_index(item)?] = true,
}
}
}
}
let (s, e) = time_part
.split_once('-')
.ok_or_else(|| format!("{spec:?}: expected HH:MM-HH:MM"))?;
let (start, end) = (
parse_hm(s, false).map_err(|e| format!("{spec:?}: {e}"))?,
parse_hm(e, true).map_err(|e| format!("{spec:?}: {e}"))?,
);
if start == end {
return Err(format!("{spec:?}: the window is empty"));
}
Ok(Window { days, start, end })
}
impl Window {
pub fn contains(&self, t: LocalTime) -> bool {
let today = self.days[t.weekday as usize % 7];
let yesterday = self.days[(t.weekday as usize + 6) % 7];
if self.start < self.end {
today && t.minute >= self.start && t.minute < self.end
} else {
(today && t.minute >= self.start) || (yesterday && t.minute < self.end)
}
}
}
pub fn is_open(specs: &[String], t: LocalTime) -> bool {
specs
.iter()
.filter_map(|s| parse_window(s).ok())
.any(|w| w.contains(t))
}
#[cfg(test)]
mod tests {
use super::*;
fn at(day: &str, hm: &str) -> LocalTime {
LocalTime {
weekday: day_index(day).unwrap() as u8,
minute: parse_hm(hm, false).unwrap(),
}
}
#[test]
fn a_window_past_midnight_belongs_to_the_day_it_starts() {
let w = [String::from("mon-fri 19:00-08:00")];
assert!(is_open(&w, at("mon", "19:00")));
assert!(
is_open(&w, at("tue", "07:59")),
"Monday's window runs into Tuesday"
);
assert!(!is_open(&w, at("tue", "08:00")));
assert!(!is_open(&w, at("mon", "12:00")));
assert!(
is_open(&w, at("sat", "03:00")),
"Friday night runs into Saturday"
);
assert!(!is_open(&w, at("sat", "19:00")));
assert!(!is_open(&w, at("mon", "03:00")), "Sunday has no window");
}
#[test]
fn a_same_day_window_and_the_day_forms() {
assert!(is_open(&["sat,sun 09:00-17:00".into()], at("sun", "10:00")));
assert!(!is_open(
&["sat,sun 09:00-17:00".into()],
at("mon", "10:00")
));
assert!(
is_open(&["22:00-24:00".into()], at("wed", "23:30")),
"no days = daily"
);
assert!(is_open(&["daily 00:00-24:00".into()], at("thu", "00:00")));
assert!(
is_open(&["fri-mon 10:00-11:00".into()], at("sun", "10:30")),
"a range may wrap"
);
assert!(!is_open(
&["fri-mon 10:00-11:00".into()],
at("wed", "10:30")
));
assert!(
is_open(&["Monday 10:00-11:00".into()], at("mon", "10:00")),
"full names"
);
}
#[test]
fn two_windows_are_a_union_and_none_is_closed() {
let w = ["mon 09:00-10:00".to_string(), "tue 09:00-10:00".to_string()];
assert!(is_open(&w, at("tue", "09:30")));
assert!(!is_open(&w, at("wed", "09:30")));
assert!(!is_open(&[], at("mon", "09:30")));
}
#[test]
fn bad_windows_are_errors() {
for bad in [
"mon-fri",
"19:00",
"mon 19:00-19:00",
"mon 25:00-26:00",
"mon 19:61-20:00",
"someday 19:00-20:00",
"mon 24:00-08:00",
"mon 19:00-24:30",
] {
assert!(parse_window(bad).is_err(), "{bad}");
}
}
}