A Rust crate that converts bytes into human-readable values.
It can return either KB/MB/GB/TB or KiB/MiB/GiB/TiB via the bibytes
feature,
which enables the power of 2 unit system.
(1 KB = 1024 B, 1 KiB = 1024 B, the only thing that changes is the suffix).
It supports from 0 bytes to several yottabytes (I cannot tell how many because I have to use u128
s
to fit a single YB)
Add to your Cargo.toml
:
```toml [dependencies] human_bytes = "0.3"
human_bytes = { version = "0.3", features = ["bibytes"] } ```
And then
```rust use humanbytes::humanbytes;
asserteq!(humanbytes(563200u32), "550 KB".tostring());
// or
asserteq!(humanbytes(563200u64 as f64), "550 KB".tostring());
// __________/
// |
// | Needed only when you're using u64
values,
// | because f64
doesn't implement std::convert::From<u64>
// With the bibytes
feature enabled:
asserteq!(humanbytes(563200u32), "550 KiB".to_string());
```
The crate is dependency-free, but if you want an +/- 15% speed improvement, there's a fast
feature
that uses lexical instead of std::format!
in the number-to-string conversion
toml
[dependencies]
human_bytes = { version = "0.3", features = ["fast"] }
The code is based on a PHP function I found here.
It is useful because you don't have to provide a prefix, it does it on its own.
It'll always return 1 MB
instead of 1000 KB
It has some tests I wrote to check that the conversion is correct, and it returns decimals (e.g. 16.5 GB
)
Check the CHANGELOG.md
BSD 2-clause (c) 2020 Namkhai B.