-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff_match_patch.h
2596 lines (2430 loc) · 94.1 KB
/
diff_match_patch.h
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 2008 Google Inc. All Rights Reserved.
* Author: fraser@google.com (Neil Fraser)
* Author: mikeslemmer@gmail.com (Mike Slemmer)
* Author: snhere@gmail.com (Sergey Nozhenko)
*
* 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
*
* http://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.
*
* Diff Match and Patch
* http://code.google.com/p/google-diff-match-patch/
*/
#ifndef DIFF_MATCH_PATCH_H
#define DIFF_MATCH_PATCH_H
#include <limits>
#include <list>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cwchar>
#include <time.h>
/*
* Functions for diff, match and patch.
* Computes the difference between two texts to create a patch.
* Applies the patch onto another text, allowing for errors.
*
* @author fraser@google.com (Neil Fraser)
*
* Qt/C++ port by mikeslemmer@gmail.com (Mike Slemmer)
*
* STL-only port by snhere@gmail.com (Sergey Nozhenko)
* and some tweaks for std::string by leutloff@sundancer.oche.de (Christian Leutloff)
*
* Here is a trivial sample program:
*
#include "diff_match_patch.h"
#include <string>
using namespace std;
int main(int argc, char **argv) {
diff_match_patch<wstring> dmp;
wstring str1 = L"First string in diff";
wstring str2 = L"Second string in diff";
wstring strPatch = dmp.patch_toText(dmp.patch_make(str1, str2));
pair<wstring, vector<bool> > out
= dmp.patch_apply(dmp.patch_fromText(strPatch), str1);
wstring strResult = out.first;
// here, strResult will equal str2 above.
return 0;
}
*/
// Character type dependencies
template <class char_t> struct diff_match_patch_traits {};
/**
* Class containing the diff, match and patch methods.
* Also contains the behaviour settings.
*/
template <class stringT, class traits = diff_match_patch_traits<typename stringT::value_type> >
class diff_match_patch {
public:
/**
* String and character types
*/
typedef stringT string_t;
typedef typename string_t::value_type char_t;
/**-
* The data structure representing a diff is a Linked list of Diff objects:
* {Diff(Operation.DELETE, "Hello"), Diff(Operation.INSERT, "Goodbye"),
* Diff(Operation.EQUAL, " world.")}
* which means: delete "Hello", add "Goodbye" and keep " world."
*/
enum Operation {
DELETE, INSERT, EQUAL
};
/**
* Class representing one diff operation.
*/
class Diff {
public:
Operation operation;
// One of: INSERT, DELETE or EQUAL.
string_t text;
// The text associated with this diff operation.
/**
* Constructor. Initializes the diff with the provided values.
* @param operation One of INSERT, DELETE or EQUAL.
* @param text The text being applied.
*/
Diff(Operation _operation, const string_t &_text) : operation(_operation), text(_text) {}
Diff() {}
/**
* Display a human-readable version of this Diff.
* @return text version.
*/
string_t toString() const {
string_t prettyText = text;
// Replace linebreaks with Pilcrow signs.
for (typename string_t::iterator i = prettyText.begin(); i != prettyText.end(); ++i)
if (traits::to_wchar(*i) == L'\n') *i = traits::from_wchar(L'\u00b6');
return traits::cs(L"Diff(") + strOperation(operation) + traits::cs(L",\"") + prettyText + traits::cs(L"\")");
}
/**
* Is this Diff equivalent to another Diff?
* @param d Another Diff to compare against
* @return true or false
*/
bool operator==(const Diff &d) const {
return (d.operation == this->operation) && (d.text == this->text);
}
bool operator!=(const Diff &d) const { return !(operator == (d)); }
static string_t strOperation(Operation op) {
switch (op) {
case INSERT:
return traits::cs(L"INSERT");
case DELETE:
return traits::cs(L"DELETE");
case EQUAL:
return traits::cs(L"EQUAL");
}
throw string_t(traits::cs(L"Invalid operation."));
}
};
typedef std::list<Diff> Diffs;
/**
* Class representing one patch operation.
*/
class Patch {
public:
Diffs diffs;
int start1;
int start2;
int length1;
int length2;
/**
* Constructor. Initializes with an empty list of diffs.
*/
Patch() : start1(0), start2(0), length1(0), length2(0) {}
bool isNull() const {
return start1 == 0 && start2 == 0 && length1 == 0 && length2 == 0 && diffs.size() == 0;
}
/**
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* Indices are printed as 1-based, not 0-based.
* @return The GNU diff string
*/
string_t toString() const {
string_t coords1, coords2;
if (length1 == 0) {
coords1 = to_string(start1) + traits::cs(L",0");
} else if (length1 == 1) {
coords1 = to_string(start1 + 1);
} else {
coords1 = to_string(start1 + 1) + traits::from_wchar(L',') + to_string(length1);
}
if (length2 == 0) {
coords2 = to_string(start2) + traits::cs(L",0");
} else if (length2 == 1) {
coords2 = to_string(start2 + 1);
} else {
coords2 = to_string(start2 + 1) + traits::from_wchar(L',') + to_string(length2);
}
string_t text(traits::cs(L"@@ -") + coords1 + traits::cs(L" +") + coords2 + traits::cs(L" @@\n"));
// Escape the body of the patch with %xx notation.
for (typename Diffs::const_iterator cur_diff = diffs.begin(); cur_diff != diffs.end(); ++cur_diff) {
switch ((*cur_diff).operation) {
case INSERT:
text += traits::from_wchar(L'+');
break;
case DELETE:
text += traits::from_wchar(L'-');
break;
case EQUAL:
text += traits::from_wchar(L' ');
break;
}
append_percent_encoded(text, (*cur_diff).text);
text += traits::from_wchar(L'\n');
}
return text;
}
};
typedef std::list<Patch> Patches;
friend class diff_match_patch_test;
public:
// Defaults.
// Set these on your diff_match_patch instance to override the defaults.
// Number of seconds to map a diff before giving up (0 for infinity).
float Diff_Timeout;
// Cost of an empty edit operation in terms of edit characters.
short Diff_EditCost;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
float Match_Threshold;
// How far to search for a match (0 = exact location, 1000+ = broad match).
// A match this many characters away from the expected location will add
// 1.0 to the score (0.0 is a perfect match).
int Match_Distance;
// When deleting a large block of text (over ~64 characters), how close does
// the contents have to match the expected contents. (0.0 = perfection,
// 1.0 = very loose). Note that Match_Threshold controls how closely the
// end points of a delete need to match.
float Patch_DeleteThreshold;
// Chunk size for context length.
short Patch_Margin;
// The number of bits in an int.
short Match_MaxBits;
public:
diff_match_patch() :
Diff_Timeout(1.0f),
Diff_EditCost(4),
Match_Threshold(0.5f),
Match_Distance(1000),
Patch_DeleteThreshold(0.5f),
Patch_Margin(4),
Match_MaxBits(32) {
}
// DIFF FUNCTIONS
/**
* Find the differences between two texts.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @param checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster slightly less optimal diff.
* Most of the time checklines is wanted, so default to true.
* @return Linked List of Diff objects.
*/
Diffs diff_main(const string_t &text1, const string_t &text2, bool checklines = true) const {
// Set a deadline by which time the diff must be complete.
clock_t deadline;
if (Diff_Timeout <= 0) {
deadline = std::numeric_limits<clock_t>::max();
} else {
deadline = clock() + (clock_t)(Diff_Timeout * CLOCKS_PER_SEC);
}
Diffs diffs;
diff_main(text1, text2, checklines, deadline, diffs);
return diffs;
}
/**
* Find the differences between two texts. Simplifies the problem by
* stripping any common prefix or suffix off the texts before diffing.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @param checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster slightly less optimal diff.
* @param deadline Time when the diff should be complete by. Used
* internally for recursive calls. Users should set DiffTimeout instead.
* @param Linked List of Diff objects.
*/
private:
static void diff_main(const string_t &text1, const string_t &text2, bool checklines, clock_t deadline, Diffs& diffs) {
diffs.clear();
// Check for equality (speedup).
if (text1 == text2) {
if (!text1.empty()) {
diffs.push_back(Diff(EQUAL, text1));
}
}
else {
// Trim off common prefix (speedup).
int commonlength = diff_commonPrefix(text1, text2);
const string_t &commonprefix = text1.substr(0, commonlength);
string_t textChopped1 = text1.substr(commonlength);
string_t textChopped2 = text2.substr(commonlength);
// Trim off common suffix (speedup).
commonlength = diff_commonSuffix(textChopped1, textChopped2);
const string_t &commonsuffix = right(textChopped1, commonlength);
textChopped1 = textChopped1.substr(0, textChopped1.length() - commonlength);
textChopped2 = textChopped2.substr(0, textChopped2.length() - commonlength);
// Compute the diff on the middle block.
diff_compute(textChopped1, textChopped2, checklines, deadline, diffs);
// Restore the prefix and suffix.
if (!commonprefix.empty()) {
diffs.push_front(Diff(EQUAL, commonprefix));
}
if (!commonsuffix.empty()) {
diffs.push_back(Diff(EQUAL, commonsuffix));
}
diff_cleanupMerge(diffs);
}
}
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @param checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster slightly less optimal diff.
* @param deadline Time when the diff should be complete by.
* @param Linked List of Diff objects.
*/
private:
static void diff_compute(string_t text1, string_t text2, bool checklines, clock_t deadline, Diffs& diffs) {
if (text1.empty()) {
// Just add some text (speedup).
diffs.push_back(Diff(INSERT, text2));
return;
}
if (text2.empty()) {
// Just delete some text (speedup).
diffs.push_back(Diff(DELETE, text1));
return;
}
{
const string_t& longtext = text1.length() > text2.length() ? text1 : text2;
const string_t& shorttext = text1.length() > text2.length() ? text2 : text1;
const size_t i = longtext.find(shorttext);
if (i != string_t::npos) {
// Shorter text is inside the longer text (speedup).
const Operation op = (text1.length() > text2.length()) ? DELETE : INSERT;
diffs.push_back(Diff(op, longtext.substr(0, i)));
diffs.push_back(Diff(EQUAL, shorttext));
diffs.push_back(Diff(op, safeMid(longtext, i + shorttext.length())));
return;
}
if (shorttext.length() == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
diffs.push_back(Diff(DELETE, text1));
diffs.push_back(Diff(INSERT, text2));
return;
}
// Garbage collect longtext and shorttext by scoping out.
}
// Don't risk returning a non-optimal diff if we have unlimited time.
if (deadline != std::numeric_limits<clock_t>::max()) {
// Check to see if the problem can be split in two.
HalfMatchResult hm;
if (diff_halfMatch(text1, text2, hm)) {
// A half-match was found, sort out the return data.
// Send both pairs off for separate processing.
diff_main(hm.text1_a, hm.text2_a, checklines, deadline, diffs);
diffs.push_back(Diff(EQUAL, hm.mid_common));
Diffs diffs_b;
diff_main(hm.text1_b, hm.text2_b, checklines, deadline, diffs_b);
diffs.splice(diffs.end(), diffs_b);
return;
}
}
// Perform a real diff.
if (checklines && text1.length() > 100 && text2.length() > 100) {
diff_lineMode(text1, text2, deadline, diffs);
return;
}
diff_bisect(text1, text2, deadline, diffs);
}
/**
* Do a quick line-level diff on both strings, then rediff the parts for
* greater accuracy.
* This speedup can produce non-minimal diffs.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @param deadline Time when the diff should be complete by.
* @param Linked List of Diff objects.
*/
private:
static void diff_lineMode(string_t text1, string_t text2, clock_t deadline, Diffs& diffs) {
// Scan the text on a line-by-line basis first.
Lines linearray;
diff_linesToChars(text1, text2, linearray);
diff_main(text1, text2, false, deadline, diffs);
// Convert the diff back to original text.
diff_charsToLines(diffs, linearray);
// Eliminate freak matches (e.g. blank lines)
diff_cleanupSemantic(diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.push_back(Diff(EQUAL, string_t()));
int count_delete = 0;
int count_insert = 0;
string_t text_delete;
string_t text_insert;
for (typename Diffs::iterator cur_diff = diffs.begin(); cur_diff != diffs.end(); ++cur_diff) {
switch ((*cur_diff).operation) {
case INSERT:
count_insert++;
text_insert += (*cur_diff).text;
break;
case DELETE:
count_delete++;
text_delete += (*cur_diff).text;
break;
case EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (count_delete >= 1 && count_insert >= 1) {
// Delete the offending records and add the merged ones.
typename Diffs::iterator last = cur_diff;
std::advance(cur_diff, -(count_delete + count_insert));
cur_diff = diffs.erase(cur_diff, last);
Diffs new_diffs;
diff_main(text_delete, text_insert, false, deadline, new_diffs);
diffs.splice(cur_diff++, new_diffs);
--cur_diff;
}
count_insert = 0;
count_delete = 0;
text_delete.clear();
text_insert.clear();
break;
}
}
diffs.pop_back(); // Remove the dummy entry at the end.
}
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @return Linked List of Diff objects.
*/
protected:
static Diffs diff_bisect(const string_t &text1, const string_t &text2, clock_t deadline) {
Diffs diffs;
diff_bisect(text1, text2, deadline, diffs);
return diffs;
}
private:
static void diff_bisect(const string_t &text1, const string_t &text2, clock_t deadline, Diffs& diffs) {
// Cache the text lengths to prevent multiple calls.
const int text1_length = text1.length();
const int text2_length = text2.length();
const int max_d = (text1_length + text2_length + 1) / 2;
const int v_offset = max_d;
const int v_length = 2 * max_d;
std::vector<int> v1(v_length, -1),
v2(v_length, -1);
v1[v_offset + 1] = 0;
v2[v_offset + 1] = 0;
const int delta = text1_length - text2_length;
// If the total number of characters is odd, then the front path will
// collide with the reverse path.
const bool front = (delta % 2 != 0);
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
int k1start = 0;
int k1end = 0;
int k2start = 0;
int k2end = 0;
for (int d = 0; d < max_d; d++) {
// Bail out if deadline is reached.
if (clock() > deadline) {
break;
}
// Walk the front path one step.
for (int k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
const int k1_offset = v_offset + k1;
int x1;
if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
x1 = v1[k1_offset + 1];
} else {
x1 = v1[k1_offset - 1] + 1;
}
int y1 = x1 - k1;
while (x1 < text1_length && y1 < text2_length
&& text1[x1] == text2[y1]) {
x1++;
y1++;
}
v1[k1_offset] = x1;
if (x1 > text1_length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2_length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
int k2_offset = v_offset + delta - k1;
if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
// Mirror x2 onto top-left coordinate system.
int x2 = text1_length - v2[k2_offset];
if (x1 >= x2) {
// Overlap detected.
diff_bisectSplit(text1, text2, x1, y1, deadline, diffs);
return;
}
}
}
}
// Walk the reverse path one step.
for (int k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
const int k2_offset = v_offset + k2;
int x2;
if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
x2 = v2[k2_offset + 1];
} else {
x2 = v2[k2_offset - 1] + 1;
}
int y2 = x2 - k2;
while (x2 < text1_length && y2 < text2_length
&& text1[text1_length - x2 - 1] == text2[text2_length - y2 - 1]) {
x2++;
y2++;
}
v2[k2_offset] = x2;
if (x2 > text1_length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2_length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
int k1_offset = v_offset + delta - k2;
if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
int x1 = v1[k1_offset];
int y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2;
if (x1 >= x2) {
// Overlap detected.
diff_bisectSplit(text1, text2, x1, y1, deadline, diffs);
return;
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
diffs.clear();
diffs.push_back(Diff(DELETE, text1));
diffs.push_back(Diff(INSERT, text2));
}
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param text1 Old string to be diffed.
* @param text2 New string to be diffed.
* @param x Index of split point in text1.
* @param y Index of split point in text2.
* @param deadline Time at which to bail if not yet complete.
* @return LinkedList of Diff objects.
*/
private:
static void diff_bisectSplit(const string_t &text1, const string_t &text2, int x, int y, clock_t deadline, Diffs& diffs) {
string_t text1a = text1.substr(0, x);
string_t text2a = text2.substr(0, y);
string_t text1b = safeMid(text1, x);
string_t text2b = safeMid(text2, y);
// Compute both diffs serially.
diff_main(text1a, text2a, false, deadline, diffs);
Diffs diffs_b;
diff_main(text1b, text2b, false, deadline, diffs_b);
diffs.splice(diffs.end(), diffs_b);
}
/**
* Split two texts into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param text1 First string.
* @param text2 Second string.
* @return Lines object, containing the encoded text1, the
* encoded text2 and the List of pointers to unique strings. The zeroth element
* of the List of unique strings is intentionally blank.
*/
protected:
struct LinePtr : std::pair<typename string_t::const_pointer, size_t> {
LinePtr() {}
LinePtr(typename string_t::const_pointer p, size_t n) : std::pair<typename string_t::const_pointer, size_t>(p, n) {}
bool operator<(const LinePtr& p) const
{ return this->second < p.second? true : this->second > p.second? false : string_t::traits_type::compare(this->first, p.first, this->second) < 0; }
};
struct Lines : std::vector<LinePtr> { string_t text1, text2; };
static void diff_linesToChars(string_t &text1, string_t &text2, Lines& lineArray) {
std::map<LinePtr, size_t> lineHash;
lineArray.text1.swap(text1), lineArray.text2.swap(text2);
// e.g. linearray[4] == "Hello\n"
// e.g. linehash.get("Hello\n") == 4
// "\x00" is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
text1 = diff_linesToCharsMunge(lineArray.text1, lineHash);
text2 = diff_linesToCharsMunge(lineArray.text2, lineHash);
lineArray.resize(lineHash.size() + 1);
for (typename std::map<LinePtr, size_t>::const_iterator i = lineHash.begin(); i != lineHash.end(); ++i)
lineArray[(*i).second] = (*i).first;
}
/**
* Split a text into a list of pointers to strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param text String to encode.
* @param lineHash Map of string pointers to indices.
* @return Encoded string.
*/
private:
static string_t diff_linesToCharsMunge(const string_t &text, std::map<LinePtr, size_t> &lineHash) {
string_t chars;
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
typename string_t::size_type lineLen;
for (typename string_t::const_pointer lineStart = text.c_str(), textEnd = lineStart + text.size(); lineStart < textEnd; lineStart += lineLen + 1) {
lineLen = next_token(text, traits::from_wchar(L'\n'), lineStart);
if (lineStart + lineLen == textEnd) --lineLen;
chars += (char_t)(*lineHash.insert(std::make_pair(LinePtr(lineStart, lineLen + 1), lineHash.size() + 1)).first).second;
}
return chars;
}
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param diffs LinkedList of Diff objects.
* @param lineArray List of pointers to unique strings.
*/
private:
static void diff_charsToLines(Diffs &diffs, const Lines& lineArray) {
for (typename Diffs::iterator cur_diff = diffs.begin(); cur_diff != diffs.end(); ++cur_diff) {
string_t text;
for (int y = 0; y < (int)(*cur_diff).text.length(); y++) {
const LinePtr& lp = lineArray[static_cast<size_t>((*cur_diff).text[y])];
text.append(lp.first, lp.second);
}
(*cur_diff).text.swap(text);
}
}
/**
* Determine the common prefix of two strings.
* @param text1 First string.
* @param text2 Second string.
* @return The number of characters common to the start of each string.
*/
public:
static int diff_commonPrefix(const string_t &text1, const string_t &text2) {
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
const int n = std::min(text1.length(), text2.length());
for (int i = 0; i < n; i++) {
if (text1[i] != text2[i]) {
return i;
}
}
return n;
}
/**
* Determine the common suffix of two strings.
* @param text1 First string.
* @param text2 Second string.
* @return The number of characters common to the end of each string.
*/
public:
static int diff_commonSuffix(const string_t &text1, const string_t &text2) {
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
const int text1_length = text1.length();
const int text2_length = text2.length();
const int n = std::min(text1_length, text2_length);
for (int i = 1; i <= n; i++) {
if (text1[text1_length - i] != text2[text2_length - i]) {
return i - 1;
}
}
return n;
}
/**
* Determine if the suffix of one string is the prefix of another.
* @param text1 First string.
* @param text2 Second string.
* @return The number of characters common to the end of the first
* string and the start of the second string.
*/
protected:
static int diff_commonOverlap(const string_t &text1, const string_t &text2) {
// Cache the text lengths to prevent multiple calls.
const int text1_length = text1.length();
const int text2_length = text2.length();
// Eliminate the null case.
if (text1_length == 0 || text2_length == 0) {
return 0;
}
// Truncate the longer string.
string_t text1_trunc = text1;
string_t text2_trunc = text2;
if (text1_length > text2_length) {
text1_trunc = right(text1, text2_length);
} else if (text1_length < text2_length) {
text2_trunc = text2.substr(0, text1_length);
}
const int text_length = std::min(text1_length, text2_length);
// Quick check for the worst case.
if (text1_trunc == text2_trunc) {
return text_length;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
int best = 0;
int length = 1;
while (true) {
string_t pattern = right(text1_trunc, length);
size_t found = text2_trunc.find(pattern);
if (found == string_t::npos) {
return best;
}
length += found;
if (found == 0 || right(text1_trunc, length) == text2_trunc.substr(0, length)) {
best = length;
length++;
}
}
}
/**
* Do the two texts share a substring which is at least half the length of
* the longer text?
* This speedup can produce non-minimal diffs.
* @param text1 First string.
* @param text2 Second string.
* @param HalfMatchResult object, containing the prefix of text1, the
* suffix of text1, the prefix of text2, the suffix of text2 and the
* common middle.
* @return Boolean true if there was a match, false otherwise.
*/
protected:
struct HalfMatchResult {
string_t text1_a, text1_b, text2_a, text2_b, mid_common;
void swap(HalfMatchResult& hm) {
text1_a.swap(hm.text1_a), text1_b.swap(hm.text1_b), text2_a.swap(hm.text2_a), text2_b.swap(hm.text2_b), mid_common.swap(hm.mid_common);
}
};
static bool diff_halfMatch(const string_t &text1, const string_t &text2, HalfMatchResult& hm) {
const string_t longtext = text1.length() > text2.length() ? text1 : text2;
const string_t shorttext = text1.length() > text2.length() ? text2 : text1;
if (longtext.length() < 4 || shorttext.length() * 2 < longtext.length()) {
return false; // Pointless.
}
HalfMatchResult res1, res2;
// First check if the second quarter is the seed for a half-match.
bool hm1 = diff_halfMatchI(longtext, shorttext,
(longtext.length() + 3) / 4, res1);
// Check again based on the third quarter.
bool hm2 = diff_halfMatchI(longtext, shorttext,
(longtext.length() + 1) / 2, res2);
if (!hm1 && !hm2) {
return false;
} else if (!hm2) {
hm.swap(res1);
} else if (!hm1) {
hm.swap(res2);
} else {
// Both matched. Select the longest.
hm.swap(res1.mid_common.length() > res2.mid_common.length() ? res1 : res2);
}
// A half-match was found, sort out the return data.
if (text1.length() <= text2.length()) {
hm.text1_a.swap(hm.text2_a);
hm.text1_b.swap(hm.text2_b);
}
return true;
}
/**
* Does a substring of shorttext exist within longtext such that the
* substring is at least half the length of longtext?
* @param longtext Longer string.
* @param shorttext Shorter string.
* @param i Start index of quarter length substring within longtext.
* @param HalfMatchResult object, containing the prefix of longtext, the
* suffix of longtext, the prefix of shorttext, the suffix of shorttext
* and the common middle.
* @return Boolean true if there was a match, false otherwise.
*/
private:
static bool diff_halfMatchI(const string_t &longtext, const string_t &shorttext, int i, HalfMatchResult& best) {
// Start with a 1/4 length substring at position i as a seed.
const string_t seed = safeMid(longtext, i, longtext.length() / 4);
size_t j = string_t::npos;
while ((j = shorttext.find(seed, j + 1)) != string_t::npos) {
const int prefixLength = diff_commonPrefix(safeMid(longtext, i),
safeMid(shorttext, j));
const int suffixLength = diff_commonSuffix(longtext.substr(0, i),
shorttext.substr(0, j));
if ((int)best.mid_common.length() < suffixLength + prefixLength) {
best.mid_common = safeMid(shorttext, j - suffixLength, suffixLength)
+ safeMid(shorttext, j, prefixLength);
best.text1_a = longtext.substr(0, i - suffixLength);
best.text1_b = safeMid(longtext, i + prefixLength);
best.text2_a = shorttext.substr(0, j - suffixLength);
best.text2_b = safeMid(shorttext, j + prefixLength);
}
}
return best.mid_common.length() * 2 >= longtext.length();
}
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param diffs LinkedList of Diff objects.
*/
public:
static void diff_cleanupSemantic(Diffs &diffs) {
if (diffs.empty()) {
return;
}
bool changes = false;
std::vector<typename Diffs::iterator> equalities; // Stack of equalities.
string_t lastequality; // Always equal to equalities.lastElement().text
typename Diffs::iterator cur_diff;
// Number of characters that changed prior to the equality.
int length_insertions1 = 0;
int length_deletions1 = 0;
// Number of characters that changed after the equality.
int length_insertions2 = 0;
int length_deletions2 = 0;
for (cur_diff = diffs.begin(); cur_diff != diffs.end();) {
if ((*cur_diff).operation == EQUAL) {
// Equality found.
equalities.push_back(cur_diff);
length_insertions1 = length_insertions2;
length_deletions1 = length_deletions2;
length_insertions2 = 0;
length_deletions2 = 0;
lastequality = (*cur_diff).text;
} else {
// An insertion or deletion.
if ((*cur_diff).operation == INSERT) {
length_insertions2 += (*cur_diff).text.length();
} else {
length_deletions2 += (*cur_diff).text.length();
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (!lastequality.empty()
&& ((int)lastequality.length()
<= std::max(length_insertions1, length_deletions1))
&& ((int)lastequality.length()
<= std::max(length_insertions2, length_deletions2))) {
// printf("Splitting: '%s'\n", qPrintable(lastequality));
// Walk back to offending equality.
// Change second copy to insert.
(*(cur_diff = equalities.back())).operation = INSERT;
// Duplicate record.
diffs.insert(cur_diff, Diff(DELETE, lastequality));
equalities.pop_back(); // Throw away the equality we just deleted.
if (!equalities.empty()) {
// Throw away the previous equality (it needs to be reevaluated).
equalities.pop_back();
}
length_insertions1 = 0; // Reset the counters.
length_deletions1 = 0;
length_insertions2 = 0;
length_deletions2 = 0;
lastequality = string_t();
changes = true;
if (!equalities.empty())
// There is a safe equality we can fall back to.
cur_diff = equalities.back();
else
{
// There are no previous equalities, walk back to the start.
cur_diff = diffs.begin();
continue;
}
}
}
++cur_diff;
}
// Normalize the diff.
if (changes) {
diff_cleanupMerge(diffs);
}
diff_cleanupSemanticLossless(diffs);
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
if ((cur_diff = diffs.begin()) != diffs.end()) {
for (typename Diffs::iterator prev_diff = cur_diff; ++cur_diff != diffs.end(); prev_diff = cur_diff) {
if ((*prev_diff).operation == DELETE &&
(*cur_diff).operation == INSERT) {
string_t deletion = (*prev_diff).text;
string_t insertion = (*cur_diff).text;
int overlap_length1 = diff_commonOverlap(deletion, insertion);
int overlap_length2 = diff_commonOverlap(insertion, deletion);
if (overlap_length1 >= overlap_length2) {
if (overlap_length1 >= deletion.size() / 2.0 ||
overlap_length1 >= insertion.size() / 2.0) {
// Overlap found. Insert an equality and trim the surrounding edits.
diffs.insert(cur_diff, Diff(EQUAL, insertion.substr(0, overlap_length1)));
prev_diff->text =
deletion.substr(0, deletion.length() - overlap_length1);
cur_diff->text = safeMid(insertion, overlap_length1);
// diffs.insert inserts the element before the cursor, so there is
// no need to step past the new element.
}
} else {
if (overlap_length2 >= deletion.length() / 2.0 ||
overlap_length2 >= insertion.length() / 2.0) {
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diffs.insert(cur_diff, Diff(EQUAL, deletion.substr(0, overlap_length2)));
prev_diff->operation = INSERT;
prev_diff->text =
insertion.substr(0, insertion.length() - overlap_length2);
cur_diff->operation = DELETE;
cur_diff->text = safeMid(deletion, overlap_length2);
// diffs.insert inserts the element before the cursor, so there is
// no need to step past the new element.
}
}
if (++cur_diff == diffs.end()) break;
}
}
}
}
/**
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param diffs LinkedList of Diff objects.
*/
public:
static void diff_cleanupSemanticLossless(Diffs &diffs) {
string_t equality1, edit, equality2;
string_t commonString;
int commonOffset;