patch.rs

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