imessage_database/util/
size.rs1const DIVISOR: f64 = 1024.;
6const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
7
8#[must_use]
19pub fn format_file_size(total_bytes: u64) -> String {
20 let mut index: usize = 0;
21 let mut bytes = total_bytes as f64;
22 while index < UNITS.len() - 1 && bytes > DIVISOR {
23 index += 1;
24 bytes /= DIVISOR;
25 }
26
27 format!("{bytes:.2} {}", UNITS[index])
28}
29
30#[cfg(test)]
31mod tests {
32 use crate::util::size::format_file_size;
33
34 #[test]
35 fn can_get_file_size_bytes() {
36 assert_eq!(format_file_size(100), String::from("100.00 B"));
37 }
38
39 #[test]
40 fn can_get_file_size_kb() {
41 let expected = format_file_size(2300);
42 assert_eq!(expected, String::from("2.25 KB"));
43 }
44
45 #[test]
46 fn can_get_file_size_mb() {
47 let expected = format_file_size(5612000);
48 assert_eq!(expected, String::from("5.35 MB"));
49 }
50
51 #[test]
52 fn can_get_file_size_gb() {
53 let expected = format_file_size(9234712394);
54 assert_eq!(expected, String::from("8.60 GB"));
55 }
56
57 #[test]
58 fn can_get_file_size_cap() {
59 let expected = format_file_size(u64::MAX);
60 assert_eq!(expected, String::from("16777216.00 TB"));
61 }
62}