2 releases (1 stable)
1.0.0 | Apr 5, 2025 |
---|---|
0.1.0 | May 7, 2024 |
#556 in Encoding
145 downloads per month
Used in 2 crates
10KB
91 lines
bittenhumans
A lightweight, simple byte size humanization library for Rust.
Features
- Supports both decimal (KB, MB, GB) and binary (KiB, MiB, GiB) numeral systems
- Automatic magnitude selection for appropriate unit sizing
- IEC-compliant formatting with "i" infix for binary units
- Configurable formatting with reusable formatters
Installation
Add this to your Cargo.toml
:
[dependencies]
bittenhumans = "1.0.0"
Usage
Basic Usage
use bittenhumans::ByteSizeFormatter;
use bittenhumans::consts::System;
fn main() {
// Format with automatic unit selection
let formatted = ByteSizeFormatter::format_auto(1_500_000, System::Decimal);
assert_eq!(formatted, "1.50 MB");
// Format using binary system (powers of 1024)
let formatted = ByteSizeFormatter::format_auto(1_500_000, System::Binary);
assert_eq!(formatted, "1.43 MiB");
}
Creating Reusable Formatters
use bittenhumans::ByteSizeFormatter;
use bittenhumans::consts::{Magnitude, System};
fn main() {
// Create a formatter for gigabytes
let gb_formatter = ByteSizeFormatter::new(System::Decimal, Magnitude::Giga);
// Use it multiple times with different values
let total_space = gb_formatter.format_value(1_000_000_000_000); // "1000.00 GB"
let free_space = gb_formatter.format_value(250_000_000_000); // "250.00 GB"
}
Creating Size-Appropriate Formatters
use bittenhumans::ByteSizeFormatter;
use bittenhumans::consts::System;
fn main() {
// Create a formatter that fits the largest value you'll format
let disk_size = 2_000_000_000_000; // 2 TB
let formatter = ByteSizeFormatter::fit(disk_size, System::Binary);
// All values will use the same unit for consistent display
println!("Disk size: {}", formatter.format_value(disk_size)); // "1.82 TiB"
println!("Used space: {}", formatter.format_value(disk_size/4)); // "0.45 TiB"
}
Documentation
For more detailed information, check the API documentation.
Use Cases
- Status bars and system monitors
- File managers and download managers
- System information displays
- Anywhere byte sizes need to be displayed in a human-readable format
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Dependencies
~210–630KB
~15K SLoC