| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
#[cfg(test)] |
| 13 |
mod tests; |
| 14 |
|
| 15 |
#[cfg(not(feature = "si-units"))] |
| 16 |
|
| 17 |
const SUFFIX: [&str; 9] = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; |
| 18 |
|
| 19 |
#[cfg(feature = "si-units")] |
| 20 |
|
| 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 |
|
| 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 |
|
| 44 |
.format((UNIT.powf(base - base.floor()) * 10.0).round() / 10.0) |
| 45 |
.trim_end_matches(".0"); |
| 46 |
|
| 47 |
|
| 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 |
|
| 58 |
[&result, SUFFIX[base.floor() as usize]].join(" ") |
| 59 |
} |
| 60 |
} |