shout/src/duration.rs
2026-04-02 15:18:22 -07:00

34 lines
938 B
Rust

use std::fmt;
#[derive(Debug)]
pub struct ParseDurationError(String);
impl fmt::Display for ParseDurationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Invalid duration: {}", self.0)
}
}
/// Parse a duration string like "10s", "500ms", "1m" into milliseconds.
pub fn parse_duration(s: &str) -> Result<u64, ParseDurationError> {
let (num, unit) = if let Some(rest) = s.strip_suffix("ms") {
(rest, "ms")
} else if let Some(rest) = s.strip_suffix('s') {
(rest, "s")
} else if let Some(rest) = s.strip_suffix('m') {
(rest, "m")
} else {
return Err(ParseDurationError(s.to_string()));
};
let value: f64 = num.parse().map_err(|_| ParseDurationError(s.to_string()))?;
let ms = match unit {
"ms" => value,
"s" => value * 1000.0,
"m" => value * 60_000.0,
_ => unreachable!(),
};
Ok(ms as u64)
}