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 *found_midpoint = false;
222 debug("-- %s d=%d\n", __func__, d);
224 for (k = d; k >= -d; k -= 2) {
225 if (k < -(int)right->atoms.len || k > (int)left->atoms.len) {
226 /* This diagonal is completely outside of the Myers
227 * graph, don't calculate it. */
228 if (k < -(int)right->atoms.len)
229 debug(" %d k < -(int)right->atoms.len %d\n", k,
230 -(int)right->atoms.len);
231 else
232 debug(" %d k > left->atoms.len %d\n", k,
233 left->atoms.len);
234 if (k < 0) {
235 /* We are traversing negatively, and already
236 * below the entire graph, nothing will come of
237 * this. */
238 debug(" break");
239 break;
241 debug(" continue");
242 continue;
244 debug("- k = %d\n", k);
245 if (d == 0) {
246 /* This is the initializing step. There is no prev_k
247 * yet, get the initial x from the top left of the Myers
248 * graph. */
249 x = 0;
251 /* Favoring "-" lines first means favoring moving rightwards in
252 * the Myers graph.
253 * For this, all k should derive from k - 1, only the bottom
254 * most k derive from k + 1:
256 * | d= 0 1 2
257 * ----+----------------
258 * k= |
259 * 2 | 2,0 <-- from prev_k = 2 - 1 = 1
260 * | /
261 * 1 | 1,0
262 * | /
263 * 0 | -->0,0 3,3
264 * | \\ /
265 * -1 | 0,1 <-- bottom most for d=1 from
266 * | \\ prev_k = -1 + 1 = 0
267 * -2 | 0,2 <-- bottom most for d=2 from
268 * prev_k = -2 + 1 = -1
270 * Except when a k + 1 from a previous run already means a
271 * further advancement in the graph.
272 * If k == d, there is no k + 1 and k - 1 is the only option.
273 * If k < d, use k + 1 in case that yields a larger x. Also use
274 * k + 1 if k - 1 is outside the graph.
275 */
276 else if (k > -d
277 && (k == d
278 || (k - 1 >= -(int)right->atoms.len
279 && kd_forward[k - 1] >= kd_forward[k + 1]))) {
280 /* Advance from k - 1.
281 * From position prev_k, step to the right in the Myers
282 * graph: x += 1.
283 */
284 int prev_k = k - 1;
285 int prev_x = kd_forward[prev_k];
286 x = prev_x + 1;
287 } else {
288 /* The bottom most one.
289 * From position prev_k, step to the bottom in the Myers
290 * graph: y += 1.
291 * Incrementing y is achieved by decrementing k while
292 * keeping the same x.
293 * (since we're deriving y from y = x - k).
294 */
295 int prev_k = k + 1;
296 int prev_x = kd_forward[prev_k];
297 x = prev_x;
300 int x_before_slide = x;
301 /* Slide down any snake that we might find here. */
302 while (x < left->atoms.len && xk_to_y(x, k) < right->atoms.len) {
303 bool same;
304 int r = diff_atom_same(&same,
305 &left->atoms.head[x],
306 &right->atoms.head[
307 xk_to_y(x, k)]);
308 if (r)
309 return r;
310 if (!same)
311 break;
312 x++;
314 kd_forward[k] = x;
315 if (x_before_slide != x) {
316 debug(" down %d similar lines\n", x - x_before_slide);
319 if (DEBUG) {
320 int fi;
321 for (fi = d; fi >= k; fi--) {
322 debug("kd_forward[%d] = (%d, %d)\n", fi,
323 kd_forward[fi], kd_forward[fi] - fi);
327 if (x < 0 || x > left->atoms.len
328 || xk_to_y(x, k) < 0 || xk_to_y(x, k) > right->atoms.len)
329 continue;
331 /* Figured out a new forwards traversal, see if this has gone
332 * onto or even past a preceding backwards traversal.
334 * If the delta in length is odd, then d and backwards_d hit the
335 * same state indexes:
336 * | d= 0 1 2 1 0
337 * ----+---------------- ----------------
338 * k= | c=
339 * 4 | 3
340 * |
341 * 3 | 2
342 * | same
343 * 2 | 2,0====5,3 1
344 * | / \
345 * 1 | 1,0 5,4<-- 0
346 * | / /
347 * 0 | -->0,0 3,3====4,4 -1
348 * | \ /
349 * -1 | 0,1 -2
350 * | \
351 * -2 | 0,2 -3
352 * |
354 * If the delta is even, they end up off-by-one, i.e. on
355 * different diagonals:
357 * | d= 0 1 2 1 0
358 * ----+---------------- ----------------
359 * | c=
360 * 3 | 3
361 * |
362 * 2 | 2,0 off 2
363 * | / \\
364 * 1 | 1,0 4,3 1
365 * | / // \
366 * 0 | -->0,0 3,3 4,4<-- 0
367 * | \ / /
368 * -1 | 0,1 3,4 -1
369 * | \ //
370 * -2 | 0,2 -2
371 * |
373 * So in the forward path, we can only match up diagonals when
374 * the delta is odd.
375 */
376 if ((delta & 1) == 0)
377 continue;
378 /* Forwards is done first, so the backwards one was still at
379 * d - 1. Can't do this for d == 0. */
380 int backwards_d = d - 1;
381 if (backwards_d < 0)
382 continue;
384 debug("backwards_d = %d\n", backwards_d);
386 /* If both sides have the same length, forward and backward
387 * start on the same diagonal, meaning the backwards state index
388 * c == k.
389 * As soon as the lengths are not the same, the backwards
390 * traversal starts on a different diagonal, and c = k shifted
391 * by the difference in length.
392 */
393 int c = k_to_c(k, delta);
395 /* When the file sizes are very different, the traversal trees
396 * start on far distant diagonals.
397 * They don't necessarily meet straight on. See whether this
398 * forward value is on a diagonal that is also valid in
399 * kd_backward[], and match them if so. */
400 if (c >= -backwards_d && c <= backwards_d) {
401 /* Current k is on a diagonal that exists in
402 * kd_backward[]. If the two x positions have met or
403 * passed (forward walked onto or past backward), then
404 * we've found a midpoint / a mid-box.
406 * When forwards and backwards traversals meet, the
407 * endpoints of the mid-snake are not the two points in
408 * kd_forward and kd_backward, but rather the section
409 * that was slid (if any) of the current
410 * forward/backward traversal only.
412 * For example:
414 * o
415 * \
416 * o
417 * \
418 * o
419 * \
420 * o
421 * \
422 * X o o
423 * | | |
424 * o-o-o o
425 * \|
426 * M
427 * \
428 * o
429 * \
430 * A o
431 * | |
432 * o-o-o
434 * The forward traversal reached M from the top and slid
435 * downwards to A. The backward traversal already
436 * reached X, which is not a straight line from M
437 * anymore, so picking a mid-snake from M to X would
438 * yield a mistake.
440 * The correct mid-snake is between M and A. M is where
441 * the forward traversal hit the diagonal that the
442 * backward traversal has already passed, and A is what
443 * it reaches when sliding down identical lines.
444 */
445 int backward_x = kd_backward[c];
446 debug("Compare: k=%d c=%d is (%d,%d) >= (%d,%d)?\n",
447 k, c, x, xk_to_y(x, k), backward_x,
448 xc_to_y(backward_x, c, delta));
449 if (x >= backward_x) {
450 *meeting_snake = (struct diff_box){
451 .left_start = x_before_slide,
452 .left_end = x,
453 .right_start = xc_to_y(x_before_slide,
454 c, delta),
455 .right_end = xk_to_y(x, k),
456 };
457 debug("HIT x=(%u,%u) - y=(%u,%u)\n",
458 meeting_snake->left_start,
459 meeting_snake->right_start,
460 meeting_snake->left_end,
461 meeting_snake->right_end);
462 debug_dump_myers_graph(left, right, NULL,
463 kd_forward, d,
464 kd_backward, d-1);
465 *found_midpoint = true;
466 return 0;
471 debug_dump_myers_graph(left, right, NULL, kd_forward, d,
472 kd_backward, d-1);
473 return 0;
476 /* Do one backwards step in the "divide and conquer" graph traversal.
477 * left: the left side to diff.
478 * right: the right side to diff against.
479 * kd_forward: the traversal state for forwards traversal, to find a meeting
480 * point.
481 * Since forwards is done first, after this, both kd_forward and
482 * kd_backward will be valid for d.
483 * kd_forward points at the center of the state array, allowing
484 * negative indexes.
485 * kd_backward: the traversal state for backwards traversal, to find a meeting
486 * point.
487 * This is carried over between invocations with increasing d.
488 * kd_backward points at the center of the state array, allowing
489 * negative indexes.
490 * d: Step or distance counter, indicating for what value of d the kd_backward
491 * should be populated.
492 * Before the first invocation, kd_backward[0] shall point at the bottom
493 * right of the Myers graph (left.len, right.len).
494 * The first invocation will be for d == 1.
495 * meeting_snake: resulting meeting point, if any.
496 * Return true when a meeting point has been identified.
497 */
498 static int
499 diff_divide_myers_backward(bool *found_midpoint,
500 struct diff_data *left, struct diff_data *right,
501 int *kd_forward, int *kd_backward, int d,
502 struct diff_box *meeting_snake)
504 int delta = (int)right->atoms.len - (int)left->atoms.len;
505 int c;
506 int x;
508 *found_midpoint = false;
510 debug("-- %s d=%d\n", __func__, d);
512 for (c = d; c >= -d; c -= 2) {
513 if (c < -(int)left->atoms.len || c > (int)right->atoms.len) {
514 /* This diagonal is completely outside of the Myers
515 * graph, don't calculate it. */
516 if (c < -(int)left->atoms.len)
517 debug(" %d c < -(int)left->atoms.len %d\n", c,
518 -(int)left->atoms.len);
519 else
520 debug(" %d c > right->atoms.len %d\n", c,
521 right->atoms.len);
522 if (c < 0) {
523 /* We are traversing negatively, and already
524 * below the entire graph, nothing will come of
525 * this. */
526 debug(" break");
527 break;
529 debug(" continue");
530 continue;
532 debug("- c = %d\n", c);
533 if (d == 0) {
534 /* This is the initializing step. There is no prev_c
535 * yet, get the initial x from the bottom right of the
536 * Myers graph. */
537 x = left->atoms.len;
539 /* Favoring "-" lines first means favoring moving rightwards in
540 * the Myers graph.
541 * For this, all c should derive from c - 1, only the bottom
542 * most c derive from c + 1:
544 * 2 1 0
545 * ---------------------------------------------------
546 * c=
547 * 3
549 * from prev_c = c - 1 --> 5,2 2
550 * \
551 * 5,3 1
552 * \
553 * 4,3 5,4<-- 0
554 * \ /
555 * bottom most for d=1 from c + 1 --> 4,4 -1
556 * /
557 * bottom most for d=2 --> 3,4 -2
559 * Except when a c + 1 from a previous run already means a
560 * further advancement in the graph.
561 * If c == d, there is no c + 1 and c - 1 is the only option.
562 * If c < d, use c + 1 in case that yields a larger x.
563 * Also use c + 1 if c - 1 is outside the graph.
564 */
565 else if (c > -d && (c == d
566 || (c - 1 >= -(int)right->atoms.len
567 && kd_backward[c - 1] <= kd_backward[c + 1]))) {
568 /* A top one.
569 * From position prev_c, step upwards in the Myers
570 * graph: y -= 1.
571 * Decrementing y is achieved by incrementing c while
572 * keeping the same x. (since we're deriving y from
573 * y = x - c + delta).
574 */
575 int prev_c = c - 1;
576 int prev_x = kd_backward[prev_c];
577 x = prev_x;
578 } else {
579 /* The bottom most one.
580 * From position prev_c, step to the left in the Myers
581 * graph: x -= 1.
582 */
583 int prev_c = c + 1;
584 int prev_x = kd_backward[prev_c];
585 x = prev_x - 1;
588 /* Slide up any snake that we might find here (sections of
589 * identical lines on both sides). */
590 debug("c=%d x-1=%d Yb-1=%d-1=%d\n", c, x-1, xc_to_y(x, c,
591 delta),
592 xc_to_y(x, c, delta)-1);
593 if (x > 0) {
594 debug(" l=");
595 debug_dump_atom(left, right, &left->atoms.head[x-1]);
597 if (xc_to_y(x, c, delta) > 0) {
598 debug(" r=");
599 debug_dump_atom(right, left,
600 &right->atoms.head[xc_to_y(x, c, delta)-1]);
602 int x_before_slide = x;
603 while (x > 0 && xc_to_y(x, c, delta) > 0) {
604 bool same;
605 int r = diff_atom_same(&same,
606 &left->atoms.head[x-1],
607 &right->atoms.head[
608 xc_to_y(x, c, delta)-1]);
609 if (r)
610 return r;
611 if (!same)
612 break;
613 x--;
615 kd_backward[c] = x;
616 if (x_before_slide != x) {
617 debug(" up %d similar lines\n", x_before_slide - x);
620 if (DEBUG) {
621 int fi;
622 for (fi = d; fi >= c; fi--) {
623 debug("kd_backward[%d] = (%d, %d)\n",
624 fi,
625 kd_backward[fi],
626 kd_backward[fi] - fi + delta);
630 if (x < 0 || x > left->atoms.len
631 || xc_to_y(x, c, delta) < 0
632 || xc_to_y(x, c, delta) > right->atoms.len)
633 continue;
635 /* Figured out a new backwards traversal, see if this has gone
636 * onto or even past a preceding forwards traversal.
638 * If the delta in length is even, then d and backwards_d hit
639 * the same state indexes -- note how this is different from in
640 * the forwards traversal, because now both d are the same:
642 * | d= 0 1 2 2 1 0
643 * ----+---------------- --------------------
644 * k= | c=
645 * 4 |
646 * |
647 * 3 | 3
648 * | same
649 * 2 | 2,0====5,2 2
650 * | / \
651 * 1 | 1,0 5,3 1
652 * | / / \
653 * 0 | -->0,0 3,3====4,3 5,4<-- 0
654 * | \ / /
655 * -1 | 0,1 4,4 -1
656 * | \
657 * -2 | 0,2 -2
658 * |
659 * -3
660 * If the delta is odd, they end up off-by-one, i.e. on
661 * different diagonals.
662 * So in the backward path, we can only match up diagonals when
663 * the delta is even.
664 */
665 if ((delta & 1) != 0)
666 continue;
667 /* Forwards was done first, now both d are the same. */
668 int forwards_d = d;
670 /* As soon as the lengths are not the same, the
671 * backwards traversal starts on a different diagonal,
672 * and c = k shifted by the difference in length.
673 */
674 int k = c_to_k(c, delta);
676 /* When the file sizes are very different, the traversal trees
677 * start on far distant diagonals.
678 * They don't necessarily meet straight on. See whether this
679 * backward value is also on a valid diagonal in kd_forward[],
680 * and match them if so. */
681 if (k >= -forwards_d && k <= forwards_d) {
682 /* Current c is on a diagonal that exists in
683 * kd_forward[]. If the two x positions have met or
684 * passed (backward walked onto or past forward), then
685 * we've found a midpoint / a mid-box.
687 * When forwards and backwards traversals meet, the
688 * endpoints of the mid-snake are not the two points in
689 * kd_forward and kd_backward, but rather the section
690 * that was slid (if any) of the current
691 * forward/backward traversal only.
693 * For example:
695 * o-o-o
696 * | |
697 * o A
698 * | \
699 * o o
700 * \
701 * M
702 * |\
703 * o o-o-o
704 * | | |
705 * o o X
706 * \
707 * o
708 * \
709 * o
710 * \
711 * o
713 * The backward traversal reached M from the bottom and
714 * slid upwards. The forward traversal already reached
715 * X, which is not a straight line from M anymore, so
716 * picking a mid-snake from M to X would yield a
717 * mistake.
719 * The correct mid-snake is between M and A. M is where
720 * the backward traversal hit the diagonal that the
721 * forwards traversal has already passed, and A is what
722 * it reaches when sliding up identical lines.
723 */
725 int forward_x = kd_forward[k];
726 debug("Compare: k=%d c=%d is (%d,%d) >= (%d,%d)?\n",
727 k, c, forward_x, xk_to_y(forward_x, k),
728 x, xc_to_y(x, c, delta));
729 if (forward_x >= x) {
730 *meeting_snake = (struct diff_box){
731 .left_start = x,
732 .left_end = x_before_slide,
733 .right_start = xc_to_y(x, c, delta),
734 .right_end = xk_to_y(x_before_slide, k),
735 };
736 debug("HIT x=%u,%u - y=%u,%u\n",
737 meeting_snake->left_start,
738 meeting_snake->right_start,
739 meeting_snake->left_end,
740 meeting_snake->right_end);
741 debug_dump_myers_graph(left, right, NULL,
742 kd_forward, d,
743 kd_backward, d);
744 *found_midpoint = true;
745 return 0;
749 debug_dump_myers_graph(left, right, NULL, kd_forward, d, kd_backward,
750 d);
751 return 0;
754 /* Integer square root approximation */
755 static int
756 shift_sqrt(int val)
758 int i;
759 for (i = 1; val > 0; val >>= 2)
760 i <<= 1;
761 return i;
764 /* Myers "Divide et Impera": tracing forwards from the start and backwards from
765 * the end to find a midpoint that divides the problem into smaller chunks.
766 * Requires only linear amounts of memory. */
767 int
768 diff_algo_myers_divide(const struct diff_algo_config *algo_config,
769 struct diff_state *state)
771 int rc = ENOMEM;
772 struct diff_data *left = &state->left;
773 struct diff_data *right = &state->right;
775 debug("\n** %s\n", __func__);
776 debug("left:\n");
777 debug_dump(left);
778 debug("right:\n");
779 debug_dump(right);
780 debug_dump_myers_graph(left, right, NULL, NULL, 0, NULL, 0);
782 /* Allocate two columns of a Myers graph, one for the forward and one
783 * for the backward traversal. */
784 unsigned int max = left->atoms.len + right->atoms.len;
785 size_t kd_len = max + 1;
786 size_t kd_buf_size = kd_len << 1;
787 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
788 if (!kd_buf)
789 return ENOMEM;
790 int i;
791 for (i = 0; i < kd_buf_size; i++)
792 kd_buf[i] = -1;
793 int *kd_forward = kd_buf;
794 int *kd_backward = kd_buf + kd_len;
795 int max_effort = shift_sqrt(max/2);
797 /* The 'k' axis in Myers spans positive and negative indexes, so point
798 * the kd to the middle.
799 * It is then possible to index from -max/2 .. max/2. */
800 kd_forward += max/2;
801 kd_backward += max/2;
803 int d;
804 struct diff_box mid_snake = {};
805 bool found_midpoint = false;
806 for (d = 0; d <= (max/2); d++) {
807 int r;
808 debug("-- d=%d\n", d);
809 r = diff_divide_myers_forward(&found_midpoint, left, right,
810 kd_forward, kd_backward, d,
811 &mid_snake);
812 if (r)
813 return r;
814 if (found_midpoint)
815 break;
816 r = diff_divide_myers_backward(&found_midpoint, left, right,
817 kd_forward, kd_backward, d,
818 &mid_snake);
819 if (r)
820 return r;
821 if (found_midpoint)
822 break;
824 /* Limit the effort spent looking for a mid snake. If files have
825 * very few lines in common, the effort spent to find nice mid
826 * snakes is just not worth it, the diff result will still be
827 * essentially minus everything on the left, plus everything on
828 * the right, with a few useless matches here and there. */
829 if (d > max_effort) {
830 /* pick the furthest reaching point from
831 * kd_forward and kd_backward, and use that as a
832 * midpoint, to not step into another diff algo
833 * recursion with unchanged box. */
834 int delta = (int)right->atoms.len - (int)left->atoms.len;
835 int x;
836 int y;
837 int i;
838 int best_forward_i = 0;
839 int best_forward_distance = 0;
840 int best_backward_i = 0;
841 int best_backward_distance = 0;
842 int distance;
843 int best_forward_x;
844 int best_forward_y;
845 int best_backward_x;
846 int best_backward_y;
848 debug("~~~ d = %d > max_effort = %d\n", d, max_effort);
850 for (i = d; i >= -d; i -= 2) {
851 if (i >= -(int)right->atoms.len && i <= (int)left->atoms.len) {
852 x = kd_forward[i];
853 y = xk_to_y(x, i);
854 distance = x + y;
855 if (distance > best_forward_distance) {
856 best_forward_distance = distance;
857 best_forward_i = i;
861 if (i >= -(int)left->atoms.len && i <= (int)right->atoms.len) {
862 x = kd_backward[i];
863 y = xc_to_y(x, i, delta);
864 distance = (right->atoms.len - x)
865 + (left->atoms.len - y);
866 if (distance >= best_backward_distance) {
867 best_backward_distance = distance;
868 best_backward_i = i;
873 /* The myers-divide didn't meet in the middle. We just
874 * figured out the places where the forward path
875 * advanced the most, and the backward path advanced the
876 * most. Just divide at whichever one of those two is better.
878 * o-o
879 * |
880 * o
881 * \
882 * o
883 * \
884 * F <-- cut here
888 * or here --> B
889 * \
890 * o
891 * \
892 * o
893 * |
894 * o-o
895 */
896 best_forward_x = kd_forward[best_forward_i];
897 best_forward_y = xk_to_y(best_forward_x, best_forward_i);
898 best_backward_x = kd_backward[best_backward_i];
899 best_backward_y = xc_to_y(x, best_backward_i, delta);
901 if (best_forward_distance >= best_backward_distance) {
902 x = best_forward_x;
903 y = best_forward_y;
904 } else {
905 x = best_backward_x;
906 y = best_backward_y;
909 debug("max_effort cut at x=%d y=%d\n", x, y);
910 if (x < 0 || y < 0
911 || x > left->atoms.len || y > right->atoms.len)
912 break;
914 found_midpoint = true;
915 mid_snake = (struct diff_box){
916 .left_start = x,
917 .left_end = x,
918 .right_start = y,
919 .right_end = y,
920 };
921 break;
925 if (!found_midpoint) {
926 /* Divide and conquer failed to find a meeting point. Use the
927 * fallback_algo defined in the algo_config (leave this to the
928 * caller). This is just paranoia/sanity, we normally should
929 * always find a midpoint.
930 */
931 debug(" no midpoint \n");
932 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
933 goto return_rc;
934 } else {
935 debug(" mid snake L: %u to %u of %u R: %u to %u of %u\n",
936 mid_snake.left_start, mid_snake.left_end, left->atoms.len,
937 mid_snake.right_start, mid_snake.right_end,
938 right->atoms.len);
940 /* Section before the mid-snake. */
941 debug("Section before the mid-snake\n");
943 struct diff_atom *left_atom = &left->atoms.head[0];
944 unsigned int left_section_len = mid_snake.left_start;
945 struct diff_atom *right_atom = &right->atoms.head[0];
946 unsigned int right_section_len = mid_snake.right_start;
948 if (left_section_len && right_section_len) {
949 /* Record an unsolved chunk, the caller will apply
950 * inner_algo() on this chunk. */
951 if (!diff_state_add_chunk(state, false,
952 left_atom, left_section_len,
953 right_atom,
954 right_section_len))
955 goto return_rc;
956 } else if (left_section_len && !right_section_len) {
957 /* Only left atoms and none on the right, they form a
958 * "minus" chunk, then. */
959 if (!diff_state_add_chunk(state, true,
960 left_atom, left_section_len,
961 right_atom, 0))
962 goto return_rc;
963 } else if (!left_section_len && right_section_len) {
964 /* No left atoms, only atoms on the right, they form a
965 * "plus" chunk, then. */
966 if (!diff_state_add_chunk(state, true,
967 left_atom, 0,
968 right_atom,
969 right_section_len))
970 goto return_rc;
972 /* else: left_section_len == 0 and right_section_len == 0, i.e.
973 * nothing before the mid-snake. */
975 if (mid_snake.left_end > mid_snake.left_start) {
976 /* The midpoint is a "snake", i.e. on a section of
977 * identical data on both sides: that section
978 * immediately becomes a solved diff chunk. */
979 debug("the mid-snake\n");
980 if (!diff_state_add_chunk(state, true,
981 &left->atoms.head[mid_snake.left_start],
982 mid_snake.left_end - mid_snake.left_start,
983 &right->atoms.head[mid_snake.right_start],
984 mid_snake.right_end - mid_snake.right_start))
985 goto return_rc;
988 /* Section after the mid-snake. */
989 debug("Section after the mid-snake\n");
990 debug(" left_end %u right_end %u\n",
991 mid_snake.left_end, mid_snake.right_end);
992 debug(" left_count %u right_count %u\n",
993 left->atoms.len, right->atoms.len);
994 left_atom = &left->atoms.head[mid_snake.left_end];
995 left_section_len = left->atoms.len - mid_snake.left_end;
996 right_atom = &right->atoms.head[mid_snake.right_end];
997 right_section_len = right->atoms.len - mid_snake.right_end;
999 if (left_section_len && right_section_len) {
1000 /* Record an unsolved chunk, the caller will apply
1001 * inner_algo() on this chunk. */
1002 if (!diff_state_add_chunk(state, false,
1003 left_atom, left_section_len,
1004 right_atom,
1005 right_section_len))
1006 goto return_rc;
1007 } else if (left_section_len && !right_section_len) {
1008 /* Only left atoms and none on the right, they form a
1009 * "minus" chunk, then. */
1010 if (!diff_state_add_chunk(state, true,
1011 left_atom, left_section_len,
1012 right_atom, 0))
1013 goto return_rc;
1014 } else if (!left_section_len && right_section_len) {
1015 /* No left atoms, only atoms on the right, they form a
1016 * "plus" chunk, then. */
1017 if (!diff_state_add_chunk(state, true,
1018 left_atom, 0,
1019 right_atom,
1020 right_section_len))
1021 goto return_rc;
1023 /* else: left_section_len == 0 and right_section_len == 0, i.e.
1024 * nothing after the mid-snake. */
1027 rc = DIFF_RC_OK;
1029 return_rc:
1030 free(kd_buf);
1031 debug("** END %s\n", __func__);
1032 return rc;
1035 /* Myers Diff tracing from the start all the way through to the end, requiring
1036 * quadratic amounts of memory. This can fail if the required space surpasses
1037 * algo_config->permitted_state_size. */
1038 int
1039 diff_algo_myers(const struct diff_algo_config *algo_config,
1040 struct diff_state *state)
1042 /* do a diff_divide_myers_forward() without a _backward(), so that it
1043 * walks forward across the entire files to reach the end. Keep each
1044 * run's state, and do a final backtrace. */
1045 int rc = ENOMEM;
1046 struct diff_data *left = &state->left;
1047 struct diff_data *right = &state->right;
1049 debug("\n** %s\n", __func__);
1050 debug("left:\n");
1051 debug_dump(left);
1052 debug("right:\n");
1053 debug_dump(right);
1054 debug_dump_myers_graph(left, right, NULL, NULL, 0, NULL, 0);
1056 /* Allocate two columns of a Myers graph, one for the forward and one
1057 * for the backward traversal. */
1058 unsigned int max = left->atoms.len + right->atoms.len;
1059 size_t kd_len = max + 1 + max;
1060 size_t kd_buf_size = kd_len * kd_len;
1061 size_t kd_state_size = kd_buf_size * sizeof(int);
1062 debug("state size: %zu\n", kd_buf_size);
1063 if (kd_buf_size < kd_len /* overflow? */
1064 || kd_state_size > algo_config->permitted_state_size) {
1065 debug("state size %zu > permitted_state_size %zu, use fallback_algo\n",
1066 kd_state_size, algo_config->permitted_state_size);
1067 return DIFF_RC_USE_DIFF_ALGO_FALLBACK;
1070 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
1071 if (!kd_buf)
1072 return ENOMEM;
1073 int i;
1074 for (i = 0; i < kd_buf_size; i++)
1075 kd_buf[i] = -1;
1077 /* The 'k' axis in Myers spans positive and negative indexes, so point
1078 * the kd to the middle.
1079 * It is then possible to index from -max .. max. */
1080 int *kd_origin = kd_buf + max;
1081 int *kd_column = kd_origin;
1083 int d;
1084 int backtrack_d = -1;
1085 int backtrack_k = 0;
1086 int k;
1087 int x, y;
1088 for (d = 0; d <= max; d++, kd_column += kd_len) {
1089 debug("-- d=%d\n", d);
1091 debug("-- %s d=%d\n", __func__, d);
1093 for (k = d; k >= -d; k -= 2) {
1094 if (k < -(int)right->atoms.len
1095 || k > (int)left->atoms.len) {
1096 /* This diagonal is completely outside of the
1097 * Myers graph, don't calculate it. */
1098 if (k < -(int)right->atoms.len)
1099 debug(" %d k <"
1100 " -(int)right->atoms.len %d\n",
1101 k, -(int)right->atoms.len);
1102 else
1103 debug(" %d k > left->atoms.len %d\n", k,
1104 left->atoms.len);
1105 if (k < 0) {
1106 /* We are traversing negatively, and
1107 * already below the entire graph,
1108 * nothing will come of this. */
1109 debug(" break");
1110 break;
1112 debug(" continue");
1113 continue;
1116 debug("- k = %d\n", k);
1117 if (d == 0) {
1118 /* This is the initializing step. There is no
1119 * prev_k yet, get the initial x from the top
1120 * left of the Myers graph. */
1121 x = 0;
1122 } else {
1123 int *kd_prev_column = kd_column - kd_len;
1125 /* Favoring "-" lines first means favoring
1126 * moving rightwards in the Myers graph.
1127 * For this, all k should derive from k - 1,
1128 * only the bottom most k derive from k + 1:
1130 * | d= 0 1 2
1131 * ----+----------------
1132 * k= |
1133 * 2 | 2,0 <-- from
1134 * | / prev_k = 2 - 1 = 1
1135 * 1 | 1,0
1136 * | /
1137 * 0 | -->0,0 3,3
1138 * | \\ /
1139 * -1 | 0,1 <-- bottom most for d=1
1140 * | \\ from prev_k = -1+1 = 0
1141 * -2 | 0,2 <-- bottom most for
1142 * d=2 from
1143 * prev_k = -2+1 = -1
1145 * Except when a k + 1 from a previous run
1146 * already means a further advancement in the
1147 * graph.
1148 * If k == d, there is no k + 1 and k - 1 is the
1149 * only option.
1150 * If k < d, use k + 1 in case that yields a
1151 * larger x. Also use k + 1 if k - 1 is outside
1152 * the graph.
1154 if (k > -d
1155 && (k == d
1156 || (k - 1 >= -(int)right->atoms.len
1157 && kd_prev_column[k - 1]
1158 >= kd_prev_column[k + 1]))) {
1159 /* Advance from k - 1.
1160 * From position prev_k, step to the
1161 * right in the Myers graph: x += 1.
1163 int prev_k = k - 1;
1164 int prev_x = kd_prev_column[prev_k];
1165 x = prev_x + 1;
1166 } else {
1167 /* The bottom most one.
1168 * From position prev_k, step to the
1169 * bottom in the Myers graph: y += 1.
1170 * Incrementing y is achieved by
1171 * decrementing k while keeping the same
1172 * x. (since we're deriving y from y =
1173 * x - k).
1175 int prev_k = k + 1;
1176 int prev_x = kd_prev_column[prev_k];
1177 x = prev_x;
1181 /* Slide down any snake that we might find here. */
1182 while (x < left->atoms.len
1183 && xk_to_y(x, k) < right->atoms.len) {
1184 bool same;
1185 int r = diff_atom_same(&same,
1186 &left->atoms.head[x],
1187 &right->atoms.head[
1188 xk_to_y(x, k)]);
1189 if (r)
1190 return r;
1191 if (!same)
1192 break;
1193 x++;
1195 kd_column[k] = x;
1197 if (DEBUG) {
1198 int fi;
1199 for (fi = d; fi >= k; fi-=2) {
1200 debug("kd_column[%d] = (%d, %d)\n", fi,
1201 kd_column[fi],
1202 kd_column[fi] - fi);
1206 if (x == left->atoms.len
1207 && xk_to_y(x, k) == right->atoms.len) {
1208 /* Found a path */
1209 backtrack_d = d;
1210 backtrack_k = k;
1211 debug("Reached the end at d = %d, k = %d\n",
1212 backtrack_d, backtrack_k);
1213 break;
1217 if (backtrack_d >= 0)
1218 break;
1221 debug_dump_myers_graph(left, right, kd_origin, NULL, 0, NULL, 0);
1223 /* backtrack. A matrix spanning from start to end of the file is ready:
1225 * | d= 0 1 2 3 4
1226 * ----+---------------------------------
1227 * k= |
1228 * 3 |
1229 * |
1230 * 2 | 2,0
1231 * | /
1232 * 1 | 1,0 4,3
1233 * | / / \
1234 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4, backtrack_k = 0
1235 * | \ / \
1236 * -1 | 0,1 3,4
1237 * | \
1238 * -2 | 0,2
1239 * |
1241 * From (4,4) backwards, find the previous position that is the largest, and remember it.
1244 for (d = backtrack_d, k = backtrack_k; d >= 0; d--) {
1245 x = kd_column[k];
1246 y = xk_to_y(x, k);
1248 /* When the best position is identified, remember it for that
1249 * kd_column.
1250 * That kd_column is no longer needed otherwise, so just
1251 * re-purpose kd_column[0] = x and kd_column[1] = y,
1252 * so that there is no need to allocate more memory.
1254 kd_column[0] = x;
1255 kd_column[1] = y;
1256 debug("Backtrack d=%d: xy=(%d, %d)\n",
1257 d, kd_column[0], kd_column[1]);
1259 /* Don't access memory before kd_buf */
1260 if (d == 0)
1261 break;
1262 int *kd_prev_column = kd_column - kd_len;
1264 /* When y == 0, backtracking downwards (k-1) is the only way.
1265 * When x == 0, backtracking upwards (k+1) is the only way.
1267 * | d= 0 1 2 3 4
1268 * ----+---------------------------------
1269 * k= |
1270 * 3 |
1271 * | ..y == 0
1272 * 2 | 2,0
1273 * | /
1274 * 1 | 1,0 4,3
1275 * | / / \
1276 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4,
1277 * | \ / \ backtrack_k = 0
1278 * -1 | 0,1 3,4
1279 * | \
1280 * -2 | 0,2__
1281 * | x == 0
1283 debug("prev[k-1] = %d,%d prev[k+1] = %d,%d\n",
1284 kd_prev_column[k-1], xk_to_y(kd_prev_column[k-1],k-1),
1285 kd_prev_column[k+1], xk_to_y(kd_prev_column[k+1],k+1));
1286 if (y == 0
1287 || (x > 0
1288 && kd_prev_column[k - 1] >= kd_prev_column[k + 1])) {
1289 k = k - 1;
1290 debug("prev k=k-1=%d x=%d y=%d\n",
1291 k, kd_prev_column[k],
1292 xk_to_y(kd_prev_column[k], k));
1293 } else {
1294 k = k + 1;
1295 debug("prev k=k+1=%d x=%d y=%d\n",
1296 k, kd_prev_column[k],
1297 xk_to_y(kd_prev_column[k], k));
1299 kd_column = kd_prev_column;
1302 /* Forwards again, this time recording the diff chunks.
1303 * Definitely start from 0,0. kd_column[0] may actually point to the
1304 * bottom of a snake starting at 0,0 */
1305 x = 0;
1306 y = 0;
1308 kd_column = kd_origin;
1309 for (d = 0; d <= backtrack_d; d++, kd_column += kd_len) {
1310 int next_x = kd_column[0];
1311 int next_y = kd_column[1];
1312 debug("Forward track from xy(%d,%d) to xy(%d,%d)\n",
1313 x, y, next_x, next_y);
1315 struct diff_atom *left_atom = &left->atoms.head[x];
1316 int left_section_len = next_x - x;
1317 struct diff_atom *right_atom = &right->atoms.head[y];
1318 int right_section_len = next_y - y;
1320 rc = ENOMEM;
1321 if (left_section_len && right_section_len) {
1322 /* This must be a snake slide.
1323 * Snake slides have a straight line leading into them
1324 * (except when starting at (0,0)). Find out whether the
1325 * lead-in is horizontal or vertical:
1327 * left
1328 * ---------->
1329 * |
1330 * r| o-o o
1331 * i| \ |
1332 * g| o o
1333 * h| \ \
1334 * t| o o
1335 * v
1337 * If left_section_len > right_section_len, the lead-in
1338 * is horizontal, meaning first remove one atom from the
1339 * left before sliding down the snake.
1340 * If right_section_len > left_section_len, the lead-in
1341 * is vetical, so add one atom from the right before
1342 * sliding down the snake. */
1343 if (left_section_len == right_section_len + 1) {
1344 if (!diff_state_add_chunk(state, true,
1345 left_atom, 1,
1346 right_atom, 0))
1347 goto return_rc;
1348 left_atom++;
1349 left_section_len--;
1350 } else if (right_section_len == left_section_len + 1) {
1351 if (!diff_state_add_chunk(state, true,
1352 left_atom, 0,
1353 right_atom, 1))
1354 goto return_rc;
1355 right_atom++;
1356 right_section_len--;
1357 } else if (left_section_len != right_section_len) {
1358 /* The numbers are making no sense. Should never
1359 * happen. */
1360 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
1361 goto return_rc;
1364 if (!diff_state_add_chunk(state, true,
1365 left_atom, left_section_len,
1366 right_atom,
1367 right_section_len))
1368 goto return_rc;
1369 } else if (left_section_len && !right_section_len) {
1370 /* Only left atoms and none on the right, they form a
1371 * "minus" chunk, then. */
1372 if (!diff_state_add_chunk(state, true,
1373 left_atom, left_section_len,
1374 right_atom, 0))
1375 goto return_rc;
1376 } else if (!left_section_len && right_section_len) {
1377 /* No left atoms, only atoms on the right, they form a
1378 * "plus" chunk, then. */
1379 if (!diff_state_add_chunk(state, true,
1380 left_atom, 0,
1381 right_atom,
1382 right_section_len))
1383 goto return_rc;
1386 x = next_x;
1387 y = next_y;
1390 rc = DIFF_RC_OK;
1392 return_rc:
1393 free(kd_buf);
1394 debug("** END %s rc=%d\n", __func__, rc);
1395 return rc;