fix: enforce range and canonical form in from_str - #5
Open
gaoflow wants to merge 1 commit into
Open
Conversation
Roman::from enforces the 1..=3999 range invariant, but Roman::from_str
bypassed it: from_str("MMMM") returned Ok(4000) while from(4000) returned
Err(OutOfRange), and from_str("") returned Ok(0). from_str also accepted
non-canonical grammar (e.g. "IIII", "IC", "VV", "XXXX", "MIM", "IIX")
and normalized it on round-trip, so "IV" and "IIII" both parsed to 4 and
collided. The Error::InvalidNumber variant ("could not be parsed as a single
roman numeral") existed but was never returned by from_str.
This patch makes from_str enforce the same invariants as from:
* Range check: reject val == 0 || val > 3999 with OutOfRange (matching
the constructor).
* Canonical round-trip validator: reject inputs whose parsed value's
canonical form (from(val).to_string()) does not equal the input
(compared case-insensitively, so lowercase canonical inputs such as
"vii" still parse, matching existing from_byte acceptance) with
InvalidNumber, making that variant reachable per its documented meaning.
from_unchecked remains the documented escape hatch for arbitrary/large
values and is untouched. All canonical inputs (1..=3999, incl. lowercase)
continue to parse correctly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Roman::from_strdoes not enforce the invariants thatRoman::fromenforces, and accepts non-canonical grammar. TheError::InvalidNumbervariant is dead code — declared insrc/errors.rsbut never returned by the parser.Internal-consistency smoking gun (no external oracle needed)
Roman::fromrejectsval == 0 || val > 3999withError::OutOfRange, butfrom_straccumulates the value and returnsOk(Roman(acc.val))directly, bypassing the constructor. The parser builds values the constructor forbids:fromandfrom_strdisagree within the same library.Canonical round-trip collision
from_stris a char-level tokenizer with a naive left-to-right subtractive accumulator. It has no grammar rules, so it accepts inputs that violate standard Roman-numeral grammar and normalizes them on round-trip. Distinct strings collide to the same value, breaking injectivity of thestring -> valuemapping:A non-canonical string is accepted and then re-emitted in canonical form by
to_string(), sofrom_str(s).to_string() != sfor non-canonicals.Dead
InvalidNumberError::InvalidNumber("could not be parsed as a single roman numeral") exists insrc/errors.rsbut is never returned byfrom_str(unreachable from the parser).The fix
In
src/roman.rsfrom_str, after accumulating the numeric value and before returningOk, add two checks:from's invariant:if acc.val == 0 || acc.val > 3999 { return Err(Error::OutOfRange(acc.val)); }(same error/variantfromuses).let canonical = Roman::from(acc.val)?.to_string(); if canonical != s.to_ascii_uppercase() { return Err(Error::InvalidNumber(acc.val)); }. The comparison is case-insensitive (input uppercased) so lowercase canonical inputs such as"vii"still parse, matching the existingDigit::from_bytelowercase acceptance and the lib.rs doc-tests. Non-canonical inputs are rejected withInvalidNumber, making the previously-dead variant reachable per its documented meaning.Roman::from_unchecked(the documented escape hatch for arbitrary/large values) is untouched. All canonical inputs (1..=3999, incl. lowercase) continue to parse correctly.Test results
cargo test→ PASS (existing 8 + 4 + 9 doc-tests + 6 new tests = 27 total; 0 fail).cargo fmt --check→ clean.cargo clippy --all-targets→ only 3 pre-existingrecursive_format_impllints insrc/errors.rs(untouched by this PR; present on pristine HEAD2f8cff1). 0 new warnings/errors.Pre-fix RED / post-fix GREEN (scanner harness)
from_str("MMMM")Ok(4000)Err(OutOfRange(4000))from_str("")Ok(0)Err(OutOfRange(0))from_str("MMMMMMMM")Ok(8000)Err(OutOfRange(8000))from_str("IIII")Ok(4)Err(InvalidNumber(4))from_str("IC")Ok(99)Err(InvalidNumber(99))from_str("VV")Ok(10)Err(InvalidNumber(10))from_str("MIM")Ok(1999)Err(InvalidNumber(1999))Canonical inputs unchanged
from_str("I")=Ok(1),("IV")=Ok(4),("XCIX")=Ok(99),("MMMCMXCIX")=Ok(3999),("vii")=Ok(7),("dxxxii")=Ok(532);from_str("ABC")=Err(InvalidDigit('A'))(bad-char path unchanged).New regression tests (
tests/roman.rs)from_str_rejects_range_bypass—MMMM/MMMMMMMM/""→Err(OutOfRange).from_str_rejects_non_canonical_grammar—IIII/VV/IC/IIX/XXXX/MIM→Err(InvalidNumber).from_str_accepts_canonical_controls—I/IV/XCIX/MMMCMXCIXstill Ok & correct.from_str_still_rejects_bad_char—ABC→InvalidDigit('A').from_str_accepts_lowercase_canonical—vii/dxxxii/mmmcmxcix.from_str_canonical_round_trip_property— everynin 1..=3999:from(n).to_string()parses back ton; non-canonical spellings rejected.2 files changed:
src/roman.rs(+19/-0 infrom_str),tests/roman.rs(+97/-0). 1 commit.