]> git.lizzy.rs Git - rust.git/blob - crates/text_edit/src/lib.rs
forgot a dbg
[rust.git] / crates / text_edit / src / lib.rs
1 //! Representation of a `TextEdit`.
2 //!
3 //! `rust-analyzer` never mutates text itself and only sends diffs to clients,
4 //! so `TextEdit` is the ultimate representation of the work done by
5 //! rust-analyzer.
6 use std::collections::HashSet;
7
8 pub use text_size::{TextRange, TextSize};
9
10 /// `InsertDelete` -- a single "atomic" change to text
11 ///
12 /// Must not overlap with other `InDel`s
13 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
14 pub struct Indel {
15     pub insert: String,
16     /// Refers to offsets in the original text
17     pub delete: TextRange,
18 }
19
20 #[derive(Default, Debug, Clone)]
21 pub struct TextEdit {
22     /// Invariant: disjoint and sorted by `delete`.
23     indels: Vec<Indel>,
24 }
25
26 #[derive(Debug, Default, Clone)]
27 pub struct TextEditBuilder {
28     indels: Vec<Indel>,
29 }
30
31 impl Indel {
32     pub fn insert(offset: TextSize, text: String) -> Indel {
33         Indel::replace(TextRange::empty(offset), text)
34     }
35     pub fn delete(range: TextRange) -> Indel {
36         Indel::replace(range, String::new())
37     }
38     pub fn replace(range: TextRange, replace_with: String) -> Indel {
39         Indel { delete: range, insert: replace_with }
40     }
41
42     pub fn apply(&self, text: &mut String) {
43         let start: usize = self.delete.start().into();
44         let end: usize = self.delete.end().into();
45         text.replace_range(start..end, &self.insert);
46     }
47 }
48
49 impl TextEdit {
50     pub fn builder() -> TextEditBuilder {
51         TextEditBuilder::default()
52     }
53
54     pub fn insert(offset: TextSize, text: String) -> TextEdit {
55         let mut builder = TextEdit::builder();
56         builder.insert(offset, text);
57         builder.finish()
58     }
59
60     pub fn delete(range: TextRange) -> TextEdit {
61         let mut builder = TextEdit::builder();
62         builder.delete(range);
63         builder.finish()
64     }
65
66     pub fn replace(range: TextRange, replace_with: String) -> TextEdit {
67         let mut builder = TextEdit::builder();
68         builder.replace(range, replace_with);
69         builder.finish()
70     }
71
72     pub fn len(&self) -> usize {
73         self.indels.len()
74     }
75
76     pub fn is_empty(&self) -> bool {
77         self.indels.is_empty()
78     }
79
80     pub fn iter(&self) -> std::slice::Iter<'_, Indel> {
81         self.into_iter()
82     }
83
84     pub fn apply(&self, text: &mut String) {
85         match self.len() {
86             0 => return,
87             1 => {
88                 self.indels[0].apply(text);
89                 return;
90             }
91             _ => (),
92         }
93
94         let mut total_len = TextSize::of(&*text);
95         for indel in &self.indels {
96             total_len += TextSize::of(&indel.insert);
97             total_len -= indel.delete.end() - indel.delete.start();
98         }
99         let mut buf = String::with_capacity(total_len.into());
100         let mut prev = 0;
101         for indel in &self.indels {
102             let start: usize = indel.delete.start().into();
103             let end: usize = indel.delete.end().into();
104             if start > prev {
105                 buf.push_str(&text[prev..start]);
106             }
107             buf.push_str(&indel.insert);
108             prev = end;
109         }
110         buf.push_str(&text[prev..text.len()]);
111         assert_eq!(TextSize::of(&buf), total_len);
112
113         // FIXME: figure out a way to mutate the text in-place or reuse the
114         // memory in some other way
115         *text = buf;
116     }
117
118     pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {
119         // FIXME: can be done without allocating intermediate vector
120         let mut all = self.iter().chain(other.iter()).collect::<Vec<_>>();
121         if !check_disjoint_or_equal(&mut all) {
122             return Err(other);
123         }
124
125         // remove duplicates
126         // FIXME: maybe make indels a HashSet instead to get rid of this?
127         let our_indels = self.indels.clone();
128         let our_indels = our_indels.iter().collect::<HashSet<_>>();
129         let other_indels = other.indels.into_iter().filter(|i| !our_indels.contains(i));
130
131         self.indels.extend(other_indels);
132         Ok(())
133     }
134
135     pub fn apply_to_offset(&self, offset: TextSize) -> Option<TextSize> {
136         let mut res = offset;
137         for indel in &self.indels {
138             if indel.delete.start() >= offset {
139                 break;
140             }
141             if offset < indel.delete.end() {
142                 return None;
143             }
144             res += TextSize::of(&indel.insert);
145             res -= indel.delete.len();
146         }
147         Some(res)
148     }
149 }
150
151 impl IntoIterator for TextEdit {
152     type Item = Indel;
153     type IntoIter = std::vec::IntoIter<Indel>;
154
155     fn into_iter(self) -> Self::IntoIter {
156         self.indels.into_iter()
157     }
158 }
159
160 impl<'a> IntoIterator for &'a TextEdit {
161     type Item = &'a Indel;
162     type IntoIter = std::slice::Iter<'a, Indel>;
163
164     fn into_iter(self) -> Self::IntoIter {
165         self.indels.iter()
166     }
167 }
168
169 impl TextEditBuilder {
170     pub fn is_empty(&self) -> bool {
171         self.indels.is_empty()
172     }
173     pub fn replace(&mut self, range: TextRange, replace_with: String) {
174         self.indel(Indel::replace(range, replace_with));
175     }
176     pub fn delete(&mut self, range: TextRange) {
177         self.indel(Indel::delete(range));
178     }
179     pub fn insert(&mut self, offset: TextSize, text: String) {
180         self.indel(Indel::insert(offset, text));
181     }
182     pub fn finish(self) -> TextEdit {
183         let mut indels = self.indels;
184         assert_disjoint_or_equal(&mut indels);
185         TextEdit { indels }
186     }
187     pub fn invalidates_offset(&self, offset: TextSize) -> bool {
188         self.indels.iter().any(|indel| indel.delete.contains_inclusive(offset))
189     }
190     fn indel(&mut self, indel: Indel) {
191         self.indels.push(indel);
192         if self.indels.len() <= 16 {
193             assert_disjoint_or_equal(&mut self.indels);
194         }
195     }
196 }
197
198 fn assert_disjoint_or_equal(indels: &mut [impl std::borrow::Borrow<Indel>]) {
199     assert!(check_disjoint_or_equal(indels));
200 }
201 fn check_disjoint_or_equal(indels: &mut [impl std::borrow::Borrow<Indel>]) -> bool {
202     indels.sort_by_key(|indel| (indel.borrow().delete.start(), indel.borrow().delete.end()));
203     indels.iter().zip(indels.iter().skip(1)).all(|(l, r)| {
204         let l = l.borrow();
205         let r = r.borrow();
206         l.delete.end() <= r.delete.start() || l == r
207     })
208 }