Crate parse_size

Source
Expand description

parse-size is an accurate, customizable, allocation-free library for parsing byte size into integer.

use parse_size::parse_size;

assert_eq!(parse_size("0.2 MiB"), Ok(209715));
assert_eq!(parse_size("14.2e+8"), Ok(14_2000_0000));

§Features

Supports both binary and decimal based prefix up to exabytes.

assert_eq!(parse_size("1 B"), Ok(1));
assert_eq!(parse_size("1 KiB"), Ok(1 << 10));
assert_eq!(parse_size("1 MiB"), Ok(1 << 20));
assert_eq!(parse_size("1 GiB"), Ok(1 << 30));
assert_eq!(parse_size("1 TiB"), Ok(1 << 40));
assert_eq!(parse_size("1 PiB"), Ok(1 << 50));
assert_eq!(parse_size("1 EiB"), Ok(1 << 60));
assert_eq!(parse_size("1 KB"), Ok(1_000));
assert_eq!(parse_size("1 MB"), Ok(1_000_000));
assert_eq!(parse_size("1 GB"), Ok(1_000_000_000));
assert_eq!(parse_size("1 TB"), Ok(1_000_000_000_000));
assert_eq!(parse_size("1 PB"), Ok(1_000_000_000_000_000));
assert_eq!(parse_size("1 EB"), Ok(1_000_000_000_000_000_000));

Numbers can be fractional and/or in scientific notation. parse-size can accurately parse the input using the full 64-bit precision.

assert_eq!(parse_size("2.999999999999999999e18"), Ok(2999999999999999999));
assert_eq!(parse_size("3.000000000000000001 EB"), Ok(3000000000000000001));

The unit is case-insensitive. The “B” suffix is also optional.

assert_eq!(parse_size("5gb"), Ok(5_000_000_000));
assert_eq!(parse_size("2ki"), Ok(2048));

Fractional bytes are allowed, and rounded to nearest integer.

assert_eq!(parse_size("0.333333 KB"), Ok(333));
assert_eq!(parse_size("2.666666 KB"), Ok(2667));

Underscores and spaces in the numbers are ignored to support digit grouping.

assert_eq!(parse_size(" 69_420_000"), Ok(69_420_000));

Conventional units (KB, GB, …) can be configured to use the binary system.

use parse_size::Config;

let cfg = Config::new().with_binary();
assert_eq!(cfg.parse_size("1 KB"), Ok(1024));
assert_eq!(cfg.parse_size("1 KiB"), Ok(1024));
assert_eq!(cfg.parse_size("1 MB"), Ok(1048576));
assert_eq!(cfg.parse_size("1 MiB"), Ok(1048576));

§Integration examples

Use with clap v4:

use clap::Parser;
use parse_size::parse_size;

#[derive(Parser)]
pub struct Opt {
    #[arg(long, value_parser = |s: &str| parse_size(s))]
    pub size: u64,
}

let opt = Opt::parse_from(&["./app", "--size", "2.5 K"]);
assert_eq!(opt.size, 2500);

Structs§

Config
Configuration of the parser.

Enums§

ByteSuffix
How to deal with the “B” suffix.
Error
The error returned when parse failed.
UnitSystem
The system to use when parsing prefixes like “KB” and “GB”.

Functions§

parse_size
Parses the string input into the number of bytes it represents using the default configuration.