jj_lib/
diff.rs

1// Copyright 2021 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![expect(missing_docs)]
16
17use std::collections::BTreeMap;
18use std::hash::BuildHasher;
19use std::hash::Hash;
20use std::hash::Hasher;
21use std::hash::RandomState;
22use std::iter;
23use std::ops::Range;
24use std::slice;
25
26use bstr::BStr;
27use hashbrown::HashTable;
28use itertools::Itertools as _;
29use smallvec::SmallVec;
30use smallvec::smallvec;
31
32pub fn find_line_ranges(text: &[u8]) -> Vec<Range<usize>> {
33    text.split_inclusive(|b| *b == b'\n')
34        .scan(0, |total, line| {
35            let start = *total;
36            *total += line.len();
37            Some(start..*total)
38        })
39        .collect()
40}
41
42fn is_word_byte(b: u8) -> bool {
43    // TODO: Make this configurable (probably higher up in the call stack)
44    matches!(
45        b,
46        // Count 0x80..0xff as word bytes so multi-byte UTF-8 chars are
47        // treated as a single unit.
48        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'\x80'..=b'\xff'
49    )
50}
51
52pub fn find_word_ranges(text: &[u8]) -> Vec<Range<usize>> {
53    let mut word_ranges = vec![];
54    let mut word_start_pos = 0;
55    let mut in_word = false;
56    for (i, b) in text.iter().enumerate() {
57        if in_word && !is_word_byte(*b) {
58            in_word = false;
59            word_ranges.push(word_start_pos..i);
60            word_start_pos = i;
61        } else if !in_word && is_word_byte(*b) {
62            in_word = true;
63            word_start_pos = i;
64        }
65    }
66    if in_word && word_start_pos < text.len() {
67        word_ranges.push(word_start_pos..text.len());
68    }
69    word_ranges
70}
71
72pub fn find_nonword_ranges(text: &[u8]) -> Vec<Range<usize>> {
73    text.iter()
74        .positions(|b| !is_word_byte(*b))
75        .map(|i| i..i + 1)
76        .collect()
77}
78
79fn bytes_ignore_all_whitespace(text: &[u8]) -> impl Iterator<Item = u8> {
80    text.iter().copied().filter(|b| !b.is_ascii_whitespace())
81}
82
83fn bytes_ignore_whitespace_amount(text: &[u8]) -> impl Iterator<Item = u8> {
84    let mut prev_was_space = false;
85    text.iter().filter_map(move |&b| {
86        let was_space = prev_was_space;
87        let is_space = b.is_ascii_whitespace();
88        prev_was_space = is_space;
89        match (was_space, is_space) {
90            (_, false) => Some(b),
91            (false, true) => Some(b' '),
92            (true, true) => None,
93        }
94    })
95}
96
97fn hash_with_length_suffix<I, H>(data: I, state: &mut H)
98where
99    I: IntoIterator,
100    I::Item: Hash,
101    H: Hasher,
102{
103    let mut len: usize = 0;
104    for d in data {
105        d.hash(state);
106        len += 1;
107    }
108    state.write_usize(len);
109}
110
111/// Compares byte sequences based on a certain equivalence property.
112///
113/// This isn't a newtype `Wrapper<'a>(&'a [u8])` but an external comparison
114/// object for the following reasons:
115///
116/// a. If it were newtype, a generic `wrap` function would be needed. It
117///    couldn't be expressed as a simple closure:
118///    `for<'a> Fn(&'a [u8]) -> ???<'a>`
119/// b. Dynamic comparison object can be implemented intuitively. For example,
120///    `pattern: &Regex` would have to be copied to all newtype instances if it
121///    were newtype.
122/// c. Hash values can be cached if hashing is controlled externally.
123pub trait CompareBytes {
124    /// Returns true if `left` and `right` are equivalent.
125    fn eq(&self, left: &[u8], right: &[u8]) -> bool;
126
127    /// Generates hash which respects the following property:
128    /// `eq(left, right) => hash(left) == hash(right)`
129    fn hash<H: Hasher>(&self, text: &[u8], state: &mut H);
130}
131
132// An instance might have e.g. Regex pattern, which can't be trivially copied.
133// Such comparison object can be passed by reference.
134impl<C: CompareBytes + ?Sized> CompareBytes for &C {
135    fn eq(&self, left: &[u8], right: &[u8]) -> bool {
136        <C as CompareBytes>::eq(self, left, right)
137    }
138
139    fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
140        <C as CompareBytes>::hash(self, text, state);
141    }
142}
143
144/// Compares byte sequences literally.
145#[derive(Clone, Debug, Default)]
146pub struct CompareBytesExactly;
147
148impl CompareBytes for CompareBytesExactly {
149    fn eq(&self, left: &[u8], right: &[u8]) -> bool {
150        left == right
151    }
152
153    fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
154        text.hash(state);
155    }
156}
157
158/// Compares byte sequences ignoring any whitespace occurrences.
159#[derive(Clone, Debug, Default)]
160pub struct CompareBytesIgnoreAllWhitespace;
161
162impl CompareBytes for CompareBytesIgnoreAllWhitespace {
163    fn eq(&self, left: &[u8], right: &[u8]) -> bool {
164        bytes_ignore_all_whitespace(left).eq(bytes_ignore_all_whitespace(right))
165    }
166
167    fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
168        hash_with_length_suffix(bytes_ignore_all_whitespace(text), state);
169    }
170}
171
172/// Compares byte sequences ignoring changes in whitespace amount.
173#[derive(Clone, Debug, Default)]
174pub struct CompareBytesIgnoreWhitespaceAmount;
175
176impl CompareBytes for CompareBytesIgnoreWhitespaceAmount {
177    fn eq(&self, left: &[u8], right: &[u8]) -> bool {
178        bytes_ignore_whitespace_amount(left).eq(bytes_ignore_whitespace_amount(right))
179    }
180
181    fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
182        hash_with_length_suffix(bytes_ignore_whitespace_amount(text), state);
183    }
184}
185
186// Not implementing Eq because the text should be compared by WordComparator.
187#[derive(Clone, Copy, Debug)]
188struct HashedWord<'input> {
189    hash: u64,
190    text: &'input BStr,
191}
192
193/// Compares words (or tokens) under a certain hasher configuration.
194#[derive(Clone, Debug, Default)]
195struct WordComparator<C, S> {
196    compare: C,
197    hash_builder: S,
198}
199
200impl<C: CompareBytes> WordComparator<C, RandomState> {
201    fn new(compare: C) -> Self {
202        Self {
203            compare,
204            // TODO: switch to ahash for better performance?
205            hash_builder: RandomState::new(),
206        }
207    }
208}
209
210impl<C: CompareBytes, S: BuildHasher> WordComparator<C, S> {
211    fn eq(&self, left: &[u8], right: &[u8]) -> bool {
212        self.compare.eq(left, right)
213    }
214
215    fn eq_hashed(&self, left: HashedWord<'_>, right: HashedWord<'_>) -> bool {
216        left.hash == right.hash && self.compare.eq(left.text, right.text)
217    }
218
219    fn hash_one(&self, text: &[u8]) -> u64 {
220        let mut state = self.hash_builder.build_hasher();
221        self.compare.hash(text, &mut state);
222        state.finish()
223    }
224}
225
226/// Index in a list of word (or token) ranges in `DiffSource`.
227#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
228struct WordPosition(usize);
229
230/// Index in a list of word (or token) ranges in `LocalDiffSource`.
231#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
232struct LocalWordPosition(usize);
233
234#[derive(Clone, Debug)]
235struct DiffSource<'input, 'aux> {
236    text: &'input BStr,
237    ranges: &'aux [Range<usize>],
238    hashes: Vec<u64>,
239}
240
241impl<'input, 'aux> DiffSource<'input, 'aux> {
242    fn new<T: AsRef<[u8]> + ?Sized, C: CompareBytes, S: BuildHasher>(
243        text: &'input T,
244        ranges: &'aux [Range<usize>],
245        comp: &WordComparator<C, S>,
246    ) -> Self {
247        let text = BStr::new(text);
248        let hashes = ranges
249            .iter()
250            .map(|range| comp.hash_one(&text[range.clone()]))
251            .collect();
252        Self {
253            text,
254            ranges,
255            hashes,
256        }
257    }
258
259    fn local(&self) -> LocalDiffSource<'input, '_> {
260        LocalDiffSource {
261            text: self.text,
262            ranges: self.ranges,
263            hashes: &self.hashes,
264            global_offset: WordPosition(0),
265        }
266    }
267
268    fn range_at(&self, position: WordPosition) -> Range<usize> {
269        self.ranges[position.0].clone()
270    }
271}
272
273#[derive(Clone, Debug)]
274struct LocalDiffSource<'input, 'aux> {
275    text: &'input BStr,
276    ranges: &'aux [Range<usize>],
277    hashes: &'aux [u64],
278    /// The number of preceding word ranges excluded from the self `ranges`.
279    global_offset: WordPosition,
280}
281
282impl<'input> LocalDiffSource<'input, '_> {
283    fn narrowed(&self, positions: Range<LocalWordPosition>) -> Self {
284        Self {
285            text: self.text,
286            ranges: &self.ranges[positions.start.0..positions.end.0],
287            hashes: &self.hashes[positions.start.0..positions.end.0],
288            global_offset: self.map_to_global(positions.start),
289        }
290    }
291
292    fn map_to_global(&self, position: LocalWordPosition) -> WordPosition {
293        WordPosition(self.global_offset.0 + position.0)
294    }
295
296    fn hashed_words(
297        &self,
298    ) -> impl DoubleEndedIterator<Item = HashedWord<'input>> + ExactSizeIterator {
299        iter::zip(self.ranges, self.hashes).map(|(range, &hash)| {
300            let text = &self.text[range.clone()];
301            HashedWord { hash, text }
302        })
303    }
304}
305
306struct Histogram<'input> {
307    word_to_positions: HashTable<HistogramEntry<'input>>,
308}
309
310// Many of the words are unique. We can inline up to 2 word positions (16 bytes
311// on 64-bit platform) in SmallVec for free.
312type HistogramEntry<'input> = (HashedWord<'input>, SmallVec<[LocalWordPosition; 2]>);
313
314impl<'input> Histogram<'input> {
315    fn calculate<C: CompareBytes, S: BuildHasher>(
316        source: &LocalDiffSource<'input, '_>,
317        comp: &WordComparator<C, S>,
318        max_occurrences: usize,
319    ) -> Self {
320        let mut word_to_positions: HashTable<HistogramEntry> = HashTable::new();
321        for (i, word) in source.hashed_words().enumerate() {
322            let pos = LocalWordPosition(i);
323            word_to_positions
324                .entry(
325                    word.hash,
326                    |(w, _)| comp.eq(w.text, word.text),
327                    |(w, _)| w.hash,
328                )
329                .and_modify(|(_, positions)| {
330                    // Allow one more than max_occurrences, so we can later skip
331                    // those with more than max_occurrences
332                    if positions.len() <= max_occurrences {
333                        positions.push(pos);
334                    }
335                })
336                .or_insert_with(|| (word, smallvec![pos]));
337        }
338        Self { word_to_positions }
339    }
340
341    fn build_count_to_entries(&self) -> BTreeMap<usize, Vec<&HistogramEntry<'input>>> {
342        let mut count_to_entries: BTreeMap<usize, Vec<_>> = BTreeMap::new();
343        for entry in &self.word_to_positions {
344            let (_, positions) = entry;
345            let entries = count_to_entries.entry(positions.len()).or_default();
346            entries.push(entry);
347        }
348        count_to_entries
349    }
350
351    fn positions_by_word<C: CompareBytes, S: BuildHasher>(
352        &self,
353        word: HashedWord<'input>,
354        comp: &WordComparator<C, S>,
355    ) -> Option<&[LocalWordPosition]> {
356        let (_, positions) = self
357            .word_to_positions
358            .find(word.hash, |(w, _)| comp.eq(w.text, word.text))?;
359        Some(positions)
360    }
361}
362
363/// Finds the LCS given a array where the value of `input[i]` indicates that
364/// the position of element `i` in the right array is at position `input[i]` in
365/// the left array.
366///
367/// For example (some have multiple valid outputs):
368///
369/// [0,1,2] => [(0,0),(1,1),(2,2)]
370/// [2,1,0] => [(0,2)]
371/// [0,1,4,2,3,5,6] => [(0,0),(1,1),(2,3),(3,4),(5,5),(6,6)]
372/// [0,1,4,3,2,5,6] => [(0,0),(1,1),(4,2),(5,5),(6,6)]
373fn find_lcs(input: &[usize]) -> Vec<(usize, usize)> {
374    if input.is_empty() {
375        return vec![];
376    }
377
378    let mut chain = vec![(0, 0, 0); input.len()];
379    let mut global_longest = 0;
380    let mut global_longest_right_pos = 0;
381    for (right_pos, &left_pos) in input.iter().enumerate() {
382        let mut longest_from_here = 1;
383        let mut previous_right_pos = usize::MAX;
384        for i in (0..right_pos).rev() {
385            let (previous_len, previous_left_pos, _) = chain[i];
386            if previous_left_pos < left_pos {
387                let len = previous_len + 1;
388                if len > longest_from_here {
389                    longest_from_here = len;
390                    previous_right_pos = i;
391                    if len > global_longest {
392                        global_longest = len;
393                        global_longest_right_pos = right_pos;
394                        // If this is the longest chain globally so far, we cannot find a
395                        // longer one by using a previous value, so break early.
396                        break;
397                    }
398                }
399            }
400        }
401        chain[right_pos] = (longest_from_here, left_pos, previous_right_pos);
402    }
403
404    let mut result = vec![];
405    let mut right_pos = global_longest_right_pos;
406    loop {
407        let (_, left_pos, previous_right_pos) = chain[right_pos];
408        result.push((left_pos, right_pos));
409        if previous_right_pos == usize::MAX {
410            break;
411        }
412        right_pos = previous_right_pos;
413    }
414    result.reverse();
415
416    result
417}
418
419/// Finds unchanged word (or token) positions among the ones given as
420/// arguments. The data between those words is ignored.
421fn collect_unchanged_words<C: CompareBytes, S: BuildHasher>(
422    found_positions: &mut Vec<(WordPosition, WordPosition)>,
423    left: &LocalDiffSource,
424    right: &LocalDiffSource,
425    comp: &WordComparator<C, S>,
426) {
427    if left.ranges.is_empty() || right.ranges.is_empty() {
428        return;
429    }
430
431    // Prioritize LCS-based algorithm than leading/trailing matches
432    let old_len = found_positions.len();
433    collect_unchanged_words_lcs(found_positions, left, right, comp);
434    if found_positions.len() != old_len {
435        return;
436    }
437
438    // Trim leading common ranges (i.e. grow previous unchanged region)
439    let common_leading_len = iter::zip(left.hashed_words(), right.hashed_words())
440        .take_while(|&(l, r)| comp.eq_hashed(l, r))
441        .count();
442    let left_hashed_words = left.hashed_words().skip(common_leading_len);
443    let right_hashed_words = right.hashed_words().skip(common_leading_len);
444
445    // Trim trailing common ranges (i.e. grow next unchanged region)
446    let common_trailing_len = iter::zip(left_hashed_words.rev(), right_hashed_words.rev())
447        .take_while(|&(l, r)| comp.eq_hashed(l, r))
448        .count();
449
450    found_positions.extend(itertools::chain(
451        (0..common_leading_len).map(|i| {
452            (
453                left.map_to_global(LocalWordPosition(i)),
454                right.map_to_global(LocalWordPosition(i)),
455            )
456        }),
457        (1..=common_trailing_len).rev().map(|i| {
458            (
459                left.map_to_global(LocalWordPosition(left.ranges.len() - i)),
460                right.map_to_global(LocalWordPosition(right.ranges.len() - i)),
461            )
462        }),
463    ));
464}
465
466fn collect_unchanged_words_lcs<C: CompareBytes, S: BuildHasher>(
467    found_positions: &mut Vec<(WordPosition, WordPosition)>,
468    left: &LocalDiffSource,
469    right: &LocalDiffSource,
470    comp: &WordComparator<C, S>,
471) {
472    let max_occurrences = 100;
473    let left_histogram = Histogram::calculate(left, comp, max_occurrences);
474    let left_count_to_entries = left_histogram.build_count_to_entries();
475    if *left_count_to_entries.keys().next().unwrap() > max_occurrences {
476        // If there are very many occurrences of all words, then we just give up.
477        return;
478    }
479    let right_histogram = Histogram::calculate(right, comp, max_occurrences);
480    // Look for words with few occurrences in `left` (could equally well have picked
481    // `right`?). If any of them also occur in `right`, then we add the words to
482    // the LCS.
483    let Some(uncommon_shared_word_positions) =
484        left_count_to_entries.values().find_map(|left_entries| {
485            let mut both_positions = left_entries
486                .iter()
487                .filter_map(|&(word, left_positions)| {
488                    let right_positions = right_histogram.positions_by_word(*word, comp)?;
489                    (left_positions.len() == right_positions.len())
490                        .then_some((left_positions, right_positions))
491                })
492                .peekable();
493            both_positions.peek().is_some().then_some(both_positions)
494        })
495    else {
496        return;
497    };
498
499    // [(index into ranges, serial to identify {word, occurrence #})]
500    let (mut left_positions, mut right_positions): (Vec<_>, Vec<_>) =
501        uncommon_shared_word_positions
502            .flat_map(|(lefts, rights)| iter::zip(lefts, rights))
503            .enumerate()
504            .map(|(serial, (&left_pos, &right_pos))| ((left_pos, serial), (right_pos, serial)))
505            .unzip();
506    left_positions.sort_unstable_by_key(|&(pos, _serial)| pos);
507    right_positions.sort_unstable_by_key(|&(pos, _serial)| pos);
508    let left_index_by_right_index: Vec<usize> = {
509        let mut left_index_map = vec![0; left_positions.len()];
510        for (i, &(_pos, serial)) in left_positions.iter().enumerate() {
511            left_index_map[serial] = i;
512        }
513        right_positions
514            .iter()
515            .map(|&(_pos, serial)| left_index_map[serial])
516            .collect()
517    };
518
519    let lcs = find_lcs(&left_index_by_right_index);
520
521    // Produce output word positions, recursing into the modified areas between
522    // the elements in the LCS.
523    let mut previous_left_position = LocalWordPosition(0);
524    let mut previous_right_position = LocalWordPosition(0);
525    for (left_index, right_index) in lcs {
526        let (left_position, _) = left_positions[left_index];
527        let (right_position, _) = right_positions[right_index];
528        collect_unchanged_words(
529            found_positions,
530            &left.narrowed(previous_left_position..left_position),
531            &right.narrowed(previous_right_position..right_position),
532            comp,
533        );
534        found_positions.push((
535            left.map_to_global(left_position),
536            right.map_to_global(right_position),
537        ));
538        previous_left_position = LocalWordPosition(left_position.0 + 1);
539        previous_right_position = LocalWordPosition(right_position.0 + 1);
540    }
541    // Also recurse into range at end (after common ranges).
542    collect_unchanged_words(
543        found_positions,
544        &left.narrowed(previous_left_position..LocalWordPosition(left.ranges.len())),
545        &right.narrowed(previous_right_position..LocalWordPosition(right.ranges.len())),
546        comp,
547    );
548}
549
550/// Intersects two sorted sequences of `(base, other)` word positions by
551/// `base`. `base` positions should refer to the same source text.
552fn intersect_unchanged_words(
553    current_positions: Vec<(WordPosition, Vec<WordPosition>)>,
554    new_positions: &[(WordPosition, WordPosition)],
555) -> Vec<(WordPosition, Vec<WordPosition>)> {
556    itertools::merge_join_by(
557        current_positions,
558        new_positions,
559        |(cur_base_pos, _), (new_base_pos, _)| cur_base_pos.cmp(new_base_pos),
560    )
561    .filter_map(|entry| entry.both())
562    .map(|((base_pos, mut other_positions), &(_, new_other_pos))| {
563        other_positions.push(new_other_pos);
564        (base_pos, other_positions)
565    })
566    .collect()
567}
568
569#[derive(Clone, PartialEq, Eq, Debug)]
570struct UnchangedRange {
571    // Inline up to two sides (base + one other)
572    base: Range<usize>,
573    others: SmallVec<[Range<usize>; 1]>,
574}
575
576impl UnchangedRange {
577    /// Translates word positions to byte ranges in the source texts.
578    fn from_word_positions(
579        base_source: &DiffSource,
580        other_sources: &[DiffSource],
581        base_position: WordPosition,
582        other_positions: &[WordPosition],
583    ) -> Self {
584        assert_eq!(other_sources.len(), other_positions.len());
585        let base = base_source.range_at(base_position);
586        let others = iter::zip(other_sources, other_positions)
587            .map(|(source, pos)| source.range_at(*pos))
588            .collect();
589        Self { base, others }
590    }
591
592    fn is_all_empty(&self) -> bool {
593        self.base.is_empty() && self.others.iter().all(|r| r.is_empty())
594    }
595}
596
597/// Takes any number of inputs and finds regions that are them same between all
598/// of them.
599#[derive(Clone, Debug)]
600pub struct ContentDiff<'input> {
601    base_input: &'input BStr,
602    other_inputs: SmallVec<[&'input BStr; 1]>,
603    /// Sorted list of ranges of unchanged regions in bytes.
604    ///
605    /// The list should never be empty. The first and the last region may be
606    /// empty if inputs start/end with changes.
607    unchanged_regions: Vec<UnchangedRange>,
608}
609
610impl<'input> ContentDiff<'input> {
611    pub fn for_tokenizer<T: AsRef<[u8]> + ?Sized + 'input>(
612        inputs: impl IntoIterator<Item = &'input T>,
613        tokenizer: impl Fn(&[u8]) -> Vec<Range<usize>>,
614        compare: impl CompareBytes,
615    ) -> Self {
616        let mut inputs = inputs.into_iter().map(BStr::new);
617        let base_input = inputs.next().expect("inputs must not be empty");
618        let other_inputs: SmallVec<[&BStr; 1]> = inputs.collect();
619        // First tokenize each input
620        let base_token_ranges: Vec<Range<usize>>;
621        let other_token_ranges: Vec<Vec<Range<usize>>>;
622        // No need to tokenize if one of the inputs is empty. Non-empty inputs
623        // are all different as long as the tokenizer emits non-empty ranges.
624        // This means "" and " " are different even if the compare function is
625        // ignore-whitespace. They are tokenized as [] and [" "] respectively.
626        if base_input.is_empty() || other_inputs.iter().any(|input| input.is_empty()) {
627            base_token_ranges = vec![];
628            other_token_ranges = std::iter::repeat_n(vec![], other_inputs.len()).collect();
629        } else {
630            base_token_ranges = tokenizer(base_input);
631            other_token_ranges = other_inputs
632                .iter()
633                .map(|other_input| tokenizer(other_input))
634                .collect();
635        }
636        Self::with_inputs_and_token_ranges(
637            base_input,
638            other_inputs,
639            &base_token_ranges,
640            &other_token_ranges,
641            compare,
642        )
643    }
644
645    fn with_inputs_and_token_ranges(
646        base_input: &'input BStr,
647        other_inputs: SmallVec<[&'input BStr; 1]>,
648        base_token_ranges: &[Range<usize>],
649        other_token_ranges: &[Vec<Range<usize>>],
650        compare: impl CompareBytes,
651    ) -> Self {
652        assert_eq!(other_inputs.len(), other_token_ranges.len());
653        let comp = WordComparator::new(compare);
654        let base_source = DiffSource::new(base_input, base_token_ranges, &comp);
655        let other_sources = iter::zip(&other_inputs, other_token_ranges)
656            .map(|(input, token_ranges)| DiffSource::new(input, token_ranges, &comp))
657            .collect_vec();
658        let unchanged_regions = match &*other_sources {
659            // Consider the whole range of the base input as unchanged compared
660            // to itself.
661            [] => {
662                let whole_range = UnchangedRange {
663                    base: 0..base_source.text.len(),
664                    others: smallvec![],
665                };
666                vec![whole_range]
667            }
668            // Diff each other input against the base. Intersect the previously
669            // found ranges with the ranges in the diff.
670            [first_other_source, tail_other_sources @ ..] => {
671                let mut unchanged_regions = Vec::new();
672                // Add an empty range at the start to make life easier for hunks().
673                unchanged_regions.push(UnchangedRange {
674                    base: 0..0,
675                    others: smallvec![0..0; other_inputs.len()],
676                });
677                let mut first_positions = Vec::new();
678                collect_unchanged_words(
679                    &mut first_positions,
680                    &base_source.local(),
681                    &first_other_source.local(),
682                    &comp,
683                );
684                if tail_other_sources.is_empty() {
685                    unchanged_regions.extend(first_positions.iter().map(
686                        |&(base_pos, other_pos)| {
687                            UnchangedRange::from_word_positions(
688                                &base_source,
689                                &other_sources,
690                                base_pos,
691                                &[other_pos],
692                            )
693                        },
694                    ));
695                } else {
696                    let first_positions = first_positions
697                        .iter()
698                        .map(|&(base_pos, other_pos)| (base_pos, vec![other_pos]))
699                        .collect();
700                    let intersected_positions = tail_other_sources.iter().fold(
701                        first_positions,
702                        |current_positions, other_source| {
703                            let mut new_positions = Vec::new();
704                            collect_unchanged_words(
705                                &mut new_positions,
706                                &base_source.local(),
707                                &other_source.local(),
708                                &comp,
709                            );
710                            intersect_unchanged_words(current_positions, &new_positions)
711                        },
712                    );
713                    unchanged_regions.extend(intersected_positions.iter().map(
714                        |(base_pos, other_positions)| {
715                            UnchangedRange::from_word_positions(
716                                &base_source,
717                                &other_sources,
718                                *base_pos,
719                                other_positions,
720                            )
721                        },
722                    ));
723                };
724                // Add an empty range at the end to make life easier for hunks().
725                unchanged_regions.push(UnchangedRange {
726                    base: base_input.len()..base_input.len(),
727                    others: other_inputs
728                        .iter()
729                        .map(|input| input.len()..input.len())
730                        .collect(),
731                });
732                unchanged_regions
733            }
734        };
735
736        let mut diff = Self {
737            base_input,
738            other_inputs,
739            unchanged_regions,
740        };
741        diff.compact_unchanged_regions();
742        diff
743    }
744
745    pub fn unrefined<T: AsRef<[u8]> + ?Sized + 'input>(
746        inputs: impl IntoIterator<Item = &'input T>,
747    ) -> Self {
748        ContentDiff::for_tokenizer(inputs, |_| vec![], CompareBytesExactly)
749    }
750
751    /// Compares `inputs` line by line.
752    pub fn by_line<T: AsRef<[u8]> + ?Sized + 'input>(
753        inputs: impl IntoIterator<Item = &'input T>,
754    ) -> Self {
755        ContentDiff::for_tokenizer(inputs, find_line_ranges, CompareBytesExactly)
756    }
757
758    /// Compares `inputs` word by word.
759    ///
760    /// The `inputs` is usually a changed hunk (e.g. a `DiffHunk::Different`)
761    /// that was the output from a line-by-line diff.
762    pub fn by_word<T: AsRef<[u8]> + ?Sized + 'input>(
763        inputs: impl IntoIterator<Item = &'input T>,
764    ) -> Self {
765        let mut diff = ContentDiff::for_tokenizer(inputs, find_word_ranges, CompareBytesExactly);
766        diff.refine_changed_regions(find_nonword_ranges, CompareBytesExactly);
767        diff
768    }
769
770    /// Returns iterator over matching and different texts.
771    pub fn hunks(&self) -> DiffHunkIterator<'_, 'input> {
772        let ranges = self.hunk_ranges();
773        DiffHunkIterator { diff: self, ranges }
774    }
775
776    /// Returns iterator over matching and different ranges in bytes.
777    pub fn hunk_ranges(&self) -> DiffHunkRangeIterator<'_> {
778        DiffHunkRangeIterator::new(self)
779    }
780
781    /// Returns contents at the unchanged `range`.
782    fn hunk_at(&self, range: &UnchangedRange) -> impl Iterator<Item = &'input BStr> {
783        itertools::chain(
784            iter::once(&self.base_input[range.base.clone()]),
785            iter::zip(&self.other_inputs, &range.others).map(|(input, r)| &input[r.clone()]),
786        )
787    }
788
789    /// Returns contents between the `previous` ends and the `current` starts.
790    fn hunk_between(
791        &self,
792        previous: &UnchangedRange,
793        current: &UnchangedRange,
794    ) -> impl Iterator<Item = &'input BStr> {
795        itertools::chain(
796            iter::once(&self.base_input[previous.base.end..current.base.start]),
797            itertools::izip!(&self.other_inputs, &previous.others, &current.others)
798                .map(|(input, prev, cur)| &input[prev.end..cur.start]),
799        )
800    }
801
802    /// Uses the given tokenizer to split the changed regions into smaller
803    /// regions. Then tries to finds unchanged regions among them.
804    pub fn refine_changed_regions(
805        &mut self,
806        tokenizer: impl Fn(&[u8]) -> Vec<Range<usize>>,
807        compare: impl CompareBytes,
808    ) {
809        let mut new_unchanged_ranges = vec![self.unchanged_regions[0].clone()];
810        for window in self.unchanged_regions.windows(2) {
811            let [previous, current]: &[_; 2] = window.try_into().unwrap();
812            // For the changed region between the previous region and the current one,
813            // create a new Diff instance. Then adjust the start positions and
814            // offsets to be valid in the context of the larger Diff instance
815            // (`self`).
816            let refined_diff = ContentDiff::for_tokenizer(
817                self.hunk_between(previous, current),
818                &tokenizer,
819                &compare,
820            );
821            for refined in &refined_diff.unchanged_regions {
822                let new_base_start = refined.base.start + previous.base.end;
823                let new_base_end = refined.base.end + previous.base.end;
824                let new_others = iter::zip(&refined.others, &previous.others)
825                    .map(|(refi, prev)| (refi.start + prev.end)..(refi.end + prev.end))
826                    .collect();
827                new_unchanged_ranges.push(UnchangedRange {
828                    base: new_base_start..new_base_end,
829                    others: new_others,
830                });
831            }
832            new_unchanged_ranges.push(current.clone());
833        }
834        self.unchanged_regions = new_unchanged_ranges;
835        self.compact_unchanged_regions();
836    }
837
838    fn compact_unchanged_regions(&mut self) {
839        let mut compacted = vec![];
840        let mut maybe_previous: Option<UnchangedRange> = None;
841        for current in &self.unchanged_regions {
842            if let Some(previous) = maybe_previous {
843                if previous.base.end == current.base.start
844                    && iter::zip(&previous.others, &current.others)
845                        .all(|(prev, cur)| prev.end == cur.start)
846                {
847                    maybe_previous = Some(UnchangedRange {
848                        base: previous.base.start..current.base.end,
849                        others: iter::zip(&previous.others, &current.others)
850                            .map(|(prev, cur)| prev.start..cur.end)
851                            .collect(),
852                    });
853                    continue;
854                }
855                compacted.push(previous);
856            }
857            maybe_previous = Some(current.clone());
858        }
859        if let Some(previous) = maybe_previous {
860            compacted.push(previous);
861        }
862        self.unchanged_regions = compacted;
863    }
864}
865
866/// Hunk texts.
867#[derive(Clone, Debug, Eq, PartialEq)]
868pub struct DiffHunk<'input> {
869    pub kind: DiffHunkKind,
870    pub contents: DiffHunkContentVec<'input>,
871}
872
873impl<'input> DiffHunk<'input> {
874    pub fn matching<T: AsRef<[u8]> + ?Sized + 'input>(
875        contents: impl IntoIterator<Item = &'input T>,
876    ) -> Self {
877        Self {
878            kind: DiffHunkKind::Matching,
879            contents: contents.into_iter().map(BStr::new).collect(),
880        }
881    }
882
883    pub fn different<T: AsRef<[u8]> + ?Sized + 'input>(
884        contents: impl IntoIterator<Item = &'input T>,
885    ) -> Self {
886        Self {
887            kind: DiffHunkKind::Different,
888            contents: contents.into_iter().map(BStr::new).collect(),
889        }
890    }
891}
892
893#[derive(Clone, Copy, Debug, Eq, PartialEq)]
894pub enum DiffHunkKind {
895    Matching,
896    Different,
897}
898
899// Inline up to two sides
900pub type DiffHunkContentVec<'input> = SmallVec<[&'input BStr; 2]>;
901
902/// Iterator over matching and different texts.
903#[derive(Clone, Debug)]
904pub struct DiffHunkIterator<'diff, 'input> {
905    diff: &'diff ContentDiff<'input>,
906    ranges: DiffHunkRangeIterator<'diff>,
907}
908
909impl<'input> Iterator for DiffHunkIterator<'_, 'input> {
910    type Item = DiffHunk<'input>;
911
912    fn next(&mut self) -> Option<Self::Item> {
913        self.ranges.next_with(
914            |previous| {
915                let contents = self.diff.hunk_at(previous).collect();
916                let kind = DiffHunkKind::Matching;
917                DiffHunk { kind, contents }
918            },
919            |previous, current| {
920                let contents: DiffHunkContentVec =
921                    self.diff.hunk_between(previous, current).collect();
922                debug_assert!(
923                    contents.iter().any(|content| !content.is_empty()),
924                    "unchanged regions should have been compacted"
925                );
926                let kind = DiffHunkKind::Different;
927                DiffHunk { kind, contents }
928            },
929        )
930    }
931}
932
933/// Hunk ranges in bytes.
934#[derive(Clone, Debug, Eq, PartialEq)]
935pub struct DiffHunkRange {
936    pub kind: DiffHunkKind,
937    pub ranges: DiffHunkRangeVec,
938}
939
940// Inline up to two sides
941pub type DiffHunkRangeVec = SmallVec<[Range<usize>; 2]>;
942
943/// Iterator over matching and different ranges in bytes.
944#[derive(Clone, Debug)]
945pub struct DiffHunkRangeIterator<'diff> {
946    previous: &'diff UnchangedRange,
947    unchanged_emitted: bool,
948    unchanged_iter: slice::Iter<'diff, UnchangedRange>,
949}
950
951impl<'diff> DiffHunkRangeIterator<'diff> {
952    fn new(diff: &'diff ContentDiff) -> Self {
953        let mut unchanged_iter = diff.unchanged_regions.iter();
954        let previous = unchanged_iter.next().unwrap();
955        Self {
956            previous,
957            unchanged_emitted: previous.is_all_empty(),
958            unchanged_iter,
959        }
960    }
961
962    fn next_with<T>(
963        &mut self,
964        hunk_at: impl FnOnce(&UnchangedRange) -> T,
965        hunk_between: impl FnOnce(&UnchangedRange, &UnchangedRange) -> T,
966    ) -> Option<T> {
967        if !self.unchanged_emitted {
968            self.unchanged_emitted = true;
969            return Some(hunk_at(self.previous));
970        }
971        let current = self.unchanged_iter.next()?;
972        let hunk = hunk_between(self.previous, current);
973        self.previous = current;
974        self.unchanged_emitted = self.previous.is_all_empty();
975        Some(hunk)
976    }
977}
978
979impl Iterator for DiffHunkRangeIterator<'_> {
980    type Item = DiffHunkRange;
981
982    fn next(&mut self) -> Option<Self::Item> {
983        self.next_with(
984            |previous| {
985                let ranges = itertools::chain(iter::once(&previous.base), &previous.others)
986                    .cloned()
987                    .collect();
988                let kind = DiffHunkKind::Matching;
989                DiffHunkRange { kind, ranges }
990            },
991            |previous, current| {
992                let ranges: DiffHunkRangeVec = itertools::chain(
993                    iter::once(previous.base.end..current.base.start),
994                    iter::zip(&previous.others, &current.others)
995                        .map(|(prev, cur)| prev.end..cur.start),
996                )
997                .collect();
998                debug_assert!(
999                    ranges.iter().any(|range| !range.is_empty()),
1000                    "unchanged regions should have been compacted"
1001                );
1002                let kind = DiffHunkKind::Different;
1003                DiffHunkRange { kind, ranges }
1004            },
1005        )
1006    }
1007}
1008
1009/// Diffs slices of bytes.
1010///
1011/// The returned diff hunks may be any length (may span many lines or
1012/// may be only part of a line). This currently uses Histogram diff
1013/// (or maybe something similar; I'm not sure I understood the
1014/// algorithm correctly). It first diffs lines in the input and then
1015/// refines the changed ranges at the word level.
1016pub fn diff<'a, T: AsRef<[u8]> + ?Sized + 'a>(
1017    inputs: impl IntoIterator<Item = &'a T>,
1018) -> Vec<DiffHunk<'a>> {
1019    let mut diff = ContentDiff::for_tokenizer(inputs, find_line_ranges, CompareBytesExactly);
1020    diff.refine_changed_regions(find_word_ranges, CompareBytesExactly);
1021    diff.refine_changed_regions(find_nonword_ranges, CompareBytesExactly);
1022    diff.hunks().collect()
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027    use super::*;
1028
1029    // Extracted to a function because type inference is ambiguous due to
1030    // `impl PartialEq<aho_corasick::util::search::Span> for std::ops::Range<usize>`
1031    fn no_ranges() -> Vec<Range<usize>> {
1032        vec![]
1033    }
1034
1035    #[test]
1036    fn test_find_line_ranges_empty() {
1037        assert_eq!(find_line_ranges(b""), no_ranges());
1038    }
1039
1040    #[test]
1041    fn test_find_line_ranges_blank_line() {
1042        assert_eq!(find_line_ranges(b"\n"), vec![0..1]);
1043    }
1044
1045    #[test]
1046    fn test_find_line_ranges_missing_newline_at_eof() {
1047        assert_eq!(find_line_ranges(b"foo"), vec![0..3]);
1048    }
1049
1050    #[test]
1051    fn test_find_line_ranges_multiple_lines() {
1052        assert_eq!(find_line_ranges(b"a\nbb\nccc\n"), vec![0..2, 2..5, 5..9]);
1053    }
1054
1055    #[test]
1056    fn test_find_word_ranges_empty() {
1057        assert_eq!(find_word_ranges(b""), no_ranges());
1058    }
1059
1060    #[test]
1061    fn test_find_word_ranges_single_word() {
1062        assert_eq!(find_word_ranges(b"Abc"), vec![0..3]);
1063    }
1064
1065    #[test]
1066    fn test_find_word_ranges_no_word() {
1067        assert_eq!(find_word_ranges(b"+-*/"), no_ranges());
1068    }
1069
1070    #[test]
1071    fn test_find_word_ranges_word_then_non_word() {
1072        assert_eq!(find_word_ranges(b"Abc   "), vec![0..3]);
1073    }
1074
1075    #[test]
1076    fn test_find_word_ranges_non_word_then_word() {
1077        assert_eq!(find_word_ranges(b"   Abc"), vec![3..6]);
1078    }
1079
1080    #[test]
1081    fn test_find_word_ranges_multibyte() {
1082        assert_eq!(find_word_ranges("⊢".as_bytes()), vec![0..3]);
1083    }
1084
1085    #[test]
1086    fn test_find_lcs_empty() {
1087        let empty: Vec<(usize, usize)> = vec![];
1088        assert_eq!(find_lcs(&[]), empty);
1089    }
1090
1091    #[test]
1092    fn test_find_lcs_single_element() {
1093        assert_eq!(find_lcs(&[0]), vec![(0, 0)]);
1094    }
1095
1096    #[test]
1097    fn test_find_lcs_in_order() {
1098        assert_eq!(find_lcs(&[0, 1, 2]), vec![(0, 0), (1, 1), (2, 2)]);
1099    }
1100
1101    #[test]
1102    fn test_find_lcs_reverse_order() {
1103        assert_eq!(find_lcs(&[2, 1, 0]), vec![(2, 0)]);
1104    }
1105
1106    #[test]
1107    fn test_find_lcs_two_swapped() {
1108        assert_eq!(
1109            find_lcs(&[0, 1, 4, 3, 2, 5, 6]),
1110            vec![(0, 0), (1, 1), (2, 4), (5, 5), (6, 6)]
1111        );
1112    }
1113
1114    #[test]
1115    fn test_find_lcs_element_moved_earlier() {
1116        assert_eq!(
1117            find_lcs(&[0, 1, 4, 2, 3, 5, 6]),
1118            vec![(0, 0), (1, 1), (2, 3), (3, 4), (5, 5), (6, 6)]
1119        );
1120    }
1121
1122    #[test]
1123    fn test_find_lcs_element_moved_later() {
1124        assert_eq!(
1125            find_lcs(&[0, 1, 3, 4, 2, 5, 6]),
1126            vec![(0, 0), (1, 1), (3, 2), (4, 3), (5, 5), (6, 6)]
1127        );
1128    }
1129
1130    #[test]
1131    fn test_find_lcs_interleaved_longest_chains() {
1132        assert_eq!(
1133            find_lcs(&[0, 4, 2, 9, 6, 5, 1, 3, 7, 8]),
1134            vec![(0, 0), (1, 6), (3, 7), (7, 8), (8, 9)]
1135        );
1136    }
1137
1138    #[test]
1139    fn test_find_word_ranges_many_words() {
1140        assert_eq!(
1141            find_word_ranges(b"fn find_words(text: &[u8])"),
1142            vec![0..2, 3..13, 14..18, 22..24]
1143        );
1144    }
1145
1146    #[test]
1147    fn test_compare_bytes_ignore_all_whitespace() {
1148        let comp = WordComparator::new(CompareBytesIgnoreAllWhitespace);
1149        let hash = |data: &[u8]| comp.hash_one(data);
1150
1151        assert!(comp.eq(b"", b""));
1152        assert!(comp.eq(b"", b" "));
1153        assert!(comp.eq(b"\t", b"\r"));
1154        assert_eq!(hash(b""), hash(b""));
1155        assert_eq!(hash(b""), hash(b" "));
1156        assert_eq!(hash(b""), hash(b"\t"));
1157        assert_eq!(hash(b""), hash(b"\r"));
1158
1159        assert!(comp.eq(b"ab", b" a  b\t"));
1160        assert_eq!(hash(b"ab"), hash(b" a  b\t"));
1161
1162        assert!(!comp.eq(b"a", b""));
1163        assert!(!comp.eq(b"a", b" "));
1164        assert!(!comp.eq(b"a", b"ab"));
1165        assert!(!comp.eq(b"ab", b"ba"));
1166    }
1167
1168    #[test]
1169    fn test_compare_bytes_ignore_whitespace_amount() {
1170        let comp = WordComparator::new(CompareBytesIgnoreWhitespaceAmount);
1171        let hash = |data: &[u8]| comp.hash_one(data);
1172
1173        assert!(comp.eq(b"", b""));
1174        assert!(comp.eq(b"\n", b" \n"));
1175        assert!(comp.eq(b"\t", b"\r"));
1176        assert_eq!(hash(b""), hash(b""));
1177        assert_eq!(hash(b" "), hash(b"\n"));
1178        assert_eq!(hash(b" "), hash(b" \n"));
1179        assert_eq!(hash(b" "), hash(b"\t"));
1180        assert_eq!(hash(b" "), hash(b"\r"));
1181
1182        assert!(comp.eq(b"a b c\n", b"a  b\tc\r\n"));
1183        assert_eq!(hash(b"a b c\n"), hash(b"a  b\tc\r\n"));
1184
1185        assert!(!comp.eq(b"", b" "));
1186        assert!(!comp.eq(b"a", b""));
1187        assert!(!comp.eq(b"a", b" "));
1188        assert!(!comp.eq(b"a", b"a "));
1189        assert!(!comp.eq(b"a", b" a"));
1190        assert!(!comp.eq(b"a", b"ab"));
1191        assert!(!comp.eq(b"ab", b"ba"));
1192        assert!(!comp.eq(b"ab", b"a b"));
1193    }
1194
1195    fn unchanged_ranges(
1196        (left_text, left_ranges): (&[u8], &[Range<usize>]),
1197        (right_text, right_ranges): (&[u8], &[Range<usize>]),
1198    ) -> Vec<(Range<usize>, Range<usize>)> {
1199        let comp = WordComparator::new(CompareBytesExactly);
1200        let left = DiffSource::new(left_text, left_ranges, &comp);
1201        let right = DiffSource::new(right_text, right_ranges, &comp);
1202        let mut positions = Vec::new();
1203        collect_unchanged_words(&mut positions, &left.local(), &right.local(), &comp);
1204        positions
1205            .into_iter()
1206            .map(|(left_pos, right_pos)| (left.range_at(left_pos), right.range_at(right_pos)))
1207            .collect()
1208    }
1209
1210    #[test]
1211    fn test_unchanged_ranges_insert_in_middle() {
1212        assert_eq!(
1213            unchanged_ranges(
1214                (b"a b b c", &[0..1, 2..3, 4..5, 6..7]),
1215                (b"a b X b c", &[0..1, 2..3, 4..5, 6..7, 8..9]),
1216            ),
1217            vec![(0..1, 0..1), (2..3, 2..3), (4..5, 6..7), (6..7, 8..9)]
1218        );
1219    }
1220
1221    #[test]
1222    fn test_unchanged_ranges_non_unique_removed() {
1223        // We used to consider the first two "a" in the first input to match the two
1224        // "a"s in the second input. We no longer do.
1225        assert_eq!(
1226            unchanged_ranges(
1227                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1228                (b"a b a c", &[0..1, 2..3, 4..5, 6..7]),
1229            ),
1230            vec![(0..1, 0..1)]
1231        );
1232        assert_eq!(
1233            unchanged_ranges(
1234                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1235                (b"b a c a", &[0..1, 2..3, 4..5, 6..7]),
1236            ),
1237            vec![(6..7, 6..7)]
1238        );
1239        assert_eq!(
1240            unchanged_ranges(
1241                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1242                (b"b a a c", &[0..1, 2..3, 4..5, 6..7]),
1243            ),
1244            vec![]
1245        );
1246        assert_eq!(
1247            unchanged_ranges(
1248                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1249                (b"a b c a", &[0..1, 2..3, 4..5, 6..7]),
1250            ),
1251            vec![(0..1, 0..1), (6..7, 6..7)]
1252        );
1253    }
1254
1255    #[test]
1256    fn test_unchanged_ranges_non_unique_added() {
1257        // We used to consider the first two "a" in the first input to match the two
1258        // "a"s in the second input. We no longer do.
1259        assert_eq!(
1260            unchanged_ranges(
1261                (b"a b a c", &[0..1, 2..3, 4..5, 6..7]),
1262                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1263            ),
1264            vec![(0..1, 0..1)]
1265        );
1266        assert_eq!(
1267            unchanged_ranges(
1268                (b"b a c a", &[0..1, 2..3, 4..5, 6..7]),
1269                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1270            ),
1271            vec![(6..7, 6..7)]
1272        );
1273        assert_eq!(
1274            unchanged_ranges(
1275                (b"b a a c", &[0..1, 2..3, 4..5, 6..7]),
1276                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1277            ),
1278            vec![]
1279        );
1280        assert_eq!(
1281            unchanged_ranges(
1282                (b"a b c a", &[0..1, 2..3, 4..5, 6..7]),
1283                (b"a a a a", &[0..1, 2..3, 4..5, 6..7]),
1284            ),
1285            vec![(0..1, 0..1), (6..7, 6..7)]
1286        );
1287    }
1288
1289    #[test]
1290    fn test_unchanged_ranges_recursion_needed() {
1291        // "|" matches first, then "b" matches within the left/right range.
1292        assert_eq!(
1293            unchanged_ranges(
1294                (b"a b | b", &[0..1, 2..3, 4..5, 6..7]),
1295                (b"b c d |", &[0..1, 2..3, 4..5, 6..7]),
1296            ),
1297            vec![(2..3, 0..1), (4..5, 6..7)]
1298        );
1299        assert_eq!(
1300            unchanged_ranges(
1301                (b"| b c d", &[0..1, 2..3, 4..5, 6..7]),
1302                (b"b | a b", &[0..1, 2..3, 4..5, 6..7]),
1303            ),
1304            vec![(0..1, 2..3), (2..3, 6..7)]
1305        );
1306        // "|" matches first, then the middle range is trimmed.
1307        assert_eq!(
1308            unchanged_ranges(
1309                (b"| b c |", &[0..1, 2..3, 4..5, 6..7]),
1310                (b"| b b |", &[0..1, 2..3, 4..5, 6..7]),
1311            ),
1312            vec![(0..1, 0..1), (2..3, 2..3), (6..7, 6..7)]
1313        );
1314        assert_eq!(
1315            unchanged_ranges(
1316                (b"| c c |", &[0..1, 2..3, 4..5, 6..7]),
1317                (b"| b c |", &[0..1, 2..3, 4..5, 6..7]),
1318            ),
1319            vec![(0..1, 0..1), (4..5, 4..5), (6..7, 6..7)]
1320        );
1321        // "|" matches first, then "a", then "b".
1322        assert_eq!(
1323            unchanged_ranges(
1324                (b"a b c | a", &[0..1, 2..3, 4..5, 6..7, 8..9]),
1325                (b"b a b |", &[0..1, 2..3, 4..5, 6..7]),
1326            ),
1327            vec![(0..1, 2..3), (2..3, 4..5), (6..7, 6..7)]
1328        );
1329        assert_eq!(
1330            unchanged_ranges(
1331                (b"| b a b", &[0..1, 2..3, 4..5, 6..7]),
1332                (b"a | a b c", &[0..1, 2..3, 4..5, 6..7, 8..9]),
1333            ),
1334            vec![(0..1, 2..3), (4..5, 4..5), (6..7, 6..7)]
1335        );
1336    }
1337
1338    #[test]
1339    fn test_diff_single_input() {
1340        assert_eq!(diff(["abc"]), vec![DiffHunk::matching(["abc"])]);
1341    }
1342
1343    #[test]
1344    fn test_diff_some_empty_inputs() {
1345        // All empty
1346        assert_eq!(diff([""]), vec![]);
1347        assert_eq!(diff(["", ""]), vec![]);
1348        assert_eq!(diff(["", "", ""]), vec![]);
1349
1350        // One empty
1351        assert_eq!(diff(["a b", ""]), vec![DiffHunk::different(["a b", ""])]);
1352        assert_eq!(diff(["", "a b"]), vec![DiffHunk::different(["", "a b"])]);
1353
1354        // One empty, two match
1355        assert_eq!(
1356            diff(["a b", "", "a b"]),
1357            vec![DiffHunk::different(["a b", "", "a b"])]
1358        );
1359        assert_eq!(
1360            diff(["", "a b", "a b"]),
1361            vec![DiffHunk::different(["", "a b", "a b"])]
1362        );
1363
1364        // Two empty, one differs
1365        assert_eq!(
1366            diff(["a b", "", ""]),
1367            vec![DiffHunk::different(["a b", "", ""])]
1368        );
1369        assert_eq!(
1370            diff(["", "a b", ""]),
1371            vec![DiffHunk::different(["", "a b", ""])]
1372        );
1373    }
1374
1375    #[test]
1376    fn test_diff_two_inputs_one_different() {
1377        assert_eq!(
1378            diff(["a b c", "a X c"]),
1379            vec![
1380                DiffHunk::matching(["a "].repeat(2)),
1381                DiffHunk::different(["b", "X"]),
1382                DiffHunk::matching([" c"].repeat(2)),
1383            ]
1384        );
1385    }
1386
1387    #[test]
1388    fn test_diff_multiple_inputs_one_different() {
1389        assert_eq!(
1390            diff(["a b c", "a X c", "a b c"]),
1391            vec![
1392                DiffHunk::matching(["a "].repeat(3)),
1393                DiffHunk::different(["b", "X", "b"]),
1394                DiffHunk::matching([" c"].repeat(3)),
1395            ]
1396        );
1397    }
1398
1399    #[test]
1400    fn test_diff_multiple_inputs_all_different() {
1401        assert_eq!(
1402            diff(["a b c", "a X c", "a c X"]),
1403            vec![
1404                DiffHunk::matching(["a "].repeat(3)),
1405                DiffHunk::different(["b ", "X ", ""]),
1406                DiffHunk::matching(["c"].repeat(3)),
1407                DiffHunk::different(["", "", " X"]),
1408            ]
1409        );
1410    }
1411
1412    #[test]
1413    fn test_diff_for_tokenizer_compacted() {
1414        // Tests that unchanged regions are compacted when using for_tokenizer()
1415        let diff = ContentDiff::for_tokenizer(
1416            ["a\nb\nc\nd\ne\nf\ng", "a\nb\nc\nX\ne\nf\ng"],
1417            find_line_ranges,
1418            CompareBytesExactly,
1419        );
1420        assert_eq!(
1421            diff.hunks().collect_vec(),
1422            vec![
1423                DiffHunk::matching(["a\nb\nc\n"].repeat(2)),
1424                DiffHunk::different(["d\n", "X\n"]),
1425                DiffHunk::matching(["e\nf\ng"].repeat(2)),
1426            ]
1427        );
1428    }
1429
1430    #[test]
1431    fn test_diff_nothing_in_common() {
1432        assert_eq!(
1433            diff(["aaa", "bb"]),
1434            vec![DiffHunk::different(["aaa", "bb"])]
1435        );
1436    }
1437
1438    #[test]
1439    fn test_diff_insert_in_middle() {
1440        assert_eq!(
1441            diff(["a z", "a S z"]),
1442            vec![
1443                DiffHunk::matching(["a "].repeat(2)),
1444                DiffHunk::different(["", "S "]),
1445                DiffHunk::matching(["z"].repeat(2)),
1446            ]
1447        );
1448    }
1449
1450    #[test]
1451    fn test_diff_no_unique_middle_flips() {
1452        assert_eq!(
1453            diff(["a R R S S z", "a S S R R z"]),
1454            vec![
1455                DiffHunk::matching(["a "].repeat(2)),
1456                DiffHunk::different(["R R ", ""]),
1457                DiffHunk::matching(["S S "].repeat(2)),
1458                DiffHunk::different(["", "R R "]),
1459                DiffHunk::matching(["z"].repeat(2))
1460            ],
1461        );
1462    }
1463
1464    #[test]
1465    fn test_diff_recursion_needed() {
1466        assert_eq!(
1467            diff([
1468                "a q x q y q z q b q y q x q c",
1469                "a r r x q y z q b y q x r r c",
1470            ]),
1471            vec![
1472                DiffHunk::matching(["a "].repeat(2)),
1473                DiffHunk::different(["q", "r"]),
1474                DiffHunk::matching([" "].repeat(2)),
1475                DiffHunk::different(["", "r "]),
1476                DiffHunk::matching(["x q y "].repeat(2)),
1477                DiffHunk::different(["q ", ""]),
1478                DiffHunk::matching(["z q b "].repeat(2)),
1479                DiffHunk::different(["q ", ""]),
1480                DiffHunk::matching(["y q x "].repeat(2)),
1481                DiffHunk::different(["q", "r"]),
1482                DiffHunk::matching([" "].repeat(2)),
1483                DiffHunk::different(["", "r "]),
1484                DiffHunk::matching(["c"].repeat(2)),
1485            ]
1486        );
1487    }
1488
1489    #[test]
1490    fn test_diff_ignore_all_whitespace() {
1491        fn diff(inputs: [&str; 2]) -> Vec<DiffHunk<'_>> {
1492            let diff = ContentDiff::for_tokenizer(
1493                inputs,
1494                find_line_ranges,
1495                CompareBytesIgnoreAllWhitespace,
1496            );
1497            diff.hunks().collect()
1498        }
1499
1500        assert_eq!(diff(["", "\n"]), vec![DiffHunk::different(["", "\n"])]);
1501        assert_eq!(
1502            diff(["a\n", " a\r\n"]),
1503            vec![DiffHunk::matching(["a\n", " a\r\n"])]
1504        );
1505        assert_eq!(
1506            diff(["a\n", " a\nb"]),
1507            vec![
1508                DiffHunk::matching(["a\n", " a\n"]),
1509                DiffHunk::different(["", "b"]),
1510            ]
1511        );
1512
1513        // No LCS matches, so trim leading/trailing common lines
1514        assert_eq!(
1515            diff(["a\nc\n", " a\n a\n"]),
1516            vec![
1517                DiffHunk::matching(["a\n", " a\n"]),
1518                DiffHunk::different(["c\n", " a\n"]),
1519            ]
1520        );
1521        assert_eq!(
1522            diff(["c\na\n", " a\n a\n"]),
1523            vec![
1524                DiffHunk::different(["c\n", " a\n"]),
1525                DiffHunk::matching(["a\n", " a\n"]),
1526            ]
1527        );
1528    }
1529
1530    #[test]
1531    fn test_diff_ignore_whitespace_amount() {
1532        fn diff(inputs: [&str; 2]) -> Vec<DiffHunk<'_>> {
1533            let diff = ContentDiff::for_tokenizer(
1534                inputs,
1535                find_line_ranges,
1536                CompareBytesIgnoreWhitespaceAmount,
1537            );
1538            diff.hunks().collect()
1539        }
1540
1541        assert_eq!(diff(["", "\n"]), vec![DiffHunk::different(["", "\n"])]);
1542        // whitespace at line end is ignored
1543        assert_eq!(
1544            diff(["a\n", "a\r\n"]),
1545            vec![DiffHunk::matching(["a\n", "a\r\n"])]
1546        );
1547        // but whitespace at line start isn't
1548        assert_eq!(
1549            diff(["a\n", " a\n"]),
1550            vec![DiffHunk::different(["a\n", " a\n"])]
1551        );
1552        assert_eq!(
1553            diff(["a\n", "a \nb"]),
1554            vec![
1555                DiffHunk::matching(["a\n", "a \n"]),
1556                DiffHunk::different(["", "b"]),
1557            ]
1558        );
1559    }
1560
1561    #[test]
1562    fn test_diff_hunk_iterator() {
1563        let diff = ContentDiff::by_word(["a b c", "a XX c", "a b "]);
1564        assert_eq!(
1565            diff.hunks().collect_vec(),
1566            vec![
1567                DiffHunk::matching(["a "].repeat(3)),
1568                DiffHunk::different(["b", "XX", "b"]),
1569                DiffHunk::matching([" "].repeat(3)),
1570                DiffHunk::different(["c", "c", ""]),
1571            ]
1572        );
1573        assert_eq!(
1574            diff.hunk_ranges().collect_vec(),
1575            vec![
1576                DiffHunkRange {
1577                    kind: DiffHunkKind::Matching,
1578                    ranges: smallvec![0..2, 0..2, 0..2],
1579                },
1580                DiffHunkRange {
1581                    kind: DiffHunkKind::Different,
1582                    ranges: smallvec![2..3, 2..4, 2..3],
1583                },
1584                DiffHunkRange {
1585                    kind: DiffHunkKind::Matching,
1586                    ranges: smallvec![3..4, 4..5, 3..4],
1587                },
1588                DiffHunkRange {
1589                    kind: DiffHunkKind::Different,
1590                    ranges: smallvec![4..5, 5..6, 4..4],
1591                },
1592            ]
1593        );
1594    }
1595
1596    #[test]
1597    fn test_diff_real_case_write_fmt() {
1598        // This is from src/ui.rs in commit f44d246e3f88 in this repo. It highlights the
1599        // need for recursion into the range at the end: after splitting at "Arguments"
1600        // and "formatter", the region at the end has the unique words "write_fmt"
1601        // and "fmt", but we forgot to recurse into that region, so we ended up
1602        // saying that "write_fmt(fmt).unwrap()" was replaced by b"write_fmt(fmt)".
1603        #[rustfmt::skip]
1604        assert_eq!(
1605            diff([
1606                "    pub fn write_fmt(&mut self, fmt: fmt::Arguments<\'_>) {\n        self.styler().write_fmt(fmt).unwrap()\n",
1607                "    pub fn write_fmt(&mut self, fmt: fmt::Arguments<\'_>) -> io::Result<()> {\n        self.styler().write_fmt(fmt)\n"
1608            ]),
1609            vec![
1610                DiffHunk::matching(["    pub fn write_fmt(&mut self, fmt: fmt::Arguments<\'_>) "].repeat(2)),
1611                DiffHunk::different(["", "-> io::Result<()> "]),
1612                DiffHunk::matching(["{\n        self.styler().write_fmt(fmt)"].repeat(2)),
1613                DiffHunk::different([".unwrap()", ""]),
1614                DiffHunk::matching(["\n"].repeat(2))
1615            ]
1616        );
1617    }
1618
1619    #[test]
1620    fn test_diff_real_case_gitgit_read_tree_c() {
1621        // This is the diff from commit e497ea2a9b in the git.git repo
1622        #[rustfmt::skip]
1623        assert_eq!(
1624            diff([
1625                r##"/*
1626 * GIT - The information manager from hell
1627 *
1628 * Copyright (C) Linus Torvalds, 2005
1629 */
1630#include "#cache.h"
1631
1632static int unpack(unsigned char *sha1)
1633{
1634	void *buffer;
1635	unsigned long size;
1636	char type[20];
1637
1638	buffer = read_sha1_file(sha1, type, &size);
1639	if (!buffer)
1640		usage("unable to read sha1 file");
1641	if (strcmp(type, "tree"))
1642		usage("expected a 'tree' node");
1643	while (size) {
1644		int len = strlen(buffer)+1;
1645		unsigned char *sha1 = buffer + len;
1646		char *path = strchr(buffer, ' ')+1;
1647		unsigned int mode;
1648		if (size < len + 20 || sscanf(buffer, "%o", &mode) != 1)
1649			usage("corrupt 'tree' file");
1650		buffer = sha1 + 20;
1651		size -= len + 20;
1652		printf("%o %s (%s)\n", mode, path, sha1_to_hex(sha1));
1653	}
1654	return 0;
1655}
1656
1657int main(int argc, char **argv)
1658{
1659	int fd;
1660	unsigned char sha1[20];
1661
1662	if (argc != 2)
1663		usage("read-tree <key>");
1664	if (get_sha1_hex(argv[1], sha1) < 0)
1665		usage("read-tree <key>");
1666	sha1_file_directory = getenv(DB_ENVIRONMENT);
1667	if (!sha1_file_directory)
1668		sha1_file_directory = DEFAULT_DB_ENVIRONMENT;
1669	if (unpack(sha1) < 0)
1670		usage("unpack failed");
1671	return 0;
1672}
1673"##,
1674                r##"/*
1675 * GIT - The information manager from hell
1676 *
1677 * Copyright (C) Linus Torvalds, 2005
1678 */
1679#include "#cache.h"
1680
1681static void create_directories(const char *path)
1682{
1683	int len = strlen(path);
1684	char *buf = malloc(len + 1);
1685	const char *slash = path;
1686
1687	while ((slash = strchr(slash+1, '/')) != NULL) {
1688		len = slash - path;
1689		memcpy(buf, path, len);
1690		buf[len] = 0;
1691		mkdir(buf, 0700);
1692	}
1693}
1694
1695static int create_file(const char *path)
1696{
1697	int fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1698	if (fd < 0) {
1699		if (errno == ENOENT) {
1700			create_directories(path);
1701			fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1702		}
1703	}
1704	return fd;
1705}
1706
1707static int unpack(unsigned char *sha1)
1708{
1709	void *buffer;
1710	unsigned long size;
1711	char type[20];
1712
1713	buffer = read_sha1_file(sha1, type, &size);
1714	if (!buffer)
1715		usage("unable to read sha1 file");
1716	if (strcmp(type, "tree"))
1717		usage("expected a 'tree' node");
1718	while (size) {
1719		int len = strlen(buffer)+1;
1720		unsigned char *sha1 = buffer + len;
1721		char *path = strchr(buffer, ' ')+1;
1722		char *data;
1723		unsigned long filesize;
1724		unsigned int mode;
1725		int fd;
1726
1727		if (size < len + 20 || sscanf(buffer, "%o", &mode) != 1)
1728			usage("corrupt 'tree' file");
1729		buffer = sha1 + 20;
1730		size -= len + 20;
1731		data = read_sha1_file(sha1, type, &filesize);
1732		if (!data || strcmp(type, "blob"))
1733			usage("tree file refers to bad file data");
1734		fd = create_file(path);
1735		if (fd < 0)
1736			usage("unable to create file");
1737		if (write(fd, data, filesize) != filesize)
1738			usage("unable to write file");
1739		fchmod(fd, mode);
1740		close(fd);
1741		free(data);
1742	}
1743	return 0;
1744}
1745
1746int main(int argc, char **argv)
1747{
1748	int fd;
1749	unsigned char sha1[20];
1750
1751	if (argc != 2)
1752		usage("read-tree <key>");
1753	if (get_sha1_hex(argv[1], sha1) < 0)
1754		usage("read-tree <key>");
1755	sha1_file_directory = getenv(DB_ENVIRONMENT);
1756	if (!sha1_file_directory)
1757		sha1_file_directory = DEFAULT_DB_ENVIRONMENT;
1758	if (unpack(sha1) < 0)
1759		usage("unpack failed");
1760	return 0;
1761}
1762"##,
1763            ]),
1764            vec![
1765               DiffHunk::matching(["/*\n * GIT - The information manager from hell\n *\n * Copyright (C) Linus Torvalds, 2005\n */\n#include \"#cache.h\"\n\n"].repeat(2)),
1766               DiffHunk::different(["", "static void create_directories(const char *path)\n{\n\tint len = strlen(path);\n\tchar *buf = malloc(len + 1);\n\tconst char *slash = path;\n\n\twhile ((slash = strchr(slash+1, \'/\')) != NULL) {\n\t\tlen = slash - path;\n\t\tmemcpy(buf, path, len);\n\t\tbuf[len] = 0;\n\t\tmkdir(buf, 0700);\n\t}\n}\n\nstatic int create_file(const char *path)\n{\n\tint fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0600);\n\tif (fd < 0) {\n\t\tif (errno == ENOENT) {\n\t\t\tcreate_directories(path);\n\t\t\tfd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0600);\n\t\t}\n\t}\n\treturn fd;\n}\n\n"]),
1767               DiffHunk::matching(["static int unpack(unsigned char *sha1)\n{\n\tvoid *buffer;\n\tunsigned long size;\n\tchar type[20];\n\n\tbuffer = read_sha1_file(sha1, type, &size);\n\tif (!buffer)\n\t\tusage(\"unable to read sha1 file\");\n\tif (strcmp(type, \"tree\"))\n\t\tusage(\"expected a \'tree\' node\");\n\twhile (size) {\n\t\tint len = strlen(buffer)+1;\n\t\tunsigned char *sha1 = buffer + len;\n\t\tchar *path = strchr(buffer, \' \')+1;\n"].repeat(2)),
1768               DiffHunk::different(["", "\t\tchar *data;\n\t\tunsigned long filesize;\n"]),
1769               DiffHunk::matching(["\t\tunsigned int mode;\n"].repeat(2)),
1770               DiffHunk::different(["", "\t\tint fd;\n\n"]),
1771               DiffHunk::matching(["\t\tif (size < len + 20 || sscanf(buffer, \"%o\", &mode) != 1)\n\t\t\tusage(\"corrupt \'tree\' file\");\n\t\tbuffer = sha1 + 20;\n\t\tsize -= len + 20;\n\t\t"].repeat(2)),
1772               DiffHunk::different(["printf(\"%o %s (%s)\\n\", mode, path,", "data ="]),
1773               DiffHunk::matching([" "].repeat(2)),
1774               DiffHunk::different(["sha1_to_hex", "read_sha1_file"]),
1775               DiffHunk::matching(["(sha1"].repeat(2)),
1776               DiffHunk::different([")", ", type, &filesize);\n\t\tif (!data || strcmp(type, \"blob\"))\n\t\t\tusage(\"tree file refers to bad file data\");\n\t\tfd = create_file(path);\n\t\tif (fd < 0)\n\t\t\tusage(\"unable to create file\");\n\t\tif (write(fd, data, filesize) != filesize)\n\t\t\tusage(\"unable to write file\");\n\t\tfchmod(fd, mode);\n\t\tclose(fd);\n\t\tfree(data"]),
1777               DiffHunk::matching([");\n\t}\n\treturn 0;\n}\n\nint main(int argc, char **argv)\n{\n\tint fd;\n\tunsigned char sha1[20];\n\n\tif (argc != 2)\n\t\tusage(\"read-tree <key>\");\n\tif (get_sha1_hex(argv[1], sha1) < 0)\n\t\tusage(\"read-tree <key>\");\n\tsha1_file_directory = getenv(DB_ENVIRONMENT);\n\tif (!sha1_file_directory)\n\t\tsha1_file_directory = DEFAULT_DB_ENVIRONMENT;\n\tif (unpack(sha1) < 0)\n\t\tusage(\"unpack failed\");\n\treturn 0;\n}\n"].repeat(2)),
1778            ]
1779        );
1780    }
1781}