3 const UNIT_PREFIXES: [&str; 6] = ["", "k", "M", "G", "T", "P"];
10 pub fn new(bytes: u64) -> Self {
17 impl std::fmt::Display for Bytes {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 debug_assert!(num >= 0.0);
22 return write!(f, "{} B", num);
24 let delimiter = 1000_f64;
25 let exponent = cmp::min((num.ln() / 6.90775).floor() as i32, 4);
27 write!(f, "{:.2} ", num / delimiter.powi(exponent))?;
28 write!(f, "{}B", UNIT_PREFIXES[exponent as usize])
37 fn test_bytes_formatting() {
38 fn format_bytes(bytes: u64) -> String {
39 format!("{}", Bytes::new(bytes))
46 assert_eq!("0 B", format_bytes(0)); // This is weird
47 assert_eq!("1.00 B", format_bytes(b));
48 assert_eq!("999.00 B", format_bytes(b * 999));
49 assert_eq!("12.00 MB", format_bytes(mb * 12));
50 assert_eq!("123.00 MB", format_bytes(mb * 123));
51 assert_eq!("5.50 MB", format_bytes(mb * 5 + kb * 500));
52 assert_eq!("7.54 GB", format_bytes(gb * 7 + 540 * mb));
53 assert_eq!("1.20 TB", format_bytes(gb * 1200));
56 assert_eq!("234.00 B", format_bytes(234));
57 assert_eq!("999.00 B", format_bytes(999));
59 assert_eq!("2.23 kB", format_bytes(2234));
60 assert_eq!("62.50 kB", format_bytes(62500));
61 assert_eq!("329.99 kB", format_bytes(329990));
63 assert_eq!("2.75 MB", format_bytes(2750000));
64 assert_eq!("55.00 MB", format_bytes(55000000));
65 assert_eq!("987.65 MB", format_bytes(987654321));
67 assert_eq!("5.28 GB", format_bytes(5280000000));
68 assert_eq!("95.20 GB", format_bytes(95200000000));
69 assert_eq!("302.00 GB", format_bytes(302000000000));