fn human_size(x: u64) -> String {
let unit = 1000; // mac unix 1000 windows 1024
let units = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
let mut l = 0;
let mut n_float = 0.00; // just for integer part
let mut n = x;
while n >= unit && l < units.len() {
n_float = (n as f64) / (unit as f64);
n /= unit;
l += 1;
}
let part_integer = format!("{}", n);
let mut res = format!("{}", part_integer);
if n_float.fract() != 0.0 {
let s = format!("{}", n_float.fract());
let substring = &s[2..3]; // 0.99 get 9
res = format!("{}.{}", part_integer, substring)
}
format!("{} {}", res, units[l]) // integer part add digit
}
#[cfg(test)]
mod tests {
use crate::dir::human_size;
#[tokio::test]
async fn test_convert_bytes_to_units() {
println!("{}", human_size(98595176));// 98.59 MB on mac
let unit = 1000;
println!("{}", human_size(unit)); // 1 KB
println!("{}", human_size(unit - 1)); // 999 B
println!("{}", human_size(unit * unit)); // 1 MB
println!("{}", human_size(unit * unit - 1)); // 999 KB
println!("{}", human_size(unit * unit * unit)); // 1 GB
println!("{}", human_size(unit * unit * unit - 1)); // 999.9 MB
println!("{}", human_size(unit * unit * unit * unit)); // 1 TB
println!("{}", human_size(unit * unit * unit * unit - 1));
println!("{}", human_size(unit * unit * unit * unit * unit)); // 1 PB
println!("{}", human_size(unit * unit * unit * unit * unit - 1));
}
}