-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDiffMatchPatch.m
More file actions
2442 lines (1938 loc) · 79.4 KB
/
DiffMatchPatch.m
File metadata and controls
2442 lines (1938 loc) · 79.4 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
/*
* Diff Match and Patch
*
* Copyright 2010 geheimwerk.de.
* http://code.google.com/p/google-diff-match-patch/
*
* 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.
*
* Author: fraser@google.com (Neil Fraser)
* ObjC port: jan@geheimwerk.de (Jan Weiß)
* Refactoring & mangling: @inquisitivesoft (Harry Jordan)
*/
#import "DiffMatchPatch.h"
#import "DiffMatchPatchInternals.h"
// Object Classes
#import "DMDiff.h"
#import "DMPatch.h"
// Text parsing and conversion
#import "DiffMatchPatchCFUtilities.h"
#import "NSString+UriCompatibility.h"
#import "NSString+EscapeHTMLCharacters.h"
#pragma mark -
#pragma mark Helpers which define the default properties
DiffProperties diff_defaultDiffProperties()
{
DiffProperties diffProperties;
diffProperties.checkLines = FALSE; // Perform a slower, more accurate diff
diffProperties.deadline = 0.0; // No timeout
return diffProperties;
}
MatchProperties match_defaultMatchProperties()
{
MatchProperties properties;
properties.matchThreshold = 0.5f;
properties.matchDistance = 1000;
properties.matchMaximumBits = 32;
return properties;
}
PatchProperties patch_defaultPatchProperties()
{
PatchProperties properties;
properties.diffProperties = diff_defaultDiffProperties();
properties.matchProperties = match_defaultMatchProperties();
properties.diffEditingCost = 4;
properties.patchDeleteThreshold = 0.5f;
properties.patchMargin = 4;
return properties;
}
#pragma mark -
#pragma mark Diff Functions
// Described in DiffMatchPatch.h
NSArray *diff_diffsBetweenTexts(NSString *text1, NSString *text2)
{
DiffProperties properties = diff_defaultDiffProperties();
return diff_diffsBetweenTextsWithProperties(text1, text2, properties);
}
// Described in DiffMatchPatch.h
NSArray *diff_diffsBetweenTextsWithOptions(NSString *text1, NSString *text2, BOOL highQuality, NSTimeInterval timeLimit)
{
timeLimit = MAX(0.0, timeLimit);
if(timeLimit > 0.0) {
timeLimit = [NSDate timeIntervalSinceReferenceDate] + timeLimit;
}
DiffProperties properties = diff_defaultDiffProperties();
properties.checkLines = !highQuality;
properties.deadline = timeLimit;
return diff_diffsBetweenTextsWithProperties(text1, text2, properties);
}
/**
* Find the differences between two texts. Simplifies the problem by
* stripping any common prefix or suffix off the texts before diffing.
*
* @param text1 Old NSString to be diffed.
* @param text2 New NSString to be diffed.
* @param properties See the DiffProperties struct for settings
* @return NSMutableArray of DMDiff objects.
*/
NSMutableArray *diff_diffsBetweenTextsWithProperties(NSString *text1, NSString *text2, DiffProperties properties)
{
// Check for null inputs.
if(text1 == nil || text2 == nil) {
NSLog(@"Null inputs. (diff_diffsBetweenTextsWithProperties)");
return nil;
}
// Test if the deadline is zero or has already passed
if(fabs(properties.deadline) < 0.00000001) {
properties.deadline = [[NSDate distantFuture] timeIntervalSinceReferenceDate];
} else {
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
if(properties.deadline < currentTime) {
// The deadline has already passed so use a fairly tight deadline
properties.deadline = currentTime + 0.3f; // 300 milliseconds
}
}
// Check for equality (speedup).
NSMutableArray *diffs;
if([text1 isEqualToString:text2]) {
diffs = [NSMutableArray array];
if(text1.length != 0) {
[diffs addObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:text1]];
}
return diffs;
}
// Trim off common prefix (speedup).
NSUInteger commonlength = (NSUInteger)diff_commonPrefix((__bridge CFStringRef)text1, (__bridge CFStringRef)text2);
NSString *commonprefix = [text1 substringToIndex:commonlength];
text1 = [text1 substringFromIndex:commonlength];
text2 = [text2 substringFromIndex:commonlength];
// Trim off common suffix (speedup).
commonlength = (NSUInteger)diff_commonSuffix((__bridge CFStringRef)text1, (__bridge CFStringRef)text2);
NSString *commonsuffix = [text1 substringFromIndex:text1.length - commonlength];
text1 = [text1 substringToIndex:(text1.length - commonlength)];
text2 = [text2 substringToIndex:(text2.length - commonlength)];
// Compute the diff on the middle block.
diffs = diff_computeDiffsBetweenTexts(text1, text2, properties);
// Restore the prefix and suffix.
if(commonprefix.length != 0) {
[diffs insertObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:commonprefix] atIndex:0];
}
if(commonsuffix.length != 0) {
[diffs addObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:commonsuffix]];
}
diff_cleanupMerge(&diffs);
return diffs;
}
/**
* Compute the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
*
* @param text1 Old NSString to be diffed.
* @param text2 New NSString to be diffed.
* @param checklines Speedup flag. If NO, then don't run a
* line-level diff first to identify the changed areas.
* If YES, then run a faster slightly less optimal diff.
* @param deadline Time the diff should be complete by.
* @return NSMutableArray of Diff objects.
*/
NSMutableArray *diff_computeDiffsBetweenTexts(NSString *text1, NSString *text2, DiffProperties properties) {
NSMutableArray *diffs = [[NSMutableArray alloc] init];
if(text1.length == 0) {
// Just add some text (speedup).
[diffs addObject:[DMDiff diffWithOperation:DIFF_INSERT andText:text2]];
return diffs;
}
if(text2.length == 0) {
// Just delete some text (speedup).
[diffs addObject:[DMDiff diffWithOperation:DIFF_DELETE andText:text1]];
return diffs;
}
NSString *longtext = text1.length > text2.length ? text1 : text2;
NSString *shorttext = text1.length > text2.length ? text2 : text1;
NSUInteger i = [longtext rangeOfString:shorttext].location;
if(i != NSNotFound) {
// Shorter text is inside the longer text (speedup).
DMDiffOperation op = (text1.length > text2.length) ? DIFF_DELETE : DIFF_INSERT;
[diffs addObject:[DMDiff diffWithOperation:op andText:[longtext substringToIndex:i]]];
[diffs addObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:shorttext]];
[diffs addObject:[DMDiff diffWithOperation:op andText:[longtext substringFromIndex:(i + shorttext.length)]]];
return diffs;
}
if(shorttext.length == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
[diffs addObject:[DMDiff diffWithOperation:DIFF_DELETE andText:text1]];
[diffs addObject:[DMDiff diffWithOperation:DIFF_INSERT andText:text2]];
return diffs;
}
// Check to see if the problem can be split in two.
NSArray *hm = nil;
// Only risk returning a non-optimal diff if we have limited time.
if(properties.deadline != [[NSDate distantFuture] timeIntervalSinceReferenceDate]) {
hm = (__bridge_transfer NSArray *)diff_halfMatchCreate((__bridge CFStringRef)text1, (__bridge CFStringRef)text2);
}
if(hm != nil) {
@autoreleasepool {
// A half-match was found, sort out the return data.
NSString *text1_a = hm[0];
NSString *text1_b = hm[1];
NSString *text2_a = hm[2];
NSString *text2_b = hm[3];
NSString *mid_common = hm[4];
// Send both pairs off for separate processing.
NSMutableArray *diffs_a = diff_diffsBetweenTextsWithProperties(text1_a, text2_a, properties);
NSMutableArray *diffs_b = diff_diffsBetweenTextsWithProperties(text1_b, text2_b, properties);
// Merge the results.
[diffs_a addObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:mid_common]];
[diffs_a addObjectsFromArray:diffs_b];
diffs = diffs_a;
}
return diffs;
}
if(properties.checkLines && text1.length > 100 && text2.length > 100) {
return diff_computeDiffsUsingLineMode(text1, text2, properties);
}
return diff_bisectOfStrings(text1, text2, properties);
}
/**
* 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 NSString to be diffed.
* @param text2 New NSString to be diffed.
* @param deadline Time when the diff should be complete by.
* @return NSMutableArray of Diff objects.
*/
NSMutableArray *diff_computeDiffsUsingLineMode(NSString *text1, NSString *text2, DiffProperties properties)
{
DiffProperties nextDiffProperties = properties;
nextDiffProperties.checkLines = FALSE;
// Scan the text on a line-by-line basis first.
NSArray *b = diff_linesToCharsForStrings(text1, text2);
text1 = (NSString *)b[0];
text2 = (NSString *)b[1];
NSMutableArray *linearray = (NSMutableArray *)b[2];
NSMutableArray *diffs = diff_diffsBetweenTextsWithProperties(text1, text2, nextDiffProperties);
// 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 addObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:@""]];
NSUInteger indexOfCurrentDiff = 0;
NSUInteger count_delete = 0;
NSUInteger count_insert = 0;
NSString *text_delete = @"";
NSString *text_insert = @"";
while(indexOfCurrentDiff < diffs.count) {
switch(((DMDiff *)diffs[indexOfCurrentDiff]).operation) {
case DIFF_INSERT:
count_insert++;
text_insert = [text_insert stringByAppendingString:((DMDiff *)diffs[indexOfCurrentDiff]).text];
break;
case DIFF_DELETE:
count_delete++;
text_delete = [text_delete stringByAppendingString:((DMDiff *)diffs[indexOfCurrentDiff]).text];
break;
case DIFF_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.
NSMutableArray *a = diff_diffsBetweenTextsWithProperties(text_delete, text_insert, nextDiffProperties);
[diffs removeObjectsInRange:NSMakeRange(indexOfCurrentDiff - count_delete - count_insert, count_delete + count_insert)];
indexOfCurrentDiff = indexOfCurrentDiff - count_delete - count_insert;
NSUInteger insertionIndex = indexOfCurrentDiff;
for(DMDiff *thisDiff in a) {
[diffs insertObject:thisDiff atIndex:insertionIndex];
insertionIndex++;
}
indexOfCurrentDiff = indexOfCurrentDiff + a.count;
}
count_insert = 0;
count_delete = 0;
text_delete = @"";
text_insert = @"";
break;
}
indexOfCurrentDiff++;
}
[diffs removeLastObject]; // Remove the dummy entry at the end.
return diffs;
}
/**
* 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.
* @param deadline Time at which to bail if not yet complete.
* @return NSMutableArray of Diff objects.
*/
NSMutableArray *diff_bisectOfStrings(NSString *text1, NSString *text2, DiffProperties properties)
{
BOOL validDeadline = properties.deadline != [[NSDate distantFuture] timeIntervalSinceReferenceDate];
NSMutableArray *diffs = nil;
BOOL haveFoundDiffs = FALSE;
CFStringRef _text1 = (__bridge CFStringRef)text1;
CFStringRef _text2 = (__bridge CFStringRef)text2;
// Cache the text lengths to prevent multiple calls.
CFIndex text1_length = CFStringGetLength(_text1);
CFIndex text2_length = CFStringGetLength(_text2);
CFIndex max_d = (text1_length + text2_length + 1) / 2;
CFIndex v_offset = max_d;
CFIndex v_length = 2 * max_d;
CFIndex *v1 = malloc(v_length * sizeof(CFIndex));
CFIndex *v2 = malloc(v_length * sizeof(CFIndex));
for(CFIndex x = 0; x < v_length; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[v_offset + 1] = 0;
v2[v_offset + 1] = 0;
CFIndex delta = text1_length - text2_length;
// Prepare access to chars arrays for text1 (massive speedup).
const UniChar *text1_chars;
UniChar *text1_buffer = NULL;
diff_CFStringPrepareUniCharBuffer(_text1, &text1_chars, &text1_buffer, CFRangeMake(0, text1_length));
// Prepare access to chars arrays for text2 (massive speedup).
const UniChar *text2_chars;
UniChar *text2_buffer = NULL;
diff_CFStringPrepareUniCharBuffer(_text2, &text2_chars, &text2_buffer, CFRangeMake(0, text2_length));
// If the total number of characters is odd, then the front path will collide with the reverse path.
BOOL front = (delta % 2 != 0);
// Offsets for start and end of k loop. Prevents mapping of space beyond the grid.
CFIndex k1start = 0;
CFIndex k1end = 0;
CFIndex k2start = 0;
CFIndex k2end = 0;
for(CFIndex d = 0; d < max_d; d++) {
// Bail out if deadline is reached.
if(validDeadline && ([NSDate timeIntervalSinceReferenceDate] > properties.deadline)) {
break;
}
// Walk the front path one step.
for(CFIndex k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
CFIndex k1_offset = v_offset + k1;
CFIndex 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;
}
CFIndex y1 = x1 - k1;
while(x1 < text1_length && y1 < text2_length && text1_chars[x1] == text2_chars[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) {
CFIndex 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.
CFIndex x2 = text1_length - v2[k2_offset];
if(x1 >= x2) {
// Overlap detected.
diffs = diff_bisectSplitOfStrings(text1, text2, x1, y1, properties);
haveFoundDiffs = TRUE;
break;
}
}
}
}
if(haveFoundDiffs) {
break;
}
// Walk the reverse path one step.
for(CFIndex k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
CFIndex k2_offset = v_offset + k2;
CFIndex 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;
}
CFIndex y2 = x2 - k2;
while((x2 < text1_length && y2 < text2_length) && (text1_chars[text1_length - x2 - 1] == text2_chars[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) {
CFIndex k1_offset = v_offset + delta - k2;
if(k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
CFIndex x1 = v1[k1_offset];
CFIndex y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2;
if(x1 >= x2) {
// Overlap detected.
diffs = diff_bisectSplitOfStrings(text1, text2, x1, y1, properties);
haveFoundDiffs = TRUE;
break;
}
}
}
}
if(haveFoundDiffs) {
break;
}
}
// Free buffers
if(text1_buffer != NULL) {
free(text1_buffer);
};
if(text2_buffer != NULL) {
free(text2_buffer);
};
free(v1);
free(v2);
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
if(!diffs) {
diffs = [[NSMutableArray alloc] initWithCapacity:2];
[diffs addObject:[DMDiff diffWithOperation:DIFF_DELETE andText:text1]];
[diffs addObject:[DMDiff diffWithOperation:DIFF_INSERT andText:text2]];
}
return diffs;
}
/**
* 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 NSMutableArray of Diff objects.
*/
NSMutableArray *diff_bisectSplitOfStrings(NSString *text1, NSString *text2, NSUInteger x, NSUInteger y, DiffProperties properties)
{
NSString *text1a = [text1 substringToIndex:x];
NSString *text2a = [text2 substringToIndex:y];
NSString *text1b = [text1 substringFromIndex:x];
NSString *text2b = [text2 substringFromIndex:y];
// Compute both diffs serially.
NSMutableArray *diffs = diff_diffsBetweenTextsWithProperties(text1a, text2a, properties);
NSMutableArray *diffsb = diff_diffsBetweenTextsWithProperties(text1b, text2b, properties);
[diffs addObjectsFromArray:diffsb];
return diffs;
}
/**
* 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 NSString.
* @param text2 Second NSString.
* @return Three element NSArray, containing the encoded text1, the
* encoded text2 and the NSMutableArray of unique strings. The zeroth element
* of the NSArray of unique strings is intentionally blank.
*/
NSArray *diff_linesToCharsForStrings(NSString *text1, NSString *text2)
{
NSMutableArray *lineArray = [NSMutableArray array]; // NSString objects
CFMutableDictionaryRef lineHash = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);
// keys: NSString, values:raw CFIndex
// e.g. [lineArray objectAtIndex:4] == "Hello\n"
// e.g. [lineHash objectForKey:"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 nil character.
[lineArray addObject:@""];
NSString *chars1 = (NSString *)CFBridgingRelease(diff_linesToCharsMungeCFStringCreate((__bridge CFStringRef)text1, (__bridge CFMutableArrayRef)lineArray, lineHash));
NSString *chars2 = (NSString *)CFBridgingRelease(diff_linesToCharsMungeCFStringCreate((__bridge CFStringRef)text2, (__bridge CFMutableArrayRef)lineArray, lineHash));
NSArray *result = @[chars1, chars2, lineArray];
CFRelease(lineHash);
return result;
}
/**
* Split two texts into a list of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one token (or boundary between tokens).
* A token can be a type of text fragment: a word, sentence, paragraph or line.
* The type is determined by the mode object.
* @param text1 First NSString.
* @param text2 Second NSString.
* @param mode value determining the tokenization mode.
* @return Three element NSArray, containing the encoded text1, the
* encoded text2 and the NSMutableArray of unique strings. The zeroth element
* of the NSArray of unique strings is intentionally blank.
*/
NSArray *diff_tokensToCharsForStrings(NSString *text1, NSString *text2, DiffTokenMode mode)
{
CFOptionFlags tokenizerOptions = 0;
switch(mode) {
case DiffWordTokens:
tokenizerOptions = kCFStringTokenizerUnitWordBoundary;
break;
case DiffSentenceTokens:
tokenizerOptions = kCFStringTokenizerUnitSentence;
break;
case DiffLineBreakDelimiteredTokens:
tokenizerOptions = kCFStringTokenizerUnitLineBreak;
break;
case DiffParagraphTokens:
default:
tokenizerOptions = kCFStringTokenizerUnitParagraph;
break;
}
NSMutableArray *tokenArray = [NSMutableArray array]; // NSString objects
CFMutableDictionaryRef tokenHash = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);
// keys: NSString, values:raw CFIndex
// e.g. [tokenArray objectAtIndex:4] == "Hello"
// e.g. [tokenHash objectForKey:"Hello"] == 4
// "\x00" is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a nil character.
[tokenArray addObject:@""];
NSString *tokens1 = (__bridge_transfer NSString *)diff_tokensToCharsMungeCFStringCreate((__bridge CFStringRef)text1, (__bridge CFMutableArrayRef)tokenArray, tokenHash, tokenizerOptions);
NSString *tokens2 = (__bridge_transfer NSString *)diff_tokensToCharsMungeCFStringCreate((__bridge CFStringRef)text2, (__bridge CFMutableArrayRef)tokenArray, tokenHash, tokenizerOptions);
NSArray *result = @[tokens1, tokens2, tokenArray];
CFRelease(tokenHash);
return result;
}
/**
* Rehydrate the text in a diff from an NSString of line hashes to real lines
* of text.
* @param NSArray of Diff objects.
* @param NSArray of unique strings.
*/
void diff_charsToLines(NSArray **diffs, NSArray *lineArray)
{
if(diffs == NULL) {
return;
}
for(DMDiff *diff in *diffs) {
diff.text = (__bridge_transfer NSString *)diff_charsToTokenCFStringCreate((__bridge CFStringRef)diff.text, (__bridge CFArrayRef)lineArray);
}
}
/**
* Rehydrate the text in a diff from an NSString of token hashes to real text tokens.
* @param NSArray of Diff objects.
* @param NSArray of unique strings.
*/
void diff_charsToTokens(NSArray **diffs, NSArray *tokenArray)
{
if(diffs == NULL) {
return;
}
for(DMDiff *diff in *diffs) {
diff.text = (__bridge_transfer NSString *)diff_charsToTokenCFStringCreate((__bridge CFStringRef)diff.text, (__bridge CFArrayRef)tokenArray);
}
}
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param diffs NSMutableArray of Diff objects.
*/
void diff_cleanupMerge(NSMutableArray **inputDiffs)
{
if(inputDiffs == NULL || [*inputDiffs count] == 0) {
return;
}
NSMutableArray *diffs = *inputDiffs;
[diffs addObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:@""]]; // Add a dummy entry at the end.
NSUInteger indexOfCurrentDiff = 0;
NSUInteger count_delete = 0;
NSUInteger count_insert = 0;
NSString *text_delete = @"";
NSString *text_insert = @"";
NSUInteger commonlength;
while(indexOfCurrentDiff < diffs.count) {
DMDiff *thisDiff = diffs[indexOfCurrentDiff];
switch(thisDiff.operation) {
case DIFF_INSERT:
count_insert++;
text_insert = [text_insert stringByAppendingString:thisDiff.text];
indexOfCurrentDiff++;
break;
case DIFF_DELETE:
count_delete++;
text_delete = [text_delete stringByAppendingString:thisDiff.text];
indexOfCurrentDiff++;
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if(count_delete + count_insert > 1) {
if(count_delete != 0 && count_insert != 0) {
// Factor out any common prefixes.
commonlength = (NSUInteger)diff_commonPrefix((__bridge CFStringRef)text_insert, (__bridge CFStringRef)text_delete);
if(commonlength != 0) {
if((indexOfCurrentDiff - count_delete - count_insert) > 0 && ((DMDiff *)[diffs objectAtIndex:(indexOfCurrentDiff - count_delete - count_insert - 1)]).operation == DIFF_EQUAL) {
((DMDiff *)[diffs objectAtIndex:(indexOfCurrentDiff - count_delete - count_insert - 1)]).text = [((DMDiff *)[diffs objectAtIndex:(indexOfCurrentDiff - count_delete - count_insert - 1)]).text stringByAppendingString:[text_insert substringToIndex:commonlength]];
} else {
[diffs insertObject:[DMDiff diffWithOperation:DIFF_EQUAL andText:[text_insert substringToIndex:commonlength]] atIndex:0];
indexOfCurrentDiff++;
}
text_insert = [text_insert substringFromIndex:commonlength];
text_delete = [text_delete substringFromIndex:commonlength];
}
// Factor out any common suffixes.
commonlength = (NSUInteger)diff_commonSuffix((__bridge CFStringRef)text_insert, (__bridge CFStringRef)text_delete);
if(commonlength != 0) {
thisDiff.text = [[text_insert substringFromIndex:(text_insert.length - commonlength)] stringByAppendingString:thisDiff.text];
text_insert = [text_insert substringWithRange:NSMakeRange(0, text_insert.length - commonlength)];
text_delete = [text_delete substringWithRange:NSMakeRange(0, text_delete.length - commonlength)];
}
}
// Delete the offending records and add the merged ones.
if(count_delete == 0) {
diff_spliceTwoArrays(&diffs, indexOfCurrentDiff - count_insert, count_delete + count_insert, [NSMutableArray arrayWithObject:[DMDiff diffWithOperation:DIFF_INSERT andText:text_insert]]);
} else if(count_insert == 0) {
diff_spliceTwoArrays(&diffs, indexOfCurrentDiff - count_delete, count_delete + count_insert, [NSMutableArray arrayWithObject:[DMDiff diffWithOperation:DIFF_DELETE andText:text_delete]]);
} else {
diff_spliceTwoArrays(&diffs, indexOfCurrentDiff - count_delete - count_insert, count_delete + count_insert, [NSMutableArray arrayWithObjects:[DMDiff diffWithOperation:DIFF_DELETE andText:text_delete], [DMDiff diffWithOperation:DIFF_INSERT andText:text_insert], nil]);
}
indexOfCurrentDiff = indexOfCurrentDiff - count_delete - count_insert +
(count_delete != 0 ? 1 : 0) + (count_insert != 0 ? 1 : 0) + 1;
} else if(indexOfCurrentDiff != 0 && ((DMDiff *)diffs[indexOfCurrentDiff - 1]).operation == DIFF_EQUAL) {
// Merge this equality with the previous one.
DMDiff *prevDiff = diffs[indexOfCurrentDiff - 1];
prevDiff.text = [prevDiff.text stringByAppendingString:thisDiff.text];
[diffs removeObjectAtIndex:indexOfCurrentDiff];
} else {
indexOfCurrentDiff++;
}
count_insert = 0;
count_delete = 0;
text_delete = @"";
text_insert = @"";
break;
}
}
if(((DMDiff *)diffs.lastObject).text.length == 0) {
[diffs removeLastObject]; // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by
// equalities which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
BOOL changes = NO;
indexOfCurrentDiff = 1;
// Intentionally ignore the first and last element (as they don't need checking).
while(indexOfCurrentDiff < (diffs.count - 1)) {
DMDiff *prevDiff = diffs[indexOfCurrentDiff - 1];
DMDiff *thisDiff = diffs[indexOfCurrentDiff];
DMDiff *nextDiff = diffs[indexOfCurrentDiff + 1];
if(prevDiff.operation == DIFF_EQUAL && nextDiff.operation == DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
if([thisDiff.text hasSuffix:prevDiff.text]) {
// Shift the edit over the previous equality.
thisDiff.text = [prevDiff.text stringByAppendingString:[thisDiff.text substringToIndex:(thisDiff.text.length - prevDiff.text.length)]];
nextDiff.text = [prevDiff.text stringByAppendingString:nextDiff.text];
diff_spliceTwoArrays(inputDiffs, indexOfCurrentDiff - 1, 1, nil);
changes = YES;
} else if([thisDiff.text hasPrefix:nextDiff.text]) {
// Shift the edit over the next equality.
prevDiff.text = [prevDiff.text stringByAppendingString:nextDiff.text];
thisDiff.text = [[thisDiff.text substringFromIndex:nextDiff.text.length] stringByAppendingString:nextDiff.text];
diff_spliceTwoArrays(inputDiffs, indexOfCurrentDiff + 1, 1, nil);
changes = YES;
}
}
indexOfCurrentDiff++;
}
// If shifts were made, the diff needs reordering and another shift sweep.
if(changes) {
diff_cleanupMerge(inputDiffs);
}
}
/**
* 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 NSMutableArray of Diff objects.
*/
void diff_cleanupSemanticLossless(NSMutableArray **mutableDiffs)
{
if(mutableDiffs == NULL || [*mutableDiffs count] == 0) {
return;
}
NSMutableArray *diffs = *mutableDiffs;
NSUInteger indexOfCurrentDiff = 1;
// Intentionally ignore the first and last element (as they don't need checking).
while(indexOfCurrentDiff < (diffs.count - 1)) {
DMDiff *prevDiff = diffs[indexOfCurrentDiff - 1];
DMDiff *thisDiff = diffs[indexOfCurrentDiff];
DMDiff *nextDiff = diffs[indexOfCurrentDiff + 1];
if(prevDiff.operation == DIFF_EQUAL && nextDiff.operation == DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
NSString *equality1 = prevDiff.text;
NSString *edit = thisDiff.text;
NSString *equality2 = nextDiff.text;
// First, shift the edit as far left as possible.
NSUInteger commonOffset = (NSUInteger)diff_commonSuffix((__bridge CFStringRef)equality1, (__bridge CFStringRef)edit);
if(commonOffset > 0) {
NSString *commonString = [edit substringFromIndex:(edit.length - commonOffset)];
equality1 = [equality1 substringToIndex:(equality1.length - commonOffset)];
edit = [commonString stringByAppendingString:[edit substringToIndex:(edit.length - commonOffset)]];
equality2 = [commonString stringByAppendingString:equality2];
}
// Second, step right character by character,
// looking for the best fit.
NSString *bestEquality1 = equality1;
NSString *bestEdit = edit;
NSString *bestEquality2 = equality2;
CFIndex bestScore = diff_cleanupSemanticScore((__bridge CFStringRef)equality1, (__bridge CFStringRef)edit) + diff_cleanupSemanticScore((__bridge CFStringRef)edit, (__bridge CFStringRef)equality2);
while((edit.length != 0 && equality2.length != 0) && ([edit characterAtIndex:0] == [equality2 characterAtIndex:0])) {
equality1 = [equality1 stringByAppendingString:[edit substringToIndex:1]];
edit = [[edit substringFromIndex:1] stringByAppendingString:[equality2 substringToIndex:1]];
equality2 = [equality2 substringFromIndex:1];
CFIndex score = diff_cleanupSemanticScore((__bridge CFStringRef)equality1, (__bridge CFStringRef)edit) + diff_cleanupSemanticScore((__bridge CFStringRef)edit, (__bridge CFStringRef)equality2);
// The >= encourages trailing rather than leading whitespace on edits.
if(score >= bestScore) {
bestScore = score;
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
}
}
if(prevDiff.text != bestEquality1) {
// We have an improvement, save it back to the diff.
if(bestEquality1.length != 0) {
prevDiff.text = bestEquality1;
} else {
[diffs removeObjectAtIndex:indexOfCurrentDiff - 1];
indexOfCurrentDiff--;
}
thisDiff.text = bestEdit;
if(bestEquality2.length != 0) {
nextDiff.text = bestEquality2;
} else {
[diffs removeObjectAtIndex:indexOfCurrentDiff + 1];
indexOfCurrentDiff--;
}
}
}
indexOfCurrentDiff++;
}
}
/**
* Reduce the number of edits by eliminating operationally trivial
* equalities.
* @param diffs NSMutableArray of Diff objects.
*/
void patch_cleanupDiffsForEfficiency(NSMutableArray **diffs, PatchProperties properties)
{
if(diffs == NULL || [*diffs count] == 0) {
return;
}
BOOL changes = NO;
// Stack of indices where equalities are found.
CFMutableArrayRef equalities = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
// Always equal to equalities.lastObject.text
NSString *lastequality = nil;
CFIndex indexOfCurrentDiff = 0; // Index of current position.
BOOL pre_ins = NO; // Is there an insertion operation before the last equality.
BOOL pre_del = NO; // Is there a deletion operation before the last equality.
BOOL post_ins = NO; // Is there an insertion operation after the last equality.
BOOL post_del = NO; // Is there a deletion operation after the last equality.
NSUInteger indexToChange = 0;
DMDiff *diffToChange = nil;
while(indexOfCurrentDiff < [*diffs count]) {
DMDiff *thisDiff = [*diffs objectAtIndex:indexOfCurrentDiff];
if(thisDiff.operation == DIFF_EQUAL) {
// Equality found.
if(thisDiff.text.length < properties.diffEditingCost && (post_ins || post_del)) {
// Candidate found.
CFArrayAppendValue(equalities, (void *)indexOfCurrentDiff);
pre_ins = post_ins;
pre_del = post_del;
lastequality = thisDiff.text;
} else {
// Not a candidate, and can never become one.
CFArrayRemoveAllValues(equalities);
lastequality = nil;
}
post_ins = post_del = NO;
} else {
// An insertion or deletion.
if(thisDiff.operation == DIFF_DELETE) {
post_del = YES;
} else {
post_ins = YES;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if((lastequality != nil) && ((pre_ins && pre_del && post_ins && post_del)
|| ((lastequality.length < properties.diffEditingCost / 2)
&& ((pre_ins ? 1 : 0) + (pre_del ? 1 : 0) + (post_ins ? 1 : 0) + (post_del ? 1 : 0)) == 3))) {
// Duplicate record.
CFIndex indexOfLastEquality = diff_CFArrayLastValueAsCFIndex(equalities);
[*diffs insertObject:[DMDiff diffWithOperation:DIFF_DELETE andText:lastequality] atIndex:indexOfLastEquality];
// Change second copy to insert.
indexToChange = indexOfLastEquality + 1;
diffToChange = [*diffs objectAtIndex:indexToChange];
// The following assumes, that the diff we are changing is currently not used in a collection where its hash determines its position (e.g. a dictionary)
diffToChange.operation = DIFF_INSERT;
diff_CFArrayRemoveLastValue(equalities); // Throw away the equality we just deleted.
lastequality = nil;
if(pre_ins && pre_del) {
// No changes made which could affect previous entry, keep going.
post_ins = post_del = YES;