mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 10:18:05 +00:00
craft-math: review fixes: a number base after a number, a cap on kept OMML, is_number without a Vec
From the second review round: - A number base right after a digit, `.` or `,` keeps its brackets. Bare, it continued the number before it: `1` then `23^4` was written `123^4` and read back with 123 as the base, and the same for a one-digit base (`12^4`), `x.` then `5^2` and `1,` then `5^2`. This came with the bare number base, before the first review round. A number base after a letter or an operator stays bare (`a2^4`, `1+2^4`). - Both parses of kept OMML are capped at the elements the reader keeps (MAX_ELEMENTS × 2) instead of craft-xml's defaults, and roxmltree gets the same cap as `nodes_limit`. Kept OMML can come from a hostile JSON document; larger kept OMML is written from its nodes. The reader can't keep more than this, so OMML read from a file is unaffected. - is_number scans bytes instead of collecting a Vec<char>: everything a number holds is ASCII. The two new tests fail without their fix.
This commit is contained in:
+10
-5
@@ -527,10 +527,11 @@ fn first_lin_char(n: &MNode) -> Option<char> {
|
||||
/// `.` or `,` continues it only before a digit (`2.5`, `1,000`), and a leading `.` before a digit
|
||||
/// starts one (`.5`). `2.` isn't one: the parser leaves the point out.
|
||||
fn is_number(t: &str) -> bool {
|
||||
let c: Vec<char> = t.chars().collect();
|
||||
let digit = |k: usize| c.get(k).is_some_and(|c| c.is_ascii_digit());
|
||||
(digit(0) || (c.first() == Some(&'.') && digit(1)))
|
||||
&& c.iter().enumerate().all(|(k, &ch)| ch.is_ascii_digit() || (matches!(ch, '.' | ',') && digit(k + 1)))
|
||||
// Every character of a number is ASCII, so the bytes do.
|
||||
let b = t.as_bytes();
|
||||
let digit = |k: usize| b.get(k).is_some_and(u8::is_ascii_digit);
|
||||
(digit(0) || (b.first() == Some(&b'.') && digit(1)))
|
||||
&& b.iter().enumerate().all(|(k, &c)| c.is_ascii_digit() || (matches!(c, b'.' | b',') && digit(k + 1)))
|
||||
}
|
||||
|
||||
/// Whether `a` is written bare as an operand: a single simple atom.
|
||||
@@ -579,7 +580,11 @@ fn lin_base(a: &[MNode], s: &mut String, depth: usize) {
|
||||
// A number by the parser's rule (`1,000`, `2.5`, `.5`) is one item, so it stays bare too.
|
||||
let number = matches!(a, [MNode::Run(r)] if is_number(&r.text));
|
||||
let letters = matches!(a, [MNode::Run(r)] if r.text.chars().nth(1).is_some() && !number && !name(r));
|
||||
if (simple_operand(a) || number) && !inner.is_empty() && !invisible && !operator && !letters {
|
||||
// A base starting with a digit or `.` right after a digit, `.` or `,` would continue the number
|
||||
// before it (`1` then `23^4` is `123^4`), so it keeps its brackets: `1〖23〗^4`.
|
||||
let joins = s.chars().next_back().is_some_and(|c| c.is_ascii_digit() || matches!(c, '.' | ','))
|
||||
&& inner.chars().next().is_some_and(|c| c.is_ascii_digit() || c == '.');
|
||||
if (simple_operand(a) || number) && !inner.is_empty() && !invisible && !operator && !letters && !joins {
|
||||
s.push_str(&inner);
|
||||
} else {
|
||||
s.push('〖');
|
||||
|
||||
@@ -75,11 +75,17 @@ fn is_well_formed(xml: &str) -> bool {
|
||||
// The name ends at `>` or XML whitespace (XML 1.0 §2.3 S), not at `/>` (an empty equation) or
|
||||
// a longer name (`m:oMathPara`).
|
||||
let named = xml.strip_prefix("<m:oMath").and_then(|r| r.chars().next()).is_some_and(|c| matches!(c, '>' | ' ' | '\t' | '\r' | '\n'));
|
||||
if !named || Options::default().strict().parse(xml.as_bytes()).is_err() {
|
||||
// Both parses are capped as the reader caps what it keeps ([`parse`]): kept OMML can come from
|
||||
// a hostile JSON document, and a larger one is written from its nodes.
|
||||
let limits = craft_xml::Limits { max_nodes: MAX_ELEMENTS.saturating_mul(2), ..craft_xml::Limits::DEFAULT };
|
||||
if !named || Options::default().strict().with_limits(limits).parse(xml.as_bytes()).is_err() {
|
||||
return false;
|
||||
}
|
||||
let wrapped = format!("<x xmlns:m=\"{MATH_NS}\" xmlns:w=\"{W_NS}\" xmlns:mc=\"{MC_NS}\">{xml}</x>");
|
||||
let Ok(doc) = roxmltree::Document::parse(&wrapped) else { return false };
|
||||
// The wrapper and the document root are two more nodes.
|
||||
let nodes_limit = u32::try_from(limits.max_nodes.saturating_add(2)).unwrap_or(u32::MAX);
|
||||
let options = roxmltree::ParsingOptions { nodes_limit, ..roxmltree::ParsingOptions::default() };
|
||||
let Ok(doc) = roxmltree::Document::parse_with_options(&wrapped, options) else { return false };
|
||||
let mut nodes = doc.root_element().children();
|
||||
matches!((nodes.next(), nodes.next()), (Some(e), None) if e.tag_name().namespace() == Some(MATH_NS) && e.tag_name().name() == "oMath")
|
||||
}
|
||||
|
||||
@@ -257,6 +257,18 @@ fn kept_xml_that_is_not_an_omath_is_rewritten_from_the_nodes() {
|
||||
assert_eq!(read(&out).nodes, a("NODES"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_omml_larger_than_the_reader_keeps_is_rewritten_from_the_nodes() {
|
||||
// The same cap as the reader's: one more element than it reads is written from the nodes,
|
||||
// one fewer is kept.
|
||||
let cap = crate::omml::MAX_ELEMENTS * 2;
|
||||
let kept = |runs: usize| format!("<m:oMath>{}</m:oMath>", "<m:r/>".repeat(runs));
|
||||
let over = Math { nodes: a("NODES"), omml: kept(cap + 1), ..Default::default() };
|
||||
assert_eq!(read(&write(&over, "linear", false, None)).nodes, a("NODES"));
|
||||
let under = Math { nodes: a("NODES"), omml: kept(cap - 10), ..Default::default() };
|
||||
assert!(write(&under, "linear", false, None).contains(&under.omml));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_nodes_the_linear_text_is_written() {
|
||||
let out = write(&Math::default(), "a/b", false, None);
|
||||
|
||||
@@ -121,3 +121,16 @@ fn a_comma_before_a_digit_after_a_script_stays_outside_it() {
|
||||
// A comma before anything else ends the script on its own: no space is added.
|
||||
assert_eq!(craft_math::math::to_linear(&[sup("x", "2"), r(", y")]), "x^2, y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_base_after_a_number_keeps_its_brackets() {
|
||||
// Bare, the base would continue the number before it: `1` then `23^4` would read `123^4`.
|
||||
for (before, base, want) in
|
||||
[("1", "23", "1〖23〗^4"), ("1", "2", "1〖2〗^4"), ("x.", "5", "x.〖5〗^4"), ("1,", "5", "1,〖5〗^4"), ("1", ".5", "1〖.5〗^4")]
|
||||
{
|
||||
prints_back(vec![r(before), sup(base, "4")], want);
|
||||
}
|
||||
// After a letter or an operator it can't, so it stays bare.
|
||||
prints_back(vec![r("a"), sup("2", "4")], "a2^4");
|
||||
prints_back(vec![r("1+"), sup("2", "4")], "1+2^4");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user