Helper crate to work with bit, byte, and block sizes.
This crate provides three dedicated types, [NumBits
], [NumBytes
], and
[NumBlocks
], to represent numbers of bits, bytes, and blocks, respectively. It
implements the usual traits for numeric operators such that calculations on them can
be carried out with succinct syntax. All operations will panic on errors, such as
over- or underflows. This is an intentional design decision to prevent subtly
incorrect results and behavior. In addition, this crate provides formatting and
parsing for byte sizes.
This crate is no_std
-compatible.
Conversions
The provided types support convenient conversions to each other:
# use ;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
const BLOCK_SIZE: NumBytes = kibibytes;
assert_eq!;
assert_eq!;
assert_eq!;
Calculations
Calculations can be performed with the types as well as with [u64
] integers:
# use ;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Comparisons
Comparisons are supported on the types as well as with [u64
] integers:
# use ;
assert!;
assert!;
assert_eq!;
assert_eq!;
assert!;
Formatting
Formatting of byte sizes maximizes the unit while minimizing the integer part towards one. For example:
# use NumBytes;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
The usual formatting syntax can be used to limit the precision:
# use NumBytes;
assert_eq!;
Parsing
Byte sizes must follow the following syntax:
⟨byte-size⟩ ::= ⟨int⟩ [ '.' ⟨int⟩ ] [ ' '* ⟨unit⟩ ]
⟨int⟩ ::= [0-9_]+
⟨unit⟩ ::= 'B' | 'K' … 'E' | 'kB' … 'EB' | 'KiB' … 'EiB' (case-insensitive)
The units (K
... E
) are interpreted as binary units (KiB
... EiB
). Generally,
unit parsing is case-insensitive.
# use FromStr;
# use NumBytes;
assert_eq!;
assert_eq!;
assert_eq!;
Parsing also works in const
contexts using [NumBytes::parse_str
] or
[NumBytes::parse_ascii
]:
# use FromStr;
# use NumBytes;
const BLOCK_SIZE: NumBytes = match parse_str ;
The parser has been extensively fuzz-tested, ensuring that no input leads to panics.
Serialization and Deserialization
By enabling the serde
feature, [NumBits
], [NumBytes
], and [NumBlocks
] can be
serialized and deserialized. All tree types always serialize as [u64
] integers.
Deserialization of [NumBytes
] is also supported from strings.