Skip to content

VectorCraft: An open-source, vector art tool written by scratch in pure Rust

Accept an explicit leading plus sign in Unit::parse

NetterSilver56d34d4ced5b
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 1ba52a0e3..49342ca54 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -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,
diff --git a/crates/doc/src/tests_units.rs b/crates/doc/src/tests_units.rs
index a5dbe9fb3..5b3319f18 100644
--- a/crates/doc/src/tests_units.rs
+++ b/crates/doc/src/tests_units.rs
@@ -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;