cloud_disk_sync/utils/
format.rs

1pub fn format_bytes(bytes: u64) -> String {
2    const UNITS: [&str; 6] = ["B", "KB", "MB", "GB", "TB", "PB"];
3    if bytes == 0 {
4        return "0 B".to_string();
5    }
6    let base = 1024.0;
7    let exponent = (bytes as f64).log(base).floor() as u32;
8    let unit = UNITS[exponent.min(5) as usize];
9    let value = bytes as f64 / base.powi(exponent as i32);
10    format!("{:.2} {}", value, unit)
11}
12
13pub fn truncate_string(s: &str, max_width: usize) -> String {
14    use unicode_width::UnicodeWidthChar;
15
16    let mut width = 0;
17    let mut result = String::new();
18    for c in s.chars() {
19        let w = UnicodeWidthChar::width(c).unwrap_or(0);
20        if width + w > max_width {
21            if width + 3 <= max_width {
22                result.push_str("...");
23            }
24            break;
25        }
26        width += w;
27        result.push(c);
28    }
29    result
30}
31
32#[cfg(test)]
33mod tests {
34    use super::format_bytes;
35    #[test]
36    fn test_format_bytes_basic() {
37        assert_eq!(format_bytes(0), "0 B");
38        assert_eq!(format_bytes(1024), "1.00 KB");
39        assert_eq!(format_bytes(1024 * 1024), "1.00 MB");
40    }
41}