ByteScale

ByteScale is a utility for human-readable byte count representations.
Features:
- Pre-defined constants for various size units (e.g., B, Kb, Kib, Mb, Mib, Gb, Gib, ... PB).
ByteScale type which presents size units convertible to different size units.
- Arithmetic operations for
ByteScale.
- FromStr impl for
ByteScale, allowing to parse from string size representations like 1.5KiB and 521TiB.
- Serde support for binary and human-readable deserializers like JSON.
API Documentation
Example
Human readable representations (SI unit and Binary unit)
use bytescale::ByteScale;
fn assert_display(expected: &str, b: ByteScale) {
assert_eq!(expected, format!("{}", b));
}
fn test_display() {
assert_display("215 B", ByteScale::b(215));
assert_display("1.0 KiB", ByteScale::kib(1));
assert_display("301.0 KiB", ByteScale::kib(301));
assert_display("419.0 MiB", ByteScale::mib(419));
assert_display("518.0 GiB", ByteScale::gib(518));
assert_display("815.0 TiB", ByteScale::tib(815));
assert_display("609.0 PiB", ByteScale::pib(609));
}
fn test_display_alignment() {
assert_eq!("|357 B |", format!("|{:10}|", ByteScale(357)));
assert_eq!("| 357 B|", format!("|{:>10}|", ByteScale(357)));
assert_eq!("|357 B |", format!("|{:<10}|", ByteScale(357)));
assert_eq!("| 357 B |", format!("|{:^10}|", ByteScale(357)));
assert_eq!("|-----357 B|", format!("|{:->10}|", ByteScale(357)));
assert_eq!("|357 B-----|", format!("|{:-<10}|", ByteScale(357)));
assert_eq!("|--357 B---|", format!("|{:-^10}|", ByteScale(357)));
}
fn assert_to_string(expected: &str, b: ByteScale, si: bool) {
assert_eq!(expected.to_string(), b.to_string_as(si));
}
fn test_to_string_as() {
assert_to_string("215 B", ByteScale::b(215), true);
assert_to_string("215 B", ByteScale::b(215), false);
assert_to_string("1.0 KiB", ByteScale::kib(1), true);
assert_to_string("1.0 KB", ByteScale::kib(1), false);
assert_to_string("293.9 KiB", ByteScale::kb(301), true);
assert_to_string("301.0 KB", ByteScale::kb(301), false);
assert_to_string("1.0 MiB", ByteScale::mib(1), true);
assert_to_string("1048.6 KB", ByteScale::mib(1), false);
assert_to_string("399.6 MiB", ByteScale::mb(419), true);
assert_to_string("419.0 MB", ByteScale::mb(419), false);
assert_to_string("482.4 GiB", ByteScale::gb(518), true);
assert_to_string("518.0 GB", ByteScale::gb(518), false);
assert_to_string("741.2 TiB", ByteScale::tb(815), true);
assert_to_string("815.0 TB", ByteScale::tb(815), false);
assert_to_string("540.9 PiB", ByteScale::pb(609), true);
assert_to_string("609.0 PB", ByteScale::pb(609), false);
}
Arithmetic operations
use bytescale::ByteScale;
fn byte_arithmetic_operator() {
let x = ByteScale::mb(1);
let y = ByteScale::kb(100);
let plus = x + y;
print!("{}", plus);
let minus = ByteScale::tb(100) + ByteScale::gb(4);
print!("{}", minus);
}