Parse a PromQL duration string (e.g., "5m", "1h30m", "300s").
(s: &str)
| 73 | |
| 74 | /// Parse a PromQL duration string (e.g., "5m", "1h30m", "300s"). |
| 75 | pub fn parse(s: &str) -> Option<Self> { |
| 76 | let mut total_ms: i64 = 0; |
| 77 | let mut num_buf = String::new(); |
| 78 | |
| 79 | for ch in s.chars() { |
| 80 | if ch.is_ascii_digit() || ch == '.' { |
| 81 | num_buf.push(ch); |
| 82 | } else { |
| 83 | let n: f64 = num_buf.parse().ok()?; |
| 84 | num_buf.clear(); |
| 85 | let multiplier: i64 = match ch { |
| 86 | 'y' => 365 * 24 * 3600 * 1000, |
| 87 | 'w' => 7 * 24 * 3600 * 1000, |
| 88 | 'd' => 24 * 3600 * 1000, |
| 89 | 'h' => 3600 * 1000, |
| 90 | 'm' => 60 * 1000, |
| 91 | 's' => 1000, |
| 92 | _ => return None, |
| 93 | }; |
| 94 | total_ms += (n * multiplier as f64) as i64; |
| 95 | } |
| 96 | } |
| 97 | // Bare number without suffix = seconds. |
| 98 | if !num_buf.is_empty() { |
| 99 | let n: f64 = num_buf.parse().ok()?; |
| 100 | total_ms += (n * 1000.0) as i64; |
| 101 | } |
| 102 | |
| 103 | if total_ms > 0 { |
| 104 | Some(Self(total_ms)) |
| 105 | } else { |
| 106 | None |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | /// Binary operators. |