CLI utility functions.
(bytes: usize)
| 1 | //! CLI utility functions. |
| 2 | |
| 3 | pub fn format_bytes(bytes: usize) -> String { |
| 4 | const KB: f64 = 1024.0; |
| 5 | const MB: f64 = KB * 1024.0; |
| 6 | // Threshold chosen to avoid displaying "1024.0 KB" due to rounding. |
| 7 | // At 1_048_524 bytes (1023.99 KB), we still show KB. |
| 8 | // At 1_048_525 bytes and above, we switch to MB display. |
| 9 | const KB_TO_MB_ROUNDING_THRESHOLD: usize = 1_048_525; |
| 10 | |
| 11 | if bytes < 1024 { |
| 12 | format!("{} B", bytes) |
| 13 | } else if bytes < KB_TO_MB_ROUNDING_THRESHOLD { |
| 14 | format!("{:.1} KB", bytes as f64 / KB) |
| 15 | } else { |
| 16 | format!("{:.2} MB", bytes as f64 / MB) |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | #[cfg(test)] |
| 21 | mod tests { |
no outgoing calls