human_bytesize

Macro human_bytesize 

Source
human_bytesize!() { /* proc-macro */ }
Expand description

A procedural macro for converting human-readable byte size expressions into their corresponding byte values at compile time.

  • Macro evaluation: Numeric literals are evaluated directly by the macro at compile time, producing a constant value.
  • Compiler evaluation: Expressions are expanded into code, leaving the final computation to the Rust compiler at compile time.

Returns a value of type i128 or a multiplication expression that evaluates to i128, representing the computed size in bytes.

§Usage

  • Numeric literals: Use numbers followed by a unit, e.g., 100KB or 16 KiB.
  • Expressions: Enclose a valid Rust expression in curly braces, followed by the unit.

§Example

use human_bytesize_procmacro::human_bytesize;

// Using numeric literals
assert_eq!(human_bytesize!(-4B), -4);
assert_eq!(human_bytesize!(10KB), 10 * 1000);
assert_eq!(human_bytesize!(16 KiB), 16 * 1024);

// Using expressions
let variable = 320;
assert_eq!(human_bytesize!({ variable } MiB), variable * 1024 * 1024);

const TOTAL_MEGABYTES: i128 = 16;
assert_eq!(human_bytesize!({ TOTAL_MEGABYTES } MB), TOTAL_MEGABYTES * 1000 * 1000);

§Limitations

§Exponent Notation Conflict

The E unit (e.g., 100EB for exabytes) may conflict with Rust’s scientific notation parser, which expects an exponent after E.

For example:

let x = human_bytesize!(100EB); // This results in a parsing error.

To work around this limitation, use a space between the number and the unit:

let x = human_bytesize!(100 EB); // This compiles correctly.

§Error Handling

The macro will panic if the input format is invalid. Ensure you use one of the following formats:

  • <number><unit>: Example: 100KB, 16 KiB
  • {<expression>}<unit>: Example: {variable}MB, { CONST_VAL } G

§Common Pitfalls

  • Spacing: While both 100KB and 100 KB are valid, ensure consistency in formatting.
  • Expression Wrapping: When using a variable or an expression, wrap it in {} before specifying the unit.