From 8692e89b0ae94d9ff8350a66b7c8907dc759edff Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Sat, 23 Jan 2021 22:29:10 +0100 Subject: [PATCH] Add utility methods to diff that capture --- src/algorithms/capture.rs | 9 ++++++--- src/algorithms/mod.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/algorithms/capture.rs b/src/algorithms/capture.rs index 7c0a154..183f54c 100644 --- a/src/algorithms/capture.rs +++ b/src/algorithms/capture.rs @@ -123,8 +123,7 @@ impl Capture { /// Isolate change clusters by eliminating ranges with no changes. /// - /// This will leave holes behind in long periods of equal ranges so that - /// you can build things like unified diffs. + /// This is equivalent to calling [`group_diff_ops`] on [`Capture::into_ops`]. pub fn into_grouped_ops(self, n: usize) -> Vec> { group_diff_ops(self.into_ops(), n) } @@ -135,7 +134,11 @@ impl Capture { } } -fn group_diff_ops(mut ops: Vec, n: usize) -> Vec> { +/// Isolate change clusters by eliminating ranges with no changes. +/// +/// This will leave holes behind in long periods of equal ranges so that +/// you can build things like unified diffs. +pub fn group_diff_ops(mut ops: Vec, n: usize) -> Vec> { if ops.is_empty() { return vec![]; } diff --git a/src/algorithms/mod.rs b/src/algorithms/mod.rs index beac4de..339e3b5 100644 --- a/src/algorithms/mod.rs +++ b/src/algorithms/mod.rs @@ -77,3 +77,35 @@ where { diff(alg, d, old, 0..old.len(), new, 0..new.len()) } + +/// Creates a diff between old and new with the given algorithm capturing the ops. +/// +/// This is like [`diff`] but instead of using an arbitrary hook this will +/// always use [`Replace`] + [`Capture`] and return the captured [`DiffOp`]s. +pub fn capture_diff( + alg: Algorithm, + old: &Old, + old_range: Range, + new: &New, + new_range: Range, +) -> Vec +where + Old: Index + ?Sized, + New: Index + ?Sized, + Old::Output: Hash + Eq + Ord, + New::Output: PartialEq + Hash + Eq + Ord, +{ + let mut d = Replace::new(Capture::new()); + diff(alg, &mut d, old, old_range, new, new_range).unwrap(); + d.into_inner().into_ops() +} + +/// Creates a diff between old and new with the given algorithm capturing the ops. +pub fn capture_diff_slices(alg: Algorithm, old: &[T], new: &[T]) -> Vec +where + T: Eq + Hash + Ord, +{ + let mut d = Replace::new(Capture::new()); + diff_slices(alg, &mut d, old, new).unwrap(); + d.into_inner().into_ops() +}