typed-bytes
A
![no_std], const first Rust library for strongly-typed data size units (KiB, MiB, KB, MB, etc.).
Features
no_std- Fully typed data size units (IEC and SI)
- Operator overloading
Why
During our work at haxiom.io we found many cases of file size comparisons
where we accidentally mixed IEC and SI units. Likewise, using plain u64 for file sizes
led to many bugs even if they are named correctly, for example MAX_FILE_SIZE could be
interpreted as either bytes or kilobytes! This library provides a safe and type-safe way to
handle file sizes with proper units, ensuring that the correct unit is used in each
comparison. Note that most of the work has been lifted from the internal implementation at haxiom internal
repository.
Installation
Add this to your Cargo.toml:
[]
= "1.0.0"
Usage
This library provides both IEC and SI units.
IEC Units (Base 2)
use ;
use Bytes;
let size = KiB;
let bytes: Bytes = size.into; // 5 * 1024 = 5120 bytes
assert_eq!;
assert_eq!;
SI Units (Base 10)
use ;
use Bytes;
let size = KB;
let bytes: Bytes = size.into; // 5 * 1000 = 5000 bytes
assert_eq!;
assert_eq!;
Comparisons & Safety
To prevent "footguns" (accidental mixing of binary and decimal units), there are no implicit comparisons between SI and IEC units. You must strictly convert them to a common type (like Bytes) or explicitly convert one to the other before comparing.
This compilation failure is a feature, not a bug:
use KiB;
use KB;
let kib = KiB;
let kb = KB;
// This fails to compile!
if kib > kb
This will compile:
use KiB;
use KB;
use Bytes;
let kib = KiB;
let kb = KB;
if from > from
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.