Blob


1 /* Myers diff algorithm implementation, invented by Eugene W. Myers [1].
2 * Implementations of both the Myers Divide Et Impera (using linear space)
3 * and the canonical Myers algorithm (using quadratic space). */
4 /*
5 * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
20 #include <inttypes.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <errno.h>
27 #include <arraylist.h>
28 #include <diff_main.h>
30 #include "diff_internal.h"
31 #include "diff_debug.h"
33 /* Myers' diff algorithm [1] is nicely explained in [2].
34 * [1] http://www.xmailserver.org/diff2.pdf
35 * [2] https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/ ff.
36 *
37 * Myers approaches finding the smallest diff as a graph problem.
38 * The crux is that the original algorithm requires quadratic amount of memory:
39 * both sides' lengths added, and that squared. So if we're diffing lines of
40 * text, two files with 1000 lines each would blow up to a matrix of about
41 * 2000 * 2000 ints of state, about 16 Mb of RAM to figure out 2 kb of text.
42 * The solution is using Myers' "divide and conquer" extension algorithm, which
43 * does the original traversal from both ends of the files to reach a middle
44 * where these "snakes" touch, hence does not need to backtrace the traversal,
45 * and so gets away with only keeping a single column of that huge state matrix
46 * in memory.
47 */
49 struct diff_box {
50 unsigned int left_start;
51 unsigned int left_end;
52 unsigned int right_start;
53 unsigned int right_end;
54 };
56 /* If the two contents of a file are A B C D E and X B C Y,
57 * the Myers diff graph looks like:
58 *
59 * k0 k1
60 * \ \
61 * k-1 0 1 2 3 4 5
62 * \ A B C D E
63 * 0 o-o-o-o-o-o
64 * X | | | | | |
65 * 1 o-o-o-o-o-o
66 * B | |\| | | |
67 * 2 o-o-o-o-o-o
68 * C | | |\| | |
69 * 3 o-o-o-o-o-o
70 * Y | | | | | |\
71 * 4 o-o-o-o-o-o c1
72 * \ \
73 * c-1 c0
74 *
75 * Moving right means delete an atom from the left-hand-side,
76 * Moving down means add an atom from the right-hand-side.
77 * Diagonals indicate identical atoms on both sides, the challenge is to use as
78 * many diagonals as possible.
79 *
80 * The original Myers algorithm walks all the way from the top left to the
81 * bottom right, remembers all steps, and then backtraces to find the shortest
82 * path. However, that requires keeping the entire graph in memory, which needs
83 * quadratic space.
84 *
85 * Myers adds a variant that uses linear space -- note, not linear time, only
86 * linear space: walk forward and backward, find a meeting point in the middle,
87 * and recurse on the two separate sections. This is called "divide and
88 * conquer".
89 *
90 * d: the step number, starting with 0, a.k.a. the distance from the starting
91 * point.
92 * k: relative index in the state array for the forward scan, indicating on
93 * which diagonal through the diff graph we currently are.
94 * c: relative index in the state array for the backward scan, indicating the
95 * diagonal number from the bottom up.
96 *
97 * The "divide and conquer" traversal through the Myers graph looks like this:
98 *
99 * | d= 0 1 2 3 2 1 0
100 * ----+--------------------------------------------
101 * k= | c=
102 * 4 | 3
103 * |
104 * 3 | 3,0 5,2 2
105 * | / \
106 * 2 | 2,0 5,3 1
107 * | / \
108 * 1 | 1,0 4,3 >= 4,3 5,4<-- 0
109 * | / / \ /
110 * 0 | -->0,0 3,3 4,4 -1
111 * | \ / /
112 * -1 | 0,1 1,2 3,4 -2
113 * | \ /
114 * -2 | 0,2 -3
115 * | \
116 * | 0,3
117 * | forward-> <-backward
119 * x,y pairs here are the coordinates in the Myers graph:
120 * x = atom index in left-side source, y = atom index in the right-side source.
122 * Only one forward column and one backward column are kept in mem, each need at
123 * most left.len + 1 + right.len items. Note that each d step occupies either
124 * the even or the odd items of a column: if e.g. the previous column is in the
125 * odd items, the next column is formed in the even items, without overwriting
126 * the previous column's results.
128 * Also note that from the diagonal index k and the x coordinate, the y
129 * coordinate can be derived:
130 * y = x - k
131 * Hence the state array only needs to keep the x coordinate, i.e. the position
132 * in the left-hand file, and the y coordinate, i.e. position in the right-hand
133 * file, is derived from the index in the state array.
135 * The two traces meet at 4,3, the first step (here found in the forward
136 * traversal) where a forward position is on or past a backward traced position
137 * on the same diagonal.
139 * This divides the problem space into:
141 * 0 1 2 3 4 5
142 * A B C D E
143 * 0 o-o-o-o-o
144 * X | | | | |
145 * 1 o-o-o-o-o
146 * B | |\| | |
147 * 2 o-o-o-o-o
148 * C | | |\| |
149 * 3 o-o-o-o-*-o *: forward and backward meet here
150 * Y | |
151 * 4 o-o
153 * Doing the same on each section lead to:
155 * 0 1 2 3 4 5
156 * A B C D E
157 * 0 o-o
158 * X | |
159 * 1 o-b b: backward d=1 first reaches here (sliding up the snake)
160 * B \ f: then forward d=2 reaches here (sliding down the snake)
161 * 2 o As result, the box from b to f is found to be identical;
162 * C \ leaving a top box from 0,0 to 1,1 and a bottom trivial
163 * 3 f-o tail 3,3 to 4,3.
165 * 3 o-*
166 * Y |
167 * 4 o *: forward and backward meet here
169 * and solving the last top left box gives:
171 * 0 1 2 3 4 5
172 * A B C D E -A
173 * 0 o-o +X
174 * X | B
175 * 1 o C
176 * B \ -D
177 * 2 o -E
178 * C \ +Y
179 * 3 o-o-o
180 * Y |
181 * 4 o
183 */
185 #define xk_to_y(X, K) ((X) - (K))
186 #define xc_to_y(X, C, DELTA) ((X) - (C) + (DELTA))
187 #define k_to_c(K, DELTA) ((K) + (DELTA))
188 #define c_to_k(C, DELTA) ((C) - (DELTA))
190 /* Do one forwards step in the "divide and conquer" graph traversal.
191 * left: the left side to diff.
192 * right: the right side to diff against.
193 * kd_forward: the traversal state for forwards traversal, modified by this
194 * function.
195 * This is carried over between invocations with increasing d.
196 * kd_forward points at the center of the state array, allowing
197 * negative indexes.
198 * kd_backward: the traversal state for backwards traversal, to find a meeting
199 * point.
200 * Since forwards is done first, kd_backward will be valid for d -
201 * 1, not d.
202 * kd_backward points at the center of the state array, allowing
203 * negative indexes.
204 * d: Step or distance counter, indicating for what value of d the kd_forward
205 * should be populated.
206 * For d == 0, kd_forward[0] is initialized, i.e. the first invocation should
207 * be for d == 0.
208 * meeting_snake: resulting meeting point, if any.
209 * Return true when a meeting point has been identified.
210 */
211 static int
212 diff_divide_myers_forward(bool *found_midpoint,
213 struct diff_data *left, struct diff_data *right,
214 int *kd_forward, int *kd_backward, int d,
215 struct diff_box *meeting_snake)
217 int delta = (int)right->atoms.len - (int)left->atoms.len;
218 int k;
219 int x;
220 int prev_x;
221 int prev_y;
222 int x_before_slide;
223 *found_midpoint = false;
225 debug("-- %s d=%d\n", __func__, d);
227 for (k = d; k >= -d; k -= 2) {
228 if (k < -(int)right->atoms.len || k > (int)left->atoms.len) {
229 /* This diagonal is completely outside of the Myers
230 * graph, don't calculate it. */
231 if (k < -(int)right->atoms.len)
232 debug(" %d k < -(int)right->atoms.len %d\n", k,
233 -(int)right->atoms.len);
234 else
235 debug(" %d k > left->atoms.len %d\n", k,
236 left->atoms.len);
237 if (k < 0) {
238 /* We are traversing negatively, and already
239 * below the entire graph, nothing will come of
240 * this. */
241 debug(" break");
242 break;
244 debug(" continue");
245 continue;
247 debug("- k = %d\n", k);
248 if (d == 0) {
249 /* This is the initializing step. There is no prev_k
250 * yet, get the initial x from the top left of the Myers
251 * graph. */
252 x = 0;
254 /* Favoring "-" lines first means favoring moving rightwards in
255 * the Myers graph.
256 * For this, all k should derive from k - 1, only the bottom
257 * most k derive from k + 1:
259 * | d= 0 1 2
260 * ----+----------------
261 * k= |
262 * 2 | 2,0 <-- from prev_k = 2 - 1 = 1
263 * | /
264 * 1 | 1,0
265 * | /
266 * 0 | -->0,0 3,3
267 * | \\ /
268 * -1 | 0,1 <-- bottom most for d=1 from
269 * | \\ prev_k = -1 + 1 = 0
270 * -2 | 0,2 <-- bottom most for d=2 from
271 * prev_k = -2 + 1 = -1
273 * Except when a k + 1 from a previous run already means a
274 * further advancement in the graph.
275 * If k == d, there is no k + 1 and k - 1 is the only option.
276 * If k < d, use k + 1 in case that yields a larger x. Also use
277 * k + 1 if k - 1 is outside the graph.
278 */
279 else if (k > -d
280 && (k == d
281 || (k - 1 >= -(int)right->atoms.len
282 && kd_forward[k - 1] >= kd_forward[k + 1]))) {
283 /* Advance from k - 1.
284 * From position prev_k, step to the right in the Myers
285 * graph: x += 1.
286 */
287 int prev_k = k - 1;
288 prev_x = kd_forward[prev_k];
289 prev_y = xk_to_y(prev_x, prev_k);
290 x = prev_x + 1;
291 } else {
292 /* The bottom most one.
293 * From position prev_k, step to the bottom in the Myers
294 * graph: y += 1.
295 * Incrementing y is achieved by decrementing k while
296 * keeping the same x.
297 * (since we're deriving y from y = x - k).
298 */
299 int prev_k = k + 1;
300 prev_x = kd_forward[prev_k];
301 prev_y = xk_to_y(prev_x, prev_k);
302 x = prev_x;
305 x_before_slide = x;
306 /* Slide down any snake that we might find here. */
307 while (x < left->atoms.len && xk_to_y(x, k) < right->atoms.len) {
308 bool same;
309 int r = diff_atom_same(&same,
310 &left->atoms.head[x],
311 &right->atoms.head[
312 xk_to_y(x, k)]);
313 if (r)
314 return r;
315 if (!same)
316 break;
317 x++;
319 kd_forward[k] = x;
320 if (x_before_slide != x) {
321 debug(" down %d similar lines\n", x - x_before_slide);
324 #if DEBUG
326 int fi;
327 for (fi = d; fi >= k; fi--) {
328 debug("kd_forward[%d] = (%d, %d)\n", fi,
329 kd_forward[fi], kd_forward[fi] - fi);
332 #endif
334 if (x < 0 || x > left->atoms.len
335 || xk_to_y(x, k) < 0 || xk_to_y(x, k) > right->atoms.len)
336 continue;
338 /* Figured out a new forwards traversal, see if this has gone
339 * onto or even past a preceding backwards traversal.
341 * If the delta in length is odd, then d and backwards_d hit the
342 * same state indexes:
343 * | d= 0 1 2 1 0
344 * ----+---------------- ----------------
345 * k= | c=
346 * 4 | 3
347 * |
348 * 3 | 2
349 * | same
350 * 2 | 2,0====5,3 1
351 * | / \
352 * 1 | 1,0 5,4<-- 0
353 * | / /
354 * 0 | -->0,0 3,3====4,4 -1
355 * | \ /
356 * -1 | 0,1 -2
357 * | \
358 * -2 | 0,2 -3
359 * |
361 * If the delta is even, they end up off-by-one, i.e. on
362 * different diagonals:
364 * | d= 0 1 2 1 0
365 * ----+---------------- ----------------
366 * | c=
367 * 3 | 3
368 * |
369 * 2 | 2,0 off 2
370 * | / \\
371 * 1 | 1,0 4,3 1
372 * | / // \
373 * 0 | -->0,0 3,3 4,4<-- 0
374 * | \ / /
375 * -1 | 0,1 3,4 -1
376 * | \ //
377 * -2 | 0,2 -2
378 * |
380 * So in the forward path, we can only match up diagonals when
381 * the delta is odd.
382 */
383 if ((delta & 1) == 0)
384 continue;
385 /* Forwards is done first, so the backwards one was still at
386 * d - 1. Can't do this for d == 0. */
387 int backwards_d = d - 1;
388 if (backwards_d < 0)
389 continue;
391 debug("backwards_d = %d\n", backwards_d);
393 /* If both sides have the same length, forward and backward
394 * start on the same diagonal, meaning the backwards state index
395 * c == k.
396 * As soon as the lengths are not the same, the backwards
397 * traversal starts on a different diagonal, and c = k shifted
398 * by the difference in length.
399 */
400 int c = k_to_c(k, delta);
402 /* When the file sizes are very different, the traversal trees
403 * start on far distant diagonals.
404 * They don't necessarily meet straight on. See whether this
405 * forward value is on a diagonal that is also valid in
406 * kd_backward[], and match them if so. */
407 if (c >= -backwards_d && c <= backwards_d) {
408 /* Current k is on a diagonal that exists in
409 * kd_backward[]. If the two x positions have met or
410 * passed (forward walked onto or past backward), then
411 * we've found a midpoint / a mid-box.
413 * When forwards and backwards traversals meet, the
414 * endpoints of the mid-snake are not the two points in
415 * kd_forward and kd_backward, but rather the section
416 * that was slid (if any) of the current
417 * forward/backward traversal only.
419 * For example:
421 * o
422 * \
423 * o
424 * \
425 * o
426 * \
427 * o
428 * \
429 * X o o
430 * | | |
431 * o-o-o o
432 * \|
433 * M
434 * \
435 * o
436 * \
437 * A o
438 * | |
439 * o-o-o
441 * The forward traversal reached M from the top and slid
442 * downwards to A. The backward traversal already
443 * reached X, which is not a straight line from M
444 * anymore, so picking a mid-snake from M to X would
445 * yield a mistake.
447 * The correct mid-snake is between M and A. M is where
448 * the forward traversal hit the diagonal that the
449 * backward traversal has already passed, and A is what
450 * it reaches when sliding down identical lines.
451 */
452 int backward_x = kd_backward[c];
453 debug("Compare: k=%d c=%d is (%d,%d) >= (%d,%d)?\n",
454 k, c, x, xk_to_y(x, k), backward_x,
455 xc_to_y(backward_x, c, delta));
456 if (x >= backward_x) {
457 if (x_before_slide != x) {
458 /* met after sliding up a mid-snake */
459 *meeting_snake = (struct diff_box){
460 .left_start = x_before_slide,
461 .left_end = x,
462 .right_start = xc_to_y(x_before_slide,
463 c, delta),
464 .right_end = xk_to_y(x, k),
465 };
466 } else {
467 /* met after a side step, non-identical
468 * line. Mark that as box divider
469 * instead. This makes sure that
470 * myers_divide never returns the same
471 * box that came as input, avoiding
472 * "infinite" looping. */
473 *meeting_snake = (struct diff_box){
474 .left_start = prev_x,
475 .left_end = x,
476 .right_start = prev_y,
477 .right_end = xk_to_y(x, k),
478 };
480 debug("HIT x=(%u,%u) - y=(%u,%u)\n",
481 meeting_snake->left_start,
482 meeting_snake->right_start,
483 meeting_snake->left_end,
484 meeting_snake->right_end);
485 debug_dump_myers_graph(left, right, NULL,
486 kd_forward, d,
487 kd_backward, d-1);
488 *found_midpoint = true;
489 return 0;
494 debug_dump_myers_graph(left, right, NULL, kd_forward, d,
495 kd_backward, d-1);
496 return 0;
499 /* Do one backwards step in the "divide and conquer" graph traversal.
500 * left: the left side to diff.
501 * right: the right side to diff against.
502 * kd_forward: the traversal state for forwards traversal, to find a meeting
503 * point.
504 * Since forwards is done first, after this, both kd_forward and
505 * kd_backward will be valid for d.
506 * kd_forward points at the center of the state array, allowing
507 * negative indexes.
508 * kd_backward: the traversal state for backwards traversal, to find a meeting
509 * point.
510 * This is carried over between invocations with increasing d.
511 * kd_backward points at the center of the state array, allowing
512 * negative indexes.
513 * d: Step or distance counter, indicating for what value of d the kd_backward
514 * should be populated.
515 * Before the first invocation, kd_backward[0] shall point at the bottom
516 * right of the Myers graph (left.len, right.len).
517 * The first invocation will be for d == 1.
518 * meeting_snake: resulting meeting point, if any.
519 * Return true when a meeting point has been identified.
520 */
521 static int
522 diff_divide_myers_backward(bool *found_midpoint,
523 struct diff_data *left, struct diff_data *right,
524 int *kd_forward, int *kd_backward, int d,
525 struct diff_box *meeting_snake)
527 int delta = (int)right->atoms.len - (int)left->atoms.len;
528 int c;
529 int x;
530 int prev_x;
531 int prev_y;
532 int x_before_slide;
534 *found_midpoint = false;
536 debug("-- %s d=%d\n", __func__, d);
538 for (c = d; c >= -d; c -= 2) {
539 if (c < -(int)left->atoms.len || c > (int)right->atoms.len) {
540 /* This diagonal is completely outside of the Myers
541 * graph, don't calculate it. */
542 if (c < -(int)left->atoms.len)
543 debug(" %d c < -(int)left->atoms.len %d\n", c,
544 -(int)left->atoms.len);
545 else
546 debug(" %d c > right->atoms.len %d\n", c,
547 right->atoms.len);
548 if (c < 0) {
549 /* We are traversing negatively, and already
550 * below the entire graph, nothing will come of
551 * this. */
552 debug(" break");
553 break;
555 debug(" continue");
556 continue;
558 debug("- c = %d\n", c);
559 if (d == 0) {
560 /* This is the initializing step. There is no prev_c
561 * yet, get the initial x from the bottom right of the
562 * Myers graph. */
563 x = left->atoms.len;
565 /* Favoring "-" lines first means favoring moving rightwards in
566 * the Myers graph.
567 * For this, all c should derive from c - 1, only the bottom
568 * most c derive from c + 1:
570 * 2 1 0
571 * ---------------------------------------------------
572 * c=
573 * 3
575 * from prev_c = c - 1 --> 5,2 2
576 * \
577 * 5,3 1
578 * \
579 * 4,3 5,4<-- 0
580 * \ /
581 * bottom most for d=1 from c + 1 --> 4,4 -1
582 * /
583 * bottom most for d=2 --> 3,4 -2
585 * Except when a c + 1 from a previous run already means a
586 * further advancement in the graph.
587 * If c == d, there is no c + 1 and c - 1 is the only option.
588 * If c < d, use c + 1 in case that yields a larger x.
589 * Also use c + 1 if c - 1 is outside the graph.
590 */
591 else if (c > -d && (c == d
592 || (c - 1 >= -(int)right->atoms.len
593 && kd_backward[c - 1] <= kd_backward[c + 1]))) {
594 /* A top one.
595 * From position prev_c, step upwards in the Myers
596 * graph: y -= 1.
597 * Decrementing y is achieved by incrementing c while
598 * keeping the same x. (since we're deriving y from
599 * y = x - c + delta).
600 */
601 int prev_c = c - 1;
602 prev_x = kd_backward[prev_c];
603 prev_y = xc_to_y(prev_x, prev_c, delta);
604 x = prev_x;
605 } else {
606 /* The bottom most one.
607 * From position prev_c, step to the left in the Myers
608 * graph: x -= 1.
609 */
610 int prev_c = c + 1;
611 prev_x = kd_backward[prev_c];
612 prev_y = xc_to_y(prev_x, prev_c, delta);
613 x = prev_x - 1;
616 /* Slide up any snake that we might find here (sections of
617 * identical lines on both sides). */
618 debug("c=%d x-1=%d Yb-1=%d-1=%d\n", c, x-1, xc_to_y(x, c,
619 delta),
620 xc_to_y(x, c, delta)-1);
621 if (x > 0) {
622 debug(" l=");
623 debug_dump_atom(left, right, &left->atoms.head[x-1]);
625 if (xc_to_y(x, c, delta) > 0) {
626 debug(" r=");
627 debug_dump_atom(right, left,
628 &right->atoms.head[xc_to_y(x, c, delta)-1]);
630 x_before_slide = x;
631 while (x > 0 && xc_to_y(x, c, delta) > 0) {
632 bool same;
633 int r = diff_atom_same(&same,
634 &left->atoms.head[x-1],
635 &right->atoms.head[
636 xc_to_y(x, c, delta)-1]);
637 if (r)
638 return r;
639 if (!same)
640 break;
641 x--;
643 kd_backward[c] = x;
644 if (x_before_slide != x) {
645 debug(" up %d similar lines\n", x_before_slide - x);
648 if (DEBUG) {
649 int fi;
650 for (fi = d; fi >= c; fi--) {
651 debug("kd_backward[%d] = (%d, %d)\n",
652 fi,
653 kd_backward[fi],
654 kd_backward[fi] - fi + delta);
658 if (x < 0 || x > left->atoms.len
659 || xc_to_y(x, c, delta) < 0
660 || xc_to_y(x, c, delta) > right->atoms.len)
661 continue;
663 /* Figured out a new backwards traversal, see if this has gone
664 * onto or even past a preceding forwards traversal.
666 * If the delta in length is even, then d and backwards_d hit
667 * the same state indexes -- note how this is different from in
668 * the forwards traversal, because now both d are the same:
670 * | d= 0 1 2 2 1 0
671 * ----+---------------- --------------------
672 * k= | c=
673 * 4 |
674 * |
675 * 3 | 3
676 * | same
677 * 2 | 2,0====5,2 2
678 * | / \
679 * 1 | 1,0 5,3 1
680 * | / / \
681 * 0 | -->0,0 3,3====4,3 5,4<-- 0
682 * | \ / /
683 * -1 | 0,1 4,4 -1
684 * | \
685 * -2 | 0,2 -2
686 * |
687 * -3
688 * If the delta is odd, they end up off-by-one, i.e. on
689 * different diagonals.
690 * So in the backward path, we can only match up diagonals when
691 * the delta is even.
692 */
693 if ((delta & 1) != 0)
694 continue;
695 /* Forwards was done first, now both d are the same. */
696 int forwards_d = d;
698 /* As soon as the lengths are not the same, the
699 * backwards traversal starts on a different diagonal,
700 * and c = k shifted by the difference in length.
701 */
702 int k = c_to_k(c, delta);
704 /* When the file sizes are very different, the traversal trees
705 * start on far distant diagonals.
706 * They don't necessarily meet straight on. See whether this
707 * backward value is also on a valid diagonal in kd_forward[],
708 * and match them if so. */
709 if (k >= -forwards_d && k <= forwards_d) {
710 /* Current c is on a diagonal that exists in
711 * kd_forward[]. If the two x positions have met or
712 * passed (backward walked onto or past forward), then
713 * we've found a midpoint / a mid-box.
715 * When forwards and backwards traversals meet, the
716 * endpoints of the mid-snake are not the two points in
717 * kd_forward and kd_backward, but rather the section
718 * that was slid (if any) of the current
719 * forward/backward traversal only.
721 * For example:
723 * o-o-o
724 * | |
725 * o A
726 * | \
727 * o o
728 * \
729 * M
730 * |\
731 * o o-o-o
732 * | | |
733 * o o X
734 * \
735 * o
736 * \
737 * o
738 * \
739 * o
741 * The backward traversal reached M from the bottom and
742 * slid upwards. The forward traversal already reached
743 * X, which is not a straight line from M anymore, so
744 * picking a mid-snake from M to X would yield a
745 * mistake.
747 * The correct mid-snake is between M and A. M is where
748 * the backward traversal hit the diagonal that the
749 * forwards traversal has already passed, and A is what
750 * it reaches when sliding up identical lines.
751 */
753 int forward_x = kd_forward[k];
754 debug("Compare: k=%d c=%d is (%d,%d) >= (%d,%d)?\n",
755 k, c, forward_x, xk_to_y(forward_x, k),
756 x, xc_to_y(x, c, delta));
757 if (forward_x >= x) {
758 if (x_before_slide != x) {
759 /* met after sliding down a mid-snake */
760 *meeting_snake = (struct diff_box){
761 .left_start = x,
762 .left_end = x_before_slide,
763 .right_start = xc_to_y(x, c, delta),
764 .right_end = xk_to_y(x_before_slide, k),
765 };
766 } else {
767 /* met after a side step, non-identical
768 * line. Mark that as box divider
769 * instead. This makes sure that
770 * myers_divide never returns the same
771 * box that came as input, avoiding
772 * "infinite" looping. */
773 *meeting_snake = (struct diff_box){
774 .left_start = x,
775 .left_end = prev_x,
776 .right_start = xc_to_y(x, c, delta),
777 .right_end = prev_y,
778 };
780 debug("HIT x=%u,%u - y=%u,%u\n",
781 meeting_snake->left_start,
782 meeting_snake->right_start,
783 meeting_snake->left_end,
784 meeting_snake->right_end);
785 debug_dump_myers_graph(left, right, NULL,
786 kd_forward, d,
787 kd_backward, d);
788 *found_midpoint = true;
789 return 0;
793 debug_dump_myers_graph(left, right, NULL, kd_forward, d, kd_backward,
794 d);
795 return 0;
798 /* Integer square root approximation */
799 static int
800 shift_sqrt(int val)
802 int i;
803 for (i = 1; val > 0; val >>= 2)
804 i <<= 1;
805 return i;
808 /* Myers "Divide et Impera": tracing forwards from the start and backwards from
809 * the end to find a midpoint that divides the problem into smaller chunks.
810 * Requires only linear amounts of memory. */
811 int
812 diff_algo_myers_divide(const struct diff_algo_config *algo_config,
813 struct diff_state *state)
815 int rc = ENOMEM;
816 struct diff_data *left = &state->left;
817 struct diff_data *right = &state->right;
819 debug("\n** %s\n", __func__);
820 debug("left:\n");
821 debug_dump(left);
822 debug("right:\n");
823 debug_dump(right);
824 debug_dump_myers_graph(left, right, NULL, NULL, 0, NULL, 0);
826 /* Allocate two columns of a Myers graph, one for the forward and one
827 * for the backward traversal. */
828 unsigned int max = left->atoms.len + right->atoms.len;
829 size_t kd_len = max + 1;
830 size_t kd_buf_size = kd_len << 1;
831 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
832 if (!kd_buf)
833 return ENOMEM;
834 int i;
835 for (i = 0; i < kd_buf_size; i++)
836 kd_buf[i] = -1;
837 int *kd_forward = kd_buf;
838 int *kd_backward = kd_buf + kd_len;
839 int max_effort = shift_sqrt(max/2);
841 /* The 'k' axis in Myers spans positive and negative indexes, so point
842 * the kd to the middle.
843 * It is then possible to index from -max/2 .. max/2. */
844 kd_forward += max/2;
845 kd_backward += max/2;
847 int d;
848 struct diff_box mid_snake = {};
849 bool found_midpoint = false;
850 for (d = 0; d <= (max/2); d++) {
851 int r;
852 debug("-- d=%d\n", d);
853 r = diff_divide_myers_forward(&found_midpoint, left, right,
854 kd_forward, kd_backward, d,
855 &mid_snake);
856 if (r)
857 return r;
858 if (found_midpoint)
859 break;
860 r = diff_divide_myers_backward(&found_midpoint, left, right,
861 kd_forward, kd_backward, d,
862 &mid_snake);
863 if (r)
864 return r;
865 if (found_midpoint)
866 break;
868 /* Limit the effort spent looking for a mid snake. If files have
869 * very few lines in common, the effort spent to find nice mid
870 * snakes is just not worth it, the diff result will still be
871 * essentially minus everything on the left, plus everything on
872 * the right, with a few useless matches here and there. */
873 if (d > max_effort) {
874 /* pick the furthest reaching point from
875 * kd_forward and kd_backward, and use that as a
876 * midpoint, to not step into another diff algo
877 * recursion with unchanged box. */
878 int delta = (int)right->atoms.len - (int)left->atoms.len;
879 int x;
880 int y;
881 int i;
882 int best_forward_i = 0;
883 int best_forward_distance = 0;
884 int best_backward_i = 0;
885 int best_backward_distance = 0;
886 int distance;
887 int best_forward_x;
888 int best_forward_y;
889 int best_backward_x;
890 int best_backward_y;
892 debug("~~~ d = %d > max_effort = %d\n", d, max_effort);
894 for (i = d; i >= -d; i -= 2) {
895 if (i >= -(int)right->atoms.len && i <= (int)left->atoms.len) {
896 x = kd_forward[i];
897 y = xk_to_y(x, i);
898 distance = x + y;
899 if (distance > best_forward_distance) {
900 best_forward_distance = distance;
901 best_forward_i = i;
905 if (i >= -(int)left->atoms.len && i <= (int)right->atoms.len) {
906 x = kd_backward[i];
907 y = xc_to_y(x, i, delta);
908 distance = (right->atoms.len - x)
909 + (left->atoms.len - y);
910 if (distance >= best_backward_distance) {
911 best_backward_distance = distance;
912 best_backward_i = i;
917 /* The myers-divide didn't meet in the middle. We just
918 * figured out the places where the forward path
919 * advanced the most, and the backward path advanced the
920 * most. Just divide at whichever one of those two is better.
922 * o-o
923 * |
924 * o
925 * \
926 * o
927 * \
928 * F <-- cut here
932 * or here --> B
933 * \
934 * o
935 * \
936 * o
937 * |
938 * o-o
939 */
940 best_forward_x = kd_forward[best_forward_i];
941 best_forward_y = xk_to_y(best_forward_x, best_forward_i);
942 best_backward_x = kd_backward[best_backward_i];
943 best_backward_y = xc_to_y(x, best_backward_i, delta);
945 if (best_forward_distance >= best_backward_distance) {
946 x = best_forward_x;
947 y = best_forward_y;
948 } else {
949 x = best_backward_x;
950 y = best_backward_y;
953 debug("max_effort cut at x=%d y=%d\n", x, y);
954 if (x < 0 || y < 0
955 || x > left->atoms.len || y > right->atoms.len)
956 break;
958 found_midpoint = true;
959 mid_snake = (struct diff_box){
960 .left_start = x,
961 .left_end = x,
962 .right_start = y,
963 .right_end = y,
964 };
965 break;
969 if (!found_midpoint) {
970 /* Divide and conquer failed to find a meeting point. Use the
971 * fallback_algo defined in the algo_config (leave this to the
972 * caller). This is just paranoia/sanity, we normally should
973 * always find a midpoint.
974 */
975 debug(" no midpoint \n");
976 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
977 goto return_rc;
978 } else {
979 debug(" mid snake L: %u to %u of %u R: %u to %u of %u\n",
980 mid_snake.left_start, mid_snake.left_end, left->atoms.len,
981 mid_snake.right_start, mid_snake.right_end,
982 right->atoms.len);
984 /* Section before the mid-snake. */
985 debug("Section before the mid-snake\n");
987 struct diff_atom *left_atom = &left->atoms.head[0];
988 unsigned int left_section_len = mid_snake.left_start;
989 struct diff_atom *right_atom = &right->atoms.head[0];
990 unsigned int right_section_len = mid_snake.right_start;
992 if (left_section_len && right_section_len) {
993 /* Record an unsolved chunk, the caller will apply
994 * inner_algo() on this chunk. */
995 if (!diff_state_add_chunk(state, false,
996 left_atom, left_section_len,
997 right_atom,
998 right_section_len))
999 goto return_rc;
1000 } else if (left_section_len && !right_section_len) {
1001 /* Only left atoms and none on the right, they form a
1002 * "minus" chunk, then. */
1003 if (!diff_state_add_chunk(state, true,
1004 left_atom, left_section_len,
1005 right_atom, 0))
1006 goto return_rc;
1007 } else if (!left_section_len && right_section_len) {
1008 /* No left atoms, only atoms on the right, they form a
1009 * "plus" chunk, then. */
1010 if (!diff_state_add_chunk(state, true,
1011 left_atom, 0,
1012 right_atom,
1013 right_section_len))
1014 goto return_rc;
1016 /* else: left_section_len == 0 and right_section_len == 0, i.e.
1017 * nothing before the mid-snake. */
1019 if (mid_snake.left_end > mid_snake.left_start
1020 || mid_snake.right_end > mid_snake.right_start) {
1021 /* The midpoint is a section of identical data on both
1022 * sides, or a certain differing line: that section
1023 * immediately becomes a solved chunk. */
1024 debug("the mid-snake\n");
1025 if (!diff_state_add_chunk(state, true,
1026 &left->atoms.head[mid_snake.left_start],
1027 mid_snake.left_end - mid_snake.left_start,
1028 &right->atoms.head[mid_snake.right_start],
1029 mid_snake.right_end - mid_snake.right_start))
1030 goto return_rc;
1033 /* Section after the mid-snake. */
1034 debug("Section after the mid-snake\n");
1035 debug(" left_end %u right_end %u\n",
1036 mid_snake.left_end, mid_snake.right_end);
1037 debug(" left_count %u right_count %u\n",
1038 left->atoms.len, right->atoms.len);
1039 left_atom = &left->atoms.head[mid_snake.left_end];
1040 left_section_len = left->atoms.len - mid_snake.left_end;
1041 right_atom = &right->atoms.head[mid_snake.right_end];
1042 right_section_len = right->atoms.len - mid_snake.right_end;
1044 if (left_section_len && right_section_len) {
1045 /* Record an unsolved chunk, the caller will apply
1046 * inner_algo() on this chunk. */
1047 if (!diff_state_add_chunk(state, false,
1048 left_atom, left_section_len,
1049 right_atom,
1050 right_section_len))
1051 goto return_rc;
1052 } else if (left_section_len && !right_section_len) {
1053 /* Only left atoms and none on the right, they form a
1054 * "minus" chunk, then. */
1055 if (!diff_state_add_chunk(state, true,
1056 left_atom, left_section_len,
1057 right_atom, 0))
1058 goto return_rc;
1059 } else if (!left_section_len && right_section_len) {
1060 /* No left atoms, only atoms on the right, they form a
1061 * "plus" chunk, then. */
1062 if (!diff_state_add_chunk(state, true,
1063 left_atom, 0,
1064 right_atom,
1065 right_section_len))
1066 goto return_rc;
1068 /* else: left_section_len == 0 and right_section_len == 0, i.e.
1069 * nothing after the mid-snake. */
1072 rc = DIFF_RC_OK;
1074 return_rc:
1075 free(kd_buf);
1076 debug("** END %s\n", __func__);
1077 return rc;
1080 /* Myers Diff tracing from the start all the way through to the end, requiring
1081 * quadratic amounts of memory. This can fail if the required space surpasses
1082 * algo_config->permitted_state_size. */
1083 int
1084 diff_algo_myers(const struct diff_algo_config *algo_config,
1085 struct diff_state *state)
1087 /* do a diff_divide_myers_forward() without a _backward(), so that it
1088 * walks forward across the entire files to reach the end. Keep each
1089 * run's state, and do a final backtrace. */
1090 int rc = ENOMEM;
1091 struct diff_data *left = &state->left;
1092 struct diff_data *right = &state->right;
1094 debug("\n** %s\n", __func__);
1095 debug("left:\n");
1096 debug_dump(left);
1097 debug("right:\n");
1098 debug_dump(right);
1099 debug_dump_myers_graph(left, right, NULL, NULL, 0, NULL, 0);
1101 /* Allocate two columns of a Myers graph, one for the forward and one
1102 * for the backward traversal. */
1103 unsigned int max = left->atoms.len + right->atoms.len;
1104 size_t kd_len = max + 1 + max;
1105 size_t kd_buf_size = kd_len * kd_len;
1106 size_t kd_state_size = kd_buf_size * sizeof(int);
1107 debug("state size: %zu\n", kd_state_size);
1108 if (kd_buf_size < kd_len /* overflow? */
1109 || kd_state_size > algo_config->permitted_state_size) {
1110 debug("state size %zu > permitted_state_size %zu, use fallback_algo\n",
1111 kd_state_size, algo_config->permitted_state_size);
1112 return DIFF_RC_USE_DIFF_ALGO_FALLBACK;
1115 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
1116 if (!kd_buf)
1117 return ENOMEM;
1118 int i;
1119 for (i = 0; i < kd_buf_size; i++)
1120 kd_buf[i] = -1;
1122 /* The 'k' axis in Myers spans positive and negative indexes, so point
1123 * the kd to the middle.
1124 * It is then possible to index from -max .. max. */
1125 int *kd_origin = kd_buf + max;
1126 int *kd_column = kd_origin;
1128 int d;
1129 int backtrack_d = -1;
1130 int backtrack_k = 0;
1131 int k;
1132 int x, y;
1133 for (d = 0; d <= max; d++, kd_column += kd_len) {
1134 debug("-- d=%d\n", d);
1136 debug("-- %s d=%d\n", __func__, d);
1138 for (k = d; k >= -d; k -= 2) {
1139 if (k < -(int)right->atoms.len
1140 || k > (int)left->atoms.len) {
1141 /* This diagonal is completely outside of the
1142 * Myers graph, don't calculate it. */
1143 if (k < -(int)right->atoms.len)
1144 debug(" %d k <"
1145 " -(int)right->atoms.len %d\n",
1146 k, -(int)right->atoms.len);
1147 else
1148 debug(" %d k > left->atoms.len %d\n", k,
1149 left->atoms.len);
1150 if (k < 0) {
1151 /* We are traversing negatively, and
1152 * already below the entire graph,
1153 * nothing will come of this. */
1154 debug(" break");
1155 break;
1157 debug(" continue");
1158 continue;
1161 debug("- k = %d\n", k);
1162 if (d == 0) {
1163 /* This is the initializing step. There is no
1164 * prev_k yet, get the initial x from the top
1165 * left of the Myers graph. */
1166 x = 0;
1167 } else {
1168 int *kd_prev_column = kd_column - kd_len;
1170 /* Favoring "-" lines first means favoring
1171 * moving rightwards in the Myers graph.
1172 * For this, all k should derive from k - 1,
1173 * only the bottom most k derive from k + 1:
1175 * | d= 0 1 2
1176 * ----+----------------
1177 * k= |
1178 * 2 | 2,0 <-- from
1179 * | / prev_k = 2 - 1 = 1
1180 * 1 | 1,0
1181 * | /
1182 * 0 | -->0,0 3,3
1183 * | \\ /
1184 * -1 | 0,1 <-- bottom most for d=1
1185 * | \\ from prev_k = -1+1 = 0
1186 * -2 | 0,2 <-- bottom most for
1187 * d=2 from
1188 * prev_k = -2+1 = -1
1190 * Except when a k + 1 from a previous run
1191 * already means a further advancement in the
1192 * graph.
1193 * If k == d, there is no k + 1 and k - 1 is the
1194 * only option.
1195 * If k < d, use k + 1 in case that yields a
1196 * larger x. Also use k + 1 if k - 1 is outside
1197 * the graph.
1199 if (k > -d
1200 && (k == d
1201 || (k - 1 >= -(int)right->atoms.len
1202 && kd_prev_column[k - 1]
1203 >= kd_prev_column[k + 1]))) {
1204 /* Advance from k - 1.
1205 * From position prev_k, step to the
1206 * right in the Myers graph: x += 1.
1208 int prev_k = k - 1;
1209 int prev_x = kd_prev_column[prev_k];
1210 x = prev_x + 1;
1211 } else {
1212 /* The bottom most one.
1213 * From position prev_k, step to the
1214 * bottom in the Myers graph: y += 1.
1215 * Incrementing y is achieved by
1216 * decrementing k while keeping the same
1217 * x. (since we're deriving y from y =
1218 * x - k).
1220 int prev_k = k + 1;
1221 int prev_x = kd_prev_column[prev_k];
1222 x = prev_x;
1226 /* Slide down any snake that we might find here. */
1227 while (x < left->atoms.len
1228 && xk_to_y(x, k) < right->atoms.len) {
1229 bool same;
1230 int r = diff_atom_same(&same,
1231 &left->atoms.head[x],
1232 &right->atoms.head[
1233 xk_to_y(x, k)]);
1234 if (r)
1235 return r;
1236 if (!same)
1237 break;
1238 x++;
1240 kd_column[k] = x;
1242 if (DEBUG) {
1243 int fi;
1244 for (fi = d; fi >= k; fi-=2) {
1245 debug("kd_column[%d] = (%d, %d)\n", fi,
1246 kd_column[fi],
1247 kd_column[fi] - fi);
1251 if (x == left->atoms.len
1252 && xk_to_y(x, k) == right->atoms.len) {
1253 /* Found a path */
1254 backtrack_d = d;
1255 backtrack_k = k;
1256 debug("Reached the end at d = %d, k = %d\n",
1257 backtrack_d, backtrack_k);
1258 break;
1262 if (backtrack_d >= 0)
1263 break;
1266 debug_dump_myers_graph(left, right, kd_origin, NULL, 0, NULL, 0);
1268 /* backtrack. A matrix spanning from start to end of the file is ready:
1270 * | d= 0 1 2 3 4
1271 * ----+---------------------------------
1272 * k= |
1273 * 3 |
1274 * |
1275 * 2 | 2,0
1276 * | /
1277 * 1 | 1,0 4,3
1278 * | / / \
1279 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4, backtrack_k = 0
1280 * | \ / \
1281 * -1 | 0,1 3,4
1282 * | \
1283 * -2 | 0,2
1284 * |
1286 * From (4,4) backwards, find the previous position that is the largest, and remember it.
1289 for (d = backtrack_d, k = backtrack_k; d >= 0; d--) {
1290 x = kd_column[k];
1291 y = xk_to_y(x, k);
1293 /* When the best position is identified, remember it for that
1294 * kd_column.
1295 * That kd_column is no longer needed otherwise, so just
1296 * re-purpose kd_column[0] = x and kd_column[1] = y,
1297 * so that there is no need to allocate more memory.
1299 kd_column[0] = x;
1300 kd_column[1] = y;
1301 debug("Backtrack d=%d: xy=(%d, %d)\n",
1302 d, kd_column[0], kd_column[1]);
1304 /* Don't access memory before kd_buf */
1305 if (d == 0)
1306 break;
1307 int *kd_prev_column = kd_column - kd_len;
1309 /* When y == 0, backtracking downwards (k-1) is the only way.
1310 * When x == 0, backtracking upwards (k+1) is the only way.
1312 * | d= 0 1 2 3 4
1313 * ----+---------------------------------
1314 * k= |
1315 * 3 |
1316 * | ..y == 0
1317 * 2 | 2,0
1318 * | /
1319 * 1 | 1,0 4,3
1320 * | / / \
1321 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4,
1322 * | \ / \ backtrack_k = 0
1323 * -1 | 0,1 3,4
1324 * | \
1325 * -2 | 0,2__
1326 * | x == 0
1328 if (y == 0
1329 || (x > 0
1330 && kd_prev_column[k - 1] >= kd_prev_column[k + 1])) {
1331 k = k - 1;
1332 debug("prev k=k-1=%d x=%d y=%d\n",
1333 k, kd_prev_column[k],
1334 xk_to_y(kd_prev_column[k], k));
1335 } else {
1336 k = k + 1;
1337 debug("prev k=k+1=%d x=%d y=%d\n",
1338 k, kd_prev_column[k],
1339 xk_to_y(kd_prev_column[k], k));
1341 kd_column = kd_prev_column;
1344 /* Forwards again, this time recording the diff chunks.
1345 * Definitely start from 0,0. kd_column[0] may actually point to the
1346 * bottom of a snake starting at 0,0 */
1347 x = 0;
1348 y = 0;
1350 kd_column = kd_origin;
1351 for (d = 0; d <= backtrack_d; d++, kd_column += kd_len) {
1352 int next_x = kd_column[0];
1353 int next_y = kd_column[1];
1354 debug("Forward track from xy(%d,%d) to xy(%d,%d)\n",
1355 x, y, next_x, next_y);
1357 struct diff_atom *left_atom = &left->atoms.head[x];
1358 int left_section_len = next_x - x;
1359 struct diff_atom *right_atom = &right->atoms.head[y];
1360 int right_section_len = next_y - y;
1362 rc = ENOMEM;
1363 if (left_section_len && right_section_len) {
1364 /* This must be a snake slide.
1365 * Snake slides have a straight line leading into them
1366 * (except when starting at (0,0)). Find out whether the
1367 * lead-in is horizontal or vertical:
1369 * left
1370 * ---------->
1371 * |
1372 * r| o-o o
1373 * i| \ |
1374 * g| o o
1375 * h| \ \
1376 * t| o o
1377 * v
1379 * If left_section_len > right_section_len, the lead-in
1380 * is horizontal, meaning first remove one atom from the
1381 * left before sliding down the snake.
1382 * If right_section_len > left_section_len, the lead-in
1383 * is vetical, so add one atom from the right before
1384 * sliding down the snake. */
1385 if (left_section_len == right_section_len + 1) {
1386 if (!diff_state_add_chunk(state, true,
1387 left_atom, 1,
1388 right_atom, 0))
1389 goto return_rc;
1390 left_atom++;
1391 left_section_len--;
1392 } else if (right_section_len == left_section_len + 1) {
1393 if (!diff_state_add_chunk(state, true,
1394 left_atom, 0,
1395 right_atom, 1))
1396 goto return_rc;
1397 right_atom++;
1398 right_section_len--;
1399 } else if (left_section_len != right_section_len) {
1400 /* The numbers are making no sense. Should never
1401 * happen. */
1402 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
1403 goto return_rc;
1406 if (!diff_state_add_chunk(state, true,
1407 left_atom, left_section_len,
1408 right_atom,
1409 right_section_len))
1410 goto return_rc;
1411 } else if (left_section_len && !right_section_len) {
1412 /* Only left atoms and none on the right, they form a
1413 * "minus" chunk, then. */
1414 if (!diff_state_add_chunk(state, true,
1415 left_atom, left_section_len,
1416 right_atom, 0))
1417 goto return_rc;
1418 } else if (!left_section_len && right_section_len) {
1419 /* No left atoms, only atoms on the right, they form a
1420 * "plus" chunk, then. */
1421 if (!diff_state_add_chunk(state, true,
1422 left_atom, 0,
1423 right_atom,
1424 right_section_len))
1425 goto return_rc;
1428 x = next_x;
1429 y = next_y;
1432 rc = DIFF_RC_OK;
1434 return_rc:
1435 free(kd_buf);
1436 debug("** END %s rc=%d\n", __func__, rc);
1437 return rc;