-
Notifications
You must be signed in to change notification settings - Fork 25
Description
webdav-handler-rs/src/handle_gethead.rs
Lines 416 to 430 in 58ad114
| fn display_size(size: u64) -> String { | |
| if size <= 1000 { | |
| return format!("{} ", size); | |
| } | |
| if size <= 1_000_000 { | |
| return format!("{} KiB", ((size / 10) as f64) / 100f64); | |
| } | |
| if size <= 1_000_000_000 { | |
| return format!("{} MiB", ((size / 10_000) as f64) / 100f64); | |
| } | |
| if size <= 1_000_000_000_000 { | |
| return format!("{} GiB", ((size / 10_000_000) as f64) / 100f64); | |
| } | |
| format!("{:2}TiB", ((size / 10_000_000_000) as f64) / 100f64) | |
| } |
Rust function display_size is to format a given size in bytes into a human-readable string using binary prefixes (KiB, MiB, GiB, TiB). However, there are a few issues with your current implementation that need to be addressed to ensure correct usage of these units.
-
Binary vs Decimal Prefixes: The prefixes KiB, MiB, GiB, and TiB are binary prefixes, meaning they should be calculated based on powers of 2, not powers of 10. For example, 1 KiB (Kibibyte) is
$2^{10}$ bytes (1024 bytes), not 1000 bytes. -
Calculation Accuracy: The division and multiplication approach you're using to convert bytes into larger units can lead to inaccuracies. Instead, you should divide by the exact binary value for each unit. For example, divide by
$2^{10}$ for KiB,$2^{20}$ for MiB, etc.
Here's a revised version of your function:
fn display_size(size: u64) -> String {
if size < 1024 {
return format!("{} B", size);
}
if size < 1024 * 1024 {
return format!("{:.2} KiB", size as f64 / 1024f64);
}
if size < 1024 * 1024 * 1024 {
return format!("{:.2} MiB", size as f64 / (1024 * 1024) as f64);
}
if size < 1024 * 1024 * 1024 * 1024 {
return format!("{:.2} GiB", size as f64 / (1024 * 1024 * 1024) as f64);
}
format!("{:.2} TiB", size as f64 / (1024 * 1024 * 1024 * 1024) as f64)
}