1use thiserror::Error;
7
8pub const KIB: u64 = 1024;
9pub const MIB: u64 = 1024 * KIB;
10pub const GIB: u64 = 1024 * MIB;
11pub const TIB: u64 = 1024 * GIB;
12
13#[derive(Debug, Error, Clone, PartialEq, Eq)]
14pub enum UnitError {
15 #[error("empty value")]
16 Empty,
17 #[error("invalid number in {0:?}")]
18 Number(String),
19 #[error("unknown unit {0:?}")]
20 Unit(String),
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum UnitSystem {
26 #[default]
28 Iec,
29 Si,
31}
32
33fn split_number(s: &str) -> (&str, &str) {
34 let idx = s
35 .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '_'))
36 .unwrap_or(s.len());
37 (&s[..idx], s[idx..].trim())
38}
39
40pub fn parse_bytes(input: &str) -> Result<u64, UnitError> {
42 let s = input.trim();
43 if s.is_empty() {
44 return Err(UnitError::Empty);
45 }
46 let (num, unit) = split_number(s);
47 let n: f64 = num
48 .replace('_', "")
49 .parse()
50 .map_err(|_| UnitError::Number(input.to_string()))?;
51 let mult: f64 = match unit.to_ascii_lowercase().as_str() {
52 "" | "b" => 1.0,
53 "k" | "ki" | "kib" => KIB as f64,
54 "m" | "mi" | "mib" => MIB as f64,
55 "g" | "gi" | "gib" => GIB as f64,
56 "t" | "ti" | "tib" => TIB as f64,
57 "kb" => 1e3,
58 "mb" => 1e6,
59 "gb" => 1e9,
60 "tb" => 1e12,
61 other => return Err(UnitError::Unit(other.to_string())),
62 };
63 let bytes = (n * mult).round();
64 if !bytes.is_finite() || bytes >= u64::MAX as f64 {
65 return Err(UnitError::Number(input.to_string()));
66 }
67 Ok(bytes as u64)
68}
69
70pub fn parse_percent(input: &str) -> Result<f64, UnitError> {
73 let s = input.trim();
74 if s.is_empty() {
75 return Err(UnitError::Empty);
76 }
77 let (num, div) = if let Some(n) = s.strip_suffix('%') {
78 (n, 1.0)
79 } else if let Some(n) = s.strip_suffix('‰') {
80 (n, 10.0)
81 } else if let Some(n) = s.strip_suffix('‱') {
82 (n, 100.0)
83 } else {
84 (s, 1.0)
85 };
86 let v: f64 = num
87 .trim()
88 .parse()
89 .map_err(|_| UnitError::Number(input.to_string()))?;
90 let pct = v / div;
91 if !(0.0..=100.0).contains(&pct) {
92 return Err(UnitError::Number(input.to_string()));
93 }
94 Ok(pct)
95}
96
97pub fn parse_duration_s(input: &str) -> Result<f64, UnitError> {
99 let mut s = input.trim();
100 if s.is_empty() {
101 return Err(UnitError::Empty);
102 }
103 let mut total = 0.0;
104 while !s.is_empty() {
105 let (num, rest) = split_number(s);
106 if num.is_empty() {
107 return Err(UnitError::Number(input.to_string()));
108 }
109 let n: f64 = num.parse().map_err(|_| UnitError::Number(input.to_string()))?;
110 let unit_len = rest.find(|c: char| c.is_ascii_digit()).unwrap_or(rest.len());
111 let unit = &rest[..unit_len];
112 let mult = match unit.trim().to_ascii_lowercase().as_str() {
114 "" | "s" | "sec" | "secs" | "second" | "seconds" => 1.0,
115 "us" | "usec" | "µs" | "μs" => 0.000_001,
116 "ms" | "msec" => 0.001,
117 "m" | "min" | "mins" | "minute" | "minutes" => 60.0,
118 "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0,
119 "d" | "day" | "days" => 86400.0,
120 "w" | "week" | "weeks" => 7.0 * 86400.0,
121 other => return Err(UnitError::Unit(other.to_string())),
122 };
123 total += n * mult;
124 s = rest[unit_len..].trim_start();
125 }
126 if !total.is_finite() {
128 return Err(UnitError::Number(input.to_string()));
129 }
130 Ok(total)
131}
132
133pub fn format_bytes(bytes: u64, system: UnitSystem, decimals: usize) -> String {
135 let (base, units): (f64, [&str; 5]) = match system {
136 UnitSystem::Iec => (1024.0, ["B", "KiB", "MiB", "GiB", "TiB"]),
137 UnitSystem::Si => (1000.0, ["B", "KB", "MB", "GB", "TB"]),
138 };
139 let mut v = bytes as f64;
140 let mut i = 0;
141 let scale = 10f64.powi(decimals.min(9) as i32);
143 while i < units.len() - 1 && (v >= base || (i > 0 && (v * scale).round() / scale >= base)) {
144 v /= base;
145 i += 1;
146 }
147 if i == 0 {
148 format!("{bytes} B")
149 } else {
150 format!("{v:.decimals$} {}", units[i])
151 }
152}
153
154pub fn format_bytes_short(bytes: u64) -> String {
156 let units = ["B", "K", "M", "G", "T"];
157 let mut v = bytes as f64;
158 let mut i = 0;
159 while i < units.len() - 1 && (v >= 1024.0 || (i > 0 && v.round() >= 1024.0)) {
161 v /= 1024.0;
162 i += 1;
163 }
164 if i == 0 {
165 format!("{bytes}B")
166 } else if (v * 10.0).round() / 10.0 >= 100.0 {
167 format!("{v:.0}{}", units[i])
169 } else {
170 format!("{v:.1}{}", units[i])
171 }
172}
173
174pub fn format_bytes_signed(bytes: i64, system: UnitSystem, decimals: usize) -> String {
176 if bytes < 0 {
177 format!("-{}", format_bytes(bytes.unsigned_abs(), system, decimals))
178 } else {
179 format_bytes(bytes as u64, system, decimals)
180 }
181}
182
183pub fn format_duration(secs: u64) -> String {
185 if secs < 60 {
186 format!("{secs}s")
187 } else if secs < 3600 {
188 format!("{}m", secs / 60)
189 } else if secs < 86400 {
190 let h = secs / 3600;
191 let m = (secs % 3600) / 60;
192 if m == 0 || h >= 10 {
193 format!("{h}h")
194 } else {
195 format!("{h}h{m}m")
196 }
197 } else {
198 format!("{}d", secs / 86400)
199 }
200}
201
202pub fn format_pct(pct: f64) -> String {
204 if pct.is_finite() {
205 format!("{:.0}%", pct)
206 } else {
207 "n/a".to_string()
208 }
209}
210
211pub fn format_rate_per_min(bytes_per_min: f64) -> String {
213 if !bytes_per_min.is_finite() {
214 return "n/a".to_string();
215 }
216 let sign = if bytes_per_min < 0.0 { "-" } else { "+" };
217 format!(
218 "{sign}{}/min",
219 format_bytes_short(bytes_per_min.abs().round() as u64)
220 )
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 #[test]
228 fn parse_sizes() {
229 assert_eq!(parse_bytes("13G").unwrap(), 13 * GIB);
230 assert_eq!(parse_bytes("13g").unwrap(), 13 * GIB);
231 assert_eq!(parse_bytes("500M").unwrap(), 500 * MIB);
232 assert_eq!(parse_bytes("1.5GiB").unwrap(), 3 * GIB / 2);
233 assert_eq!(parse_bytes("2GB").unwrap(), 2_000_000_000);
234 assert_eq!(parse_bytes("4096").unwrap(), 4096);
235 assert_eq!(parse_bytes("13e9"), Err(UnitError::Unit("e9".into())));
236 assert!(parse_bytes("").is_err());
237 assert!(parse_bytes("abc").is_err());
238 }
239
240 #[test]
241 fn parse_durations() {
242 assert_eq!(parse_duration_s("30m").unwrap(), 1800.0);
243 assert_eq!(parse_duration_s("5h").unwrap(), 18000.0);
244 assert_eq!(parse_duration_s("2s").unwrap(), 2.0);
245 assert_eq!(parse_duration_s("500ms").unwrap(), 0.5);
246 assert_eq!(parse_duration_s("1h30m").unwrap(), 5400.0);
247 assert!(parse_duration_s("5x").is_err());
248 }
249
250 #[test]
251 fn parse_sizes_edge_cases() {
252 assert_eq!(parse_bytes("13 G").unwrap(), 13 * GIB);
253 assert_eq!(parse_bytes("2Gi").unwrap(), 2 * GIB);
254 assert_eq!(parse_bytes("1_000").unwrap(), 1000);
255 assert_eq!(parse_bytes("0.5k").unwrap(), 512);
256 assert!(parse_bytes("-5G").is_err());
257 assert!(parse_bytes("1.2.3G").is_err());
258 assert!(parse_bytes("99999999999T").is_err());
259 assert!(parse_bytes("G").is_err());
260 }
261
262 #[test]
263 fn parse_percents() {
264 assert_eq!(parse_percent("90%").unwrap(), 90.0);
265 assert_eq!(parse_percent(" 60 % ").unwrap(), 60.0);
266 assert_eq!(parse_percent("50").unwrap(), 50.0);
267 assert_eq!(parse_percent("900‰").unwrap(), 90.0);
268 assert_eq!(parse_percent("9000‱").unwrap(), 90.0);
269 assert!(parse_percent("101%").is_err());
270 assert!(parse_percent("x%").is_err());
271 assert!(parse_percent("").is_err());
272 }
273
274 #[test]
275 fn parse_systemd_timespans() {
276 assert_eq!(parse_duration_s("30s").unwrap(), 30.0);
277 assert_eq!(parse_duration_s("1min 30s").unwrap(), 90.0);
278 assert_eq!(parse_duration_s("20sec").unwrap(), 20.0);
279 assert_eq!(parse_duration_s("250msec").unwrap(), 0.25);
280 assert_eq!(parse_duration_s("2 minutes").unwrap(), 120.0);
281 assert_eq!(parse_duration_s("1w").unwrap(), 604800.0);
282 assert!(parse_duration_s("infinity").is_err());
283 }
284
285 #[test]
286 fn formatting() {
287 assert_eq!(format_pct(f64::NAN), "n/a");
288 assert_eq!(format_rate_per_min(400.0 * MIB as f64), "+400M/min");
289 assert_eq!(format_rate_per_min(-1.5 * GIB as f64), "-1.5G/min");
290 assert_eq!(format_bytes(0, UnitSystem::Iec, 1), "0 B");
291 assert_eq!(format_bytes(9_900 * MIB, UnitSystem::Iec, 1), "9.7 GiB");
292 assert_eq!(format_bytes(9_900_000_000, UnitSystem::Si, 1), "9.9 GB");
293 assert_eq!(format_bytes_short(3 * GIB), "3.0G");
294 assert_eq!(format_bytes_short(512 * MIB), "512M");
295 assert_eq!(format_duration(13200), "3h40m");
296 assert_eq!(format_duration(18000), "5h");
297 assert_eq!(format_duration(360), "6m");
298 assert_eq!(format_bytes_signed(-(GIB as i64), UnitSystem::Iec, 1), "-1.0 GiB");
299 }
300
301 #[test]
302 fn formatting_rolls_over_instead_of_printing_1024() {
303 let b = 1023 * KIB + 1000;
305 assert_eq!(format_bytes_short(b), "1.0M");
306 assert_eq!(format_bytes(b, UnitSystem::Iec, 1), "1.0 MiB");
307 assert_eq!(format_bytes(MIB - 1, UnitSystem::Iec, 3), "1023.999 KiB");
308 assert_eq!(format_bytes_short(1023 * KIB), "1023K");
309 assert_eq!(format_bytes_short(u64::MAX), "16777216T");
310 assert_eq!(format_bytes(999_960_000, UnitSystem::Si, 1), "1.0 GB");
311 assert_eq!(format_bytes(1023, UnitSystem::Iec, 1), "1023 B");
312 }
313
314 #[test]
315 fn short_form_rounds_before_dropping_the_decimal() {
316 let b = (99.96 * GIB as f64) as u64;
318 assert_eq!(format_bytes_short(b), "100G");
319 assert_eq!(format_bytes_short((99.94 * GIB as f64) as u64), "99.9G");
320 assert_eq!(format_bytes_short(100 * MIB), "100M");
321 assert_eq!(format_bytes_short((9.96 * MIB as f64) as u64), "10.0M");
322 }
323
324 #[test]
325 fn durations_reject_overflow_and_accept_greek_mu() {
326 let huge = format!("{}w", "9".repeat(400));
327 assert!(parse_duration_s(&huge).is_err());
328 assert_eq!(parse_duration_s("500μs").unwrap(), 0.0005);
329 assert_eq!(parse_duration_s("500µs").unwrap(), 0.0005);
330 }
331}