Skip to main content

fontoxide_diff/
difflib.rs

1//! The part of Python's `difflib` (CPython 3.13) that `fontTools.diff` uses:
2//! `SequenceMatcher` without a junk function, with its "popular elements"
3//! heuristic (`autojunk`), and `unified_diff`.
4
5use std::collections::HashMap;
6use std::hash::Hash;
7
8/// An operation turning a range of `a` into a range of `b` (`get_opcodes`).
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Tag {
11	/// `replace`: `a[i1:i2]` is replaced by `b[j1:j2]`.
12	Replace,
13	/// `delete`: `a[i1:i2]` is deleted.
14	Delete,
15	/// `insert`: `b[j1:j2]` is inserted at `a[i1:i1]`.
16	Insert,
17	/// `equal`: `a[i1:i2] == b[j1:j2]`.
18	Equal,
19}
20
21/// An opcode: the tag and the ranges `(i1, i2, j1, j2)`. The ranges are signed:
22/// with a negative number of context lines, `get_grouped_opcodes` makes
23/// ranges that Python slices as it does negative indices.
24pub type Opcode = (Tag, i128, i128, i128, i128);
25
26/// `SequenceMatcher(None, a, b, autojunk)`: finds the longest matching blocks
27/// of two sequences, recursively.
28#[derive(Debug)]
29pub struct SequenceMatcher<'a, T: Eq + Hash> {
30	a: &'a [T],
31	b: &'a [T],
32	/// The indices in `b` of each element, without the popular ones (`b2j`).
33	b2j: HashMap<&'a T, Vec<usize>>,
34}
35
36/// A matching block: `a[a..a + size] == b[b..b + size]` (`Match`).
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
38pub struct Match {
39	/// The start in `a`.
40	pub a: usize,
41	/// The start in `b`.
42	pub b: usize,
43	/// The length.
44	pub size: usize,
45}
46
47impl<'a, T: Eq + Hash> SequenceMatcher<'a, T> {
48	/// `SequenceMatcher(None, a, b, autojunk=autojunk)`.
49	pub fn new(a: &'a [T], b: &'a [T], autojunk: bool) -> Self {
50		// `__chain_b`.
51		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		// Purge popular elements that are not junk.
56		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	/// `find_longest_match(alo, ahi, blo, bhi)`: the longest matching block in
65	/// `a[alo..ahi]` and `b[blo..bhi]`, the earliest in `a`, then in `b`; then
66	/// extended by the popular elements around it.
67	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		// j2len[j] = length of longest match ending with a[i-1] and b[j].
71		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					// a[i] matches b[j]
78					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		// Extend the best by non-junk elements on each end; without a junk
102		// function, nothing is junk.
103		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	/// `get_matching_blocks`: the matching blocks, increasing in `a` and `b`,
122	/// adjacent ones collapsed, ending with `(len(a), len(b), 0)`.
123	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		// Collapse adjacent blocks.
143		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	/// `get_opcodes`: how to turn `a` into `b`.
175	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	/// `get_grouped_opcodes(n)`: the groups of changes with `n` lines of
201	/// context.
202	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		// Fixup leading and trailing groups if they show no changes.
208		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			// End the current group and start a new one whenever there is a
226			// large range with no changes.
227			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
242/// `seq[start:stop]` with Python's slicing of negative and out-of-range
243/// indices.
244fn 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
258/// `_format_range_unified`: a range in the "ed" format.
259fn format_range_unified(start: i128, stop: i128) -> String {
260	let mut beginning = start + 1; // lines start numbering with one
261	let length = stop - start;
262	if length == 1 {
263		return beginning.to_string();
264	}
265	if length == 0 {
266		beginning -= 1; // empty ranges begin at line just before the range
267	}
268	format!("{beginning},{length}")
269}
270
271/// `unified_diff(a, b, fromfile, tofile, fromfiledate, tofiledate, n,
272/// lineterm)`: the lines of the unified diff of two sequences of lines, with
273/// `n` lines of context.
274#[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	//! The doctests of `difflib.SequenceMatcher`.
326
327	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()); // Make an insertion
387		b[20] += "x"; // Make a replacement
388		b.drain(23..28); // Make a deletion
389		b[30] += "y"; // Make another replacement
390		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		// Identical sequences have no diff, except with a negative context.
444		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}