refact: edit text in place in TextEdit::apply
@@ -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]);
+
+ if let Some(additional) = total_len.checked_sub(text_size.into()) {
+ text.reserve(additional.into());
}
- buf.push_str(&indel.insert);
- prev = end;
+
+ 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> {
