Accept an explicit leading plus sign in Unit::parse

Found while testing crates/doc/src/lib.rs:379 (number_unit, reached from parse_measure at :374)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NetterSilver
2026-10-23 02:10:57 +07:00
committed by bflatastic
co-authored by Claude Haiku 5.5
parent 4b7969a05c
commit 56d34d4ced
2 changed files with 11 additions and 1 deletions
+3 -1
View File
@@ -378,7 +378,9 @@ fn parse_measure(s: &str, default: Unit) -> Option<f64> {
/// A number with an optional unit suffix (`12`, `3 mm`, `2in`) → (the number, its unit).
fn number_unit(s: &str) -> Option<(f64, Option<Unit>)> {
let s = s.trim();
let num_end = s.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).unwrap_or(s.len());
// A leading `+` is a sign (`+5`), like `-`.
let sign = usize::from(s.starts_with('+'));
let num_end = s.get(sign..)?.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).map_or(s.len(), |i| i + sign);
let v: f64 = s.get(..num_end)?.trim().parse().ok()?;
let unit = match s.get(num_end..)?.trim() {
"" => None,
+8
View File
@@ -23,6 +23,14 @@ fn every_unit_round_trips_through_its_field_text() {
}
}
#[test]
fn an_explicit_leading_plus_is_accepted() {
assert_eq!(Unit::Points.parse("+5"), Some(5.0));
assert_eq!(Unit::Millimeters.parse("+5mm"), Some(Unit::Millimeters.to_pt(5.0)));
assert_eq!(Unit::Points.parse("+5+3"), Some(8.0));
assert_eq!(Unit::Points.parse("5+-3"), Some(2.0));
}
#[test]
fn typed_units_win_over_the_fields_unit() {
let mm = 72.0 / 25.4;