From 0044d2f2efeddc8c2d682680f0fd8f5989d0a0c6 Mon Sep 17 00:00:00 2001 From: gakaki Date: Sat, 2 Mar 2024 02:00:45 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20=20display=20static=20file=20siz?= =?UTF-8?q?e=20to=20mb=20kb=20gb=20tb=20pb=20eb=20(#709)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/serve-static/src/dir.rs | 51 +++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/serve-static/src/dir.rs b/crates/serve-static/src/dir.rs index c3cceaa20..3a5a9e53f 100644 --- a/crates/serve-static/src/dir.rs +++ b/crates/serve-static/src/dir.rs @@ -503,6 +503,29 @@ fn list_xml(current: &CurrentInfo) -> String { ftxt.push_str(""); ftxt } +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 +} fn list_html(current: &CurrentInfo) -> String { fn header_links(path: &str) -> String { let segments = path.trim_start_matches('/').trim_end_matches('/').split('/'); @@ -557,7 +580,7 @@ fn list_html(current: &CurrentInfo) -> String { encode_url_path(&file.name), file.name, file.modified.format(&format).expect("format time failed"), - file.size + human_size(file.size) ) .ok(); } @@ -611,3 +634,29 @@ const HTML_STYLE: &str = r#" const DIR_ICON: &str = r#""#; const FILE_ICON: &str = r#""#; const HOME_ICON: &str = r#""#; + +#[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)); // 1023.9 B + + println!("{}", human_size(unit * unit)); // 1 MB + println!("{}", human_size(unit * unit - 1)); // 1023.9 KB + + println!("{}", human_size(unit * unit * unit)); // 1 GB + println!("{}", human_size(unit * unit * unit - 1)); // 1023.9 MB + + println!("{}", human_size(unit * unit * unit * unit)); // 1 TB + println!("{}", human_size(unit * unit * unit * unit - 1)); // 1023.9 GB + + println!("{}", human_size(unit * unit * unit * unit * unit)); // 1 PB + println!("{}", human_size(unit * unit * unit * unit * unit - 1)); //1023.9 TB + } +} \ No newline at end of file