Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! [![github]](https://github.com/dtolnay/dissimilar) [![crates-io]](https://crates.io/crates/dissimilar) [![docs-rs]](https://docs.rs/dissimilar)
2 //!
3 //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4 //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5 //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K
6 //!
7 //! <br>
8 //!
9 //! ## Diff library with semantic cleanup, based on Google's diff-match-patch
10 //!
11 //! This library is a port of the Diff component of [Diff Match Patch] to Rust.
12 //! The diff implementation is based on [Myers' diff algorithm] but includes
13 //! some [semantic cleanups] to increase human readability by factoring out
14 //! commonalities which are likely to be coincidental.
15 //!
16 //! Diff Match Patch was originally built in 2006 to power Google Docs.
17 //!
18 //! # Interface
19 //!
20 //! Here is the entire API of the Rust implementation. It operates on borrowed
21 //! strings and the return value of the diff algorithm is a vector of chunks
22 //! pointing into slices of those input strings.
23 //!
24 //! ```
25 //! pub enum Chunk<'a> {
26 //! Equal(&'a str),
27 //! Delete(&'a str),
28 //! Insert(&'a str),
29 //! }
30 //!
31 //! # const IGNORE: &str = stringify! {
32 //! pub fn diff(text1: &str, text2: &str) -> Vec<Chunk>;
33 //! # };
34 //! ```
35 //!
36 //! [Diff Match Patch]: https://github.com/google/diff-match-patch
37 //! [Myers' diff algorithm]: https://neil.fraser.name/writing/diff/myers.pdf
38 //! [semantic cleanups]: https://neil.fraser.name/writing/diff/
39
40 #![doc(html_root_url = "https://docs.rs/dissimilar/1.0.2")]
41 #![allow(
42 clippy::blocks_in_if_conditions,
43 clippy::collapsible_if,
44 clippy::comparison_chain,
45 clippy::new_without_default
46 )]
47
48 mod find;
49 mod range;
50
51 #[cfg(test)]
52 mod tests;
53
54 use crate::range::{bytes, str, Range};
55 use std::cmp;
56 use std::collections::VecDeque;
57 use std::fmt::{self, Debug};
58
59 #[derive(Copy, Clone, PartialEq, Eq)]
60 pub enum Chunk<'a> {
61 Equal(&'a str),
62 Delete(&'a str),
63 Insert(&'a str),
64 }
65
66 #[derive(Copy, Clone)]
67 enum Diff<'a, 'b> {
68 Equal(Range<'a>, Range<'b>),
69 Delete(Range<'a>),
70 Insert(Range<'b>),
71 }
72
73 impl<'tmp, 'a: 'tmp, 'b: 'tmp> Diff<'a, 'b> {
74 fn text(&self) -> Range<'tmp> {
75 match *self {
76 Diff::Equal(range, _) | Diff::Delete(range) | Diff::Insert(range) => range,
77 }
78 }
79
80 fn grow_left(&mut self, increment: usize) {
81 self.for_each(|range| {
82 range.offset -= increment;
83 range.len += increment;
84 });
85 }
86
87 fn grow_right(&mut self, increment: usize) {
88 self.for_each(|range| range.len += increment);
89 }
90
91 fn shift_left(&mut self, increment: usize) {
92 self.for_each(|range| range.offset -= increment);
93 }
94
95 fn shift_right(&mut self, increment: usize) {
96 self.for_each(|range| range.offset += increment);
97 }
98
99 fn for_each(&mut self, f: impl Fn(&mut Range)) {
100 match self {
101 Diff::Equal(range1, range2) => {
102 f(range1);
103 f(range2);
104 }
105 Diff::Delete(range) => f(range),
106 Diff::Insert(range) => f(range),
107 }
108 }
109 }
110
111 pub fn diff<'a>(text1: &'a str, text2: &'a str) -> Vec<Chunk<'a>> {
112 let text1 = Range::new(text1, ..);
113 let text2 = Range::new(text2, ..);
114 let mut solution = main(text1, text2);
115 cleanup_char_boundary(&mut solution);
116 cleanup_semantic(&mut solution);
117 cleanup_merge(&mut solution);
118 solution.diffs.into_iter().map(Chunk::from).collect()
119 }
120
121 struct Solution<'a, 'b> {
122 text1: Range<'a>,
123 text2: Range<'b>,
124 diffs: Vec<Diff<'a, 'b>>,
125 utf8: bool,
126 }
127
128 fn main<'a, 'b>(mut text1: Range<'a>, mut text2: Range<'b>) -> Solution<'a, 'b> {
129 let whole1 = text1;
130 let whole2 = text2;
131
132 // Trim off common prefix.
133 let common_prefix_len = common_prefix_bytes(text1, text2);
134 let common_prefix = Diff::Equal(
135 text1.substring(..common_prefix_len),
136 text2.substring(..common_prefix_len),
137 );
138 text1 = text1.substring(common_prefix_len..);
139 text2 = text2.substring(common_prefix_len..);
140
141 // Trim off common suffix.
142 let common_suffix_len = common_suffix_bytes(text1, text2);
143 let common_suffix = Diff::Equal(
144 text1.substring(text1.len - common_suffix_len..),
145 text2.substring(text2.len - common_suffix_len..),
146 );
147 text1 = text1.substring(..text1.len - common_suffix_len);
148 text2 = text2.substring(..text2.len - common_suffix_len);
149
150 // Compute the diff on the middle block.
151 let mut solution = Solution {
152 text1: whole1,
153 text2: whole2,
154 diffs: compute(text1, text2),
155 utf8: false,
156 };
157
158 // Restore the prefix and suffix.
159 if common_prefix_len > 0 {
160 solution.diffs.insert(0, common_prefix);
161 }
162 if common_suffix_len > 0 {
163 solution.diffs.push(common_suffix);
164 }
165
166 cleanup_merge(&mut solution);
167
168 solution
169 }
170
171 // Find the differences between two texts. Assumes that the texts do not have
172 // any common prefix or suffix.
173 fn compute<'a, 'b>(text1: Range<'a>, text2: Range<'b>) -> Vec<Diff<'a, 'b>> {
174 match (text1.is_empty(), text2.is_empty()) {
175 (true, true) => return Vec::new(),
176 (true, false) => return vec![Diff::Insert(text2)],
177 (false, true) => return vec![Diff::Delete(text1)],
178 (false, false) => {}
179 }
180
181 // Check for entire shorter text inside the longer text.
182 if text1.len > text2.len {
183 if let Some(i) = text1.find(text2) {
184 return vec![
185 Diff::Delete(text1.substring(..i)),
186 Diff::Equal(text1.substring(i..i + text2.len), text2),
187 Diff::Delete(text1.substring(i + text2.len..)),
188 ];
189 }
190 } else {
191 if let Some(i) = text2.find(text1) {
192 return vec![
193 Diff::Insert(text2.substring(..i)),
194 Diff::Equal(text1, text2.substring(i..i + text1.len)),
195 Diff::Insert(text2.substring(i + text1.len..)),
196 ];
197 }
198 }
199
200 if text1.len == 1 || text2.len == 1 {
201 // Single character string.
202 // After the previous check, the character can't be an equality.
203 return vec![Diff::Delete(text1), Diff::Insert(text2)];
204 }
205
206 bisect(text1, text2)
207 }
208
209 // Find the 'middle snake' of a diff, split the problem in two and return the
210 // recursively constructed diff.
211 //
212 // See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
213 fn bisect<'a, 'b>(text1: Range<'a>, text2: Range<'b>) -> Vec<Diff<'a, 'b>> {
214 let max_d = (text1.len + text2.len + 1) / 2;
215 let v_offset = max_d;
216 let v_len = 2 * max_d;
217 let mut v1 = vec![-1isize; v_len];
218 let mut v2 = vec![-1isize; v_len];
219 v1[v_offset + 1] = 0;
220 v2[v_offset + 1] = 0;
221 let delta = text1.len as isize - text2.len as isize;
222 // If the total number of characters is odd, then the front path will
223 // collide with the reverse path.
224 let front = delta % 2 != 0;
225 // Offsets for start and end of k loop.
226 // Prevents mapping of space beyond the grid.
227 let mut k1start = 0;
228 let mut k1end = 0;
229 let mut k2start = 0;
230 let mut k2end = 0;
231 for d in 0..max_d as isize {
232 // Walk the front path one step.
233 let mut k1 = -d + k1start;
234 while k1 <= d - k1end {
235 let k1_offset = (v_offset as isize + k1) as usize;
236 let mut x1 = if k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1]) {
237 v1[k1_offset + 1]
238 } else {
239 v1[k1_offset - 1] + 1
240 } as usize;
241 let mut y1 = (x1 as isize - k1) as usize;
242 if let (Some(s1), Some(s2)) = (text1.get(x1..), text2.get(y1..)) {
243 let advance = common_prefix_bytes(s1, s2);
244 x1 += advance;
245 y1 += advance;
246 }
247 v1[k1_offset] = x1 as isize;
248 if x1 > text1.len {
249 // Ran off the right of the graph.
250 k1end += 2;
251 } else if y1 > text2.len {
252 // Ran off the bottom of the graph.
253 k1start += 2;
254 } else if front {
255 let k2_offset = v_offset as isize + delta - k1;
256 if k2_offset >= 0 && k2_offset < v_len as isize && v2[k2_offset as usize] != -1 {
257 // Mirror x2 onto top-left coordinate system.
258 let x2 = text1.len as isize - v2[k2_offset as usize];
259 if x1 as isize >= x2 {
260 // Overlap detected.
261 return bisect_split(text1, text2, x1, y1);
262 }
263 }
264 }
265 k1 += 2;
266 }
267
268 // Walk the reverse path one step.
269 let mut k2 = -d + k2start;
270 while k2 <= d - k2end {
271 let k2_offset = (v_offset as isize + k2) as usize;
272 let mut x2 = if k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1]) {
273 v2[k2_offset + 1]
274 } else {
275 v2[k2_offset - 1] + 1
276 } as usize;
277 let mut y2 = (x2 as isize - k2) as usize;
278 if x2 < text1.len && y2 < text2.len {
279 let advance = common_suffix_bytes(
280 text1.substring(..text1.len - x2),
281 text2.substring(..text2.len - y2),
282 );
283 x2 += advance;
284 y2 += advance;
285 }
286 v2[k2_offset] = x2 as isize;
287 if x2 > text1.len {
288 // Ran off the left of the graph.
289 k2end += 2;
290 } else if y2 > text2.len {
291 // Ran off the top of the graph.
292 k2start += 2;
293 } else if !front {
294 let k1_offset = v_offset as isize + delta - k2;
295 if k1_offset >= 0 && k1_offset < v_len as isize && v1[k1_offset as usize] != -1 {
296 let x1 = v1[k1_offset as usize] as usize;
297 let y1 = v_offset + x1 - k1_offset as usize;
298 // Mirror x2 onto top-left coordinate system.
299 x2 = text1.len - x2;
300 if x1 >= x2 {
301 // Overlap detected.
302 return bisect_split(text1, text2, x1, y1);
303 }
304 }
305 }
306 k2 += 2;
307 }
308 }
309 // Number of diffs equals number of characters, no commonality at all.
310 vec![Diff::Delete(text1), Diff::Insert(text2)]
311 }
312
313 // Given the location of the 'middle snake', split the diff in two parts and
314 // recurse.
315 fn bisect_split<'a, 'b>(
316 text1: Range<'a>,
317 text2: Range<'b>,
318 x: usize,
319 y: usize,
320 ) -> Vec<Diff<'a, 'b>> {
321 let (text1a, text1b) = text1.split_at(x);
322 let (text2a, text2b) = text2.split_at(y);
323
324 // Compute both diffs serially.
325 let mut diffs = main(text1a, text2a).diffs;
326 diffs.extend(main(text1b, text2b).diffs);
327
328 diffs
329 }
330
331 // Determine the length of the common prefix of two strings.
332 fn common_prefix(text1: Range, text2: Range) -> usize {
333 for ((i, ch1), ch2) in text1.char_indices().zip(text2.chars()) {
334 if ch1 != ch2 {
335 return i;
336 }
337 }
338 cmp::min(text1.len, text2.len)
339 }
340
341 // Determine the length of the common suffix of two strings.
342 fn common_suffix(text1: Range, text2: Range) -> usize {
343 for ((i, ch1), ch2) in text1.char_indices().rev().zip(text2.chars().rev()) {
344 if ch1 != ch2 {
345 return text1.len - i - ch1.len_utf8();
346 }
347 }
348 cmp::min(text1.len, text2.len)
349 }
350
351 fn common_prefix_bytes(text1: Range, text2: Range) -> usize {
352 for (i, (b1, b2)) in text1.bytes().zip(text2.bytes()).enumerate() {
353 if b1 != b2 {
354 return i;
355 }
356 }
357 cmp::min(text1.len, text2.len)
358 }
359
360 fn common_suffix_bytes(text1: Range, text2: Range) -> usize {
361 for (i, (b1, b2)) in text1.bytes().rev().zip(text2.bytes().rev()).enumerate() {
362 if b1 != b2 {
363 return i;
364 }
365 }
366 cmp::min(text1.len, text2.len)
367 }
368
369 // Determine if the suffix of one string is the prefix of another.
370 //
371 // Returns the number of characters common to the end of the first string and
372 // the start of the second string.
373 fn common_overlap(mut text1: Range, mut text2: Range) -> usize {
374 // Eliminate the null case.
375 if text1.is_empty() || text2.is_empty() {
376 return 0;
377 }
378 // Truncate the longer string.
379 if text1.len > text2.len {
380 text1 = text1.substring(text1.len - text2.len..);
381 } else if text1.len < text2.len {
382 text2 = text2.substring(..text1.len);
383 }
384 // Quick check for the worst case.
385 if bytes(text1) == bytes(text2) {
386 return text1.len;
387 }
388
389 // Start by looking for a single character match
390 // and increase length until no match is found.
391 // Performance analysis: https://neil.fraser.name/news/2010/11/04/
392 let mut best = 0;
393 let mut length = 1;
394 loop {
395 let pattern = text1.substring(text1.len - length..);
396 let found = match text2.find(pattern) {
397 Some(found) => found,
398 None => return best,
399 };
400 length += found;
401 if found == 0
402 || bytes(text1.substring(text1.len - length..)) == bytes(text2.substring(..length))
403 {
404 best = length;
405 length += 1;
406 }
407 }
408 }
409
410 fn cleanup_char_boundary(solution: &mut Solution) {
411 fn boundary_down(doc: &str, pos: usize) -> usize {
412 let mut adjust = 0;
413 while !doc.is_char_boundary(pos - adjust) {
414 adjust += 1;
415 }
416 adjust
417 }
418
419 fn boundary_up(doc: &str, pos: usize) -> usize {
420 let mut adjust = 0;
421 while !doc.is_char_boundary(pos + adjust) {
422 adjust += 1;
423 }
424 adjust
425 }
426
427 for diff in &mut solution.diffs {
428 match diff {
429 Diff::Equal(range1, range2) => {
430 let adjust = boundary_up(range1.doc, range1.offset);
431 range1.offset += adjust;
432 range1.len -= adjust;
433 range2.offset += adjust;
434 range2.len -= adjust;
435 let adjust = boundary_down(range1.doc, range1.offset + range1.len);
436 range1.len -= adjust;
437 range2.len -= adjust;
438 }
439 Diff::Delete(range) => {
440 let adjust = boundary_down(range.doc, range.offset);
441 range.offset -= adjust;
442 range.len += adjust;
443 let adjust = boundary_up(range.doc, range.offset + range.len);
444 range.len += adjust;
445 }
446 Diff::Insert(range) => {
447 let adjust = boundary_down(range.doc, range.offset);
448 range.offset -= adjust;
449 range.len += adjust;
450 let adjust = boundary_up(range.doc, range.offset + range.len);
451 range.len += adjust;
452 }
453 }
454 }
455
456 solution.utf8 = true;
457 }
458
459 // Reduce the number of edits by eliminating semantically trivial equalities.
460 fn cleanup_semantic(solution: &mut Solution) {
461 let mut diffs = &mut solution.diffs;
462 if diffs.is_empty() {
463 return;
464 }
465
466 let mut changes = false;
467 let mut equalities = VecDeque::new(); // Double-ended queue of equalities.
468 let mut last_equality = None; // Always equal to equalities.peek().text
469 let mut pointer = 0;
470 // Number of characters that changed prior to the equality.
471 let mut len_insertions1 = 0;
472 let mut len_deletions1 = 0;
473 // Number of characters that changed after the equality.
474 let mut len_insertions2 = 0;
475 let mut len_deletions2 = 0;
476 while let Some(&this_diff) = diffs.get(pointer) {
477 match this_diff {
478 Diff::Equal(text1, text2) => {
479 equalities.push_back(pointer);
480 len_insertions1 = len_insertions2;
481 len_deletions1 = len_deletions2;
482 len_insertions2 = 0;
483 len_deletions2 = 0;
484 last_equality = Some((text1, text2));
485 pointer += 1;
486 continue;
487 }
488 Diff::Delete(text) => len_deletions2 += text.len,
489 Diff::Insert(text) => len_insertions2 += text.len,
490 }
491 // Eliminate an equality that is smaller or equal to the edits on both
492 // sides of it.
493 if last_equality.map_or(false, |(last_equality, _)| {
494 last_equality.len <= cmp::max(len_insertions1, len_deletions1)
495 && last_equality.len <= cmp::max(len_insertions2, len_deletions2)
496 }) {
497 // Jump back to offending equality.
498 pointer = equalities.pop_back().unwrap();
499
500 // Replace equality with a delete.
501 diffs[pointer] = Diff::Delete(last_equality.unwrap().0);
502 // Insert a corresponding insert.
503 diffs.insert(pointer + 1, Diff::Insert(last_equality.unwrap().1));
504
505 len_insertions1 = 0; // Reset the counters.
506 len_insertions2 = 0;
507 len_deletions1 = 0;
508 len_deletions2 = 0;
509 last_equality = None;
510 changes = true;
511
512 // Throw away the previous equality (it needs to be reevaluated).
513 equalities.pop_back();
514 if let Some(back) = equalities.back() {
515 // There is a safe equality we can fall back to.
516 pointer = *back;
517 } else {
518 // There are no previous equalities, jump back to the start.
519 pointer = 0;
520 continue;
521 }
522 }
523 pointer += 1;
524 }
525
526 // Normalize the diff.
527 if changes {
528 cleanup_merge(solution);
529 }
530 cleanup_semantic_lossless(solution);
531 diffs = &mut solution.diffs;
532
533 // Find any overlaps between deletions and insertions.
534 // e.g: <del>abcxxx</del><ins>xxxdef</ins>
535 // -> <del>abc</del>xxx<ins>def</ins>
536 // e.g: <del>xxxabc</del><ins>defxxx</ins>
537 // -> <ins>def</ins>xxx<del>abc</del>
538 // Only extract an overlap if it is as big as the edit ahead or behind it.
539 let mut pointer = 1;
540 while let Some(&this_diff) = diffs.get(pointer) {
541 let prev_diff = diffs[pointer - 1];
542 if let (Diff::Delete(deletion), Diff::Insert(insertion)) = (prev_diff, this_diff) {
543 let overlap_len1 = common_overlap(deletion, insertion);
544 let overlap_len2 = common_overlap(insertion, deletion);
545 let overlap_min = cmp::min(deletion.len, insertion.len);
546 if overlap_len1 >= overlap_len2 && 2 * overlap_len1 >= overlap_min {
547 // Overlap found. Insert an equality and trim the surrounding edits.
548 diffs.insert(
549 pointer,
550 Diff::Equal(
551 deletion.substring(deletion.len - overlap_len1..deletion.len),
552 insertion.substring(..overlap_len1),
553 ),
554 );
555 diffs[pointer - 1] =
556 Diff::Delete(deletion.substring(..deletion.len - overlap_len1));
557 diffs[pointer + 1] = Diff::Insert(insertion.substring(overlap_len1..));
558 } else if overlap_len1 < overlap_len2 && 2 * overlap_len2 >= overlap_min {
559 // Reverse overlap found.
560 // Insert an equality and swap and trim the surrounding edits.
561 diffs.insert(
562 pointer,
563 Diff::Equal(
564 deletion.substring(..overlap_len2),
565 insertion.substring(insertion.len - overlap_len2..insertion.len),
566 ),
567 );
568 diffs[pointer - 1] =
569 Diff::Insert(insertion.substring(..insertion.len - overlap_len2));
570 diffs[pointer + 1] = Diff::Delete(deletion.substring(overlap_len2..));
571 }
572 pointer += 1;
573 }
574 pointer += 1;
575 }
576 }
577
578 // Look for single edits surrounded on both sides by equalities which can be
579 // shifted sideways to align the edit to a word boundary.
580 //
581 // e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
582 fn cleanup_semantic_lossless(solution: &mut Solution) {
583 let diffs = &mut solution.diffs;
584 let mut pointer = 1;
585 while let Some(&next_diff) = diffs.get(pointer + 1) {
586 let prev_diff = diffs[pointer - 1];
587 if let (
588 Diff::Equal(mut prev_equal1, mut prev_equal2),
589 Diff::Equal(mut next_equal1, mut next_equal2),
590 ) = (prev_diff, next_diff)
591 {
592 // This is a single edit surrounded by equalities.
593 let mut edit = diffs[pointer];
594
595 // First, shift the edit as far left as possible.
596 let common_offset = common_suffix(prev_equal1, edit.text());
597 let original_prev_len = prev_equal1.len;
598 prev_equal1.len -= common_offset;
599 prev_equal2.len -= common_offset;
600 edit.shift_left(common_offset);
601 next_equal1.offset -= common_offset;
602 next_equal1.len += common_offset;
603 next_equal2.offset -= common_offset;
604 next_equal2.len += common_offset;
605
606 // Second, step character by character right, looking for the best fit.
607 let mut best_prev_equal = (prev_equal1, prev_equal2);
608 let mut best_edit = edit;
609 let mut best_next_equal = (next_equal1, next_equal2);
610 let mut best_score = cleanup_semantic_score(prev_equal1, edit.text())
611 + cleanup_semantic_score(edit.text(), next_equal1);
612 while !edit.text().is_empty()
613 && !next_equal1.is_empty()
614 && edit.text().chars().next().unwrap() == next_equal1.chars().next().unwrap()
615 {
616 let increment = edit.text().chars().next().unwrap().len_utf8();
617 prev_equal1.len += increment;
618 prev_equal2.len += increment;
619 edit.shift_right(increment);
620 next_equal1.offset += increment;
621 next_equal1.len -= increment;
622 next_equal2.offset += increment;
623 next_equal2.len -= increment;
624 let score = cleanup_semantic_score(prev_equal1, edit.text())
625 + cleanup_semantic_score(edit.text(), next_equal1);
626 // The >= encourages trailing rather than leading whitespace on edits.
627 if score >= best_score {
628 best_score = score;
629 best_prev_equal = (prev_equal1, prev_equal2);
630 best_edit = edit;
631 best_next_equal = (next_equal1, next_equal2);
632 }
633 }
634
635 if original_prev_len != best_prev_equal.0.len {
636 // We have an improvement, save it back to the diff.
637 if best_next_equal.0.is_empty() {
638 diffs.remove(pointer + 1);
639 } else {
640 diffs[pointer + 1] = Diff::Equal(best_next_equal.0, best_next_equal.1);
641 }
642 diffs[pointer] = best_edit;
643 if best_prev_equal.0.is_empty() {
644 diffs.remove(pointer - 1);
645 pointer -= 1;
646 } else {
647 diffs[pointer - 1] = Diff::Equal(best_prev_equal.0, best_prev_equal.1);
648 }
649 }
650 }
651 pointer += 1;
652 }
653 }
654
655 // Given two strings, compute a score representing whether the internal boundary
656 // falls on logical boundaries.
657 //
658 // Scores range from 6 (best) to 0 (worst).
659 fn cleanup_semantic_score(one: Range, two: Range) -> usize {
660 if one.is_empty() || two.is_empty() {
661 // Edges are the best.
662 return 6;
663 }
664
665 // Each port of this function behaves slightly differently due to subtle
666 // differences in each language's definition of things like 'whitespace'.
667 // Since this function's purpose is largely cosmetic, the choice has been
668 // made to use each language's native features rather than force total
669 // conformity.
670 let char1 = one.chars().next_back().unwrap();
671 let char2 = two.chars().next().unwrap();
672 let non_alphanumeric1 = !char1.is_ascii_alphanumeric();
673 let non_alphanumeric2 = !char2.is_ascii_alphanumeric();
674 let whitespace1 = non_alphanumeric1 && char1.is_ascii_whitespace();
675 let whitespace2 = non_alphanumeric2 && char2.is_ascii_whitespace();
676 let line_break1 = whitespace1 && char1.is_control();
677 let line_break2 = whitespace2 && char2.is_control();
678 let blank_line1 = line_break1 && (one.ends_with("\n\n") || one.ends_with("\n\r\n"));
679 let blank_line2 = line_break2 && (two.starts_with("\n\n") || two.starts_with("\r\n\r\n"));
680
681 if blank_line1 || blank_line2 {
682 // Five points for blank lines.
683 5
684 } else if line_break1 || line_break2 {
685 // Four points for line breaks.
686 4
687 } else if non_alphanumeric1 && !whitespace1 && whitespace2 {
688 // Three points for end of sentences.
689 3
690 } else if whitespace1 || whitespace2 {
691 // Two points for whitespace.
692 2
693 } else if non_alphanumeric1 || non_alphanumeric2 {
694 // One point for non-alphanumeric.
695 1
696 } else {
697 0
698 }
699 }
700
701 // Reorder and merge like edit sections. Merge equalities. Any edit section can
702 // move as long as it doesn't cross an equality.
703 fn cleanup_merge(solution: &mut Solution) {
704 let diffs = &mut solution.diffs;
705 let common_prefix = if solution.utf8 {
706 common_prefix
707 } else {
708 common_prefix_bytes
709 };
710 let common_suffix = if solution.utf8 {
711 common_suffix
712 } else {
713 common_suffix_bytes
714 };
715
716 loop {
717 if diffs.is_empty() {
718 return;
719 }
720
721 diffs.push(Diff::Equal(
722 solution.text1.substring(solution.text1.len..),
723 solution.text2.substring(solution.text2.len..),
724 )); // Add a dummy entry at the end.
725 let mut pointer = 0;
726 let mut count_delete = 0;
727 let mut count_insert = 0;
728 let mut text_delete = Range::empty();
729 let mut text_insert = Range::empty();
730 while let Some(&this_diff) = diffs.get(pointer) {
731 match this_diff {
732 Diff::Insert(text) => {
733 count_insert += 1;
734 if text_insert.is_empty() {
735 text_insert = text;
736 } else {
737 text_insert.len += text.len;
738 }
739 }
740 Diff::Delete(text) => {
741 count_delete += 1;
742 if text_delete.is_empty() {
743 text_delete = text;
744 } else {
745 text_delete.len += text.len;
746 }
747 }
748 Diff::Equal(text, _) => {
749 let count_both = count_delete + count_insert;
750 if count_both > 1 {
751 let both_types = count_delete != 0 && count_insert != 0;
752 // Delete the offending records.
753 diffs.splice(pointer - count_both..pointer, None);
754 pointer -= count_both;
755 if both_types {
756 // Factor out any common prefix.
757 let common_length = common_prefix(text_insert, text_delete);
758 if common_length != 0 {
759 if pointer > 0 {
760 match &mut diffs[pointer - 1] {
761 Diff::Equal(this_diff1, this_diff2) => {
762 this_diff1.len += common_length;
763 this_diff2.len += common_length;
764 }
765 _ => unreachable!(
766 "previous diff should have been an equality"
767 ),
768 }
769 } else {
770 diffs.insert(
771 pointer,
772 Diff::Equal(
773 text_delete.substring(..common_length),
774 text_insert.substring(..common_length),
775 ),
776 );
777 pointer += 1;
778 }
779 text_insert = text_insert.substring(common_length..);
780 text_delete = text_delete.substring(common_length..);
781 }
782 // Factor out any common suffix.
783 let common_length = common_suffix(text_insert, text_delete);
784 if common_length != 0 {
785 diffs[pointer].grow_left(common_length);
786 text_insert.len -= common_length;
787 text_delete.len -= common_length;
788 }
789 }
790 // Insert the merged records.
791 if !text_delete.is_empty() {
792 diffs.insert(pointer, Diff::Delete(text_delete));
793 pointer += 1;
794 }
795 if !text_insert.is_empty() {
796 diffs.insert(pointer, Diff::Insert(text_insert));
797 pointer += 1;
798 }
799 } else if pointer > 0 {
800 if let Some(Diff::Equal(prev_equal1, prev_equal2)) =
801 diffs.get_mut(pointer - 1)
802 {
803 // Merge this equality with the previous one.
804 prev_equal1.len += text.len;
805 prev_equal2.len += text.len;
806 diffs.remove(pointer);
807 pointer -= 1;
808 }
809 }
810 count_insert = 0;
811 count_delete = 0;
812 text_delete = Range::empty();
813 text_insert = Range::empty();
814 }
815 }
816 pointer += 1;
817 }
818 if diffs.last().unwrap().text().is_empty() {
819 diffs.pop(); // Remove the dummy entry at the end.
820 }
821
822 // Second pass: look for single edits surrounded on both sides by equalities
823 // which can be shifted sideways to eliminate an equality.
824 // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
825 let mut changes = false;
826 let mut pointer = 1;
827 // Intentionally ignore the first and last element (don't need checking).
828 while let Some(&next_diff) = diffs.get(pointer + 1) {
829 let prev_diff = diffs[pointer - 1];
830 let this_diff = diffs[pointer];
831 if let (Diff::Equal(prev_diff, _), Diff::Equal(next_diff, _)) = (prev_diff, next_diff) {
832 // This is a single edit surrounded by equalities.
833 if this_diff.text().ends_with(prev_diff) {
834 // Shift the edit over the previous equality.
835 diffs[pointer].shift_left(prev_diff.len);
836 diffs[pointer + 1].grow_left(prev_diff.len);
837 diffs.remove(pointer - 1); // Delete prev_diff.
838 changes = true;
839 } else if this_diff.text().starts_with(next_diff) {
840 // Shift the edit over the next equality.
841 diffs[pointer - 1].grow_right(next_diff.len);
842 diffs[pointer].shift_right(next_diff.len);
843 diffs.remove(pointer + 1); // Delete next_diff.
844 changes = true;
845 }
846 }
847 pointer += 1;
848 }
849 // If shifts were made, the diff needs reordering and another shift sweep.
850 if !changes {
851 return;
852 }
853 }
854 }
855
856 impl Debug for Chunk<'_> {
857 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
858 let (name, text) = match *self {
859 Chunk::Equal(text) => ("Equal", text),
860 Chunk::Delete(text) => ("Delete", text),
861 Chunk::Insert(text) => ("Insert", text),
862 };
863 write!(formatter, "{}({:?})", name, text)
864 }
865 }
866
867 impl Debug for Diff<'_, '_> {
868 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
869 let (name, bytes) = match *self {
870 Diff::Equal(range, _) => ("Equal", bytes(range)),
871 Diff::Delete(range) => ("Delete", bytes(range)),
872 Diff::Insert(range) => ("Insert", bytes(range)),
873 };
874 let text = String::from_utf8_lossy(bytes);
875 write!(formatter, "{}({:?})", name, text)
876 }
877 }
878
879 impl<'a> From<Diff<'a, 'a>> for Chunk<'a> {
880 fn from(diff: Diff<'a, 'a>) -> Self {
881 match diff {
882 Diff::Equal(range, _) => Chunk::Equal(str(range)),
883 Diff::Delete(range) => Chunk::Delete(str(range)),
884 Diff::Insert(range) => Chunk::Insert(str(range)),
885 }
886 }
887 }