Skip to main content

laminar_core/time/
duration_str.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 {
37    use super::*;
38
39    #[test]
40    fn bare_seconds() {
41        assert_eq!(parse_duration_str("5"), Some(Duration::from_secs(5)));
42        assert_eq!(parse_duration_str(" 42 "), Some(Duration::from_secs(42)));
43    }
44
45    #[test]
46    fn suffixed() {
47        assert_eq!(
48            parse_duration_str("250ms"),
49            Some(Duration::from_millis(250))
50        );
51        assert_eq!(parse_duration_str("5s"), Some(Duration::from_secs(5)));
52        assert_eq!(parse_duration_str("10m"), Some(Duration::from_secs(600)));
53        assert_eq!(parse_duration_str("2h"), Some(Duration::from_secs(7200)));
54        assert_eq!(parse_duration_str("1d"), Some(Duration::from_secs(86_400)));
55    }
56
57    #[test]
58    fn malformed() {
59        assert_eq!(parse_duration_str(""), None);
60        assert_eq!(parse_duration_str("abc"), None);
61        assert_eq!(parse_duration_str("5x"), None);
62        assert_eq!(parse_duration_str("ms"), None);
63    }
64}