#bytes #conversion #format #utility #value-formatting

human_bytes

Crate to convert bytes into human-readable values

5 unstable releases

0.3.1 Feb 23, 2022
0.3.0 Apr 21, 2021
0.2.1 Apr 8, 2020
0.2.0 Feb 15, 2020
0.1.0 Feb 7, 2020

#20 in Value formatting

Download history 166/week @ 2022-04-23 246/week @ 2022-04-30 140/week @ 2022-05-07 325/week @ 2022-05-14 196/week @ 2022-05-21 303/week @ 2022-05-28 317/week @ 2022-06-04 176/week @ 2022-06-11 465/week @ 2022-06-18 389/week @ 2022-06-25 552/week @ 2022-07-02 238/week @ 2022-07-09 326/week @ 2022-07-16 351/week @ 2022-07-23 480/week @ 2022-07-30 383/week @ 2022-08-06

1,608 downloads per month
Used in fewer than 8 crates

BSD-2-Clause

10KB
163 lines

human_bytes

A Rust crate that converts bytes into human-readable values.

License Latest version Build status

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 u128s to fit a single YB)

Usage

Add to your Cargo.toml:

[dependencies]
human_bytes = "0.3"
# Or
human_bytes = { version = "0.3", features = ["bibytes"] }

And then

use human_bytes::human_bytes;

assert_eq!(human_bytes(563_200_u32), "550 KB".to_string());
// or
assert_eq!(human_bytes(563_200_u64 as f64), "550 KB".to_string());
// ________________________________/
// |
// | Needed only when you're using `u64` values,
// | because `f64` doesn't implement `std::convert::From<u64>`

// With the `bibytes` feature enabled:
assert_eq!(human_bytes(563_200_u32), "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

[dependencies]
human_bytes = { version = "0.3", features = ["fast"] }

About

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)

Changelog

Check the CHANGELOG.md

License

BSD 2-clause (c) 2020 Namkhai B.

Dependencies

~86KB