parse_size

Function parse_size 

Source
pub fn parse_size(size_str: &str) -> Result<u64>
Expand description

Parse a human-readable size string into bytes.

Supports both decimal (KB, MB, GB) and binary (KiB, MiB, GiB) units, as well as decimal numbers (e.g., “1.5GB”).

§Arguments

  • size_str - A string representing the size (e.g., “100MB”, “1.5GiB”, “1,000,000”)

§Returns

  • Ok(u64) - The size in bytes
  • Err(anyhow::Error) - If the string format is invalid or causes overflow

§Errors

This function will return an error if:

  • The size string format is invalid (e.g., “1.2.3MB”, “invalid”)
  • The number cannot be parsed as a valid integer or decimal
  • The resulting value would overflow u64
  • The decimal has too many fractional digits (more than 9)

§Examples

assert_eq!(parse_size("100KB")?, 100_000);
assert_eq!(parse_size("1.5MB")?, 1_500_000);
assert_eq!(parse_size("1GiB")?, 1_073_741_824);

§Supported Units

  • Decimal: KB (1000), MB (1000²), GB (1000³)
  • Binary: KiB (1024), MiB (1024²), GiB (1024³)
  • Bytes: Plain numbers without units