rust/crates/text-edit/src/lib.rs

317 lines
9.0 KiB
Rust
Raw Normal View History

2020-05-05 16:15:49 -05:00
//! Representation of a `TextEdit`.
//!
//! `rust-analyzer` never mutates text itself and only sends diffs to clients,
//! so `TextEdit` is the ultimate representation of the work done by
//! rust-analyzer.
#![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
use itertools::Itertools;
use std::cmp::max;
2020-05-06 04:31:26 -05:00
pub use text_size::{TextRange, TextSize};
2020-05-05 16:15:49 -05:00
/// `InsertDelete` -- a single "atomic" change to text
///
/// Must not overlap with other `InDel`s
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2020-05-05 16:15:49 -05:00
pub struct Indel {
pub insert: String,
/// Refers to offsets in the original text
pub delete: TextRange,
}
2020-05-21 12:50:23 -05:00
#[derive(Default, Debug, Clone)]
2020-05-05 16:15:49 -05:00
pub struct TextEdit {
/// Invariant: disjoint and sorted by `delete`.
2020-05-05 16:15:49 -05:00
indels: Vec<Indel>,
}
#[derive(Debug, Default, Clone)]
2020-05-05 16:15:49 -05:00
pub struct TextEditBuilder {
indels: Vec<Indel>,
}
2020-05-05 16:15:49 -05:00
impl Indel {
pub fn insert(offset: TextSize, text: String) -> Indel {
Indel::replace(TextRange::empty(offset), text)
}
pub fn delete(range: TextRange) -> Indel {
Indel::replace(range, String::new())
}
pub fn replace(range: TextRange, replace_with: String) -> Indel {
Indel { delete: range, insert: replace_with }
}
2019-01-08 12:59:55 -06:00
pub fn apply(&self, text: &mut String) {
2020-04-24 16:40:41 -05:00
let start: usize = self.delete.start().into();
let end: usize = self.delete.end().into();
2019-01-08 12:59:55 -06:00
text.replace_range(start..end, &self.insert);
}
}
2020-05-05 16:15:49 -05:00
impl TextEdit {
2020-08-12 09:58:56 -05:00
pub fn builder() -> TextEditBuilder {
TextEditBuilder::default()
}
2020-05-05 16:15:49 -05:00
pub fn insert(offset: TextSize, text: String) -> TextEdit {
2020-08-12 09:58:56 -05:00
let mut builder = TextEdit::builder();
2020-05-05 16:15:49 -05:00
builder.insert(offset, text);
builder.finish()
}
pub fn delete(range: TextRange) -> TextEdit {
2020-08-12 09:58:56 -05:00
let mut builder = TextEdit::builder();
2020-05-05 16:15:49 -05:00
builder.delete(range);
builder.finish()
}
pub fn replace(range: TextRange, replace_with: String) -> TextEdit {
2020-08-12 09:58:56 -05:00
let mut builder = TextEdit::builder();
2020-05-05 16:15:49 -05:00
builder.replace(range, replace_with);
builder.finish()
}
2020-05-21 08:56:18 -05:00
pub fn len(&self) -> usize {
self.indels.len()
}
2020-05-06 06:08:37 -05:00
pub fn is_empty(&self) -> bool {
self.indels.is_empty()
}
2020-08-12 09:58:56 -05:00
pub fn iter(&self) -> std::slice::Iter<'_, Indel> {
self.into_iter()
2020-05-21 08:56:18 -05:00
}
pub fn apply(&self, text: &mut String) {
2020-05-21 08:56:18 -05:00
match self.len() {
0 => return,
1 => {
self.indels[0].apply(text);
return;
}
_ => (),
}
let text_size = TextSize::of(&*text);
let mut total_len = text_size;
let mut max_total_len = text_size;
2021-10-03 07:45:08 -05:00
for indel in &self.indels {
2020-05-05 16:15:49 -05:00
total_len += TextSize::of(&indel.insert);
total_len -= indel.delete.len();
max_total_len = max(max_total_len, total_len);
2020-05-05 16:15:49 -05:00
}
2022-03-12 06:43:53 -06:00
if let Some(additional) = max_total_len.checked_sub(text_size) {
text.reserve(additional.into());
}
for indel in self.indels.iter().rev() {
indel.apply(text);
2020-05-05 16:15:49 -05:00
}
assert_eq!(TextSize::of(&*text), total_len);
2020-05-05 16:15:49 -05:00
}
2020-05-21 12:50:23 -05:00
pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {
let iter_merge =
self.iter().merge_by(other.iter(), |l, r| l.delete.start() <= r.delete.start());
if !check_disjoint(&mut iter_merge.clone()) {
2020-05-21 12:50:23 -05:00
return Err(other);
}
// Only dedup deletions and replacements, keep all insertions
self.indels = iter_merge.dedup_by(|a, b| a == b && !a.delete.is_empty()).cloned().collect();
2020-05-21 12:50:23 -05:00
Ok(())
}
2020-05-05 16:15:49 -05:00
pub fn apply_to_offset(&self, offset: TextSize) -> Option<TextSize> {
let mut res = offset;
2021-10-03 07:45:08 -05:00
for indel in &self.indels {
2020-05-05 16:15:49 -05:00
if indel.delete.start() >= offset {
break;
}
if offset < indel.delete.end() {
return None;
}
res += TextSize::of(&indel.insert);
res -= indel.delete.len();
}
Some(res)
}
}
2020-08-10 07:05:01 -05:00
impl IntoIterator for TextEdit {
type Item = Indel;
2020-08-12 09:58:56 -05:00
type IntoIter = std::vec::IntoIter<Indel>;
2020-08-10 07:05:01 -05:00
fn into_iter(self) -> Self::IntoIter {
self.indels.into_iter()
2020-08-12 09:58:56 -05:00
}
}
impl<'a> IntoIterator for &'a TextEdit {
type Item = &'a Indel;
type IntoIter = std::slice::Iter<'a, Indel>;
fn into_iter(self) -> Self::IntoIter {
self.indels.iter()
2020-08-10 07:05:01 -05:00
}
}
2020-05-05 16:15:49 -05:00
impl TextEditBuilder {
pub fn is_empty(&self) -> bool {
self.indels.is_empty()
}
2020-05-05 16:15:49 -05:00
pub fn replace(&mut self, range: TextRange, replace_with: String) {
self.indel(Indel::replace(range, replace_with));
2020-05-05 16:15:49 -05:00
}
pub fn delete(&mut self, range: TextRange) {
self.indel(Indel::delete(range));
2020-05-05 16:15:49 -05:00
}
pub fn insert(&mut self, offset: TextSize, text: String) {
self.indel(Indel::insert(offset, text));
2020-05-05 16:15:49 -05:00
}
pub fn finish(self) -> TextEdit {
2020-05-21 12:50:23 -05:00
let mut indels = self.indels;
assert_disjoint_or_equal(&mut indels);
2023-03-18 10:41:38 -05:00
indels = coalesce_indels(indels);
2020-05-21 12:50:23 -05:00
TextEdit { indels }
2020-05-05 16:15:49 -05:00
}
pub fn invalidates_offset(&self, offset: TextSize) -> bool {
self.indels.iter().any(|indel| indel.delete.contains_inclusive(offset))
}
fn indel(&mut self, indel: Indel) {
self.indels.push(indel);
if self.indels.len() <= 16 {
assert_disjoint_or_equal(&mut self.indels);
}
}
2020-05-05 16:15:49 -05:00
}
2020-05-21 12:50:23 -05:00
fn assert_disjoint_or_equal(indels: &mut [Indel]) {
assert!(check_disjoint_and_sort(indels));
2020-09-03 06:24:06 -05:00
}
fn check_disjoint_and_sort(indels: &mut [Indel]) -> bool {
indels.sort_by_key(|indel| (indel.delete.start(), indel.delete.end()));
check_disjoint(&mut indels.iter())
}
fn check_disjoint<'a, I>(indels: &mut I) -> bool
where
I: std::iter::Iterator<Item = &'a Indel> + Clone,
{
indels.clone().zip(indels.skip(1)).all(|(l, r)| l.delete.end() <= r.delete.start() || l == r)
2020-05-21 12:50:23 -05:00
}
2023-03-18 10:41:38 -05:00
fn coalesce_indels(indels: Vec<Indel>) -> Vec<Indel> {
indels
.into_iter()
.coalesce(|mut a, b| {
if a.delete.end() == b.delete.start() {
a.insert.push_str(&b.insert);
a.delete = TextRange::new(a.delete.start(), b.delete.end());
Ok(a)
} else {
Err((a, b))
}
})
.collect_vec()
}
2022-02-26 19:11:56 -06:00
#[cfg(test)]
mod tests {
use super::{TextEdit, TextEditBuilder, TextRange};
fn range(start: u32, end: u32) -> TextRange {
TextRange::new(start.into(), end.into())
}
#[test]
fn test_apply() {
let mut text = "_11h1_2222_xx3333_4444_6666".to_string();
let mut builder = TextEditBuilder::default();
builder.replace(range(3, 4), "1".to_string());
builder.delete(range(11, 13));
builder.insert(22.into(), "_5555".to_string());
let text_edit = builder.finish();
text_edit.apply(&mut text);
assert_eq!(text, "_1111_2222_3333_4444_5555_6666")
}
#[test]
fn test_union() {
let mut edit1 = TextEdit::delete(range(7, 11));
let mut builder = TextEditBuilder::default();
builder.delete(range(1, 5));
builder.delete(range(13, 17));
let edit2 = builder.finish();
assert!(edit1.union(edit2).is_ok());
assert_eq!(edit1.indels.len(), 3);
}
#[test]
fn test_union_with_duplicates() {
let mut builder1 = TextEditBuilder::default();
builder1.delete(range(7, 11));
builder1.delete(range(13, 17));
let mut builder2 = TextEditBuilder::default();
builder2.delete(range(1, 5));
builder2.delete(range(13, 17));
let mut edit1 = builder1.finish();
let edit2 = builder2.finish();
assert!(edit1.union(edit2).is_ok());
assert_eq!(edit1.indels.len(), 3);
}
2022-02-26 19:11:56 -06:00
#[test]
fn test_union_panics() {
let mut edit1 = TextEdit::delete(range(7, 11));
let edit2 = TextEdit::delete(range(9, 13));
assert!(edit1.union(edit2).is_err());
}
2023-03-18 10:41:38 -05:00
#[test]
fn test_coalesce_disjoint() {
let mut builder = TextEditBuilder::default();
builder.replace(range(1, 3), "aa".into());
builder.replace(range(5, 7), "bb".into());
let edit = builder.finish();
assert_eq!(edit.indels.len(), 2);
}
#[test]
fn test_coalesce_adjacent() {
let mut builder = TextEditBuilder::default();
builder.replace(range(1, 3), "aa".into());
builder.replace(range(3, 5), "bb".into());
let edit = builder.finish();
assert_eq!(edit.indels.len(), 1);
assert_eq!(edit.indels[0].insert, "aabb");
assert_eq!(edit.indels[0].delete, range(1, 5));
}
#[test]
fn test_coalesce_adjacent_series() {
let mut builder = TextEditBuilder::default();
builder.replace(range(1, 3), "au".into());
builder.replace(range(3, 5), "www".into());
builder.replace(range(5, 8), "".into());
builder.replace(range(8, 9), "ub".into());
let edit = builder.finish();
assert_eq!(edit.indels.len(), 1);
assert_eq!(edit.indels[0].insert, "auwwwub");
assert_eq!(edit.indels[0].delete, range(1, 9));
}
2022-02-26 19:11:56 -06:00
}