use std::sync::OnceLock;
use regex::Regex;
const MONTH_DAYS: [i32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
fn days_in_month(year: i32, month: i32) -> i32 {
if 2 != month {
return MONTH_DAYS[(month - 1) as usize];
}
let leap = (0 == year % 4 && 0 != year % 100) || 0 == year % 400;
if leap {
29
} else {
28
}
}
fn time_in_range(hour: i32, minute: i32, second: i32) -> bool {
hour <= 23 && minute <= 59 && second <= 60
}
fn isodate_parts() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(concat!(
r"^([0-9]{4})-([0-9]{2})-([0-9]{2})",
r"(?:[Tt ]([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:\.[0-9]+)?)?",
r"(?:[Zz]|[-+]([0-9]{2}):([0-9]{2}))?)?$",
))
.expect("the isodate capture pattern is a literal and compiles")
})
}
fn localtime_parts() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"^([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:\.[0-9]+)?)?$")
.expect("the localtime capture pattern is a literal and compiles")
})
}
fn num(group: Option<regex::Match<'_>>) -> i32 {
group
.map(|found| found.as_str())
.filter(|text| !text.is_empty())
.and_then(|text| text.parse::<i32>().ok())
.unwrap_or(-1)
}
pub fn isodate_in_range(text: &str) -> bool {
let Some(parts) = isodate_parts().captures(text) else {
return true;
};
let (year, month, day) = (num(parts.get(1)), num(parts.get(2)), num(parts.get(3)));
if !(1..=12).contains(&month) || day < 1 || days_in_month(year, month) < day {
return false;
}
if parts.get(4).is_none() {
return true;
}
let second = num(parts.get(6)).max(0);
if !time_in_range(num(parts.get(4)), num(parts.get(5)), second) {
return false;
}
parts.get(7).is_none() || (num(parts.get(7)) <= 23 && num(parts.get(8)) <= 59)
}
pub fn localtime_in_range(text: &str) -> bool {
let Some(parts) = localtime_parts().captures(text) else {
return true;
};
let second = num(parts.get(3)).max(0);
time_in_range(num(parts.get(1)), num(parts.get(2)), second)
}