Skip to main content

syncbox/utils/
format.rs

1/// 格式化文件大小为易读格式 (B, KB, MB, GB, TB)
2/// 示例: 1024 -> "1.0 KB", 1048576 -> "1.0 MB"
3pub fn format_file_size(bytes: u64) -> String {
4    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
5    let mut size = bytes as f64;
6    let mut unit_index = 0;
7
8    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
9        size /= 1024.0;
10        unit_index += 1;
11    }
12
13    // 专业推荐:非Bytes单位都显示1位小数
14    if unit_index == 0 {
15        format!("{} {}", size as u64, UNITS[unit_index])
16    } else {
17        format!("{:.1} {}", size, UNITS[unit_index])
18    }
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[test]
26    fn test_format_file_size() {
27        assert_eq!(format_file_size(0), "0 B");
28        assert_eq!(format_file_size(999), "999 B");
29        assert_eq!(format_file_size(1024), "1.0 KB");
30        assert_eq!(format_file_size(1536), "1.5 KB");
31        assert_eq!(format_file_size(1048576), "1.0 MB");
32        assert_eq!(format_file_size(1572864), "1.5 MB");
33        assert_eq!(format_file_size(1073741824), "1.0 GB");
34    }
35
36}