[Rust] 为Salvo 添加人性化展示字节数 MB GB TB

Salvo Pull Request

Salvo框架的静态文件列表展示的文件容量为bytes 展示为MB,GB,TB更容易识别 Mac和Linux系统 下硬盘容量计算单位为1000字节Bytes = 1MB Windows环境下为1024字节Bytes=1MB n_float.fract()为小数部分 l为下一级显示的单位容量 part_integer为整数部分。 拼接一位小数在有小数的情况下 向上取整 可替换为n_float.round() 或向下取整n_float.ceil()

实现

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)); 
    }
}
ON THIS PAGE