-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathDiffMatchPatch.zig
2921 lines (2677 loc) · 110 KB
/
DiffMatchPatch.zig
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
const DiffMatchPatch = @This();
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
/// DMP with default configuration options
pub const default = DiffMatchPatch{};
pub const Diff = struct {
pub const Operation = enum {
insert,
delete,
equal,
};
operation: Operation,
text: []const u8,
pub fn format(value: Diff, _: anytype, _: anytype, writer: anytype) !void {
try writer.print("({s}, \"{s}\")", .{
switch (value.operation) {
.equal => "=",
.insert => "+",
.delete => "-",
},
value.text,
});
}
pub fn init(operation: Operation, text: []const u8) Diff {
return .{ .operation = operation, .text = text };
}
pub fn eql(a: Diff, b: Diff) bool {
return a.operation == b.operation and std.mem.eql(u8, a.text, b.text);
}
test eql {
const equal_a: Diff = .{ .operation = .equal, .text = "a" };
const insert_a: Diff = .{ .operation = .insert, .text = "a" };
const equal_b: Diff = .{ .operation = .equal, .text = "b" };
const delete_b: Diff = .{ .operation = .delete, .text = "b" };
try testing.expect(equal_a.eql(equal_a));
try testing.expect(!insert_a.eql(equal_a));
try testing.expect(!equal_a.eql(equal_b));
try testing.expect(!equal_a.eql(delete_b));
}
};
/// Number of milliseconds to map a diff before giving up (0 for infinity).
diff_timeout: u64 = 1000,
/// Cost of an empty edit operation in terms of edit characters.
diff_edit_cost: u16 = 4,
/// Number of bytes in each string needed to trigger a line-based diff
diff_check_lines_over: u64 = 100,
/// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
match_threshold: f32 = 0.5,
/// 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).
match_distance: u32 = 1000,
/// The number of bits in an int.
match_max_bits: u16 = 32,
/// When deleting a large block of text (over ~64 characters), how close
/// do the contents have to be 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.
patch_delete_threshold: f32 = 0.5,
/// Chunk size for context length.
patch_margin: u16 = 4,
pub const DiffError = error{OutOfMemory};
/// Find the differences between two texts. The return value
/// must be freed with `deinitDiffList(allocator, &diffs)`.
/// @param before Old string to be diffed.
/// @param after 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.
/// @return List of Diff objects.
pub fn diff(
dmp: DiffMatchPatch,
allocator: std.mem.Allocator,
before: []const u8,
after: []const u8,
/// 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.
check_lines: bool,
) DiffError!DiffList {
const deadline = if (dmp.diff_timeout == 0)
std.math.maxInt(u64)
else
@as(u64, @intCast(std.time.milliTimestamp())) + dmp.diff_timeout;
return dmp.diffInternal(allocator, before, after, check_lines, deadline);
}
const DiffList = ArrayListUnmanaged(Diff);
/// Deinit an `ArrayListUnmanaged(Diff)` and the allocated slices of
/// text in each `Diff`.
pub fn deinitDiffList(allocator: Allocator, diffs: *DiffList) void {
defer diffs.deinit(allocator);
for (diffs.items) |d| {
allocator.free(d.text);
}
}
fn freeRangeDiffList(
allocator: Allocator,
diffs: *DiffList,
start: usize,
len: usize,
) void {
const range = diffs.items[start..][0..len];
for (range) |d| {
allocator.free(d.text);
}
}
fn diffInternal(
dmp: DiffMatchPatch,
allocator: std.mem.Allocator,
before: []const u8,
after: []const u8,
check_lines: bool,
deadline: u64,
) DiffError!DiffList {
// Check for equality (speedup).
if (std.mem.eql(u8, before, after)) {
var diffs = DiffList{};
errdefer deinitDiffList(allocator, &diffs);
if (before.len != 0) {
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.appendAssumeCapacity(Diff.init(
.equal,
try allocator.dupe(u8, before),
));
}
return diffs;
}
// Trim off common prefix (speedup).
var common_length = diffCommonPrefix(before, after);
const common_prefix = before[0..common_length];
var trimmed_before = before[common_length..];
var trimmed_after = after[common_length..];
// Trim off common suffix (speedup).
common_length = diffCommonSuffix(trimmed_before, trimmed_after);
const common_suffix = trimmed_before[trimmed_before.len - common_length ..];
trimmed_before = trimmed_before[0 .. trimmed_before.len - common_length];
trimmed_after = trimmed_after[0 .. trimmed_after.len - common_length];
// Compute the diff on the middle block.
var diffs = try dmp.diffCompute(allocator, trimmed_before, trimmed_after, check_lines, deadline);
errdefer deinitDiffList(allocator, &diffs);
// Restore the prefix and suffix.
if (common_prefix.len != 0) {
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.insertAssumeCapacity(0, Diff.init(
.equal,
try allocator.dupe(u8, common_prefix),
));
}
if (common_suffix.len != 0) {
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.appendAssumeCapacity(Diff.init(
.equal,
try allocator.dupe(u8, common_suffix),
));
}
try diffCleanupMerge(allocator, &diffs);
return diffs;
}
fn diffCommonPrefix(before: []const u8, after: []const u8) usize {
const n = @min(before.len, after.len);
var i: usize = 0;
while (i < n) : (i += 1) {
if (before[i] != after[i]) {
return i;
}
}
return n;
}
fn diffCommonSuffix(before: []const u8, after: []const u8) usize {
const n = @min(before.len, after.len);
var i: usize = 1;
while (i <= n) : (i += 1) {
if (before[before.len - i] != after[after.len - i]) {
return i - 1;
}
}
return n;
}
/// Find the differences between two texts. Assumes that the texts do not
/// have any common prefix or suffix.
/// @param before Old string to be diffed.
/// @param after 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.
/// @return List of Diff objects.
fn diffCompute(
dmp: DiffMatchPatch,
allocator: std.mem.Allocator,
before: []const u8,
after: []const u8,
check_lines: bool,
deadline: u64,
) DiffError!DiffList {
if (before.len == 0) {
// Just add some text (speedup).
var diffs = DiffList{};
errdefer deinitDiffList(allocator, &diffs);
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.appendAssumeCapacity(Diff.init(
.insert,
try allocator.dupe(u8, after),
));
return diffs;
}
if (after.len == 0) {
// Just delete some text (speedup).
var diffs = DiffList{};
errdefer deinitDiffList(allocator, &diffs);
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.appendAssumeCapacity(Diff.init(
.delete,
try allocator.dupe(u8, before),
));
return diffs;
}
const long_text = if (before.len > after.len) before else after;
const short_text = if (before.len > after.len) after else before;
if (std.mem.indexOf(u8, long_text, short_text)) |index| {
var diffs = DiffList{};
errdefer deinitDiffList(allocator, &diffs);
// Shorter text is inside the longer text (speedup).
const op: Diff.Operation = if (before.len > after.len)
.delete
else
.insert;
try diffs.ensureUnusedCapacity(allocator, 3);
diffs.appendAssumeCapacity(Diff.init(
op,
try allocator.dupe(u8, long_text[0..index]),
));
diffs.appendAssumeCapacity(Diff.init(
.equal,
try allocator.dupe(u8, short_text),
));
diffs.appendAssumeCapacity(Diff.init(
op,
try allocator.dupe(u8, long_text[index + short_text.len ..]),
));
return diffs;
}
if (short_text.len == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
var diffs = DiffList{};
errdefer deinitDiffList(allocator, &diffs);
try diffs.ensureUnusedCapacity(allocator, 2);
diffs.appendAssumeCapacity(Diff.init(
.delete,
try allocator.dupe(u8, before),
));
diffs.appendAssumeCapacity(Diff.init(
.insert,
try allocator.dupe(u8, after),
));
return diffs;
}
// Check to see if the problem can be split in two.
if (try dmp.diffHalfMatch(allocator, before, after)) |half_match| {
// A half-match was found, sort out the return data.
defer half_match.deinit(allocator);
// Send both pairs off for separate processing.
var diffs = try dmp.diffInternal(
allocator,
half_match.prefix_before,
half_match.prefix_after,
check_lines,
deadline,
);
errdefer deinitDiffList(allocator, &diffs);
var diffs_b = try dmp.diffInternal(
allocator,
half_match.suffix_before,
half_match.suffix_after,
check_lines,
deadline,
);
defer diffs_b.deinit(allocator);
// we have to deinit regardless, so deinitDiffList would be
// a double free:
errdefer {
for (diffs_b.items) |d| {
allocator.free(d.text);
}
}
// Merge the results.
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.appendAssumeCapacity(
Diff.init(.equal, try allocator.dupe(
u8,
half_match.common_middle,
)),
);
try diffs.appendSlice(allocator, diffs_b.items);
return diffs;
}
if (check_lines and before.len > dmp.diff_check_lines_over and after.len > dmp.diff_check_lines_over) {
return dmp.diffLineMode(allocator, before, after, deadline);
}
return dmp.diffBisect(allocator, before, after, deadline);
}
const HalfMatchResult = struct {
prefix_before: []const u8,
suffix_before: []const u8,
prefix_after: []const u8,
suffix_after: []const u8,
common_middle: []const u8,
pub fn deinit(hmr: HalfMatchResult, alloc: Allocator) void {
alloc.free(hmr.prefix_before);
alloc.free(hmr.suffix_before);
alloc.free(hmr.prefix_after);
alloc.free(hmr.suffix_after);
alloc.free(hmr.common_middle);
}
};
/// 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 before First string.
/// @param after Second string.
/// @return Five element String array, containing the prefix of text1, the
/// suffix of text1, the prefix of text2, the suffix of text2 and the
/// common middle. Or null if there was no match.
fn diffHalfMatch(
dmp: DiffMatchPatch,
allocator: std.mem.Allocator,
before: []const u8,
after: []const u8,
) DiffError!?HalfMatchResult {
if (dmp.diff_timeout <= 0) {
// Don't risk returning a non-optimal diff if we have unlimited time.
return null;
}
const long_text = if (before.len > after.len) before else after;
const short_text = if (before.len > after.len) after else before;
if (long_text.len < 4 or short_text.len * 2 < long_text.len) {
return null; // Pointless.
}
// First check if the second quarter is the seed for a half-match.
const half_match_1 = try dmp.diffHalfMatchInternal(allocator, long_text, short_text, (long_text.len + 3) / 4);
errdefer {
if (half_match_1) |h_m| h_m.deinit(allocator);
}
// Check again based on the third quarter.
const half_match_2 = try dmp.diffHalfMatchInternal(allocator, long_text, short_text, (long_text.len + 1) / 2);
errdefer {
if (half_match_2) |h_m| h_m.deinit(allocator);
}
var half_match: ?HalfMatchResult = null;
if (half_match_1 == null and half_match_2 == null) {
return null;
} else if (half_match_2 == null) {
half_match = half_match_1.?;
} else if (half_match_1 == null) {
half_match = half_match_2.?;
} else {
// Both matched. Select the longest.
half_match = half: {
if (half_match_1.?.common_middle.len > half_match_2.?.common_middle.len) {
half_match_2.?.deinit(allocator);
break :half half_match_1;
} else {
half_match_1.?.deinit(allocator);
break :half half_match_2;
}
};
}
// A half-match was found, sort out the return data.
if (before.len > after.len) {
return half_match.?;
} else {
// Transfers ownership of all memory to new, permuted, half_match.
const half_match_yes = half_match.?;
return .{
.prefix_before = half_match_yes.prefix_after,
.suffix_before = half_match_yes.suffix_after,
.prefix_after = half_match_yes.prefix_before,
.suffix_after = half_match_yes.suffix_before,
.common_middle = half_match_yes.common_middle,
};
}
}
/// 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.
/// @return Five element string array, containing the prefix of longtext, the
/// suffix of longtext, the prefix of shorttext, the suffix of shorttext
/// and the common middle. Or null if there was no match.
fn diffHalfMatchInternal(
_: DiffMatchPatch,
allocator: std.mem.Allocator,
long_text: []const u8,
short_text: []const u8,
i: usize,
) DiffError!?HalfMatchResult {
// Start with a 1/4 length Substring at position i as a seed.
const seed = long_text[i .. i + long_text.len / 4];
var j: isize = -1;
var best_common = std.ArrayListUnmanaged(u8){};
defer best_common.deinit(allocator);
var best_long_text_a: []const u8 = "";
var best_long_text_b: []const u8 = "";
var best_short_text_a: []const u8 = "";
var best_short_text_b: []const u8 = "";
while (j < short_text.len and b: {
j = @as(isize, @intCast(std.mem.indexOf(u8, short_text[@as(usize, @intCast(j + 1))..], seed) orelse break :b false)) + j + 1;
break :b true;
}) {
const prefix_length = diffCommonPrefix(long_text[i..], short_text[@as(usize, @intCast(j))..]);
const suffix_length = diffCommonSuffix(long_text[0..i], short_text[0..@as(usize, @intCast(j))]);
if (best_common.items.len < suffix_length + prefix_length) {
best_common.items.len = 0;
const a = short_text[@as(usize, @intCast(j - @as(isize, @intCast(suffix_length)))) .. @as(usize, @intCast(j - @as(isize, @intCast(suffix_length)))) + suffix_length];
try best_common.appendSlice(allocator, a);
const b = short_text[@as(usize, @intCast(j)) .. @as(usize, @intCast(j)) + prefix_length];
try best_common.appendSlice(allocator, b);
best_long_text_a = long_text[0 .. i - suffix_length];
best_long_text_b = long_text[i + prefix_length ..];
best_short_text_a = short_text[0..@as(usize, @intCast(j - @as(isize, @intCast(suffix_length))))];
best_short_text_b = short_text[@as(usize, @intCast(j + @as(isize, @intCast(prefix_length))))..];
}
}
if (best_common.items.len * 2 >= long_text.len) {
const prefix_before = try allocator.dupe(u8, best_long_text_a);
errdefer allocator.free(prefix_before);
const suffix_before = try allocator.dupe(u8, best_long_text_b);
errdefer allocator.free(suffix_before);
const prefix_after = try allocator.dupe(u8, best_short_text_a);
errdefer allocator.free(prefix_after);
const suffix_after = try allocator.dupe(u8, best_short_text_b);
errdefer allocator.free(suffix_after);
const best_common_text = try best_common.toOwnedSlice(allocator);
errdefer allocator.free(best_common_text);
return .{
.prefix_before = prefix_before,
.suffix_before = suffix_before,
.prefix_after = prefix_after,
.suffix_after = suffix_after,
.common_middle = best_common_text,
};
} else {
return null;
}
}
/// 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 before Old string to be diffed.
/// @param after New string to be diffed.
/// @param deadline Time at which to bail if not yet complete.
/// @return List of Diff objects.
fn diffBisect(
dmp: DiffMatchPatch,
allocator: std.mem.Allocator,
before: []const u8,
after: []const u8,
deadline: u64,
) DiffError!DiffList {
const before_length: isize = @intCast(before.len);
const after_length: isize = @intCast(after.len);
const max_d: isize = @intCast((before.len + after.len + 1) / 2);
const v_offset = max_d;
const v_length = 2 * max_d;
var v1 = try ArrayListUnmanaged(isize).initCapacity(allocator, @as(usize, @intCast(v_length)));
defer v1.deinit(allocator);
v1.items.len = @intCast(v_length);
var v2 = try ArrayListUnmanaged(isize).initCapacity(allocator, @as(usize, @intCast(v_length)));
defer v2.deinit(allocator);
v2.items.len = @intCast(v_length);
var x: usize = 0;
while (x < v_length) : (x += 1) {
v1.items[x] = -1;
v2.items[x] = -1;
}
v1.items[@intCast(v_offset + 1)] = 0;
v2.items[@intCast(v_offset + 1)] = 0;
const delta = before_length - after_length;
// If the total number of characters is odd, then the front path will
// collide with the reverse path.
const front = (@mod(delta, 2) != 0);
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
var k1start: isize = 0;
var k1end: isize = 0;
var k2start: isize = 0;
var k2end: isize = 0;
var d: isize = 0;
while (d < max_d) : (d += 1) {
// Bail out if deadline is reached.
if (@as(u64, @intCast(std.time.milliTimestamp())) > deadline) {
break;
}
// Walk the front path one step.
var k1 = -d + k1start;
while (k1 <= d - k1end) : (k1 += 2) {
const k1_offset = v_offset + k1;
var x1: isize = 0;
if (k1 == -d or (k1 != d and
v1.items[@intCast(k1_offset - 1)] < v1.items[@intCast(k1_offset + 1)]))
{
x1 = v1.items[@intCast(k1_offset + 1)];
} else {
x1 = v1.items[@intCast(k1_offset - 1)] + 1;
}
var y1 = x1 - k1;
while (x1 < before_length and
y1 < after_length and before[@intCast(x1)] == after[@intCast(y1)])
{
x1 += 1;
y1 += 1;
}
v1.items[@intCast(k1_offset)] = x1;
if (x1 > before_length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > after_length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
const k2_offset = v_offset + delta - k1;
if (k2_offset >= 0 and k2_offset < v_length and v2.items[@intCast(k2_offset)] != -1) {
// Mirror x2 onto top-left coordinate system.
const x2 = before_length - v2.items[@intCast(k2_offset)];
if (x1 >= x2) {
// Overlap detected.
return dmp.diffBisectSplit(allocator, before, after, x1, y1, deadline);
}
}
}
}
// Walk the reverse path one step.
var k2: isize = -d + k2start;
while (k2 <= d - k2end) : (k2 += 2) {
const k2_offset = v_offset + k2;
var x2: isize = 0;
if (k2 == -d or (k2 != d and
v2.items[@intCast(k2_offset - 1)] < v2.items[@intCast(k2_offset + 1)]))
{
x2 = v2.items[@intCast(k2_offset + 1)];
} else {
x2 = v2.items[@intCast(k2_offset - 1)] + 1;
}
var y2: isize = x2 - k2;
while (x2 < before_length and y2 < after_length and
before[@intCast(before_length - x2 - 1)] ==
after[@intCast(after_length - y2 - 1)])
{
x2 += 1;
y2 += 1;
}
v2.items[@intCast(k2_offset)] = x2;
if (x2 > before_length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > after_length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
const k1_offset = v_offset + delta - k2;
if (k1_offset >= 0 and k1_offset < v_length and v1.items[@intCast(k1_offset)] != -1) {
const x1 = v1.items[@intCast(k1_offset)];
const y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = before_length - v2.items[@intCast(k2_offset)];
if (x1 >= x2) {
// Overlap detected.
return dmp.diffBisectSplit(allocator, before, after, x1, y1, deadline);
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
var diffs = DiffList{};
errdefer deinitDiffList(allocator, &diffs);
try diffs.ensureUnusedCapacity(allocator, 2);
diffs.appendAssumeCapacity(Diff.init(
.delete,
try allocator.dupe(u8, before),
));
diffs.appendAssumeCapacity(Diff.init(
.insert,
try allocator.dupe(u8, after),
));
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 LinkedList of Diff objects.
fn diffBisectSplit(
dmp: DiffMatchPatch,
allocator: std.mem.Allocator,
text1: []const u8,
text2: []const u8,
x: isize,
y: isize,
deadline: u64,
) DiffError!DiffList {
const text1a = text1[0..@intCast(x)];
const text2a = text2[0..@intCast(y)];
const text1b = text1[@intCast(x)..];
const text2b = text2[@intCast(y)..];
// Compute both diffs serially.
var diffs = try dmp.diffInternal(allocator, text1a, text2a, false, deadline);
errdefer deinitDiffList(allocator, &diffs);
var diffs_b = try dmp.diffInternal(allocator, text1b, text2b, false, deadline);
// Free the list, but not the contents:
defer diffs_b.deinit(allocator);
errdefer {
for (diffs_b.items) |d| {
allocator.free(d.text);
}
}
try diffs.appendSlice(allocator, diffs_b.items);
return 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.
/// @return List of Diff objects.
fn diffLineMode(
dmp: DiffMatchPatch,
allocator: std.mem.Allocator,
text1_in: []const u8,
text2_in: []const u8,
deadline: u64,
) DiffError!DiffList {
// Scan the text on a line-by-line basis first.
var a = try diffLinesToChars(allocator, text1_in, text2_in);
defer a.deinit(allocator);
const text1 = a.chars_1;
const text2 = a.chars_2;
const line_array = a.line_array;
var diffs: DiffList = undefined;
{
var char_diffs: DiffList = try dmp.diffInternal(allocator, text1, text2, false, deadline);
defer deinitDiffList(allocator, &char_diffs);
// Convert the diff back to original text.
diffs = try diffCharsToLines(allocator, &char_diffs, line_array.items);
// Eliminate freak matches (e.g. blank lines)
}
errdefer deinitDiffList(allocator, &diffs);
try diffCleanupSemantic(allocator, &diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
try diffs.append(allocator, Diff.init(.equal, ""));
var pointer: usize = 0;
var count_delete: usize = 0;
var count_insert: usize = 0;
var text_delete = ArrayListUnmanaged(u8){};
var text_insert = ArrayListUnmanaged(u8){};
defer {
text_delete.deinit(allocator);
text_insert.deinit(allocator);
}
while (pointer < diffs.items.len) {
switch (diffs.items[pointer].operation) {
.insert => {
count_insert += 1;
try text_insert.appendSlice(allocator, diffs.items[pointer].text);
},
.delete => {
count_delete += 1;
try text_delete.appendSlice(allocator, diffs.items[pointer].text);
},
.equal => {
// Upon reaching an equality, check for prior redundancies.
if (count_delete >= 1 and count_insert >= 1) {
// Delete the offending records and add the merged ones.
freeRangeDiffList(
allocator,
&diffs,
pointer - count_delete - count_insert,
count_delete + count_insert,
);
diffs.replaceRangeAssumeCapacity(
pointer - count_delete - count_insert,
count_delete + count_insert,
&.{},
);
pointer = pointer - count_delete - count_insert;
var sub_diff = try dmp.diffInternal(allocator, text_delete.items, text_insert.items, false, deadline);
{
errdefer deinitDiffList(allocator, &sub_diff);
try diffs.ensureUnusedCapacity(allocator, sub_diff.items.len);
}
defer sub_diff.deinit(allocator);
const new_diff = diffs.addManyAtAssumeCapacity(pointer, sub_diff.items.len);
@memcpy(new_diff, sub_diff.items);
pointer = pointer + sub_diff.items.len;
}
count_insert = 0;
count_delete = 0;
text_delete.items.len = 0;
text_insert.items.len = 0;
},
}
pointer += 1;
}
diffs.items.len -= 1; // Remove the dummy entry at the end.
return diffs;
}
const LinesToCharsResult = struct {
chars_1: []const u8,
chars_2: []const u8,
line_array: ArrayListUnmanaged([]const u8),
pub fn deinit(self: *LinesToCharsResult, allocator: Allocator) void {
allocator.free(self.chars_1);
allocator.free(self.chars_2);
self.line_array.deinit(allocator);
}
};
/// 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 Three element Object array, containing the encoded text1, the
/// encoded text2 and the List of unique strings. The zeroth element
/// of the List of unique strings is intentionally blank.
fn diffLinesToChars(
allocator: std.mem.Allocator,
text1: []const u8,
text2: []const u8,
) DiffError!LinesToCharsResult {
var line_array = ArrayListUnmanaged([]const u8){};
errdefer line_array.deinit(allocator);
var line_hash = std.StringHashMapUnmanaged(usize){};
defer line_hash.deinit(allocator);
// e.g. line_array[4] == "Hello\n"
// e.g. line_hash.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.
try line_array.append(allocator, "");
// Allocate 2/3rds of the space for text1, the rest for text2.
const chars1 = try diffLinesToCharsMunge(allocator, text1, &line_array, &line_hash, 170);
errdefer allocator.free(chars1);
const chars2 = try diffLinesToCharsMunge(allocator, text2, &line_array, &line_hash, 255);
return .{ .chars_1 = chars1, .chars_2 = chars2, .line_array = line_array };
}
/// Split a text into a list of strings. Reduce the texts to a string of
/// hashes where each Unicode character represents one line.
/// @param text String to encode.
/// @param lineArray List of unique strings.
/// @param lineHash Map of strings to indices.
/// @param maxLines Maximum length of lineArray.
/// @return Encoded string.
fn diffLinesToCharsMunge(
allocator: std.mem.Allocator,
text: []const u8,
line_array: *ArrayListUnmanaged([]const u8),
line_hash: *std.StringHashMapUnmanaged(usize),
max_lines: usize,
) DiffError![]const u8 {
var line_start: isize = 0;
var line_end: isize = -1;
var chars = ArrayListUnmanaged(u8){};
defer chars.deinit(allocator);
// Walk the text, pulling out a Substring for each line.
// TODO this can be handled with a Reader, avoiding all the manual splitting
while (line_end < @as(isize, @intCast(text.len)) - 1) {
line_end = b: {
break :b @as(isize, @intCast(std.mem.indexOf(u8, text[@intCast(line_start)..], "\n") orelse
break :b @intCast(text.len - 1))) + line_start;
};
var line = text[@intCast(line_start) .. @as(usize, @intCast(line_start)) + @as(usize, @intCast(line_end + 1 - line_start))];
if (line_hash.get(line)) |value| {
try chars.append(allocator, @intCast(value));
} else {
if (line_array.items.len == max_lines) {
// Bail out at 255 because char 256 == char 0.
line = text[@intCast(line_start)..];
line_end = @intCast(text.len);
}
try line_array.append(allocator, line);
try line_hash.put(allocator, line, line_array.items.len - 1);
try chars.append(allocator, @intCast(line_array.items.len - 1));
}
line_start = line_end + 1;
}
return try chars.toOwnedSlice(allocator);
}
/// Rehydrate the text in a diff from a string of line hashes to real lines
/// of text.
/// @param diffs List of Diff objects.
/// @param lineArray List of unique strings.
fn diffCharsToLines(
allocator: std.mem.Allocator,
char_diffs: *DiffList,
line_array: []const []const u8,
) DiffError!DiffList {
var diffs = DiffList{};
errdefer deinitDiffList(allocator, &diffs);
try diffs.ensureTotalCapacity(allocator, char_diffs.items.len);
var text = ArrayListUnmanaged(u8){};
defer text.deinit(allocator);
for (char_diffs.items) |*d| {
var j: usize = 0;
while (j < d.text.len) : (j += 1) {
try text.appendSlice(allocator, line_array[d.text[j]]);
}
diffs.appendAssumeCapacity(Diff.init(d.operation, try text.toOwnedSlice(allocator)));
}
return diffs;
}
/// Reorder and merge like edit sections. Merge equalities.
/// Any edit section can move as long as it doesn't cross an equality.
/// @param diffs List of Diff objects.
fn diffCleanupMerge(allocator: std.mem.Allocator, diffs: *DiffList) DiffError!void {
// Add a dummy entry at the end.
try diffs.append(allocator, Diff.init(.equal, ""));
var pointer: usize = 0;
var count_delete: usize = 0;
var count_insert: usize = 0;
var text_delete = ArrayListUnmanaged(u8){};
defer text_delete.deinit(allocator);
var text_insert = ArrayListUnmanaged(u8){};
defer text_insert.deinit(allocator);
var common_length: usize = undefined;
while (pointer < diffs.items.len) {
switch (diffs.items[pointer].operation) {
.insert => {
count_insert += 1;
try text_insert.appendSlice(allocator, diffs.items[pointer].text);
pointer += 1;
},
.delete => {
count_delete += 1;
try text_delete.appendSlice(allocator, diffs.items[pointer].text);
pointer += 1;
},
.equal => {
// Upon reaching an equality, check for prior redundancies.
if (count_delete + count_insert > 1) {
if (count_delete != 0 and count_insert != 0) {
// Factor out any common prefixies.
common_length = diffCommonPrefix(text_insert.items, text_delete.items);
if (common_length != 0) {
if ((pointer - count_delete - count_insert) > 0 and
diffs.items[pointer - count_delete - count_insert - 1].operation == .equal)
{
const ii = pointer - count_delete - count_insert - 1;
var nt = try allocator.alloc(u8, diffs.items[ii].text.len + common_length);
const ot = diffs.items[ii].text;
@memcpy(nt[0..ot.len], ot);
@memcpy(nt[ot.len..], text_insert.items[0..common_length]);
diffs.items[ii].text = nt;
allocator.free(ot);
} else {
try diffs.ensureUnusedCapacity(allocator, 1);
const text = try allocator.dupe(u8, text_insert.items[0..common_length]);
diffs.insertAssumeCapacity(0, Diff.init(.equal, text));
pointer += 1;
}
text_insert.replaceRangeAssumeCapacity(0, common_length, &.{});
text_delete.replaceRangeAssumeCapacity(0, common_length, &.{});
}
// Factor out any common suffixies.
// @ZigPort this seems very wrong
common_length = diffCommonSuffix(text_insert.items, text_delete.items);
if (common_length != 0) {
const old_text = diffs.items[pointer].text;
diffs.items[pointer].text = try std.mem.concat(allocator, u8, &.{
text_insert.items[text_insert.items.len - common_length ..],
old_text,
});
allocator.free(old_text);
text_insert.items.len -= common_length;
text_delete.items.len -= common_length;
}
}
// Delete the offending records and add the merged ones.
pointer -= count_delete + count_insert;
if (count_delete + count_insert > 0) {
freeRangeDiffList(allocator, diffs, pointer, count_delete + count_insert);
diffs.replaceRangeAssumeCapacity(pointer, count_delete + count_insert, &.{});
}
if (text_delete.items.len != 0) {
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.insertAssumeCapacity(pointer, Diff.init(
.delete,
try allocator.dupe(u8, text_delete.items),
));
pointer += 1;
}
if (text_insert.items.len != 0) {
try diffs.ensureUnusedCapacity(allocator, 1);
diffs.insertAssumeCapacity(pointer, Diff.init(
.insert,
try allocator.dupe(u8, text_insert.items),
));
pointer += 1;
}
pointer += 1;
} else if (pointer != 0 and diffs.items[pointer - 1].operation == .equal) {
// Merge this equality with the previous one.
// TODO: Fix using realloc or smth
// Note: can't use realloc because the text is const
var nt = try allocator.alloc(u8, diffs.items[pointer - 1].text.len + diffs.items[pointer].text.len);
const ot = diffs.items[pointer - 1].text;
defer (allocator.free(ot));
@memcpy(nt[0..ot.len], ot);
@memcpy(nt[ot.len..], diffs.items[pointer].text);
diffs.items[pointer - 1].text = nt;
const dead_diff = diffs.orderedRemove(pointer);
allocator.free(dead_diff.text);
} else {
pointer += 1;
}
count_insert = 0;
count_delete = 0;
text_delete.items.len = 0;