Skip to content

fix: parse bare decimal byte counts without a unit as bytes - #223

Open
amalsaidov wants to merge 1 commit into
bytesize-rs:masterfrom
amalsaidov:fix-parse-bare-decimal
Open

amalsaidov wants to merge 1 commit into
bytesize-rs:masterfrom
amalsaidov:fix-parse-bare-decimal

Conversation

@amalsaidov

Copy link
Copy Markdown

A bare decimal with no unit fails to parse today, even though a bare integer does:

"500".parse::<ByteSize>().unwrap().0;   // 500
"500.0".parse::<ByteSize>();            // Err: couldn't parse "" into a known SI unit
"1.5".parse::<ByteSize>();              // Err
"0.0".parse::<ByteSize>();              // Err

The error message — couldn't parse "" into a known SI unit — shows the cause: for a decimal, from_str takes the float path and then calls "".parse::<Unit>() on the (empty) suffix, which errors. Bare integers avoid this because they are handled by the u64 fast path at the top of from_str. So "500" works, "500.0" and "500.0 B" both resolve to 500, but "500.0" alone errors.

Fix

Treat an empty unit suffix as plain bytes (Unit::Byte). A bare decimal then parses the same as a bare integer and as the explicit "… B" form:

"500.0".parse::<ByteSize>().unwrap().0; // 500
"1.5".parse::<ByteSize>().unwrap().0;   // 1  (truncates, like "1.5 B")

As a side effect this also makes a bare integer that overflows u64 saturate to u64::MAX, matching the behaviour the same value already has with an explicit B suffix ("99999999999999999999B").

Malformed inputs are unaffected: the suffix is only treated as bytes when it is empty. Inputs like "", "1.3.4", "1 000 B", or "1.3 ... B" still error (covered by the existing when_err test).

Tests

Adds bare_decimal_without_unit_is_bytes covering bare decimals, truncation, trailing-dot, and overflow. It fails before this change and passes after.

Checks run locally: cargo test --all-features and --no-default-features, doc-tests, and cargo fmt --check — all green.

A bare decimal such as "500.0" or "1.5" failed to parse, returning the
confusing error "couldn't parse \"\" into a known SI unit". This happened
because, unlike bare integers (handled by the u64 fast path), a decimal with
an empty unit suffix fell through to "".parse::<Unit>(), which errors.

Treat an empty suffix as plain bytes (Unit::Byte), so bare decimals parse the
same as bare integers ("500") and explicit "500.0 B". This also makes a bare
integer that overflows u64 saturate, matching the existing behaviour of the
same value with a "B" suffix.

Add a regression test covering bare decimals, truncation, and overflow.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant