//! Time spans as the options write them: systemd's ("1d", "6h", "1h 30min") and Go's //! ("3m", "15s", "1m30s", "500ms"). use std::time::Duration; /// A span such as "1d", "6h 30m", "1m30s" or "500ms". A bare number is seconds. pub fn parse(text: &str) -> Option { let text = text.trim(); if text.is_empty() { return None; } if let Ok(secs) = text.parse::() { return (secs >= 0.0).then(|| Duration::from_secs_f64(secs)); } let mut total = 0f64; let mut rest = text; while !rest.is_empty() { rest = rest.trim_start(); let num_len = rest.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(rest.len()); if num_len == 0 { return None; } let value: f64 = rest[..num_len].parse().ok()?; rest = &rest[num_len..]; let unit_len = rest.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(rest.len()); let unit = &rest[..unit_len]; rest = &rest[unit_len..]; let factor = match unit { "ns" => 1e-9, "us" | "µs" => 1e-6, "ms" | "msec" => 1e-3, "s" | "sec" | "second" | "seconds" | "" => 1.0, "m" | "min" | "minute" | "minutes" => 60.0, "h" | "hr" | "hour" | "hours" => 3600.0, "d" | "day" | "days" => 86400.0, "w" | "week" | "weeks" => 604800.0, _ => return None, }; total += value * factor; } Some(Duration::from_secs_f64(total)) } #[cfg(test)] mod tests { use super::*; #[test] fn both_spellings_read() { assert_eq!(parse("1d"), Some(Duration::from_secs(86400))); assert_eq!(parse("6h 30min"), Some(Duration::from_secs(6 * 3600 + 1800))); assert_eq!(parse("1m30s"), Some(Duration::from_secs(90))); assert_eq!(parse("500ms"), Some(Duration::from_millis(500))); assert_eq!(parse("45"), Some(Duration::from_secs(45))); assert_eq!(parse("soon"), None); assert_eq!(parse("3x"), None); } }