use core::time::Duration;
const SECONDS_PER_DAY: u64 = 86_400;
const SECONDS_PER_WEEK: u64 = 7 * SECONDS_PER_DAY;
const SECONDS_PER_MONTH: u64 = 2_630_016;
const SECONDS_PER_YEAR: u64 = 31_557_600;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Unit {
Nanosecond,
Microsecond,
Millisecond,
Second,
Minute,
Hour,
Day,
Week,
Month,
Year,
}
impl Unit {
fn from_spelling(spelling: &str) -> Option<Self> {
Some(match spelling {
"ns" | "nsec" | "nanos" => Self::Nanosecond,
"us" | "µs" | "usec" => Self::Microsecond,
"ms" | "msec" | "millis" => Self::Millisecond,
"s" | "sec" | "secs" | "second" | "seconds" => Self::Second,
"m" | "min" | "mins" | "minute" | "minutes" => Self::Minute,
"h" | "hr" | "hrs" | "hour" | "hours" => Self::Hour,
"d" | "day" | "days" => Self::Day,
"w" | "wk" | "wks" | "week" | "weeks" => Self::Week,
"M" | "month" | "months" => Self::Month,
"y" | "yr" | "yrs" | "year" | "years" => Self::Year,
_ => return None,
})
}
fn whole(self, count: u64) -> Option<(u64, u64)> {
Some(match self {
Self::Nanosecond => (0, count),
Self::Microsecond => (0, count.checked_mul(1_000)?),
Self::Millisecond => (0, count.checked_mul(1_000_000)?),
Self::Second => (count, 0),
Self::Minute => (count.checked_mul(60)?, 0),
Self::Hour => (count.checked_mul(3_600)?, 0),
Self::Day => (count.checked_mul(SECONDS_PER_DAY)?, 0),
Self::Week => (count.checked_mul(SECONDS_PER_WEEK)?, 0),
Self::Month => (count.checked_mul(SECONDS_PER_MONTH)?, 0),
Self::Year => (count.checked_mul(SECONDS_PER_YEAR)?, 0),
})
}
fn fraction(self, numerator: u64, denominator: u64) -> Option<(u64, u64)> {
fn exact(value: u64, denominator: u64) -> Option<u64> {
value
.is_multiple_of(denominator)
.then(|| value / denominator)
}
Some(match self {
Self::Nanosecond => return None,
Self::Microsecond => (0, exact(numerator.checked_mul(1_000)?, denominator)?),
Self::Millisecond => (0, exact(numerator.checked_mul(1_000_000)?, denominator)?),
Self::Second => (
0,
exact(numerator.checked_mul(1_000_000_000)?, denominator)?,
),
Self::Minute => (
0,
exact(numerator.checked_mul(60_000_000_000)?, denominator)?,
),
Self::Hour => (exact(numerator.checked_mul(3_600)?, denominator)?, 0),
Self::Day => (
exact(numerator.checked_mul(SECONDS_PER_DAY)?, denominator)?,
0,
),
Self::Week => (
exact(numerator.checked_mul(SECONDS_PER_WEEK)?, denominator)?,
0,
),
Self::Month => (
exact(numerator.checked_mul(SECONDS_PER_MONTH)?, denominator)?,
0,
),
Self::Year => (
exact(numerator.checked_mul(SECONDS_PER_YEAR)?, denominator)?,
0,
),
})
}
}
pub(super) fn parse(text: &str) -> Option<Duration> {
if text == "0" {
return Some(Duration::ZERO);
}
Scan {
rest: text.chars(),
text,
}
.run()
}
enum Start {
Digit(u64),
End,
}
struct Scan<'a> {
rest: core::str::Chars<'a>,
text: &'a str,
}
impl Scan<'_> {
fn offset(&self) -> usize {
self.text.len() - self.rest.as_str().len()
}
fn start(&mut self) -> Option<Start> {
for c in self.rest.by_ref() {
match c {
'0'..='9' => return Some(Start::Digit(u64::from(c.to_digit(10)?))),
c if c.is_whitespace() => {}
_ => return None,
}
}
Some(Start::End)
}
fn run(mut self) -> Option<Duration> {
let Start::Digit(mut count) = self.start()? else {
return None;
};
let mut total = Duration::ZERO;
'component: loop {
let mut fraction = None;
let mut offset = self.offset();
while let Some(c) = self.rest.next() {
match c {
'0'..='9' => {
let digit = u64::from(c.to_digit(10)?);
count = count.checked_mul(10)?.checked_add(digit)?;
}
'.' => {
fraction = Some(self.fraction(&mut offset)?);
break;
}
c if c.is_whitespace() => {}
'a'..='z' | 'A'..='Z' | 'µ' => break,
_ => return None,
}
offset = self.offset();
}
let start = offset;
let mut offset = self.offset();
while let Some(c) = self.rest.next() {
match c {
'0'..='9' => {
Self::add(&mut total, self.text.get(start..offset)?, count, fraction)?;
count = u64::from(c.to_digit(10)?);
continue 'component;
}
c if c.is_whitespace() => break,
'a'..='z' | 'A'..='Z' | 'µ' => {}
_ => return None,
}
offset = self.offset();
}
Self::add(&mut total, self.text.get(start..offset)?, count, fraction)?;
match self.start()? {
Start::Digit(next) => count = next,
Start::End => return Some(total),
}
}
}
fn fraction(&mut self, offset: &mut usize) -> Option<(u64, u64)> {
let mut numerator = 0u64;
let mut denominator = 1u64;
let mut leading_zeros = true;
while let Some(c) = self.rest.next() {
match c {
'0' => {
denominator = denominator.checked_mul(10)?;
if !leading_zeros {
numerator = numerator.checked_mul(10)?;
}
}
'1'..='9' => {
leading_zeros = false;
denominator = denominator.checked_mul(10)?;
let digit = u64::from(c.to_digit(10)?);
numerator = numerator.checked_mul(10)?.checked_add(digit)?;
}
c if c.is_whitespace() => {}
'a'..='z' | 'A'..='Z' | 'µ' => break,
_ => return None,
}
*offset = self.offset();
}
(denominator != 1).then_some((numerator, denominator))
}
fn add(
total: &mut Duration,
spelling: &str,
count: u64,
fraction: Option<(u64, u64)>,
) -> Option<()> {
let unit = Unit::from_spelling(spelling)?;
let (secs, nanos) = unit.whole(count)?;
*total = accumulate(*total, secs, nanos)?;
if let Some((numerator, denominator)) = fraction {
let (secs, nanos) = unit.fraction(numerator, denominator)?;
*total = accumulate(*total, secs, nanos)?;
}
Some(())
}
}
fn accumulate(total: Duration, secs: u64, nanos: u64) -> Option<Duration> {
let mut secs = secs;
let mut nanos = u64::from(total.subsec_nanos()).checked_add(nanos)?;
if nanos >= 1_000_000_000 {
secs = secs.checked_add(nanos / 1_000_000_000)?;
nanos %= 1_000_000_000;
}
let secs = total.as_secs().checked_add(secs)?;
Some(Duration::new(secs, u32::try_from(nanos).ok()?))
}