| 1 | # human_bytes |
| 2 | |
| 3 | > A Rust crate & cli to convert bytes into human-readable values. |
| 4 | |
| 5 | [](./LICENSE) |
| 6 | [](https://crates.io/crates/human_bytes) |
| 7 | []() |
| 8 | |
| 9 | It can return either KiB/MiB/GiB/TiB or KB/MB/GB/TB by disabling the `si-units` feature. |
| 10 | |
| 11 | > 1 KiB = 1024 B, 1 KB = 1000 B |
| 12 | |
| 13 | It supports from 0 bytes to several yottabytes (I cannot tell how many because I have to use `u128`s |
| 14 | to fit a single YB) |
| 15 | |
| 16 | ## Usage |
| 17 | |
| 18 | ### As a CLI |
| 19 | |
| 20 | * (Optional) Install [Just](https://just.systems/) |
| 21 | * Build: |
| 22 | - With just: `just build-binary` |
| 23 | - Plain cargo: `cargo build --release --features 'build-binary fast' --bin hb` |
| 24 | * Copy `target/release/hb` to somewhere in your `$PATH` |
| 25 | * Run `hb <bytes>` or `echo <bytes> | hb` |
| 26 | |
| 27 | ### As a library |
| 28 | |
| 29 | Add to your `Cargo.toml`: |
| 30 | |
| 31 | ```toml |
| 32 | [dependencies] |
| 33 | human_bytes = "0.4" |
| 34 | # or, to disable the SI Units: |
| 35 | human_bytes = { version = "0.4", default-features = false } |
| 36 | ``` |
| 37 | |
| 38 | And then |
| 39 | |
| 40 | ```rust |
| 41 | use human_bytes::human_bytes; |
| 42 | |
| 43 | assert_eq!(human_bytes(563_200_u32), "550 KiB".to_string()); |
| 44 | // or |
| 45 | assert_eq!(human_bytes(563_200_u64 as f64), "550 KiB".to_string()); |
| 46 | // ________________________________/ |
| 47 | // | |
| 48 | // | Needed only when you're using `u64` values, |
| 49 | // | because `f64` doesn't implement `std::convert::From<u64>` |
| 50 | |
| 51 | // With the `si-units` feature disabled: |
| 52 | assert_eq!(human_bytes(550_000_u32), "550 KB".to_string()); |
| 53 | ``` |
| 54 | |
| 55 | The crate is dependency-free, but you can boost the speed by enabling the `fast` feature, |
| 56 | which switches from using `std::format!` to [ryu](https://github.com/dtolnay/ryu) |
| 57 | to convert floats to strings. |
| 58 | |
| 59 | ```toml |
| 60 | [dependencies] |
| 61 | human_bytes = { version = "0.4", features = ["fast"] } |
| 62 | ``` |
| 63 | |
| 64 | ## About |
| 65 | The code is based on a PHP function I found [here](https://math.stackexchange.com/questions/247444/explain-convertion-algorithm-from-bytes-to-kb-mb-gb). |
| 66 | |
| 67 | It is useful because you don't have to provide a prefix, it does it on its own. |
| 68 | It'll always return `1 MiB` instead of `1024 KiB` |
| 69 | |
| 70 | It has some tests I wrote to check that the conversion is correct, and it returns decimals (e.g. `16.5 GiB`) |
| 71 | |
| 72 | ## Changelog |
| 73 | Check the [CHANGELOG.md](./CHANGELOG.md) |
| 74 | |
| 75 | ## License |
| 76 | [BSD 2-clause](./LICENSE) (c) 2020-2022 Namkhai B. |