Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! ## A Rust crate & cli to convert bytes into human-readable values.
2
3 //! It can return either KiB/MiB/GiB/TiB or KB/MB/GB/TB by disabling the `si-units` feature.
4 //!
5 //! > 1 KiB = 1024 B, 1 KB = 1000 B
6 //!
7 //! It supports from 0 bytes to several yottabytes (I cannot tell how many because I have to use `u128`s
8 //! to fit a single YB)
9 //!
10 //! For more info, check out the [README.md](https://sr.ht/~f9/human_bytes)
11
12 #[cfg(test)]
13 mod tests;
14
15 #[cfg(not(feature = "si-units"))]
16 // Just be future-proof
17 const SUFFIX: [&str; 9] = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
18
19 #[cfg(feature = "si-units")]
20 // Just be future-proof
21 const SUFFIX: [&str; 9] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
22
23 #[cfg(not(feature = "si-units"))]
24 const UNIT: f64 = 1000.0;
25
26 #[cfg(feature = "si-units")]
27 const UNIT: f64 = 1024.0;
28
29 /// Converts bytes to human-readable values
30 pub fn human_bytes<T: Into<f64>>(bytes: T) -> String {
31 let size = bytes.into();
32
33 if size <= 0.0 {
34 return "0 B".to_string();
35 }
36
37 let base = size.log10() / UNIT.log10();
38
39 #[cfg(feature = "fast")]
40 {
41 let mut buffer = ryu::Buffer::new();
42 let result = buffer
43 // Source for this hack: https://stackoverflow.com/a/28656825
44 .format((UNIT.powf(base - base.floor()) * 10.0).round() / 10.0)
45 .trim_end_matches(".0");
46
47 // Add suffix
48 [result, SUFFIX[base.floor() as usize]].join(" ")
49 }
50
51 #[cfg(not(feature = "fast"))]
52 {
53 let result = format!("{:.1}", UNIT.powf(base - base.floor()),)
54 .trim_end_matches(".0")
55 .to_owned();
56
57 // Add suffix
58 [&result, SUFFIX[base.floor() as usize]].join(" ")
59 }
60 }