Skip to content

Correct display_size with binary prefixes #31

@ArcticLampyrid

Description

@ArcticLampyrid

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.

  1. 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.

  2. 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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions