-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathdiff.rs
More file actions
1782 lines (1625 loc) · 60.7 KB
/
Copy pathdiff.rs
File metadata and controls
1782 lines (1625 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![expect(missing_docs)]
use std::collections::BTreeMap;
use std::hash::BuildHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::hash::RandomState;
use std::iter;
use std::ops::Range;
use std::slice;
use bstr::BStr;
use hashbrown::HashTable;
use itertools::Itertools as _;
use smallvec::SmallVec;
use smallvec::smallvec;
pub fn find_line_ranges(text: &[u8]) -> Vec<Range<usize>> {
text.split_inclusive(|b| *b == b'\n')
.scan(0, |total, line| {
let start = *total;
*total += line.len();
Some(start..*total)
})
.collect()
}
fn is_word_byte(b: u8) -> bool {
// TODO: Make this configurable (probably higher up in the call stack)
matches!(
b,
// Count 0x80..0xff as word bytes so multi-byte UTF-8 chars are
// treated as a single unit.
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'\x80'..=b'\xff'
)
}
pub fn find_word_ranges(text: &[u8]) -> Vec<Range<usize>> {
let mut word_ranges = vec![];
let mut word_start_pos = 0;
let mut in_word = false;
for (i, b) in text.iter().enumerate() {
if in_word && !is_word_byte(*b) {
in_word = false;
word_ranges.push(word_start_pos..i);
word_start_pos = i;
} else if !in_word && is_word_byte(*b) {
in_word = true;
word_start_pos = i;
}
}
if in_word && word_start_pos < text.len() {
word_ranges.push(word_start_pos..text.len());
}
word_ranges
}
pub fn find_nonword_ranges(text: &[u8]) -> Vec<Range<usize>> {
text.iter()
.positions(|b| !is_word_byte(*b))
.map(|i| i..i + 1)
.collect()
}
fn bytes_ignore_all_whitespace(text: &[u8]) -> impl Iterator<Item = u8> {
text.iter().copied().filter(|b| !b.is_ascii_whitespace())
}
fn bytes_ignore_whitespace_amount(text: &[u8]) -> impl Iterator<Item = u8> {
let mut prev_was_space = false;
text.iter().filter_map(move |&b| {
let was_space = prev_was_space;
let is_space = b.is_ascii_whitespace();
prev_was_space = is_space;
match (was_space, is_space) {
(_, false) => Some(b),
(false, true) => Some(b' '),
(true, true) => None,
}
})
}
fn hash_with_length_suffix<I, H>(data: I, state: &mut H)
where
I: IntoIterator,
I::Item: Hash,
H: Hasher,
{
let mut len: usize = 0;
for d in data {
d.hash(state);
len += 1;
}
state.write_usize(len);
}
/// Compares byte sequences based on a certain equivalence property.
///
/// This isn't a newtype `Wrapper<'a>(&'a [u8])` but an external comparison
/// object for the following reasons:
///
/// a. If it were newtype, a generic `wrap` function would be needed. It
/// couldn't be expressed as a simple closure:
/// `for<'a> Fn(&'a [u8]) -> ???<'a>`
/// b. Dynamic comparison object can be implemented intuitively. For example,
/// `pattern: &Regex` would have to be copied to all newtype instances if it
/// were newtype.
/// c. Hash values can be cached if hashing is controlled externally.
pub trait CompareBytes {
/// Returns true if `left` and `right` are equivalent.
fn eq(&self, left: &[u8], right: &[u8]) -> bool;
/// Generates hash which respects the following property:
/// `eq(left, right) => hash(left) == hash(right)`
fn hash<H: Hasher>(&self, text: &[u8], state: &mut H);
}
// An instance might have e.g. Regex pattern, which can't be trivially copied.
// Such comparison object can be passed by reference.
impl<C: CompareBytes + ?Sized> CompareBytes for &C {
fn eq(&self, left: &[u8], right: &[u8]) -> bool {
<C as CompareBytes>::eq(self, left, right)
}
fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
<C as CompareBytes>::hash(self, text, state);
}
}
/// Compares byte sequences literally.
#[derive(Clone, Debug, Default)]
pub struct CompareBytesExactly;
impl CompareBytes for CompareBytesExactly {
fn eq(&self, left: &[u8], right: &[u8]) -> bool {
left == right
}
fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
text.hash(state);
}
}
/// Compares byte sequences ignoring any whitespace occurrences.
#[derive(Clone, Debug, Default)]
pub struct CompareBytesIgnoreAllWhitespace;
impl CompareBytes for CompareBytesIgnoreAllWhitespace {
fn eq(&self, left: &[u8], right: &[u8]) -> bool {
bytes_ignore_all_whitespace(left).eq(bytes_ignore_all_whitespace(right))
}
fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
hash_with_length_suffix(bytes_ignore_all_whitespace(text), state);
}
}
/// Compares byte sequences ignoring changes in whitespace amount.
#[derive(Clone, Debug, Default)]
pub struct CompareBytesIgnoreWhitespaceAmount;
impl CompareBytes for CompareBytesIgnoreWhitespaceAmount {
fn eq(&self, left: &[u8], right: &[u8]) -> bool {
bytes_ignore_whitespace_amount(left).eq(bytes_ignore_whitespace_amount(right))
}
fn hash<H: Hasher>(&self, text: &[u8], state: &mut H) {
hash_with_length_suffix(bytes_ignore_whitespace_amount(text), state);
}
}
// Not implementing Eq because the text should be compared by WordComparator.
#[derive(Clone, Copy, Debug)]
struct HashedWord<'input> {
hash: u64,
text: &'input BStr,
}
/// Compares words (or tokens) under a certain hasher configuration.
#[derive(Clone, Debug, Default)]
struct WordComparator<C, S> {
compare: C,
hash_builder: S,
}
impl<C: CompareBytes> WordComparator<C, RandomState> {
fn new(compare: C) -> Self {
Self {
compare,
// TODO: switch to ahash for better performance?
hash_builder: RandomState::new(),
}
}
}
impl<C: CompareBytes, S: BuildHasher> WordComparator<C, S> {
fn eq(&self, left: &[u8], right: &[u8]) -> bool {
self.compare.eq(left, right)
}
fn eq_hashed(&self, left: HashedWord<'_>, right: HashedWord<'_>) -> bool {
left.hash == right.hash && self.compare.eq(left.text, right.text)
}
fn hash_one(&self, text: &[u8]) -> u64 {
let mut state = self.hash_builder.build_hasher();
self.compare.hash(text, &mut state);
state.finish()
}
}
/// Index in a list of word (or token) ranges in `DiffSource`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct WordPosition(usize);
/// Index in a list of word (or token) ranges in `LocalDiffSource`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct LocalWordPosition(usize);
#[derive(Clone, Debug)]
struct DiffSource<'input, 'aux> {
text: &'input BStr,
ranges: &'aux [Range<usize>],
hashes: Vec<u64>,
}
impl<'input, 'aux> DiffSource<'input, 'aux> {
fn new<T: AsRef<[u8]> + ?Sized, C: CompareBytes, S: BuildHasher>(
text: &'input T,
ranges: &'aux [Range<usize>],
comp: &WordComparator<C, S>,
) -> Self {
let text = BStr::new(text);
let hashes = ranges
.iter()
.map(|range| comp.hash_one(&text[range.clone()]))
.collect();
Self {
text,
ranges,
hashes,
}
}
fn local(&self) -> LocalDiffSource<'input, '_> {
LocalDiffSource {
text: self.text,
ranges: self.ranges,
hashes: &self.hashes,
global_offset: WordPosition(0),
}
}
fn range_at(&self, position: WordPosition) -> Range<usize> {
self.ranges[position.0].clone()
}
}
#[derive(Clone, Debug)]
struct LocalDiffSource<'input, 'aux> {
text: &'input BStr,
ranges: &'aux [Range<usize>],
hashes: &'aux [u64],
/// The number of preceding word ranges excluded from the self `ranges`.
global_offset: WordPosition,
}
impl<'input> LocalDiffSource<'input, '_> {
fn narrowed(&self, positions: Range<LocalWordPosition>) -> Self {
Self {
text: self.text,
ranges: &self.ranges[positions.start.0..positions.end.0],
hashes: &self.hashes[positions.start.0..positions.end.0],
global_offset: self.map_to_global(positions.start),
}
}
fn map_to_global(&self, position: LocalWordPosition) -> WordPosition {
WordPosition(self.global_offset.0 + position.0)
}
fn hashed_words(
&self,
) -> impl DoubleEndedIterator<Item = HashedWord<'input>> + ExactSizeIterator {
iter::zip(self.ranges, self.hashes).map(|(range, &hash)| {
let text = &self.text[range.clone()];
HashedWord { hash, text }
})
}
}
struct Histogram<'input> {
word_to_positions: HashTable<HistogramEntry<'input>>,
}
// Many of the words are unique. We can inline up to 2 word positions (16 bytes
// on 64-bit platform) in SmallVec for free.
type HistogramEntry<'input> = (HashedWord<'input>, SmallVec<[LocalWordPosition; 2]>);
impl<'input> Histogram<'input> {
fn calculate<C: CompareBytes, S: BuildHasher>(
source: &LocalDiffSource<'input, '_>,
comp: &WordComparator<C, S>,
max_occurrences: usize,
) -> Self {
let mut word_to_positions: HashTable<HistogramEntry> = HashTable::new();
for (i, word) in source.hashed_words().enumerate() {
let pos = LocalWordPosition(i);
word_to_positions
.entry(
word.hash,
|(w, _)| comp.eq(w.text, word.text),
|(w, _)| w.hash,
)
.and_modify(|(_, positions)| {
// Allow one more than max_occurrences, so we can later skip
// those with more than max_occurrences
if positions.len() <= max_occurrences {
positions.push(pos);
}
})
.or_insert_with(|| (word, smallvec![pos]));
}
Self { word_to_positions }
}
fn build_count_to_entries(&self) -> BTreeMap<usize, Vec<&HistogramEntry<'input>>> {
let mut count_to_entries: BTreeMap<usize, Vec<_>> = BTreeMap::new();
for entry in &self.word_to_positions {
let (_, positions) = entry;
let entries = count_to_entries.entry(positions.len()).or_default();
entries.push(entry);
}
count_to_entries
}
fn positions_by_word<C: CompareBytes, S: BuildHasher>(
&self,
word: HashedWord<'input>,
comp: &WordComparator<C, S>,
) -> Option<&[LocalWordPosition]> {
let (_, positions) = self
.word_to_positions
.find(word.hash, |(w, _)| comp.eq(w.text, word.text))?;
Some(positions)
}
}
/// Finds the LCS given a array where the value of `input[i]` indicates that
/// the position of element `i` in the right array is at position `input[i]` in
/// the left array.
///
/// For example (some have multiple valid outputs):
///
/// [0,1,2] => [(0,0),(1,1),(2,2)]
/// [2,1,0] => [(0,2)]
/// [0,1,4,2,3,5,6] => [(0,0),(1,1),(2,3),(3,4),(5,5),(6,6)]
/// [0,1,4,3,2,5,6] => [(0,0),(1,1),(4,2),(5,5),(6,6)]
fn find_lcs(input: &[usize]) -> Vec<(usize, usize)> {
if input.is_empty() {
return vec![];
}
let mut chain = vec![(0, 0, 0); input.len()];
let mut global_longest = 0;
let mut global_longest_right_pos = 0;
for (right_pos, &left_pos) in input.iter().enumerate() {
let mut longest_from_here = 1;
let mut previous_right_pos = usize::MAX;
for i in (0..right_pos).rev() {
let (previous_len, previous_left_pos, _) = chain[i];
if previous_left_pos < left_pos {
let len = previous_len + 1;
if len > longest_from_here {
longest_from_here = len;
previous_right_pos = i;
if len > global_longest {
global_longest = len;
global_longest_right_pos = right_pos;
// If this is the longest chain globally so far, we cannot find a
// longer one by using a previous value, so break early.
break;
}
}
}
}
chain[right_pos] = (longest_from_here, left_pos, previous_right_pos);
}
let mut result = vec![];
let mut right_pos = global_longest_right_pos;
loop {
let (_, left_pos, previous_right_pos) = chain[right_pos];
result.push((left_pos, right_pos));
if previous_right_pos == usize::MAX {
break;
}
right_pos = previous_right_pos;
}
result.reverse();
result
}
/// Finds unchanged word (or token) positions among the ones given as
/// arguments. The data between those words is ignored.
fn collect_unchanged_words<C: CompareBytes, S: BuildHasher>(
found_positions: &mut Vec<(WordPosition, WordPosition)>,
left: &LocalDiffSource,
right: &LocalDiffSource,
comp: &WordComparator<C, S>,
) {
if left.ranges.is_empty() || right.ranges.is_empty() {
return;
}
// Prioritize LCS-based algorithm than leading/trailing matches
let old_len = found_positions.len();
collect_unchanged_words_lcs(found_positions, left, right, comp);
if found_positions.len() != old_len {
return;
}
// Trim leading common ranges (i.e. grow previous unchanged region)
let common_leading_len = iter::zip(left.hashed_words(), right.hashed_words())
.take_while(|&(l, r)| comp.eq_hashed(l, r))
.count();
let left_hashed_words = left.hashed_words().skip(common_leading_len);
let right_hashed_words = right.hashed_words().skip(common_leading_len);
// Trim trailing common ranges (i.e. grow next unchanged region)
let common_trailing_len = iter::zip(left_hashed_words.rev(), right_hashed_words.rev())
.take_while(|&(l, r)| comp.eq_hashed(l, r))
.count();
found_positions.extend(itertools::chain(
(0..common_leading_len).map(|i| {
(
left.map_to_global(LocalWordPosition(i)),
right.map_to_global(LocalWordPosition(i)),
)
}),
(1..=common_trailing_len).rev().map(|i| {
(
left.map_to_global(LocalWordPosition(left.ranges.len() - i)),
right.map_to_global(LocalWordPosition(right.ranges.len() - i)),
)
}),
));
}
fn collect_unchanged_words_lcs<C: CompareBytes, S: BuildHasher>(
found_positions: &mut Vec<(WordPosition, WordPosition)>,
left: &LocalDiffSource,
right: &LocalDiffSource,
comp: &WordComparator<C, S>,
) {
let max_occurrences = 100;
let left_histogram = Histogram::calculate(left, comp, max_occurrences);
let left_count_to_entries = left_histogram.build_count_to_entries();
if *left_count_to_entries.keys().next().unwrap() > max_occurrences {
// If there are very many occurrences of all words, then we just give up.
return;
}
let right_histogram = Histogram::calculate(right, comp, max_occurrences);
// Look for words with few occurrences in `left` (could equally well have picked
// `right`?). If any of them also occur in `right`, then we add the words to
// the LCS.
let Some(uncommon_shared_word_positions) =
left_count_to_entries.values().find_map(|left_entries| {
let mut both_positions = left_entries
.iter()
.filter_map(|&(word, left_positions)| {
let right_positions = right_histogram.positions_by_word(*word, comp)?;
(left_positions.len() == right_positions.len())
.then_some((left_positions, right_positions))
})
.peekable();
both_positions.peek().is_some().then_some(both_positions)
})
else {
return;
};
// [(index into ranges, serial to identify {word, occurrence #})]
let (mut left_positions, mut right_positions): (Vec<_>, Vec<_>) =
uncommon_shared_word_positions
.flat_map(|(lefts, rights)| iter::zip(lefts, rights))
.enumerate()
.map(|(serial, (&left_pos, &right_pos))| ((left_pos, serial), (right_pos, serial)))
.unzip();
left_positions.sort_unstable_by_key(|&(pos, _serial)| pos);
right_positions.sort_unstable_by_key(|&(pos, _serial)| pos);
let left_index_by_right_index: Vec<usize> = {
let mut left_index_map = vec![0; left_positions.len()];
for (i, &(_pos, serial)) in left_positions.iter().enumerate() {
left_index_map[serial] = i;
}
right_positions
.iter()
.map(|&(_pos, serial)| left_index_map[serial])
.collect()
};
let lcs = find_lcs(&left_index_by_right_index);
// Produce output word positions, recursing into the modified areas between
// the elements in the LCS.
let mut previous_left_position = LocalWordPosition(0);
let mut previous_right_position = LocalWordPosition(0);
for (left_index, right_index) in lcs {
let (left_position, _) = left_positions[left_index];
let (right_position, _) = right_positions[right_index];
collect_unchanged_words(
found_positions,
&left.narrowed(previous_left_position..left_position),
&right.narrowed(previous_right_position..right_position),
comp,
);
found_positions.push((
left.map_to_global(left_position),
right.map_to_global(right_position),
));
previous_left_position = LocalWordPosition(left_position.0 + 1);
previous_right_position = LocalWordPosition(right_position.0 + 1);
}
// Also recurse into range at end (after common ranges).
collect_unchanged_words(
found_positions,
&left.narrowed(previous_left_position..LocalWordPosition(left.ranges.len())),
&right.narrowed(previous_right_position..LocalWordPosition(right.ranges.len())),
comp,
);
}
/// Intersects two sorted sequences of `(base, other)` word positions by
/// `base`. `base` positions should refer to the same source text.
fn intersect_unchanged_words(
current_positions: Vec<(WordPosition, Vec<WordPosition>)>,
new_positions: &[(WordPosition, WordPosition)],
) -> Vec<(WordPosition, Vec<WordPosition>)> {
itertools::merge_join_by(
current_positions,
new_positions,
|(cur_base_pos, _), (new_base_pos, _)| cur_base_pos.cmp(new_base_pos),
)
.filter_map(|entry| entry.both())
.map(|((base_pos, mut other_positions), &(_, new_other_pos))| {
other_positions.push(new_other_pos);
(base_pos, other_positions)
})
.collect()
}
#[derive(Clone, PartialEq, Eq, Debug)]
struct UnchangedRange {
// Inline up to two sides (base + one other)
base: Range<usize>,
others: SmallVec<[Range<usize>; 1]>,
}
impl UnchangedRange {
/// Translates word positions to byte ranges in the source texts.
fn from_word_positions(
base_source: &DiffSource,
other_sources: &[DiffSource],
base_position: WordPosition,
other_positions: &[WordPosition],
) -> Self {
assert_eq!(other_sources.len(), other_positions.len());
let base = base_source.range_at(base_position);
let others = iter::zip(other_sources, other_positions)
.map(|(source, pos)| source.range_at(*pos))
.collect();
Self { base, others }
}
fn is_all_empty(&self) -> bool {
self.base.is_empty() && self.others.iter().all(|r| r.is_empty())
}
}
/// Takes any number of inputs and finds regions that are them same between all
/// of them.
#[derive(Clone, Debug)]
pub struct ContentDiff<'input> {
base_input: &'input BStr,
other_inputs: SmallVec<[&'input BStr; 1]>,
/// Sorted list of ranges of unchanged regions in bytes.
///
/// The list should never be empty. The first and the last region may be
/// empty if inputs start/end with changes.
unchanged_regions: Vec<UnchangedRange>,
}
impl<'input> ContentDiff<'input> {
pub fn for_tokenizer<T: AsRef<[u8]> + ?Sized + 'input>(
inputs: impl IntoIterator<Item = &'input T>,
tokenizer: impl Fn(&[u8]) -> Vec<Range<usize>>,
compare: impl CompareBytes,
) -> Self {
let mut inputs = inputs.into_iter().map(BStr::new);
let base_input = inputs.next().expect("inputs must not be empty");
let other_inputs: SmallVec<[&BStr; 1]> = inputs.collect();
// First tokenize each input
let base_token_ranges: Vec<Range<usize>>;
let other_token_ranges: Vec<Vec<Range<usize>>>;
// No need to tokenize if one of the inputs is empty. Non-empty inputs
// are all different as long as the tokenizer emits non-empty ranges.
// This means "" and " " are different even if the compare function is
// ignore-whitespace. They are tokenized as [] and [" "] respectively.
if base_input.is_empty() || other_inputs.iter().any(|input| input.is_empty()) {
base_token_ranges = vec![];
other_token_ranges = std::iter::repeat_n(vec![], other_inputs.len()).collect();
} else {
base_token_ranges = tokenizer(base_input);
other_token_ranges = other_inputs
.iter()
.map(|other_input| tokenizer(other_input))
.collect();
}
Self::with_inputs_and_token_ranges(
base_input,
other_inputs,
&base_token_ranges,
&other_token_ranges,
compare,
)
}
fn with_inputs_and_token_ranges(
base_input: &'input BStr,
other_inputs: SmallVec<[&'input BStr; 1]>,
base_token_ranges: &[Range<usize>],
other_token_ranges: &[Vec<Range<usize>>],
compare: impl CompareBytes,
) -> Self {
assert_eq!(other_inputs.len(), other_token_ranges.len());
let comp = WordComparator::new(compare);
let base_source = DiffSource::new(base_input, base_token_ranges, &comp);
let other_sources = iter::zip(&other_inputs, other_token_ranges)
.map(|(input, token_ranges)| DiffSource::new(input, token_ranges, &comp))
.collect_vec();
let unchanged_regions = match &*other_sources {
// Consider the whole range of the base input as unchanged compared
// to itself.
[] => {
let whole_range = UnchangedRange {
base: 0..base_source.text.len(),
others: smallvec![],
};
vec![whole_range]
}
// Diff each other input against the base. Intersect the previously
// found ranges with the ranges in the diff.
[first_other_source, tail_other_sources @ ..] => {
let mut unchanged_regions = Vec::new();
// Add an empty range at the start to make life easier for hunks().
unchanged_regions.push(UnchangedRange {
base: 0..0,
others: smallvec![0..0; other_inputs.len()],
});
let mut first_positions = Vec::new();
collect_unchanged_words(
&mut first_positions,
&base_source.local(),
&first_other_source.local(),
&comp,
);
if tail_other_sources.is_empty() {
unchanged_regions.extend(first_positions.iter().map(
|&(base_pos, other_pos)| {
UnchangedRange::from_word_positions(
&base_source,
&other_sources,
base_pos,
&[other_pos],
)
},
));
} else {
let first_positions = first_positions
.iter()
.map(|&(base_pos, other_pos)| (base_pos, vec![other_pos]))
.collect();
let intersected_positions = tail_other_sources.iter().fold(
first_positions,
|current_positions, other_source| {
let mut new_positions = Vec::new();
collect_unchanged_words(
&mut new_positions,
&base_source.local(),
&other_source.local(),
&comp,
);
intersect_unchanged_words(current_positions, &new_positions)
},
);
unchanged_regions.extend(intersected_positions.iter().map(
|(base_pos, other_positions)| {
UnchangedRange::from_word_positions(
&base_source,
&other_sources,
*base_pos,
other_positions,
)
},
));
}
// Add an empty range at the end to make life easier for hunks().
unchanged_regions.push(UnchangedRange {
base: base_input.len()..base_input.len(),
others: other_inputs
.iter()
.map(|input| input.len()..input.len())
.collect(),
});
unchanged_regions
}
};
let mut diff = Self {
base_input,
other_inputs,
unchanged_regions,
};
diff.compact_unchanged_regions();
diff
}
pub fn unrefined<T: AsRef<[u8]> + ?Sized + 'input>(
inputs: impl IntoIterator<Item = &'input T>,
) -> Self {
ContentDiff::for_tokenizer(inputs, |_| vec![], CompareBytesExactly)
}
/// Compares `inputs` line by line.
pub fn by_line<T: AsRef<[u8]> + ?Sized + 'input>(
inputs: impl IntoIterator<Item = &'input T>,
) -> Self {
ContentDiff::for_tokenizer(inputs, find_line_ranges, CompareBytesExactly)
}
/// Compares `inputs` word by word.
///
/// The `inputs` is usually a changed hunk (e.g. a `DiffHunk::Different`)
/// that was the output from a line-by-line diff.
pub fn by_word<T: AsRef<[u8]> + ?Sized + 'input>(
inputs: impl IntoIterator<Item = &'input T>,
) -> Self {
let mut diff = ContentDiff::for_tokenizer(inputs, find_word_ranges, CompareBytesExactly);
diff.refine_changed_regions(find_nonword_ranges, CompareBytesExactly);
diff
}
/// Returns iterator over matching and different texts.
pub fn hunks(&self) -> DiffHunkIterator<'_, 'input> {
let ranges = self.hunk_ranges();
DiffHunkIterator { diff: self, ranges }
}
/// Returns iterator over matching and different ranges in bytes.
pub fn hunk_ranges(&self) -> DiffHunkRangeIterator<'_> {
DiffHunkRangeIterator::new(self)
}
/// Returns contents at the unchanged `range`.
fn hunk_at(&self, range: &UnchangedRange) -> impl Iterator<Item = &'input BStr> {
itertools::chain(
iter::once(&self.base_input[range.base.clone()]),
iter::zip(&self.other_inputs, &range.others).map(|(input, r)| &input[r.clone()]),
)
}
/// Returns contents between the `previous` ends and the `current` starts.
fn hunk_between(
&self,
previous: &UnchangedRange,
current: &UnchangedRange,
) -> impl Iterator<Item = &'input BStr> {
itertools::chain(
iter::once(&self.base_input[previous.base.end..current.base.start]),
itertools::izip!(&self.other_inputs, &previous.others, ¤t.others)
.map(|(input, prev, cur)| &input[prev.end..cur.start]),
)
}
/// Uses the given tokenizer to split the changed regions into smaller
/// regions. Then tries to finds unchanged regions among them.
pub fn refine_changed_regions(
&mut self,
tokenizer: impl Fn(&[u8]) -> Vec<Range<usize>>,
compare: impl CompareBytes,
) {
let mut new_unchanged_ranges = vec![self.unchanged_regions[0].clone()];
for window in self.unchanged_regions.windows(2) {
let [previous, current]: &[_; 2] = window.try_into().unwrap();
// For the changed region between the previous region and the current one,
// create a new Diff instance. Then adjust the start positions and
// offsets to be valid in the context of the larger Diff instance
// (`self`).
let refined_diff = ContentDiff::for_tokenizer(
self.hunk_between(previous, current),
&tokenizer,
&compare,
);
for refined in &refined_diff.unchanged_regions {
let new_base_start = refined.base.start + previous.base.end;
let new_base_end = refined.base.end + previous.base.end;
let new_others = iter::zip(&refined.others, &previous.others)
.map(|(refi, prev)| (refi.start + prev.end)..(refi.end + prev.end))
.collect();
new_unchanged_ranges.push(UnchangedRange {
base: new_base_start..new_base_end,
others: new_others,
});
}
new_unchanged_ranges.push(current.clone());
}
self.unchanged_regions = new_unchanged_ranges;
self.compact_unchanged_regions();
}
fn compact_unchanged_regions(&mut self) {
let mut compacted = vec![];
let mut maybe_previous: Option<UnchangedRange> = None;
for current in &self.unchanged_regions {
if let Some(previous) = maybe_previous {
if previous.base.end == current.base.start
&& iter::zip(&previous.others, ¤t.others)
.all(|(prev, cur)| prev.end == cur.start)
{
maybe_previous = Some(UnchangedRange {
base: previous.base.start..current.base.end,
others: iter::zip(&previous.others, ¤t.others)
.map(|(prev, cur)| prev.start..cur.end)
.collect(),
});
continue;
}
compacted.push(previous);
}
maybe_previous = Some(current.clone());
}
if let Some(previous) = maybe_previous {
compacted.push(previous);
}
self.unchanged_regions = compacted;
}
}
/// Hunk texts.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiffHunk<'input> {
pub kind: DiffHunkKind,
pub contents: DiffHunkContentVec<'input>,
}
impl<'input> DiffHunk<'input> {
pub fn matching<T: AsRef<[u8]> + ?Sized + 'input>(
contents: impl IntoIterator<Item = &'input T>,
) -> Self {
Self {
kind: DiffHunkKind::Matching,
contents: contents.into_iter().map(BStr::new).collect(),
}
}
pub fn different<T: AsRef<[u8]> + ?Sized + 'input>(
contents: impl IntoIterator<Item = &'input T>,
) -> Self {
Self {
kind: DiffHunkKind::Different,
contents: contents.into_iter().map(BStr::new).collect(),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiffHunkKind {
Matching,
Different,
}
// Inline up to two sides
pub type DiffHunkContentVec<'input> = SmallVec<[&'input BStr; 2]>;
/// Iterator over matching and different texts.
#[derive(Clone, Debug)]
pub struct DiffHunkIterator<'diff, 'input> {
diff: &'diff ContentDiff<'input>,
ranges: DiffHunkRangeIterator<'diff>,
}
impl<'input> Iterator for DiffHunkIterator<'_, 'input> {
type Item = DiffHunk<'input>;
fn next(&mut self) -> Option<Self::Item> {
self.ranges.next_with(
|previous| {
let contents = self.diff.hunk_at(previous).collect();
let kind = DiffHunkKind::Matching;
DiffHunk { kind, contents }
},
|previous, current| {
let contents: DiffHunkContentVec =
self.diff.hunk_between(previous, current).collect();
debug_assert!(
contents.iter().any(|content| !content.is_empty()),
"unchanged regions should have been compacted"
);
let kind = DiffHunkKind::Different;
DiffHunk { kind, contents }
},
)
}
}
/// Hunk ranges in bytes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiffHunkRange {
pub kind: DiffHunkKind,
pub ranges: DiffHunkRangeVec,
}
// Inline up to two sides
pub type DiffHunkRangeVec = SmallVec<[Range<usize>; 2]>;
/// Iterator over matching and different ranges in bytes.
#[derive(Clone, Debug)]
pub struct DiffHunkRangeIterator<'diff> {
previous: &'diff UnchangedRange,
unchanged_emitted: bool,
unchanged_iter: slice::Iter<'diff, UnchangedRange>,
}
impl<'diff> DiffHunkRangeIterator<'diff> {
fn new(diff: &'diff ContentDiff) -> Self {
let mut unchanged_iter = diff.unchanged_regions.iter();
let previous = unchanged_iter.next().unwrap();
Self {
previous,
unchanged_emitted: previous.is_all_empty(),
unchanged_iter,
}
}
fn next_with<T>(
&mut self,
hunk_at: impl FnOnce(&UnchangedRange) -> T,
hunk_between: impl FnOnce(&UnchangedRange, &UnchangedRange) -> T,
) -> Option<T> {
if !self.unchanged_emitted {
self.unchanged_emitted = true;
return Some(hunk_at(self.previous));
}
let current = self.unchanged_iter.next()?;
let hunk = hunk_between(self.previous, current);
self.previous = current;
self.unchanged_emitted = self.previous.is_all_empty();
Some(hunk)
}
}
impl Iterator for DiffHunkRangeIterator<'_> {
type Item = DiffHunkRange;
fn next(&mut self) -> Option<Self::Item> {
self.next_with(
|previous| {
let ranges = itertools::chain(iter::once(&previous.base), &previous.others)
.cloned()
.collect();
let kind = DiffHunkKind::Matching;
DiffHunkRange { kind, ranges }
},
|previous, current| {
let ranges: DiffHunkRangeVec = itertools::chain(
iter::once(previous.base.end..current.base.start),
iter::zip(&previous.others, ¤t.others)
.map(|(prev, cur)| prev.end..cur.start),
)
.collect();
debug_assert!(
ranges.iter().any(|range| !range.is_empty()),
"unchanged regions should have been compacted"