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