use std::time::{Duration, SystemTime, UNIX_EPOCH};
const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
const EPOCH_WEEKDAY: i64 = 3;
#[must_use]
pub fn wait(value: &str) -> Option<Duration> {
let value = value.trim();
if let Ok(seconds) = value.parse::<u64>() {
return Some(Duration::from_secs(seconds));
}
let when = parse(value)?;
Some(when.duration_since(SystemTime::now()).unwrap_or_default())
}
#[must_use]
pub fn parse_prefix(text: &str) -> Option<(SystemTime, &str)> {
const IMF_FIXDATE_LEN: usize = 29;
let trimmed = text.trim_start();
let candidate = trimmed.get(..IMF_FIXDATE_LEN)?;
if let Some(next) = trimmed.as_bytes().get(IMF_FIXDATE_LEN)
&& next.is_ascii_alphanumeric()
{
return None;
}
let when = parse(candidate)?;
Some((when, candidate))
}
#[must_use]
pub fn parse(text: &str) -> Option<SystemTime> {
let mut parts = text.split(' ');
let weekday = parts.next()?.strip_suffix(',')?;
let day = digits(parts.next()?, 2)?;
let month = parts.next()?;
let year = digits(parts.next()?, 4)?;
let clock = parts.next()?;
let zone = parts.next()?;
if parts.next().is_some() || zone != "GMT" {
return None;
}
let weekday = WEEKDAYS
.iter()
.zip(0_i64..)
.find_map(|(name, index)| (*name == weekday).then_some(index))?;
let month = MONTHS
.iter()
.zip(1_i64..)
.find_map(|(name, index)| (*name == month).then_some(index))?;
if !(1..=days_in_month(year, month)).contains(&day) {
return None;
}
let mut clock = clock.split(':');
let hour = digits(clock.next()?, 2).filter(|hour| *hour < 24)?;
let minute = digits(clock.next()?, 2).filter(|minute| *minute < 60)?;
let second = digits(clock.next()?, 2).filter(|second| *second < 60)?;
if clock.next().is_some() {
return None;
}
let days = days_from_civil(year, month, day);
if (days + EPOCH_WEEKDAY).rem_euclid(7) != weekday {
return None;
}
let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second;
UNIX_EPOCH.checked_add(Duration::from_secs(u64::try_from(seconds).ok()?))
}
fn digits(text: &str, width: usize) -> Option<i64> {
if text.len() != width || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
text.parse().ok()
}
fn days_in_month(year: i64, month: i64) -> i64 {
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
match month {
2 if leap => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year.rem_euclid(400);
let shifted_month = (month + 9) % 12;
let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
#[cfg(test)]
mod tests;