Skip to main content

treewalk/walk/
format.rs

1use std::fmt;
2
3/// Units of digital information expressed in base-10
4#[derive(Clone, Copy, Debug)]
5pub enum Units {
6    B = 1,
7    KB = 1_000,
8    MB = 1_000_000,
9    GB = 1_000_000_000,
10    TB = 1_000_000_000_000,
11    PB = 1_000_000_000_000_000,
12}
13
14impl fmt::Display for Units {
15    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
16        write!(f, "{:?}", self)
17    }
18}
19
20/// takes a [u64] (representative of bytes in a file) and converts to a human readable [String]
21/// ```
22/// use treewalk::walk::format;
23/// assert_eq!(format::human_readable(1_000, false), "1000B");
24/// assert_eq!(format::human_readable(10_500, true), "10.50KB");
25/// assert_eq!(format::human_readable(10_000_000, false), "10MB");
26/// assert_eq!(format::human_readable(100_000_000, false), "100MB");
27/// assert_eq!(format::human_readable(1_000_000_000, false), "1000MB");
28/// assert_eq!(format::human_readable(1_000_000_001, false), "1GB");
29/// assert_eq!(format::human_readable(1_000_000_000_000, false), "1000GB");
30/// assert_eq!(format::human_readable(10_000_000_000_000, false), "10TB");
31/// ```
32pub fn human_readable(num: u64, as_float: bool) -> String {
33    let result = String::from("");
34    match num {
35        ..=1_000 => result + &num.to_string() + "B",
36        1_001..=1_000_000 => construct_hr_output(&num, as_float, Units::KB),
37        1_000_001..=1_000_000_000 => construct_hr_output(&num, as_float, Units::MB),
38        1_000_000_001..=1_000_000_000_000 => construct_hr_output(&num, as_float, Units::GB),
39        1_000_000_000_001..=1_000_000_000_000_000 => construct_hr_output(&num, as_float, Units::TB),
40        1_000_000_000_000_001.. => construct_hr_output(&num, as_float, Units::PB),
41    }
42}
43
44fn construct_hr_output(num: &u64, as_float: bool, unit: Units) -> String {
45    if as_float {
46        format!("{:.2}{}", *num as f64 / (unit as u64) as f64, unit)
47    } else {
48        format!("{:.2}{}", num / unit as u64, unit)
49    }
50}