pub fn parse_duration(s: &str) -> Result<Duration, String>
Expand description
Parse a duration string with time unit suffixes.
This function accepts duration strings with the following suffixes:
ms
: Milliseconds (e.g., “500ms”, “1000ms”)s
: Seconds (e.g., “30s”, “5s”)m
: Minutes (e.g., “2m”, “30m”)h
: Hours (e.g., “1h”, “24h”)
A suffix is required - strings without suffixes will return an error.
§Overflow Protection
The function includes overflow protection for time unit conversions:
- Hours are safely converted to seconds (hours * 3600) with overflow checking
- Minutes are safely converted to seconds (minutes * 60) with overflow checking
- Values that would cause integer overflow return an error
§Arguments
s
- A string slice containing the duration with required suffix
§Returns
Ok(Duration)
- Successfully parsed durationErr(String)
- Error message describing what went wrong (invalid format, overflow, etc.)
§Examples
// Different time units
assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
assert_eq!(parse_duration("5m").unwrap(), Duration::from_secs(300));
assert_eq!(parse_duration("2h").unwrap(), Duration::from_secs(7200));
// Error cases
assert!(parse_duration("invalid").is_err());
assert!(parse_duration("10x").is_err());
assert!(parse_duration("5minutes").is_err()); // Long forms not supported
assert!(parse_duration("60").is_err()); // No suffix required
// Overflow protection
let max_hours = u64::MAX / 3600;
assert!(parse_duration(&format!("{}h", max_hours)).is_ok()); // At limit
assert!(parse_duration(&format!("{}h", max_hours + 1)).is_err()); // Overflow