Parse Byte Sizes With FromStr And Error Enums

Implement FromStr for a ByteSize wrapper with a custom error enum separating empty strings, missing units, bad digits, and u64 overflow.

RustConfig Management

Code

snippet
use std::fmt;
use std::num::ParseIntError;
use std::str::FromStr;

#[derive(Debug)]
struct ByteSize(u64);

#[derive(Debug)]
enum ParseSizeError {
    Empty,
    MissingUnit,
    UnknownUnit(String),
    InvalidNumber(ParseIntError),
    Overflow,
}

impl fmt::Display for ParseSizeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "empty input"),
            Self::MissingUnit => write!(f, "missing unit suffix"),
            Self::UnknownUnit(u) => write!(f, "unknown unit {u:?}"),
            Self::InvalidNumber(e) => write!(f, "invalid integer: {e}"),
            Self::Overflow => write!(f, "byte count overflow"),
        }
    }
}

impl FromStr for ByteSize {
    type Err = ParseSizeError;
    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        let s = raw.trim();
        if s.is_empty() {
            return Err(ParseSizeError::Empty);
        }
        let idx = s.find(|c: char| !c.is_ascii_digit()).ok_or(ParseSizeError::MissingUnit)?;
        let (num_part, unit_part) = s.split_at(idx);
        let qty: u64 = num_part.parse().map_err(ParseSizeError::InvalidNumber)?;
        let factor = match unit_part.to_ascii_uppercase().as_str() {
            "B" => 1,
            "KB" => 1024,
            "MB" => 1024 * 1024,
            other => return Err(ParseSizeError::UnknownUnit(other.to_string())),
        };
        qty.checked_mul(factor).map(ByteSize).ok_or(ParseSizeError::Overflow)
    }
}

fn main() {
    for raw in ["4KB", " 2mb ", "", "64", "9XB", "abcMB"] {
        match raw.parse::<ByteSize>() {
            Ok(sz) => println!("{raw:?} -> {} bytes", sz.0),
            Err(e) => println!("{raw:?} -> error: {e}"),
        }
    }
}

Stepwise trace — Parse Byte Sizes With FromStr And Error Enums

Under the hood: the functions fmt, from_str and main.

The file repeats itself only inside for raw in ["4KB", " 2mb ", "", "64", "9XB", "abcMB"]. Result is the error channel: the caller receives the failure as a value instead of an exception. A match spells out every case; omit one and the code does not compile.

Caveats

  • Standalone snippet relying purely on packages shipped inside the base runtime.
  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Applying it

Signature: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

Statements that matter

return Err(ParseSizeError::Empty);
let idx = s.find(|c: char| !c.is_ascii_digit()).ok_or(ParseSizeError::MissingUnit)?;
let qty: u64 = num_part.parse().map_err(ParseSizeError::InvalidNumber)?;

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
How do you run Parse Byte Sizes With FromStr And Error Enums?
Execute it straight away — the program needs nothing beyond the runtime.