Unnamed repository; edit this file 'description' to name the repository.
refact: edit text in place in TextEdit::apply
Moritz Vetter 2022-02-26
parent c541f33 · commit 21d497b
-rw-r--r--crates/text_edit/src/lib.rs28
1 files changed, 11 insertions, 17 deletions
diff --git a/crates/text_edit/src/lib.rs b/crates/text_edit/src/lib.rs
index f478e4dcf5..f9d3ff9b07 100644
--- a/crates/text_edit/src/lib.rs
+++ b/crates/text_edit/src/lib.rs
@@ -90,28 +90,22 @@ impl TextEdit {
_ => (),
}
- let mut total_len = TextSize::of(&*text);
+ let text_size = TextSize::of(&*text);
+ let mut total_len = text_size.clone();
for indel in &self.indels {
total_len += TextSize::of(&indel.insert);
- total_len -= indel.delete.end() - indel.delete.start();
+ total_len -= indel.delete.len();
}
- let mut buf = String::with_capacity(total_len.into());
- let mut prev = 0;
- for indel in &self.indels {
- let start: usize = indel.delete.start().into();
- let end: usize = indel.delete.end().into();
- if start > prev {
- buf.push_str(&text[prev..start]);
- }
- buf.push_str(&indel.insert);
- prev = end;
+
+ if let Some(additional) = total_len.checked_sub(text_size.into()) {
+ text.reserve(additional.into());
+ }
+
+ for indel in self.indels.iter().rev() {
+ indel.apply(text);
}
- buf.push_str(&text[prev..text.len()]);
- assert_eq!(TextSize::of(&buf), total_len);
- // FIXME: figure out a way to mutate the text in-place or reuse the
- // memory in some other way
- *text = buf;
+ assert_eq!(TextSize::of(&*text), total_len);
}
pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {