Helper function to parse duration strings like "10s", "5m", "1h"
(s: &str)
| 425 | |
| 426 | // Helper function to parse duration strings like "10s", "5m", "1h" |
| 427 | fn parse_duration(s: &str) -> Result<Duration, String> { |
| 428 | if s.is_empty() { |
| 429 | return Err("Empty duration string".to_string()); |
| 430 | } |
| 431 | |
| 432 | let (number_part, unit_part) = if let Some(pos) = s.chars().position(|c| c.is_alphabetic()) { |
| 433 | (&s[..pos], &s[pos..]) |
| 434 | } else { |
| 435 | return Err("No unit found in duration string".to_string()); |
| 436 | }; |
| 437 | |
| 438 | let number: u64 = number_part |
| 439 | .parse() |
| 440 | .map_err(|_| format!("Invalid number: {}", number_part))?; |
| 441 | |
| 442 | let duration = match unit_part { |
| 443 | "s" | "sec" | "seconds" => Duration::from_secs(number), |
| 444 | "m" | "min" | "minutes" => Duration::from_secs(number * 60), |
| 445 | "h" | "hour" | "hours" => Duration::from_secs(number * 3600), |
| 446 | "ms" | "milliseconds" => Duration::from_millis(number), |
| 447 | _ => return Err(format!("Unknown time unit: {}", unit_part)), |
| 448 | }; |
| 449 | |
| 450 | Ok(duration) |
| 451 | } |
no test coverage detected