Byte Unit

Build Status Build status

A library for interaction with units of bytes.

The units are B for 1 byte, KB for 1000 bytes, KiB for 1024 bytes, MB for 1000000 bytes, MiB for 1048576 bytes, etc, and up to PiB which is 1125899906842624 bytes.

The data type for storing the size of bytes is u128, so don't worry about the overflow problem.

Usage

Macros

There are n_*_bytes macros can be used. The star * means the unit. For example, n_gb_bytes can be used to get a n-GB value in bytes.

```rust

[macrouse] extern crate byteunit;

let result = ngbbytes!(4);

assert_eq!(4000000000u128, result); ```

You may need to assign a primitive type if the n is not an integer.

```rust

[macrouse] extern crate byteunit;

let result = ngbbytes!(2.5, f64);

assert_eq!(2500000000u128, result); ```

Byte

The Byte structure can be used for representing a size of bytes.

The from_string associated function can parse any SIZE string and return a Byte instance in common usage. The format of a SIZE string is like "123", "123KiB" or "50.84 MB".

```rust extern crate byte_unit;

use byte_unit::Byte;

let result = Byte::from_string("50.84 MB").unwrap();

asserteq!(50840000u128, result.getbytes()); ```

You can also use the from_bytes and from_unit associated functions to create a Byte instance.

```rust extern crate byte_unit;

use byte_unit::Byte;

let result = Byte::from_bytes(1500000u128);

asserteq!(1500000u128, result.getbytes()); ```

```rust extern crate byte_unit;

use byte_unit::{Byte, ByteUnit};

let result = Byte::from_unit(1500f64, ByteUnit::KB).unwrap();

asserteq!(1500000u128, result.getbytes()); ```

AdjustedByte

To change the unit of a Byte instance, you can use the get_adjusted_unit method.

```rust extern crate byte_unit;

use byte_unit::{Byte, ByteUnit};

let byte = Byte::from_string("123KiB").unwrap();

let adjustedbyte = byte.getadjusted_unit(ByteUnit::KB);

asserteq!("125.95 KB", adjustedbyte.to_string()); ```

To change the unit of a Byte instance automatically and appropriately, you can use the get_appropriate_unit method.

```rust extern crate byte_unit;

use byte_unit::Byte;

let byte = Byte::from_bytes(1500000u128);

let adjustedbyte = byte.getappropriate_unit(false);

asserteq!("1.50 MB", adjustedbyte.to_string()); ```

```rust extern crate byte_unit;

use byte_unit::Byte;

let byte = Byte::from_bytes(1500000u128);

let adjustedbyte = byte.getappropriate_unit(true);

asserteq!("1.43 MiB", adjustedbyte.to_string()); ```

The number of fractional digits created by the to_string method of a AdjustedByte instance is always 2.

To change the number of fractional digits in the formatted string, you can use the format method instead.

```rust extern crate byte_unit;

use byte_unit::Byte;

let byte = Byte::from_bytes(1500000u128);

let adjustedbyte = byte.getappropriate_unit(false);

asserteq!("1.5 MB", adjustedbyte.format(1)); ```

Crates.io

https://crates.io/crates/byte-unit

Documentation

https://docs.rs/byte-unit

License

MIT