wordmodel: append to a paragraph in O(1) with push_text and push_object

Building a paragraph through insert_text/insert_object at its end walked
every run (and insert_object counted every object before the offset) on
each call, so n appends cost O(n^2): one paragraph of 64k runs took
8.5 minutes. push_text and push_object extend the last run or start a
new one, giving the same paragraph as inserting at len().
This commit is contained in:
kiwi4boy committed 2026-11-16 17:12:46 -05:00
1 parent 892ef9116c
commit 5541e248e8
2 files changed
+82

No files matched your search

+31
View File
@@ -296,6 +296,37 @@ impl Paragraph {
Ok(())
}
/// Append plain text (U+FFFC is dropped) with `props`. Returns the appended length. The same as
/// [`Self::insert_text`] at [`Self::len`], but it doesn't walk the runs or the text, so building
/// a paragraph of `n` pieces this way is linear rather than quadratic in `n`.
pub fn push_text(&mut self, s: &str, props: &CharProps) -> usize {
let clean: std::borrow::Cow<str> = if s.contains(OBJ) { s.chars().filter(|c| *c != OBJ).collect::<String>().into() } else { s.into() };
if clean.is_empty() {
return 0;
}
self.text.push_str(&clean);
self.push_run(clean.len(), props);
self.touch();
clean.len()
}
/// Append an object with `props`: [`Self::insert_object`] at [`Self::len`], without counting
/// the objects already there.
pub fn push_object(&mut self, obj: InlineObject, props: &CharProps) {
self.text.push(OBJ);
self.objects.push(obj);
self.push_run(OBJ.len_utf8(), props);
self.touch();
}
/// Extend the last run by `len` when it has `props`, or start a new one.
fn push_run(&mut self, len: usize, props: &CharProps) {
match self.runs.last_mut() {
Some(last) if last.props == *props => last.len += len,
_ => self.runs.push(Run { len, props: props.clone() }),
}
}
fn insert_run(&mut self, off: usize, len: usize, props: CharProps) {
// Split the run at `off`, insert, merge neighbours.
let mut start = 0;
+51
View File
@@ -644,6 +644,57 @@ fn para_of_objects(objs: Vec<InlineObject>) -> Paragraph {
p
}
/// push_text and push_object build the same paragraph as inserting at the end.
#[test]
fn pushing_matches_inserting_at_the_end() {
let bold = CharProps { bold: Some(true), ..Default::default() };
let plain = CharProps::default();
let (mut pushed, mut inserted) = (Paragraph::new(), Paragraph::new());
let steps: [(&str, &CharProps, bool); 7] = [
("Hello ", &plain, false),
("world", &bold, false),
("", &bold, true),
(", again", &bold, false),
("", &bold, false),
("x\u{FFFC}y", &plain, false),
("", &plain, true),
];
for (i, (text, props, object)) in steps.into_iter().enumerate() {
if object {
let obj = InlineObject::BookmarkStart { name: format!("b{i}") };
pushed.push_object(obj.clone(), props);
inserted.insert_object(inserted.len(), obj, props).unwrap();
} else {
let n = pushed.push_text(text, props);
assert_eq!(n, inserted.insert_text(inserted.len(), text, props).unwrap());
}
assert_eq!(pushed, inserted, "after step {i}");
}
assert_eq!(pushed.text, "Hello world\u{FFFC}, againxy\u{FFFC}");
assert_eq!(pushed.runs.len(), 3, "equal neighbours merge: {:?}", pushed.runs);
assert_eq!(pushed.objects.len(), 2);
}
#[test]
fn pushing_a_long_paragraph_is_linear() {
// Appending through insert_text/insert_object walked every run (and counted every object) on
// each call: 64k alternating runs took minutes. Pushing takes milliseconds.
let n = 64_000;
let bold = CharProps { bold: Some(true), ..Default::default() };
let plain = CharProps::default();
let t = std::time::Instant::now();
let mut p = Paragraph::new();
for i in 0..n {
p.push_text("word ", if i % 2 == 0 { &bold } else { &plain });
if i % 8 == 0 {
p.push_object(InlineObject::BookmarkStart { name: format!("b{i}") }, &plain);
}
}
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len());
assert_eq!(p.objects.len(), n / 8);
assert!(t.elapsed().as_secs_f32() < 10.0, "{:?}", t.elapsed());
}
#[test]
fn object_walks_are_linear_in_the_paragraph() {
// #3614: loops of object_offsets + object_at recounted the objects before each one, so a