Skip to content

Commit 4e8f9d6

Browse files
committed
Fix string pair edits algorithm
1 parent 6939c28 commit 4e8f9d6

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

src/edits.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::cmp::max;
1+
use std::cmp::{max, min};
22

33
use syntect::highlighting::StyleModifier;
44

@@ -48,7 +48,6 @@ pub fn get_diff_style_sections(
4848

4949
for (minus, plus) in minus_lines.iter().zip(plus_lines.iter()) {
5050
let string_pair = StringPair::new(minus, plus);
51-
let change_begin = string_pair.common_prefix_length;
5251

5352
// We require that (right-trimmed length) >= (common prefix length). Consider:
5453
// minus = "a "
@@ -58,17 +57,18 @@ pub fn get_diff_style_sections(
5857
let minus_length = max(string_pair.lengths[0], string_pair.common_prefix_length);
5958
let plus_length = max(string_pair.lengths[1], string_pair.common_prefix_length);
6059

61-
// We require that change_begin <= change_end. Consider:
62-
// minus = "a c"
63-
// plus = "a b c"
64-
// Here, the common prefix length is 2, and the common suffix length is 2, yet the
65-
// length of minus is 3. This overlap between prefix and suffix leads to a violation of
66-
// the requirement. We resolve this by taking the following maxima:
67-
let minus_change_end = max(
68-
minus_length - string_pair.common_suffix_length,
69-
change_begin,
60+
// Work backwards from the end of the strings. The end of the
61+
// change region is equal to the start of their common
62+
// suffix. To find the start of the change region, start with
63+
// the end of their common prefix, and then move leftwards
64+
// until it is before the start of the common suffix in both
65+
// strings.
66+
let minus_change_end = minus_length - string_pair.common_suffix_length;
67+
let plus_change_end = plus_length - string_pair.common_suffix_length;
68+
let change_begin = min(
69+
string_pair.common_prefix_length,
70+
min(minus_change_end, plus_change_end),
7071
);
71-
let plus_change_end = max(plus_length - string_pair.common_suffix_length, change_begin);
7272

7373
minus_line_sections.push(vec![
7474
(minus_style_modifier, minus[0..change_begin].to_string()),

0 commit comments

Comments
 (0)