#convert-bytes #byte #conversion #convert #utility #format

bin+lib human_bytes

Crate to convert bytes into human-readable values

9 releases

0.4.3 Sep 10, 2023
0.4.2 Apr 30, 2023
0.4.1 Oct 28, 2022
0.3.1 Feb 23, 2022
0.1.0 Feb 7, 2020

#18 in Value formatting

Download history 28317/week @ 2024-10-12 31086/week @ 2024-10-19 31249/week @ 2024-10-26 25762/week @ 2024-11-02 27535/week @ 2024-11-09 28188/week @ 2024-11-16 25722/week @ 2024-11-23 30048/week @ 2024-11-30 34941/week @ 2024-12-07 31357/week @ 2024-12-14 17698/week @ 2024-12-21 19688/week @ 2024-12-28 31914/week @ 2025-01-04 32491/week @ 2025-01-11 31304/week @ 2025-01-18 32553/week @ 2025-01-25

132,132 downloads per month
Used in 52 crates (45 directly)

BSD-2-Clause

10KB
148 lines

human_bytes

A Rust crate & cli to convert bytes into human-readable values.

License Latest version Build status

It can return either KiB/MiB/GiB/TiB or KB/MB/GB/TB by disabling the si-units feature.

1 KiB = 1024 B, 1 KB = 1000 B

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

As a CLI

  • (Optional) Install Just
  • Build:
    • With just: just build-binary
    • Plain cargo: cargo build --release --features 'build-binary fast' --bin hb
  • Copy target/release/hb to somewhere in your $PATH
  • Run hb <bytes> or echo <bytes> | hb

As a library

Add to your Cargo.toml:

[dependencies]
human_bytes = "0.4"
# or, to disable the SI Units:
human_bytes = { version = "0.4", default-features = false }

And then

use human_bytes::human_bytes;

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

// With the `si-units` feature disabled:
assert_eq!(human_bytes(550_000_u32), "550 KB".to_string());

The crate is dependency-free, but you can boost the speed by enabling the fast feature, which switches from using std::format! to ryu to convert floats to strings.

[dependencies]
human_bytes = { version = "0.4", 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 MiB instead of 1024 KiB

It has some tests I wrote to check that the conversion is correct, and it returns decimals (e.g. 16.5 GiB)

Changelog

Check the CHANGELOG.md

License

BSD 2-clause (c) 2020-2022 Namkhai B.

Dependencies

~68KB