Human bytes
human_bytesis a Rust crate to convert bytes into human-readable values.
Usage
Add this to your Cargo.toml:
[]
= "0.2"
And then
use human_bytes;
assert_eq!;
// or
assert_eq!;
// ________________________________/
// |
// | Needed only when you're using `u64` values,
// | because `f64` doesn't implement `std::convert::From<u64>`
human_bytes is dependency-free, but if you want an +/- 15% speed improvement, I have a fast feature (which depends on lexical)
[]
= { = "0.2", = "fast" }
About
This crate 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. This means it'll return the correct prefix, and never return "1000 KB", always "1 MB"
It has some tests I wrote to check that the conversion is correct, and it returns decimals, e.g. "16.5 GB"
Limitations
The function uses f64 floating point numbers,
which ranges from $±0000000000000000×10^{−398}$ to $±9999999999999999×10^{369}$ acording to Wikipedia
That's a number so big, that running human_bytes(std::f64::MAX) panic!'s with 'index out of bounds: the len is 9 but the index is 102'.
That's because I only have suffixes up to yottabytes, which quoting Wikipedia
In 2010, it was estimated that storing a yottabyte on terabyte-size disk drives would require one million city block-size data-centers, as big as the states of Delaware and Rhode Island combined.[1] By late 2016 memory density had increased to the point where a yottabyte could be stored on SD cards occupying roughly twice the size of the Hindenburg[2] (around 400 thousand cubic metres). so I decided not to go bigger (and anyway, the SI doesn't define bigger prefixes).
I use f64 to be able of returning decimals (e.g. 5.3 GB), but if you want to use u64 bytes, you have to write 10_u64 as f64, because f64 dousn't implement From<u64>.
And no way you're going to use u128's. Anyway, human_bytes(std::u64::MAX as f64) returns 16 EB, which is more than Google has on their servers (source).
For now, I only test correct conversions up to 2.5 terabytes.
Changelog
Check CHANGELOG.md
License
BSD 2-clause - Copyright (c) 2020 Namkhai Bourquin (forkbomb9)