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