Skip to content

Commit

Permalink
Create convert.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
Levminer committed Jul 20, 2024
1 parent d91d382 commit b05b78a
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions platforms/unix/hardwareinfo/src/convert.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use std::cmp;

pub fn convert(num: f64) -> String {
let negative = if num.is_sign_positive() { "" } else { "-" };
let num = num.abs();
let units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
if num < 1_f64 {
return format!("{}{} {}", negative, num, "B");
}
let delimiter = 1024_f64;
let exponent = cmp::min(
(num.ln() / delimiter.ln()).floor() as i32,
(units.len() - 1) as i32,
);
let pretty_bytes = format!("{:.2}", num / delimiter.powi(exponent))
.parse::<f64>()
.unwrap()
* 1_f64;
let unit = units[exponent as usize];
format!("{}{} {}", negative, pretty_bytes, unit)
}

0 comments on commit b05b78a

Please sign in to comment.