1use std::collections::HashMap;
6use std::hash::Hash;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Tag {
11 Replace,
13 Delete,
15 Insert,
17 Equal,
19}
20
21pub type Opcode = (Tag, i128, i128, i128, i128);
25
26#[derive(Debug)]
29pub struct SequenceMatcher<'a, T: Eq + Hash> {
30 a: &'a [T],
31 b: &'a [T],
32 b2j: HashMap<&'a T, Vec<usize>>,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
38pub struct Match {
39 pub a: usize,
41 pub b: usize,
43 pub size: usize,
45}
46
47impl<'a, T: Eq + Hash> SequenceMatcher<'a, T> {
48 pub fn new(a: &'a [T], b: &'a [T], autojunk: bool) -> Self {
50 let mut b2j: HashMap<&'a T, Vec<usize>> = HashMap::new();
52 for (i, elt) in b.iter().enumerate() {
53 b2j.entry(elt).or_default().push(i);
54 }
55 let n = b.len();
57 if autojunk && n >= 200 {
58 let ntest = n / 100 + 1;
59 b2j.retain(|_, idxs| idxs.len() <= ntest);
60 }
61 SequenceMatcher { a, b, b2j }
62 }
63
64 pub fn find_longest_match(&self, alo: usize, ahi: usize, blo: usize, bhi: usize) -> Match {
68 let (a, b) = (self.a, self.b);
69 let (mut besti, mut bestj, mut bestsize) = (alo, blo, 0);
70 let mut j2len: HashMap<usize, usize> = HashMap::new();
72 let mut newj2len: HashMap<usize, usize> = HashMap::new();
73 for (i, ai) in a.iter().enumerate().take(ahi).skip(alo) {
74 newj2len.clear();
75 if let Some(indices) = self.b2j.get(ai) {
76 for &j in indices {
77 if j < blo {
79 continue;
80 }
81 if j >= bhi {
82 break;
83 }
84 let k = j
85 .checked_sub(1)
86 .and_then(|p| j2len.get(&p))
87 .copied()
88 .unwrap_or(0)
89 + 1;
90 newj2len.insert(j, k);
91 if k > bestsize {
92 besti = i + 1 - k;
93 bestj = j + 1 - k;
94 bestsize = k;
95 }
96 }
97 }
98 std::mem::swap(&mut j2len, &mut newj2len);
99 }
100
101 while besti > alo && bestj > blo && a[besti - 1] == b[bestj - 1] {
104 besti -= 1;
105 bestj -= 1;
106 bestsize += 1;
107 }
108 while besti + bestsize < ahi
109 && bestj + bestsize < bhi
110 && a[besti + bestsize] == b[bestj + bestsize]
111 {
112 bestsize += 1;
113 }
114 Match {
115 a: besti,
116 b: bestj,
117 size: bestsize,
118 }
119 }
120
121 pub fn get_matching_blocks(&self) -> Vec<Match> {
124 let (la, lb) = (self.a.len(), self.b.len());
125 let mut queue = vec![(0, la, 0, lb)];
126 let mut matching_blocks = Vec::new();
127 while let Some((alo, ahi, blo, bhi)) = queue.pop() {
128 let x = self.find_longest_match(alo, ahi, blo, bhi);
129 let (i, j, k) = (x.a, x.b, x.size);
130 if k > 0 {
131 matching_blocks.push(x);
132 if alo < i && blo < j {
133 queue.push((alo, i, blo, j));
134 }
135 if i + k < ahi && j + k < bhi {
136 queue.push((i + k, ahi, j + k, bhi));
137 }
138 }
139 }
140 matching_blocks.sort();
141
142 let (mut i1, mut j1, mut k1) = (0, 0, 0);
144 let mut non_adjacent = Vec::new();
145 for m in matching_blocks {
146 if i1 + k1 == m.a && j1 + k1 == m.b {
147 k1 += m.size;
148 } else {
149 if k1 > 0 {
150 non_adjacent.push(Match {
151 a: i1,
152 b: j1,
153 size: k1,
154 });
155 }
156 (i1, j1, k1) = (m.a, m.b, m.size);
157 }
158 }
159 if k1 > 0 {
160 non_adjacent.push(Match {
161 a: i1,
162 b: j1,
163 size: k1,
164 });
165 }
166 non_adjacent.push(Match {
167 a: la,
168 b: lb,
169 size: 0,
170 });
171 non_adjacent
172 }
173
174 pub fn get_opcodes(&self) -> Vec<Opcode> {
176 let (mut i, mut j) = (0, 0);
177 let mut answer = Vec::new();
178 for m in self.get_matching_blocks() {
179 let (ai, bj, size) = (m.a, m.b, m.size);
180 let tag = if i < ai && j < bj {
181 Some(Tag::Replace)
182 } else if i < ai {
183 Some(Tag::Delete)
184 } else if j < bj {
185 Some(Tag::Insert)
186 } else {
187 None
188 };
189 if let Some(tag) = tag {
190 answer.push((tag, i as i128, ai as i128, j as i128, bj as i128));
191 }
192 (i, j) = (ai + size, bj + size);
193 if size > 0 {
194 answer.push((Tag::Equal, ai as i128, i as i128, bj as i128, j as i128));
195 }
196 }
197 answer
198 }
199
200 pub fn get_grouped_opcodes(&self, n: i128) -> Vec<Vec<Opcode>> {
203 let mut codes = self.get_opcodes();
204 if codes.is_empty() {
205 codes.push((Tag::Equal, 0, 1, 0, 1));
206 }
207 if let Some(first) = codes.first_mut()
209 && first.0 == Tag::Equal
210 {
211 let (tag, i1, i2, j1, j2) = *first;
212 *first = (tag, i1.max(i2 - n), i2, j1.max(j2 - n), j2);
213 }
214 if let Some(last) = codes.last_mut()
215 && last.0 == Tag::Equal
216 {
217 let (tag, i1, i2, j1, j2) = *last;
218 *last = (tag, i1, i2.min(i1 + n), j1, j2.min(j1 + n));
219 }
220
221 let nn = n + n;
222 let mut groups = Vec::new();
223 let mut group = Vec::new();
224 for (tag, mut i1, i2, mut j1, j2) in codes {
225 if tag == Tag::Equal && i2 - i1 > nn {
228 group.push((tag, i1, i2.min(i1 + n), j1, j2.min(j1 + n)));
229 groups.push(std::mem::take(&mut group));
230 i1 = i1.max(i2 - n);
231 j1 = j1.max(j2 - n);
232 }
233 group.push((tag, i1, i2, j1, j2));
234 }
235 if !group.is_empty() && !(group.len() == 1 && group[0].0 == Tag::Equal) {
236 groups.push(group);
237 }
238 groups
239 }
240}
241
242fn py_slice<T>(seq: &[T], start: i128, stop: i128) -> &[T] {
245 let len = seq.len() as i128;
246 let clamp = |i: i128| {
247 let i = if i < 0 { i + len } else { i };
248 i.clamp(0, len) as usize
249 };
250 let (start, stop) = (clamp(start), clamp(stop));
251 if stop <= start {
252 &[]
253 } else {
254 &seq[start..stop]
255 }
256}
257
258fn format_range_unified(start: i128, stop: i128) -> String {
260 let mut beginning = start + 1; let length = stop - start;
262 if length == 1 {
263 return beginning.to_string();
264 }
265 if length == 0 {
266 beginning -= 1; }
268 format!("{beginning},{length}")
269}
270
271#[allow(clippy::too_many_arguments)]
275pub fn unified_diff(
276 a: &[&str],
277 b: &[&str],
278 fromfile: &str,
279 tofile: &str,
280 fromfiledate: &str,
281 tofiledate: &str,
282 n: i128,
283 lineterm: &str,
284) -> Vec<String> {
285 let mut lines = Vec::new();
286 let mut started = false;
287 for group in SequenceMatcher::new(a, b, true).get_grouped_opcodes(n) {
288 if !started {
289 started = true;
290 let date = |d: &str| {
291 if d.is_empty() {
292 String::new()
293 } else {
294 format!("\t{d}")
295 }
296 };
297 lines.push(format!("--- {fromfile}{}{lineterm}", date(fromfiledate)));
298 lines.push(format!("+++ {tofile}{}{lineterm}", date(tofiledate)));
299 }
300 let (Some(first), Some(last)) = (group.first(), group.last()) else {
301 continue;
302 };
303 let file1_range = format_range_unified(first.1, last.2);
304 let file2_range = format_range_unified(first.3, last.4);
305 lines.push(format!("@@ -{file1_range} +{file2_range} @@{lineterm}"));
306
307 for &(tag, i1, i2, j1, j2) in &group {
308 if tag == Tag::Equal {
309 lines.extend(py_slice(a, i1, i2).iter().map(|line| format!(" {line}")));
310 continue;
311 }
312 if matches!(tag, Tag::Replace | Tag::Delete) {
313 lines.extend(py_slice(a, i1, i2).iter().map(|line| format!("-{line}")));
314 }
315 if matches!(tag, Tag::Replace | Tag::Insert) {
316 lines.extend(py_slice(b, j1, j2).iter().map(|line| format!("+{line}")));
317 }
318 }
319 }
320 lines
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
328
329 fn chars(s: &str) -> Vec<char> {
330 s.chars().collect()
331 }
332
333 #[test]
334 fn longest_match() {
335 let (a, b) = (chars(" abcd"), chars("abcd abcd"));
336 let s = SequenceMatcher::new(&a, &b, true);
337 assert_eq!(
338 s.find_longest_match(0, 5, 0, 9),
339 Match {
340 a: 0,
341 b: 4,
342 size: 5
343 }
344 );
345 let (a, b) = (chars("ab"), chars("c"));
346 let s = SequenceMatcher::new(&a, &b, true);
347 assert_eq!(
348 s.find_longest_match(0, 2, 0, 1),
349 Match {
350 a: 0,
351 b: 0,
352 size: 0
353 }
354 );
355 }
356
357 #[test]
358 fn matching_blocks_and_opcodes() {
359 let (a, b) = (chars("abxcd"), chars("abcd"));
360 let s = SequenceMatcher::new(&a, &b, true);
361 let blocks: Vec<_> = s
362 .get_matching_blocks()
363 .iter()
364 .map(|m| (m.a, m.b, m.size))
365 .collect();
366 assert_eq!(blocks, [(0, 0, 2), (3, 2, 2), (5, 4, 0)]);
367
368 let (a, b) = (chars("qabxcd"), chars("abycdf"));
369 let s = SequenceMatcher::new(&a, &b, true);
370 assert_eq!(
371 s.get_opcodes(),
372 [
373 (Tag::Delete, 0, 1, 0, 0),
374 (Tag::Equal, 1, 3, 0, 2),
375 (Tag::Replace, 3, 4, 2, 3),
376 (Tag::Equal, 4, 6, 3, 5),
377 (Tag::Insert, 6, 6, 5, 6),
378 ]
379 );
380 }
381
382 #[test]
383 fn grouped_opcodes() {
384 let a: Vec<String> = (1..40).map(|i| i.to_string()).collect();
385 let mut b = a.clone();
386 b.insert(8, "i".into()); b[20] += "x"; b.drain(23..28); b[30] += "y"; let s = SequenceMatcher::new(&a, &b, true);
391 use Tag::*;
392 assert_eq!(
393 s.get_grouped_opcodes(3),
394 [
395 vec![
396 (Equal, 5, 8, 5, 8),
397 (Insert, 8, 8, 8, 9),
398 (Equal, 8, 11, 9, 12)
399 ],
400 vec![
401 (Equal, 16, 19, 17, 20),
402 (Replace, 19, 20, 20, 21),
403 (Equal, 20, 22, 21, 23),
404 (Delete, 22, 27, 23, 23),
405 (Equal, 27, 30, 23, 26)
406 ],
407 vec![
408 (Equal, 31, 34, 27, 30),
409 (Replace, 34, 35, 30, 31),
410 (Equal, 35, 38, 31, 34)
411 ],
412 ]
413 );
414 }
415
416 #[test]
417 fn unified() {
418 let a = ["one", "two", "three", "four"];
419 let b = ["zero", "one", "tree", "four"];
420 assert_eq!(
421 unified_diff(
422 &a,
423 &b,
424 "Original",
425 "Current",
426 "2005-01-26 23:30:50",
427 "2010-04-02 10:20:52",
428 3,
429 ""
430 ),
431 [
432 "--- Original\t2005-01-26 23:30:50",
433 "+++ Current\t2010-04-02 10:20:52",
434 "@@ -1,4 +1,4 @@",
435 "+zero",
436 " one",
437 "-two",
438 "-three",
439 "+tree",
440 " four"
441 ]
442 );
443 assert!(unified_diff(&a, &a, "a", "b", "", "", 3, "\n").is_empty());
445 assert_eq!(
446 unified_diff(&a, &a, "a", "b", "", "", -1, "\n"),
447 ["--- a\n", "+++ b\n", "@@ -6,-1 +6,-1 @@\n"]
448 );
449 }
450}