Break long paragraphs with prefix sums
The line-breaker rescanned items[start..end] for every break pair, so a 900-word paragraph took seconds and the 2,700-word edit fixture took about 30 s. Prefix sums over natural width, stretch, shrink, glue order, box count and the last penalty give each candidate its metrics in O(1); the search now costs O(breakpoints^2) and the same document lays out in about 0.3 s. Add a 900-word regression test and note the change in TEX_CORE.
This commit is contained in:
1 parent
41c68baa5d
commit
e09e413892
3 files changed
+103
-40
No files matched your search
@@ -738,6 +738,50 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
/// alternative line counts to survive pruning; keep the cheapest few
|
||||
/// candidates per class, deduplicated by line count.
|
||||
const CANDIDATES_PER_STATE: usize = 6;
|
||||
// Prefix sums make every candidate line metrics O(1). The previous
|
||||
// implementation rescanned items[start..end] for each break pair, which is
|
||||
// cubic in practice and made a 900-word paragraph take seconds to break.
|
||||
let mut prefix_natural = vec![0_i64; items.len() + 1];
|
||||
let mut prefix_stretch = vec![0_i64; items.len() + 1];
|
||||
let mut prefix_shrink = vec![0_i64; items.len() + 1];
|
||||
let mut prefix_order = vec![[0_i64; 4]; items.len() + 1];
|
||||
let mut prefix_boxes = vec![0_usize; items.len() + 1];
|
||||
let mut prefix_last_penalty = vec![usize::MAX; items.len() + 1];
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
prefix_natural[index + 1] = prefix_natural[index];
|
||||
prefix_stretch[index + 1] = prefix_stretch[index];
|
||||
prefix_shrink[index + 1] = prefix_shrink[index];
|
||||
prefix_order[index + 1] = prefix_order[index];
|
||||
prefix_boxes[index + 1] = prefix_boxes[index];
|
||||
prefix_last_penalty[index + 1] = prefix_last_penalty[index];
|
||||
match item {
|
||||
HorizontalItem::Box(box_item) => {
|
||||
prefix_natural[index + 1] += box_item.width;
|
||||
prefix_boxes[index + 1] += 1;
|
||||
}
|
||||
HorizontalItem::Glue {
|
||||
width,
|
||||
stretch,
|
||||
shrink,
|
||||
order,
|
||||
..
|
||||
} => {
|
||||
prefix_natural[index + 1] += *width;
|
||||
prefix_shrink[index + 1] += *shrink;
|
||||
if *order == 0 {
|
||||
prefix_stretch[index + 1] += *stretch;
|
||||
} else {
|
||||
prefix_order[index + 1][*order as usize] += *stretch;
|
||||
}
|
||||
}
|
||||
HorizontalItem::Penalty { .. } => {
|
||||
prefix_last_penalty[index + 1] = index;
|
||||
}
|
||||
HorizontalItem::Discretionary { no_break_width, .. } => {
|
||||
prefix_natural[index + 1] += *no_break_width;
|
||||
}
|
||||
}
|
||||
}
|
||||
let count = breakpoints.len();
|
||||
let mut solution: Option<Vec<(usize, usize)>> = None;
|
||||
// TeX's emergency pass only exists when \emergencystretch is positive.
|
||||
@@ -776,47 +820,43 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
if start >= end {
|
||||
continue;
|
||||
}
|
||||
let mut natural = 0_i64;
|
||||
let mut stretch = 0_i64;
|
||||
let mut shrink = 0_i64;
|
||||
let mut natural = prefix_natural[end] - prefix_natural[start];
|
||||
let mut stretch = prefix_stretch[end] - prefix_stretch[start];
|
||||
let mut shrink = prefix_shrink[end] - prefix_shrink[start];
|
||||
let mut stretch_by_order = [0_i64; 4];
|
||||
let mut has_box = false;
|
||||
for order in 0..4 {
|
||||
stretch_by_order[order] = prefix_order[end][order] - prefix_order[start][order];
|
||||
}
|
||||
let has_box = prefix_boxes[end] > prefix_boxes[start];
|
||||
let mut trailing_penalty = 0_i64;
|
||||
for (offset, item) in items[start..end].iter().enumerate() {
|
||||
match item {
|
||||
HorizontalItem::Box(box_item) => {
|
||||
natural += box_item.width;
|
||||
has_box = true;
|
||||
}
|
||||
HorizontalItem::Glue {
|
||||
width,
|
||||
stretch: stretch_amount,
|
||||
shrink: shrink_amount,
|
||||
order,
|
||||
..
|
||||
} => {
|
||||
if start + offset + 1 == end {
|
||||
continue;
|
||||
}
|
||||
natural += *width;
|
||||
shrink += *shrink_amount;
|
||||
match *order {
|
||||
0 => stretch += *stretch_amount,
|
||||
order => stretch_by_order[order as usize] += *stretch_amount,
|
||||
}
|
||||
}
|
||||
HorizontalItem::Penalty { penalty, .. } => trailing_penalty = *penalty,
|
||||
HorizontalItem::Discretionary {
|
||||
pre_break_width,
|
||||
no_break_width,
|
||||
} => {
|
||||
natural += if start + offset + 1 == end {
|
||||
*pre_break_width
|
||||
} else {
|
||||
*no_break_width
|
||||
};
|
||||
let last_penalty = prefix_last_penalty[end];
|
||||
if last_penalty != usize::MAX && last_penalty >= start {
|
||||
if let HorizontalItem::Penalty { penalty, .. } = &items[last_penalty] {
|
||||
trailing_penalty = *penalty;
|
||||
}
|
||||
}
|
||||
match &items[end - 1] {
|
||||
HorizontalItem::Glue {
|
||||
width,
|
||||
stretch: stretch_amount,
|
||||
shrink: shrink_amount,
|
||||
order,
|
||||
..
|
||||
} => {
|
||||
natural -= *width;
|
||||
shrink -= *shrink_amount;
|
||||
match *order {
|
||||
0 => stretch -= *stretch_amount,
|
||||
order => stretch_by_order[order as usize] -= *stretch_amount,
|
||||
}
|
||||
}
|
||||
HorizontalItem::Discretionary {
|
||||
pre_break_width,
|
||||
no_break_width,
|
||||
} => {
|
||||
natural += *pre_break_width - *no_break_width;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !has_box {
|
||||
continue;
|
||||
@@ -841,6 +881,9 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
|
||||
};
|
||||
}
|
||||
for previous_state in 0..8 {
|
||||
if best[start_index][previous_state].is_empty() {
|
||||
continue;
|
||||
}
|
||||
let previous_bucket = best[start_index][previous_state].clone();
|
||||
for (previous_index, node) in previous_bucket.into_iter().enumerate() {
|
||||
let target = style.line_target(node.line);
|
||||
@@ -2266,6 +2309,23 @@ mod tests {
|
||||
assert!(boxes.iter().filter(|box_| box_.color.is_none()).count() >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_paragraph_breaks_without_rescanning_candidates() {
|
||||
// 900 words is the size of the server edit fixture; the breaker used to
|
||||
// rescan every candidate line, turning this into tens of seconds.
|
||||
let font = crate::cmr10::Cmr10Metrics::new();
|
||||
let style = ParagraphStyle {
|
||||
line_width: 480 * 65_536,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let text = "word ".repeat(900);
|
||||
let started = std::time::Instant::now();
|
||||
let paragraph = layout_paragraph_with_font(&text, &style, &font);
|
||||
let elapsed = started.elapsed();
|
||||
assert!(paragraph.lines.len() > 30, "{}", paragraph.lines.len());
|
||||
assert!(elapsed < std::time::Duration::from_secs(10), "{elapsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sized_segments_keep_their_own_glyph_size() {
|
||||
let style = ParagraphStyle {
|
||||
|
||||
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
|
||||
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
|
||||
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
|
||||
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
|
||||
PDF opt-in with `?engine=route-d`). 957 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 958 workspace tests are green and no oracle
|
||||
fixture is ignored. Preview JSON also carries a `warnings` array naming
|
||||
environments route-D cannot lay out and control words that survived layout, so
|
||||
unsupported source is reported instead of being silently typeset.
|
||||
|
||||
+5
-2
@@ -56,7 +56,10 @@ class execution are still ahead.
|
||||
breakpoints that minimizes TeX demerits (line penalty, badness, break
|
||||
penalties and adjacent fitness changes), applies `par_indent` to the first
|
||||
line, and bakes the justification into the glue widths of every non-final
|
||||
line;
|
||||
line; prefix sums over the item stream supply each candidate line width,
|
||||
stretch, shrink and glue order in O(1), so the search costs
|
||||
O(breakpoints^2) instead of rescanning every candidate line (a 2,700-word
|
||||
body now lays out in about 0.3 s instead of about 30 s);
|
||||
- `Paragraph { lines, height, width }` and a paragraph-backed `Unit`.
|
||||
|
||||
M1 reads real CMR10 TFM metrics at runtime (advances, height/depth, italic
|
||||
@@ -367,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
|
||||
|
||||
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
|
||||
|
||||
The crate currently has 427 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 957 tests (431 route-D unit, 341 engine binary unit, 10 route-D integration, 39 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
|
||||
The crate currently has 432 unit tests plus ten route-D integration tests and thirty-nine oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 958 tests (432 route-D unit, 341 engine binary unit, 10 route-D integration, 39 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
|
||||
Reference in new issue
Block a user