units_formatter/bytes.rs
1//
2const UNITS: &[&str] = &[
3 "iB",
4 "KiB",
5 "MiB",
6 "GiB",
7 "TiB",
8 "PiB",
9 "EiB",
10 "ZiB",
11 "YiB",
12];
13
14/// 将字节数格式化为带单位的字符串(如 KiB、MiB、GiB 等)。
15///
16/// # 参数
17/// - `bytes`: 原始字节数(`usize`)。
18/// - `round`: 可选的小数精度(默认保留 2 位,最大不超过 10)。
19///
20/// # 返回
21/// 返回一个字符串,例如 `"1.23KiB"`、`"999iB"`、`"4.56MiB"`。
22pub fn format_bytes(bytes: usize, round: Option<u8>) -> String {
23 let mut size = bytes as f64;
24 let mut unit_index = 0;
25
26 while size >= 1024.0 && unit_index < UNITS.len() - 1 {
27 size /= 1024.0;
28 unit_index += 1;
29 }
30
31 let precision = round.unwrap_or(2).min(10) as usize;
32 format!("{:.precision$}{}", size, UNITS[unit_index])
33}