mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
craft-math: the control-word check stays linear over a run of letters
ends_with_control_word walked back over the whole trailing run of letters for every letter written, so a long run took quadratic time: 200,000 letters took about 10 s in a release build, and 400,000 did not finish in 3 minutes in a test build. The output position after the last plain letter is now remembered; while the output still ends there its trailing letters are plain text and are not scanned again. Review finding on #1162 (ends_with_control_word).
This commit is contained in:
@@ -237,6 +237,9 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String {
|
||||
let parens = closers(&chars, '(', ')');
|
||||
let brackets = closers(&chars, '〖', '〗');
|
||||
let mut o = String::new();
|
||||
// Where the output ended after the last plain letter written below: while it still ends
|
||||
// there, its trailing letters are plain text, not a control word, and needn't be scanned.
|
||||
let mut plain_end = usize::MAX;
|
||||
let mut i = 0;
|
||||
let sub = |s: &str| if depth < MAX_NEST { linear_to_latex_at(s, depth + 1) } else { escape_math_text(s) };
|
||||
while let Some(&c) = chars.get(i) {
|
||||
@@ -337,10 +340,15 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String {
|
||||
// A letter after a control word would extend it. The lookahead above only sees
|
||||
// the next input character, so a character dropped in between (an unmatched
|
||||
// `〖` or `〗`, a control character) would join `\in` and `put` into `\input`.
|
||||
if c.is_ascii_alphabetic() && ends_with_control_word(&o) {
|
||||
// Scanning only when other output came since the last plain letter keeps a long
|
||||
// run of letters linear.
|
||||
if c.is_ascii_alphabetic() && o.len() != plain_end && ends_with_control_word(&o) {
|
||||
o.push(' ');
|
||||
}
|
||||
o.push(c);
|
||||
if c.is_ascii_alphabetic() {
|
||||
plain_end = o.len();
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -664,5 +672,9 @@ mod tests {
|
||||
// A command followed by a letter directly is still separated, and grouping still works.
|
||||
assert_eq!(linear_to_latex("∈x"), "\\in x");
|
||||
assert_eq!(linear_to_latex("〖a+b〗^2"), "{a+b}^2");
|
||||
// The check stays linear: a long run of letters, plain or after a command, is one pass.
|
||||
let letters = "a".repeat(400_000);
|
||||
assert_eq!(linear_to_latex(&letters).len(), 400_000);
|
||||
assert_eq!(linear_to_latex(&format!("∈〗{letters}")), format!("\\in {letters}"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user