mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-18 00:15:44 +00:00
fix(docx): correctly parse emu and case-insensitive units in measure
This commit is contained in:
1 parent
86adfd34eb
commit
f9808ae495
1 file changed
+37
-2
@@ -13,13 +13,39 @@ pub fn measure(s: &str, per_pt: f32) -> Option<f32> {
|
||||
if t.is_empty() || t.len() > 40 {
|
||||
return None;
|
||||
}
|
||||
let split = t.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')).unwrap_or(t.len());
|
||||
let bytes = t.as_bytes();
|
||||
let mut split = t.len();
|
||||
let mut in_exp = false;
|
||||
for (i, &b) in bytes.iter().enumerate() {
|
||||
if b.is_ascii_digit() || b == b'.' {
|
||||
in_exp = false;
|
||||
continue;
|
||||
}
|
||||
if (b == b'-' || b == b'+') && (i == 0 || in_exp) {
|
||||
in_exp = false;
|
||||
continue;
|
||||
}
|
||||
if b == b'e' || b == b'E' {
|
||||
let rest = &bytes[i + 1..];
|
||||
let after_sign = match rest.first() {
|
||||
Some(&s) if s == b'+' || s == b'-' => &rest[1..],
|
||||
_ => rest,
|
||||
};
|
||||
if after_sign.first().is_some_and(|c| c.is_ascii_digit()) {
|
||||
in_exp = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
split = i;
|
||||
break;
|
||||
}
|
||||
let (num, unit) = t.split_at(split);
|
||||
let v: f64 = num.parse().ok()?;
|
||||
if !v.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let pt = match unit.trim() {
|
||||
let unit_lower = unit.trim().to_ascii_lowercase();
|
||||
let pt = match unit_lower.as_str() {
|
||||
"" => v / per_pt as f64,
|
||||
"pt" => v,
|
||||
"in" => v * 72.0,
|
||||
@@ -98,6 +124,15 @@ mod tests {
|
||||
assert_eq!(measure("1e400", 20.0), None);
|
||||
assert_eq!(measure("99999999999999", 20.0), Some(MAX_LEN_PT));
|
||||
assert_eq!(measure("x", 20.0), None);
|
||||
assert_eq!(measure("12700emu", 20.0), Some(1.0));
|
||||
assert_eq!(measure("25400EMU", 20.0), Some(2.0));
|
||||
assert_eq!(measure("1IN", 20.0), Some(72.0));
|
||||
assert_eq!(measure("12PT", 2.0), Some(12.0));
|
||||
assert_eq!(measure("2.54CM", 20.0), Some(72.0));
|
||||
assert_eq!(measure("25.4MM", 20.0), Some(72.0));
|
||||
assert_eq!(measure("10PX", 20.0), Some(7.5));
|
||||
assert_eq!(measure("1e2pt", 20.0), Some(100.0));
|
||||
assert_eq!(measure("1e+2pt", 20.0), Some(100.0));
|
||||
assert_eq!(int("12.6"), Some(13));
|
||||
assert_eq!(u32_of("-5"), Some(0));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user