imessage_database/util/
size.rs

1/*!
2 Contains logic for creating human-readable file size strings.
3 */
4
5const DIVISOR: f64 = 1024.;
6const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
7
8/// Get a human readable file size for an arbitrary amount of bytes
9///
10// # Example:
11///
12/// ```
13/// use imessage_database::util::size::format_file_size;
14///
15/// let size: String = format_file_size(5612000);
16/// println!("{size}"); // 5.35 MB
17/// ```
18pub fn format_file_size(total_bytes: u64) -> String {
19    let mut index: usize = 0;
20    let mut bytes = total_bytes as f64;
21    while index < UNITS.len() - 1 && bytes > DIVISOR {
22        index += 1;
23        bytes /= DIVISOR;
24    }
25
26    format!("{bytes:.2} {}", UNITS[index])
27}
28
29#[cfg(test)]
30mod tests {
31    use crate::util::size::format_file_size;
32
33    #[test]
34    fn can_get_file_size_bytes() {
35        assert_eq!(format_file_size(100), String::from("100.00 B"));
36    }
37
38    #[test]
39    fn can_get_file_size_kb() {
40        let expected = format_file_size(2300);
41        assert_eq!(expected, String::from("2.25 KB"));
42    }
43
44    #[test]
45    fn can_get_file_size_mb() {
46        let expected = format_file_size(5612000);
47        assert_eq!(expected, String::from("5.35 MB"));
48    }
49
50    #[test]
51    fn can_get_file_size_gb() {
52        let expected = format_file_size(9234712394);
53        assert_eq!(expected, String::from("8.60 GB"));
54    }
55
56    #[test]
57    fn can_get_file_size_cap() {
58        let expected = format_file_size(u64::MAX);
59        assert_eq!(expected, String::from("16777216.00 TB"));
60    }
61}