Skip to main content

laminar_core/time/duration_str/
mod.rs

1//! Tiny duration-string parser shared by connector configs.
2//!
3//! Accepts `"5"` (bare seconds), `"100ms"`, `"5s"`, `"10m"`, `"2h"`,
4//! `"1d"`. Whitespace is trimmed. Multi-unit strings (`"1h30m"`) are
5//! not supported — config files use one unit at a time.
6
7use std::time::Duration;
8
9/// Parses a config duration string. Returns `None` on malformed input.
10///
11/// See the module docs for the accepted grammar.
12#[must_use]
13pub fn parse_duration_str(s: &str) -> Option<Duration> {
14    let s = s.trim();
15    if s.is_empty() {
16        return None;
17    }
18
19    // Longest suffixes first so "ms" doesn't get eaten by "s".
20    for (suffix, scale_secs) in [("ms", 0u64), ("s", 1), ("m", 60), ("h", 3600), ("d", 86400)] {
21        if let Some(head) = s.strip_suffix(suffix) {
22            let n: u64 = head.trim().parse().ok()?;
23            return Some(if suffix == "ms" {
24                Duration::from_millis(n)
25            } else {
26                Duration::from_secs(n.checked_mul(scale_secs)?)
27            });
28        }
29    }
30
31    // Bare number: seconds.
32    s.parse::<u64>().ok().map(Duration::from_secs)
33}
34
35#[cfg(test)]
36mod tests;