#unit #units #typed #si-units #byte

typed-bytesize

Represent bytesize in decimal or binary prefix unit

3 releases

0.1.2 Mar 23, 2024
0.1.1 Feb 25, 2024
0.1.0 Feb 25, 2024

#913 in Parser implementations

Download history 256/week @ 2024-02-23 41/week @ 2024-03-01 7/week @ 2024-03-08 1/week @ 2024-03-15 148/week @ 2024-03-22 51/week @ 2024-03-29 5/week @ 2024-04-05

206 downloads per month

MIT license

28KB
737 lines

Typed Bytesize

crates.io docs.rs check test

The library provides two types to represent bytesize:

Functions

  • Bytesize types can parse each other's units (e.g. ByteSizeIec can parse SI values like 114514GB);
  • Bytesize values will only be formatted as the unit has their owned prefix;
  • Bytesize types can be converted to each other;
  • Supporting addition, subtraction, scalar multiplication arithmetic operations;
  • Optional serde support.

Example

use typed_bytesize::{ByteSizeIec, ByteSizeSi};

// SI
assert_eq!(ByteSizeSi::b(114u64), "114".parse().unwrap());
assert_eq!(ByteSizeSi::mb(114), "114MB".parse().unwrap());
print!("{}", ByteSizeSi::kb(310)); // 310.0kB

// IEC
assert_eq!(ByteSizeIec::b(514u64), "514".parse().unwrap());
assert_eq!(ByteSizeIec::mib(514), "514MiB".parse().unwrap());
print!("{}", ByteSizeIec::gib(93696)); // 91.5GiB

For more detailed examples, refer to tests.

BNF

Parsing follows the rule:

expr    ::= num | term
term    ::= decimal " "* unit
decimal ::= num | float
float   ::= num "." num
num     ::= [0-9]+

Features

  • serde: enable serde on ByteSizeSi and ByteSizeIec.
  • u128: use u128 instead of u64 as inner numeric type to support larger units. (TODO)

Dependencies

~180KB