refact: edit text in place in TextEdit::apply

This commit is contained in:
Moritz Vetter 2022-02-26 15:50:09 +01:00
parent c541f3396c
commit 21d497b773

View file

@ -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 { for indel in &self.indels {
total_len += TextSize::of(&indel.insert); 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;
}
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 if let Some(additional) = total_len.checked_sub(text_size.into()) {
// memory in some other way text.reserve(additional.into());
*text = buf; }
for indel in self.indels.iter().rev() {
indel.apply(text);
}
assert_eq!(TextSize::of(&*text), total_len);
} }
pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> { pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {