1use crate::Edit;
2use std::{
3 cmp, mem,
4 ops::{Add, AddAssign, Sub},
5};
6
7#[derive(Clone, Default, Debug, PartialEq, Eq)]
8pub struct Patch<T>(Vec<Edit<T>>);
9
10impl<T> Patch<T>
11where
12 T: 'static
13 + Clone
14 + Copy
15 + Ord
16 + Sub<T, Output = T>
17 + Add<T, Output = T>
18 + AddAssign
19 + Default
20 + PartialEq,
21{
22 pub fn new(edits: Vec<Edit<T>>) -> Self {
23 #[cfg(debug_assertions)]
24 {
25 let mut last_edit: Option<&Edit<T>> = None;
26 for edit in &edits {
27 if let Some(last_edit) = last_edit {
28 assert!(edit.old.start > last_edit.old.end);
29 assert!(edit.new.start > last_edit.new.end);
30 }
31 last_edit = Some(edit);
32 }
33 }
34 Self(edits)
35 }
36
37 pub fn edits(&self) -> &[Edit<T>] {
38 &self.0
39 }
40
41 pub fn into_inner(self) -> Vec<Edit<T>> {
42 self.0
43 }
44
45 #[must_use]
46 pub fn compose(&self, new_edits_iter: impl IntoIterator<Item = Edit<T>>) -> Self {
47 let mut old_edits_iter = self.0.iter().cloned().peekable();
48 let mut new_edits_iter = new_edits_iter.into_iter().peekable();
49 let mut composed = Patch(Vec::new());
50
51 let mut old_start = T::default();
52 let mut new_start = T::default();
53 loop {
54 let old_edit = old_edits_iter.peek_mut();
55 let new_edit = new_edits_iter.peek_mut();
56
57 // Push the old edit if its new end is before the new edit's old start.
58 if let Some(old_edit) = old_edit.as_ref() {
59 let new_edit = new_edit.as_ref();
60 if new_edit.map_or(true, |new_edit| old_edit.new.end < new_edit.old.start) {
61 let catchup = old_edit.old.start - old_start;
62 old_start += catchup;
63 new_start += catchup;
64
65 let old_end = old_start + old_edit.old_len();
66 let new_end = new_start + old_edit.new_len();
67 composed.push(Edit {
68 old: old_start..old_end,
69 new: new_start..new_end,
70 });
71 old_start = old_end;
72 new_start = new_end;
73 old_edits_iter.next();
74 continue;
75 }
76 }
77
78 // Push the new edit if its old end is before the old edit's new start.
79 if let Some(new_edit) = new_edit.as_ref() {
80 let old_edit = old_edit.as_ref();
81 if old_edit.map_or(true, |old_edit| new_edit.old.end < old_edit.new.start) {
82 let catchup = new_edit.new.start - new_start;
83 old_start += catchup;
84 new_start += catchup;
85
86 let old_end = old_start + new_edit.old_len();
87 let new_end = new_start + new_edit.new_len();
88 composed.push(Edit {
89 old: old_start..old_end,
90 new: new_start..new_end,
91 });
92 old_start = old_end;
93 new_start = new_end;
94 new_edits_iter.next();
95 continue;
96 }
97 }
98
99 // If we still have edits by this point then they must intersect, so we compose them.
100 if let Some((old_edit, new_edit)) = old_edit.zip(new_edit) {
101 if old_edit.new.start < new_edit.old.start {
102 let catchup = old_edit.old.start - old_start;
103 old_start += catchup;
104 new_start += catchup;
105
106 let overshoot = new_edit.old.start - old_edit.new.start;
107 let old_end = cmp::min(old_start + overshoot, old_edit.old.end);
108 let new_end = new_start + overshoot;
109 composed.push(Edit {
110 old: old_start..old_end,
111 new: new_start..new_end,
112 });
113
114 old_edit.old.start = old_end;
115 old_edit.new.start += overshoot;
116 old_start = old_end;
117 new_start = new_end;
118 } else {
119 let catchup = new_edit.new.start - new_start;
120 old_start += catchup;
121 new_start += catchup;
122
123 let overshoot = old_edit.new.start - new_edit.old.start;
124 let old_end = old_start + overshoot;
125 let new_end = cmp::min(new_start + overshoot, new_edit.new.end);
126 composed.push(Edit {
127 old: old_start..old_end,
128 new: new_start..new_end,
129 });
130
131 new_edit.old.start += overshoot;
132 new_edit.new.start = new_end;
133 old_start = old_end;
134 new_start = new_end;
135 }
136
137 if old_edit.new.end > new_edit.old.end {
138 let old_end = old_start + cmp::min(old_edit.old_len(), new_edit.old_len());
139 let new_end = new_start + new_edit.new_len();
140 composed.push(Edit {
141 old: old_start..old_end,
142 new: new_start..new_end,
143 });
144
145 old_edit.old.start = old_end;
146 old_edit.new.start = new_edit.old.end;
147 old_start = old_end;
148 new_start = new_end;
149 new_edits_iter.next();
150 } else {
151 let old_end = old_start + old_edit.old_len();
152 let new_end = new_start + cmp::min(old_edit.new_len(), new_edit.new_len());
153 composed.push(Edit {
154 old: old_start..old_end,
155 new: new_start..new_end,
156 });
157
158 new_edit.old.start = old_edit.new.end;
159 new_edit.new.start = new_end;
160 old_start = old_end;
161 new_start = new_end;
162 old_edits_iter.next();
163 }
164 } else {
165 break;
166 }
167 }
168
169 composed
170 }
171
172 pub fn invert(&mut self) -> &mut Self {
173 for edit in &mut self.0 {
174 mem::swap(&mut edit.old, &mut edit.new);
175 }
176 self
177 }
178
179 pub fn clear(&mut self) {
180 self.0.clear();
181 }
182
183 pub fn is_empty(&self) -> bool {
184 self.0.is_empty()
185 }
186
187 pub fn push(&mut self, edit: Edit<T>) {
188 if edit.is_empty() {
189 return;
190 }
191
192 if let Some(last) = self.0.last_mut() {
193 if last.old.end >= edit.old.start {
194 last.old.end = edit.old.end;
195 last.new.end = edit.new.end;
196 } else {
197 self.0.push(edit);
198 }
199 } else {
200 self.0.push(edit);
201 }
202 }
203
204 pub fn old_to_new(&self, old: T) -> T {
205 let ix = match self.0.binary_search_by(|probe| probe.old.start.cmp(&old)) {
206 Ok(ix) => ix,
207 Err(ix) => {
208 if ix == 0 {
209 return old;
210 } else {
211 ix - 1
212 }
213 }
214 };
215 if let Some(edit) = self.0.get(ix) {
216 if old >= edit.old.end {
217 edit.new.end + (old - edit.old.end)
218 } else {
219 edit.new.start
220 }
221 } else {
222 old
223 }
224 }
225}
226
227impl<T: Clone> IntoIterator for Patch<T> {
228 type Item = Edit<T>;
229 type IntoIter = std::vec::IntoIter<Edit<T>>;
230
231 fn into_iter(self) -> Self::IntoIter {
232 self.0.into_iter()
233 }
234}
235
236impl<'a, T: Clone> IntoIterator for &'a Patch<T> {
237 type Item = Edit<T>;
238 type IntoIter = std::iter::Cloned<std::slice::Iter<'a, Edit<T>>>;
239
240 fn into_iter(self) -> Self::IntoIter {
241 self.0.iter().cloned()
242 }
243}
244
245impl<'a, T: Clone> IntoIterator for &'a mut Patch<T> {
246 type Item = Edit<T>;
247 type IntoIter = std::iter::Cloned<std::slice::Iter<'a, Edit<T>>>;
248
249 fn into_iter(self) -> Self::IntoIter {
250 self.0.iter().cloned()
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257 use rand::prelude::*;
258 use std::env;
259
260 #[gpui::test]
261 fn test_one_disjoint_edit() {
262 assert_patch_composition(
263 Patch(vec![Edit {
264 old: 1..3,
265 new: 1..4,
266 }]),
267 Patch(vec![Edit {
268 old: 0..0,
269 new: 0..4,
270 }]),
271 Patch(vec![
272 Edit {
273 old: 0..0,
274 new: 0..4,
275 },
276 Edit {
277 old: 1..3,
278 new: 5..8,
279 },
280 ]),
281 );
282
283 assert_patch_composition(
284 Patch(vec![Edit {
285 old: 1..3,
286 new: 1..4,
287 }]),
288 Patch(vec![Edit {
289 old: 5..9,
290 new: 5..7,
291 }]),
292 Patch(vec![
293 Edit {
294 old: 1..3,
295 new: 1..4,
296 },
297 Edit {
298 old: 4..8,
299 new: 5..7,
300 },
301 ]),
302 );
303 }
304
305 #[gpui::test]
306 fn test_one_overlapping_edit() {
307 assert_patch_composition(
308 Patch(vec![Edit {
309 old: 1..3,
310 new: 1..4,
311 }]),
312 Patch(vec![Edit {
313 old: 3..5,
314 new: 3..6,
315 }]),
316 Patch(vec![Edit {
317 old: 1..4,
318 new: 1..6,
319 }]),
320 );
321 }
322
323 #[gpui::test]
324 fn test_two_disjoint_and_overlapping() {
325 assert_patch_composition(
326 Patch(vec![
327 Edit {
328 old: 1..3,
329 new: 1..4,
330 },
331 Edit {
332 old: 8..12,
333 new: 9..11,
334 },
335 ]),
336 Patch(vec![
337 Edit {
338 old: 0..0,
339 new: 0..4,
340 },
341 Edit {
342 old: 3..10,
343 new: 7..9,
344 },
345 ]),
346 Patch(vec![
347 Edit {
348 old: 0..0,
349 new: 0..4,
350 },
351 Edit {
352 old: 1..12,
353 new: 5..10,
354 },
355 ]),
356 );
357 }
358
359 #[gpui::test]
360 fn test_two_new_edits_overlapping_one_old_edit() {
361 assert_patch_composition(
362 Patch(vec![Edit {
363 old: 0..0,
364 new: 0..3,
365 }]),
366 Patch(vec![
367 Edit {
368 old: 0..0,
369 new: 0..1,
370 },
371 Edit {
372 old: 1..2,
373 new: 2..2,
374 },
375 ]),
376 Patch(vec![Edit {
377 old: 0..0,
378 new: 0..3,
379 }]),
380 );
381
382 assert_patch_composition(
383 Patch(vec![Edit {
384 old: 2..3,
385 new: 2..4,
386 }]),
387 Patch(vec![
388 Edit {
389 old: 0..2,
390 new: 0..1,
391 },
392 Edit {
393 old: 3..3,
394 new: 2..5,
395 },
396 ]),
397 Patch(vec![Edit {
398 old: 0..3,
399 new: 0..6,
400 }]),
401 );
402
403 assert_patch_composition(
404 Patch(vec![Edit {
405 old: 0..0,
406 new: 0..2,
407 }]),
408 Patch(vec![
409 Edit {
410 old: 0..0,
411 new: 0..2,
412 },
413 Edit {
414 old: 2..5,
415 new: 4..4,
416 },
417 ]),
418 Patch(vec![Edit {
419 old: 0..3,
420 new: 0..4,
421 }]),
422 );
423 }
424
425 #[gpui::test]
426 fn test_two_new_edits_touching_one_old_edit() {
427 assert_patch_composition(
428 Patch(vec![
429 Edit {
430 old: 2..3,
431 new: 2..4,
432 },
433 Edit {
434 old: 7..7,
435 new: 8..11,
436 },
437 ]),
438 Patch(vec![
439 Edit {
440 old: 2..3,
441 new: 2..2,
442 },
443 Edit {
444 old: 4..4,
445 new: 3..4,
446 },
447 ]),
448 Patch(vec![
449 Edit {
450 old: 2..3,
451 new: 2..4,
452 },
453 Edit {
454 old: 7..7,
455 new: 8..11,
456 },
457 ]),
458 );
459 }
460
461 #[gpui::test]
462 fn test_old_to_new() {
463 let patch = Patch(vec![
464 Edit {
465 old: 2..4,
466 new: 2..4,
467 },
468 Edit {
469 old: 7..8,
470 new: 7..11,
471 },
472 ]);
473 assert_eq!(patch.old_to_new(0), 0);
474 assert_eq!(patch.old_to_new(1), 1);
475 assert_eq!(patch.old_to_new(2), 2);
476 assert_eq!(patch.old_to_new(3), 2);
477 assert_eq!(patch.old_to_new(4), 4);
478 assert_eq!(patch.old_to_new(5), 5);
479 assert_eq!(patch.old_to_new(6), 6);
480 assert_eq!(patch.old_to_new(7), 7);
481 assert_eq!(patch.old_to_new(8), 11);
482 assert_eq!(patch.old_to_new(9), 12);
483 }
484
485 #[gpui::test(iterations = 100)]
486 fn test_random_patch_compositions(mut rng: StdRng) {
487 let operations = env::var("OPERATIONS")
488 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
489 .unwrap_or(20);
490
491 let initial_chars = (0..rng.gen_range(0..=100))
492 .map(|_| rng.gen_range(b'a'..=b'z') as char)
493 .collect::<Vec<_>>();
494 log::info!("initial chars: {:?}", initial_chars);
495
496 // Generate two sequential patches
497 let mut patches = Vec::new();
498 let mut expected_chars = initial_chars.clone();
499 for i in 0..2 {
500 log::info!("patch {}:", i);
501
502 let mut delta = 0i32;
503 let mut last_edit_end = 0;
504 let mut edits = Vec::new();
505
506 for _ in 0..operations {
507 if last_edit_end >= expected_chars.len() {
508 break;
509 }
510
511 let end = rng.gen_range(last_edit_end..=expected_chars.len());
512 let start = rng.gen_range(last_edit_end..=end);
513 let old_len = end - start;
514
515 let mut new_len = rng.gen_range(0..=3);
516 if start == end && new_len == 0 {
517 new_len += 1;
518 }
519
520 last_edit_end = start + new_len + 1;
521
522 let new_chars = (0..new_len)
523 .map(|_| rng.gen_range(b'A'..=b'Z') as char)
524 .collect::<Vec<_>>();
525 log::info!(
526 " editing {:?}: {:?}",
527 start..end,
528 new_chars.iter().collect::<String>()
529 );
530 edits.push(Edit {
531 old: (start as i32 - delta) as u32..(end as i32 - delta) as u32,
532 new: start as u32..(start + new_len) as u32,
533 });
534 expected_chars.splice(start..end, new_chars);
535
536 delta += new_len as i32 - old_len as i32;
537 }
538
539 patches.push(Patch(edits));
540 }
541
542 log::info!("old patch: {:?}", &patches[0]);
543 log::info!("new patch: {:?}", &patches[1]);
544 log::info!("initial chars: {:?}", initial_chars);
545 log::info!("final chars: {:?}", expected_chars);
546
547 // Compose the patches, and verify that it has the same effect as applying the
548 // two patches separately.
549 let composed = patches[0].compose(&patches[1]);
550 log::info!("composed patch: {:?}", &composed);
551
552 let mut actual_chars = initial_chars;
553 for edit in composed.0 {
554 actual_chars.splice(
555 edit.new.start as usize..edit.new.start as usize + edit.old.len(),
556 expected_chars[edit.new.start as usize..edit.new.end as usize]
557 .iter()
558 .copied(),
559 );
560 }
561
562 assert_eq!(actual_chars, expected_chars);
563 }
564
565 #[track_caller]
566 #[allow(clippy::almost_complete_range)]
567 fn assert_patch_composition(old: Patch<u32>, new: Patch<u32>, composed: Patch<u32>) {
568 let original = ('a'..'z').collect::<Vec<_>>();
569 let inserted = ('A'..'Z').collect::<Vec<_>>();
570
571 let mut expected = original.clone();
572 apply_patch(&mut expected, &old, &inserted);
573 apply_patch(&mut expected, &new, &inserted);
574
575 let mut actual = original;
576 apply_patch(&mut actual, &composed, &expected);
577 assert_eq!(
578 actual.into_iter().collect::<String>(),
579 expected.into_iter().collect::<String>(),
580 "expected patch is incorrect"
581 );
582
583 assert_eq!(old.compose(&new), composed);
584 }
585
586 fn apply_patch(text: &mut Vec<char>, patch: &Patch<u32>, new_text: &[char]) {
587 for edit in patch.0.iter().rev() {
588 text.splice(
589 edit.old.start as usize..edit.old.end as usize,
590 new_text[edit.new.start as usize..edit.new.end as usize]
591 .iter()
592 .copied(),
593 );
594 }
595 }
596}