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