image_optimizer/file_ops/
byte_formatter.rs1#[must_use]
2pub fn format_bytes(bytes: u64) -> String {
3 const UNITS: &[&str] = &["B", "KB", "MB", "GB"];
4 #[allow(clippy::cast_precision_loss)]
5 let mut size = bytes as f64;
6 let mut unit_index = 0;
7
8 while size >= 1024.0 && unit_index < UNITS.len() - 1 {
9 size /= 1024.0;
10 unit_index += 1;
11 }
12
13 if unit_index == 0 {
14 format!("{} {}", bytes, UNITS[unit_index])
15 } else {
16 format!("{:.1} {}", size, UNITS[unit_index])
17 }
18}
19
20#[cfg(test)]
21mod tests {
22 use super::*;
23
24 #[test]
25 fn test_format_bytes() {
26 assert_eq!(format_bytes(0), "0 B");
27 assert_eq!(format_bytes(512), "512 B");
28 assert_eq!(format_bytes(1023), "1023 B");
29 assert_eq!(format_bytes(1024), "1.0 KB");
30 assert_eq!(format_bytes(1536), "1.5 KB");
31 assert_eq!(format_bytes(1048576), "1.0 MB");
32 assert_eq!(format_bytes(1073741824), "1.0 GB");
33 assert_eq!(format_bytes(2147483648), "2.0 GB");
34 }
35
36 #[test]
37 fn test_format_bytes_edge_cases() {
38 assert_eq!(format_bytes(u64::MAX), "17179869184.0 GB");
39 assert_eq!(format_bytes(1), "1 B");
40 assert_eq!(format_bytes(1025), "1.0 KB");
41 }
42}