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). */
5 * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
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.
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.
20 #include <diff/diff_main.h>
24 /* Myers' diff algorithm [1] is nicely explained in [2].
25 * [1] http://www.xmailserver.org/diff2.pdf
26 * [2] https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/ ff.
28 * Myers approaches finding the smallest diff as a graph problem.
29 * The crux is that the original algorithm requires quadratic amount of memory:
30 * both sides' lengths added, and that squared. So if we're diffing lines of text, two files with 1000 lines each would
31 * blow up to a matrix of about 2000 * 2000 ints of state, about 16 Mb of RAM to figure out 2 kb of text.
32 * The solution is using Myers' "divide and conquer" extension algorithm, which does the original traversal from both
33 * ends of the files to reach a middle where these "snakes" touch, hence does not need to backtrace the traversal, and
34 * so gets away with only keeping a single column of that huge state matrix in memory.
36 * Todo: the divide and conquer requires linear *space*, not necessarily linear *time*. It recurses, apparently doing
37 * multiple Myers passes, and also it apparently favors fragmented diffs in cases where chunks of text were moved to a
38 * different place. Up to a given count of diff atoms (text lines), it might be desirable to accept the quadratic memory
39 * usage, get nicer diffs and less re-iteration of the same data?
43 unsigned int left_start;
44 unsigned int left_end;
45 unsigned int right_start;
46 unsigned int right_end;
49 #define diff_box_empty(DIFF_SNAKE) ((DIFF_SNAKE)->left_end == 0)
52 /* If the two contents of a file are A B C D E and X B C Y,
53 * the Myers diff graph looks like:
71 * Moving right means delete an atom from the left-hand-side,
72 * Moving down means add an atom from the right-hand-side.
73 * Diagonals indicate identical atoms on both sides, the challenge is to use as many diagonals as possible.
75 * The original Myers algorithm walks all the way from the top left to the bottom right, remembers all steps, and then
76 * backtraces to find the shortest path. However, that requires keeping the entire graph in memory, which needs
79 * Myers adds a variant that uses linear space -- note, not linear time, only linear space: walk forward and backward,
80 * find a meeting point in the middle, and recurse on the two separate sections. This is called "divide and conquer".
82 * d: the step number, starting with 0, a.k.a. the distance from the starting point.
83 * k: relative index in the state array for the forward scan, indicating on which diagonal through the diff graph we
85 * c: relative index in the state array for the backward scan, indicating the diagonal number from the bottom up.
87 * The "divide and conquer" traversal through the Myers graph looks like this:
90 * ----+--------------------------------------------
98 * 1 | 1,0 4,3 >= 4,3 5,4<-- 0
100 * 0 | -->0,0 3,3 4,4 -1
102 * -1 | 0,1 1,2 3,4 -2
107 * | forward-> <-backward
109 * x,y pairs here are the coordinates in the Myers graph:
110 * x = atom index in left-side source, y = atom index in the right-side source.
112 * Only one forward column and one backward column are kept in mem, each need at most left.len + 1 + right.len items.
113 * Note that each d step occupies either the even or the odd items of a column: if e.g. the previous column is in the
114 * odd items, the next column is formed in the even items, without overwriting the previous column's results.
116 * Also note that from the diagonal index k and the x coordinate, the y coordinate can be derived:
118 * Hence the state array only needs to keep the x coordinate, i.e. the position in the left-hand file, and the y
119 * coordinate, i.e. position in the right-hand file, is derived from the index in the state array.
121 * The two traces meet at 4,3, the first step (here found in the forward traversal) where a forward position is on or
122 * past a backward traced position on the same diagonal.
124 * This divides the problem space into:
134 * 3 o-o-o-o-*-o *: forward and backward meet here
138 * Doing the same on each section lead to:
144 * 1 o-b b: backward d=1 first reaches here (sliding up the snake)
145 * B \ f: then forward d=2 reaches here (sliding down the snake)
146 * 2 o As result, the box from b to f is found to be identical;
147 * C \ leaving a top box from 0,0 to 1,1 and a bottom trivial tail 3,3 to 4,3.
152 * 4 o *: forward and backward meet here
154 * and solving the last top left box gives:
170 #define xk_to_y(X, K) ((X) - (K))
171 #define xc_to_y(X, C, DELTA) ((X) - (C) + (DELTA))
172 #define k_to_c(K, DELTA) ((K) + (DELTA))
173 #define c_to_k(C, DELTA) ((C) - (DELTA))
175 /* Do one forwards step in the "divide and conquer" graph traversal.
176 * left: the left side to diff.
177 * right: the right side to diff against.
178 * kd_forward: the traversal state for forwards traversal, modified by this function.
179 * This is carried over between invocations with increasing d.
180 * kd_forward points at the center of the state array, allowing negative indexes.
181 * kd_backward: the traversal state for backwards traversal, to find a meeting point.
182 * Since forwards is done first, kd_backward will be valid for d - 1, not d.
183 * kd_backward points at the center of the state array, allowing negative indexes.
184 * d: Step or distance counter, indicating for what value of d the kd_forward should be populated.
185 * For d == 0, kd_forward[0] is initialized, i.e. the first invocation should be for d == 0.
186 * meeting_snake: resulting meeting point, if any.
188 static void diff_divide_myers_forward(struct diff_data *left, struct diff_data *right,
189 int *kd_forward, int *kd_backward, int d,
190 struct diff_box *meeting_snake)
192 int delta = (int)right->atoms.len - (int)left->atoms.len;
198 debug("-- %s d=%d\n", __func__, d);
199 debug_dump_myers_graph(left, right, NULL);
201 for (k = d; k >= -d; k -= 2) {
202 if (k < -(int)right->atoms.len || k > (int)left->atoms.len) {
203 /* This diagonal is completely outside of the Myers graph, don't calculate it. */
204 if (k < -(int)right->atoms.len)
205 debug(" %d k < -(int)right->atoms.len %d\n", k, -(int)right->atoms.len);
207 debug(" %d k > left->atoms.len %d\n", k, left->atoms.len);
209 /* We are traversing negatively, and already below the entire graph, nothing will come
217 debug("- k = %d\n", k);
219 /* This is the initializing step. There is no prev_k yet, get the initial x from the top left of
220 * the Myers graph. */
223 /* Favoring "-" lines first means favoring moving rightwards in the Myers graph.
224 * For this, all k should derive from k - 1, only the bottom most k derive from k + 1:
227 * ----+----------------
229 * 2 | 2,0 <-- from prev_k = 2 - 1 = 1
235 * -1 | 0,1 <-- bottom most for d=1 from prev_k = -1 + 1 = 0
237 * -2 | 0,2 <-- bottom most for d=2 from prev_k = -2 + 1 = -1
239 * Except when a k + 1 from a previous run already means a further advancement in the graph.
240 * If k == d, there is no k + 1 and k - 1 is the only option.
241 * If k < d, use k + 1 in case that yields a larger x. Also use k + 1 if k - 1 is outside the graph.
243 else if (k > -d && (k == d
244 || (k - 1 >= -(int)right->atoms.len
245 && kd_forward[k - 1] >= kd_forward[k + 1]))) {
246 /* Advance from k - 1.
247 * From position prev_k, step to the right in the Myers graph: x += 1.
250 prev_x = kd_forward[prev_k];
251 prev_y = xk_to_y(prev_x, prev_k);
254 /* The bottom most one.
255 * From position prev_k, step to the bottom in the Myers graph: y += 1.
256 * Incrementing y is achieved by decrementing k while keeping the same x.
257 * (since we're deriving y from y = x - k).
260 prev_x = kd_forward[prev_k];
261 prev_y = xk_to_y(prev_x, prev_k);
265 /* Slide down any snake that we might find here. */
266 while (x < left->atoms.len && xk_to_y(x, k) < right->atoms.len
267 && diff_atom_same(&left->atoms.head[x], &right->atoms.head[xk_to_y(x, k)]))
273 for (fi = d; fi >= k; fi--) {
274 debug("kd_forward[%d] = (%d, %d)\n", fi, kd_forward[fi], kd_forward[fi] - fi);
276 if (kd_forward[fi] >= 0 && kd_forward[fi] < left->atoms.len)
277 debug_dump_atom(left, right, &left->atoms.head[kd_forward[fi]]);
280 if (kd_forward[fi]-fi >= 0 && kd_forward[fi]-fi < right->atoms.len)
281 debug_dump_atom(right, left, &right->atoms.head[kd_forward[fi]-fi]);
288 if (x < 0 || x > left->atoms.len
289 || xk_to_y(x, k) < 0 || xk_to_y(x, k) > right->atoms.len)
292 /* Figured out a new forwards traversal, see if this has gone onto or even past a preceding backwards
295 * If the delta in length is odd, then d and backwards_d hit the same state indexes:
297 * ----+---------------- ----------------
307 * 0 | -->0,0 3,3====4,4 -1
314 * If the delta is even, they end up off-by-one, i.e. on different diagonals:
317 * ----+---------------- ----------------
325 * 0 | -->0,0 3,3 4,4<-- 0
332 * So in the forward path, we can only match up diagonals when the delta is odd.
334 if ((delta & 1) == 0)
336 /* Forwards is done first, so the backwards one was still at d - 1. Can't do this for d == 0. */
337 int backwards_d = d - 1;
341 debug("backwards_d = %d\n", backwards_d);
343 /* If both sides have the same length, forward and backward start on the same diagonal, meaning the
344 * backwards state index c == k.
345 * As soon as the lengths are not the same, the backwards traversal starts on a different diagonal, and
346 * c = k shifted by the difference in length.
348 int c = k_to_c(k, delta);
350 /* When the file sizes are very different, the traversal trees start on far distant diagonals.
351 * They don't necessarily meet straight on. See whether this forward value is on a diagonal that
352 * is also valid in kd_backward[], and match them if so. */
353 if (c >= -backwards_d && c <= backwards_d) {
354 /* Current k is on a diagonal that exists in kd_backward[]. If the two x positions have
355 * met or passed (forward walked onto or past backward), then we've found a midpoint / a
358 * But we need to avoid matching a situation like this:
365 * 2 (B)o-o <--(B) backwards traversal reached here
367 * 3 o-o-o<-- prev_x, prev_y
369 * 4 o-o(F) <--(F) forwards traversal reached here
370 * x |\| | Now both are on the same diagonal and look like they passed,
371 * 5 o-o-o but actually they have sneaked past each other and have not met.
375 * The solution is to notice that prev_x,prev_y were also already past (B).
377 int backward_x = kd_backward[c];
378 int backward_y = xc_to_y(backward_x, c, delta);
379 debug(" prev_x,y = (%d,%d) c%d:backward_x,y = (%d,%d) k%d:x,y = (%d,%d)\n",
380 prev_x, prev_y, c, backward_x, backward_y, k, x, xk_to_y(x, k));
381 if (prev_x <= backward_x && prev_y <= backward_y
382 && x >= backward_x) {
383 *meeting_snake = (struct diff_box){
384 .left_start = backward_x,
386 .right_start = xc_to_y(backward_x, c, delta),
387 .right_end = xk_to_y(x, k),
389 debug("HIT x=(%u,%u) - y=(%u,%u)\n",
390 meeting_snake->left_start,
391 meeting_snake->right_start,
392 meeting_snake->left_end,
393 meeting_snake->right_end);
400 /* Do one backwards step in the "divide and conquer" graph traversal.
401 * left: the left side to diff.
402 * right: the right side to diff against.
403 * kd_forward: the traversal state for forwards traversal, to find a meeting point.
404 * Since forwards is done first, after this, both kd_forward and kd_backward will be valid for d.
405 * kd_forward points at the center of the state array, allowing negative indexes.
406 * kd_backward: the traversal state for backwards traversal, to find a meeting point.
407 * This is carried over between invocations with increasing d.
408 * kd_backward points at the center of the state array, allowing negative indexes.
409 * d: Step or distance counter, indicating for what value of d the kd_backward should be populated.
410 * Before the first invocation, kd_backward[0] shall point at the bottom right of the Myers graph
411 * (left.len, right.len).
412 * The first invocation will be for d == 1.
413 * meeting_snake: resulting meeting point, if any.
415 static void diff_divide_myers_backward(struct diff_data *left, struct diff_data *right,
416 int *kd_forward, int *kd_backward, int d,
417 struct diff_box *meeting_snake)
419 int delta = (int)right->atoms.len - (int)left->atoms.len;
425 debug("-- %s d=%d\n", __func__, d);
426 debug_dump_myers_graph(left, right, NULL);
428 for (c = d; c >= -d; c -= 2) {
429 if (c < -(int)left->atoms.len || c > (int)right->atoms.len) {
430 /* This diagonal is completely outside of the Myers graph, don't calculate it. */
431 if (c < -(int)left->atoms.len)
432 debug(" %d c < -(int)left->atoms.len %d\n", c, -(int)left->atoms.len);
434 debug(" %d c > right->atoms.len %d\n", c, right->atoms.len);
436 /* We are traversing negatively, and already below the entire graph, nothing will come
444 debug("- c = %d\n", c);
446 /* This is the initializing step. There is no prev_c yet, get the initial x from the bottom
447 * right of the Myers graph. */
450 /* Favoring "-" lines first means favoring moving rightwards in the Myers graph.
451 * For this, all c should derive from c - 1, only the bottom most c derive from c + 1:
454 * ---------------------------------------------------
458 * from prev_c = c - 1 --> 5,2 2
464 * bottom most for d=1 from c + 1 --> 4,4 -1
466 * bottom most for d=2 --> 3,4 -2
468 * Except when a c + 1 from a previous run already means a further advancement in the graph.
469 * If c == d, there is no c + 1 and c - 1 is the only option.
470 * If c < d, use c + 1 in case that yields a larger x. Also use c + 1 if c - 1 is outside the graph.
472 else if (c > -d && (c == d
473 || (c - 1 >= -(int)right->atoms.len
474 && kd_backward[c - 1] <= kd_backward[c + 1]))) {
476 * From position prev_c, step upwards in the Myers graph: y -= 1.
477 * Decrementing y is achieved by incrementing c while keeping the same x.
478 * (since we're deriving y from y = x - c + delta).
481 prev_x = kd_backward[prev_c];
482 prev_y = xc_to_y(prev_x, prev_c, delta);
485 /* The bottom most one.
486 * From position prev_c, step to the left in the Myers graph: x -= 1.
489 prev_x = kd_backward[prev_c];
490 prev_y = xc_to_y(prev_x, prev_c, delta);
494 /* Slide up any snake that we might find here. */
495 debug("c=%d x-1=%d Yb-1=%d-1=%d\n", c, x-1, xc_to_y(x, c, delta), xc_to_y(x, c, delta)-1);
497 debug(" l="); debug_dump_atom(left, right, &left->atoms.head[x-1]);
499 if (xc_to_y(x, c, delta) > 0) {
500 debug(" r="); debug_dump_atom(right, left, &right->atoms.head[xc_to_y(x, c, delta)-1]);
502 while (x > 0 && xc_to_y(x, c, delta) > 0
503 && diff_atom_same(&left->atoms.head[x-1], &right->atoms.head[xc_to_y(x, c, delta)-1]))
509 for (fi = d; fi >= c; fi--) {
510 debug("kd_backward[%d] = (%d, %d)\n", fi, kd_backward[fi],
511 kd_backward[fi] - fi + delta);
513 if (kd_backward[fi] >= 0 && kd_backward[fi] < left->atoms.len)
514 debug_dump_atom(left, right, &left->atoms.head[kd_backward[fi]]);
517 if (kd_backward[fi]-fi+delta >= 0 && kd_backward[fi]-fi+delta < right->atoms.len)
518 debug_dump_atom(right, left, &right->atoms.head[kd_backward[fi]-fi+delta]);
525 if (x < 0 || x > left->atoms.len
526 || xc_to_y(x, c, delta) < 0 || xc_to_y(x, c, delta) > right->atoms.len)
529 /* Figured out a new backwards traversal, see if this has gone onto or even past a preceding forwards
532 * If the delta in length is even, then d and backwards_d hit the same state indexes -- note how this is
533 * different from in the forwards traversal, because now both d are the same:
536 * ----+---------------- --------------------
546 * 0 | -->0,0 3,3====4,3 5,4<-- 0
553 * If the delta is odd, they end up off-by-one, i.e. on different diagonals.
554 * So in the backward path, we can only match up diagonals when the delta is even.
556 if ((delta & 1) == 0) {
557 /* Forwards was done first, now both d are the same. */
560 /* As soon as the lengths are not the same, the backwards traversal starts on a different diagonal, and
561 * c = k shifted by the difference in length.
563 int k = c_to_k(c, delta);
565 /* When the file sizes are very different, the traversal trees start on far distant diagonals.
566 * They don't necessarily meet straight on. See whether this backward value is also on a valid
567 * diagonal in kd_forward[], and match them if so. */
568 if (k >= -forwards_d && k <= forwards_d) {
569 /* Current c is on a diagonal that exists in kd_forward[]. If the two x positions have
570 * met or passed (backward walked onto or past forward), then we've found a midpoint / a
572 int forward_x = kd_forward[k];
573 int forward_y = xk_to_y(forward_x, k);
574 debug("Compare %d to %d k=%d (x=%d,y=%d) to (x=%d,y=%d)\n",
576 forward_x, xk_to_y(forward_x, k), x, xc_to_y(x, c, delta));
577 if (forward_x <= prev_x && forward_y <= prev_y
579 *meeting_snake = (struct diff_box){
581 .left_end = forward_x,
582 .right_start = xc_to_y(x, c, delta),
583 .right_end = xk_to_y(forward_x, k),
585 debug("HIT x=%u,%u - y=%u,%u\n",
586 meeting_snake->left_start,
587 meeting_snake->right_start,
588 meeting_snake->left_end,
589 meeting_snake->right_end);
597 /* Myers "Divide et Impera": tracing forwards from the start and backwards from the end to find a midpoint that divides
598 * the problem into smaller chunks. Requires only linear amounts of memory. */
599 enum diff_rc diff_algo_myers_divide(const struct diff_algo_config *algo_config, struct diff_state *state)
601 enum diff_rc rc = DIFF_RC_ENOMEM;
602 struct diff_data *left = &state->left;
603 struct diff_data *right = &state->right;
605 debug("\n** %s\n", __func__);
610 debug_dump_myers_graph(left, right, NULL);
612 /* Allocate two columns of a Myers graph, one for the forward and one for the backward traversal. */
613 unsigned int max = left->atoms.len + right->atoms.len;
614 size_t kd_len = max + 1;
615 size_t kd_buf_size = kd_len << 1;
616 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
618 return DIFF_RC_ENOMEM;
620 for (i = 0; i < kd_buf_size; i++)
622 int *kd_forward = kd_buf;
623 int *kd_backward = kd_buf + kd_len;
625 /* The 'k' axis in Myers spans positive and negative indexes, so point the kd to the middle.
626 * It is then possible to index from -max/2 .. max/2. */
628 kd_backward += max/2;
631 struct diff_box mid_snake = {};
632 for (d = 0; d <= (max/2); d++) {
633 debug("-- d=%d\n", d);
634 diff_divide_myers_forward(left, right, kd_forward, kd_backward, d, &mid_snake);
635 if (!diff_box_empty(&mid_snake))
637 diff_divide_myers_backward(left, right, kd_forward, kd_backward, d, &mid_snake);
638 if (!diff_box_empty(&mid_snake))
642 if (diff_box_empty(&mid_snake)) {
643 /* Divide and conquer failed to find a meeting point. Use the fallback_algo defined in the algo_config
644 * (leave this to the caller). This is just paranoia/sanity, we normally should always find a midpoint.
646 debug(" no midpoint \n");
647 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
650 debug(" mid snake L: %u to %u of %u R: %u to %u of %u\n",
651 mid_snake.left_start, mid_snake.left_end, left->atoms.len,
652 mid_snake.right_start, mid_snake.right_end, right->atoms.len);
654 /* Section before the mid-snake. */
655 debug("Section before the mid-snake\n");
657 struct diff_atom *left_atom = &left->atoms.head[0];
658 unsigned int left_section_len = mid_snake.left_start;
659 struct diff_atom *right_atom = &right->atoms.head[0];
660 unsigned int right_section_len = mid_snake.right_start;
662 if (left_section_len && right_section_len) {
663 /* Record an unsolved chunk, the caller will apply inner_algo() on this chunk. */
664 if (!diff_state_add_chunk(state, false,
665 left_atom, left_section_len,
666 right_atom, right_section_len))
668 } else if (left_section_len && !right_section_len) {
669 /* Only left atoms and none on the right, they form a "minus" chunk, then. */
670 if (!diff_state_add_chunk(state, true,
671 left_atom, left_section_len,
674 } else if (!left_section_len && right_section_len) {
675 /* No left atoms, only atoms on the right, they form a "plus" chunk, then. */
676 if (!diff_state_add_chunk(state, true,
678 right_atom, right_section_len))
681 /* else: left_section_len == 0 and right_section_len == 0, i.e. nothing before the mid-snake. */
683 /* the mid-snake, identical data on both sides: */
684 debug("the mid-snake\n");
685 if (!diff_state_add_chunk(state, true,
686 &left->atoms.head[mid_snake.left_start],
687 mid_snake.left_end - mid_snake.left_start,
688 &right->atoms.head[mid_snake.right_start],
689 mid_snake.right_end - mid_snake.right_start))
692 /* Section after the mid-snake. */
693 debug("Section after the mid-snake\n");
694 debug(" left_end %u right_end %u\n", mid_snake.left_end, mid_snake.right_end);
695 debug(" left_count %u right_count %u\n", left->atoms.len, right->atoms.len);
696 left_atom = &left->atoms.head[mid_snake.left_end];
697 left_section_len = left->atoms.len - mid_snake.left_end;
698 right_atom = &right->atoms.head[mid_snake.right_end];
699 right_section_len = right->atoms.len - mid_snake.right_end;
701 if (left_section_len && right_section_len) {
702 /* Record an unsolved chunk, the caller will apply inner_algo() on this chunk. */
703 if (!diff_state_add_chunk(state, false,
704 left_atom, left_section_len,
705 right_atom, right_section_len))
707 } else if (left_section_len && !right_section_len) {
708 /* Only left atoms and none on the right, they form a "minus" chunk, then. */
709 if (!diff_state_add_chunk(state, true,
710 left_atom, left_section_len,
713 } else if (!left_section_len && right_section_len) {
714 /* No left atoms, only atoms on the right, they form a "plus" chunk, then. */
715 if (!diff_state_add_chunk(state, true,
717 right_atom, right_section_len))
720 /* else: left_section_len == 0 and right_section_len == 0, i.e. nothing after the mid-snake. */
727 debug("** END %s\n", __func__);
731 /* Myers Diff tracing from the start all the way through to the end, requiring quadratic amounts of memory. This can
732 * fail if the required space surpasses algo_config->permitted_state_size. */
733 enum diff_rc diff_algo_myers(const struct diff_algo_config *algo_config, struct diff_state *state)
735 /* do a diff_divide_myers_forward() without a _backward(), so that it walks forward across the entire
736 * files to reach the end. Keep each run's state, and do a final backtrace. */
737 enum diff_rc rc = DIFF_RC_ENOMEM;
738 struct diff_data *left = &state->left;
739 struct diff_data *right = &state->right;
741 debug("\n** %s\n", __func__);
746 debug_dump_myers_graph(left, right, NULL);
748 /* Allocate two columns of a Myers graph, one for the forward and one for the backward traversal. */
749 unsigned int max = left->atoms.len + right->atoms.len;
750 size_t kd_len = max + 1 + max;
751 size_t kd_buf_size = kd_len * kd_len;
752 debug("state size: %zu\n", kd_buf_size);
753 if (kd_buf_size < kd_len /* overflow? */
754 || kd_buf_size * sizeof(int) > algo_config->permitted_state_size) {
755 debug("state size %zu > permitted_state_size %zu, use fallback_algo\n",
756 kd_buf_size, algo_config->permitted_state_size);
757 return DIFF_RC_USE_DIFF_ALGO_FALLBACK;
760 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
762 return DIFF_RC_ENOMEM;
764 for (i = 0; i < kd_buf_size; i++)
767 /* The 'k' axis in Myers spans positive and negative indexes, so point the kd to the middle.
768 * It is then possible to index from -max .. max. */
769 int *kd_origin = kd_buf + max;
770 int *kd_column = kd_origin;
773 int backtrack_d = -1;
777 for (d = 0; d <= max; d++, kd_column += kd_len) {
778 debug("-- d=%d\n", d);
780 debug("-- %s d=%d\n", __func__, d);
782 for (k = d; k >= -d; k -= 2) {
783 if (k < -(int)right->atoms.len || k > (int)left->atoms.len) {
784 /* This diagonal is completely outside of the Myers graph, don't calculate it. */
785 if (k < -(int)right->atoms.len)
786 debug(" %d k < -(int)right->atoms.len %d\n", k, -(int)right->atoms.len);
788 debug(" %d k > left->atoms.len %d\n", k, left->atoms.len);
790 /* We are traversing negatively, and already below the entire graph, nothing will come
799 debug("- k = %d\n", k);
801 /* This is the initializing step. There is no prev_k yet, get the initial x from the top left of
802 * the Myers graph. */
805 int *kd_prev_column = kd_column - kd_len;
807 /* Favoring "-" lines first means favoring moving rightwards in the Myers graph.
808 * For this, all k should derive from k - 1, only the bottom most k derive from k + 1:
811 * ----+----------------
813 * 2 | 2,0 <-- from prev_k = 2 - 1 = 1
819 * -1 | 0,1 <-- bottom most for d=1 from prev_k = -1 + 1 = 0
821 * -2 | 0,2 <-- bottom most for d=2 from prev_k = -2 + 1 = -1
823 * Except when a k + 1 from a previous run already means a further advancement in the graph.
824 * If k == d, there is no k + 1 and k - 1 is the only option.
825 * If k < d, use k + 1 in case that yields a larger x. Also use k + 1 if k - 1 is outside the graph.
827 if (k > -d && (k == d
828 || (k - 1 >= -(int)right->atoms.len
829 && kd_prev_column[k - 1] >= kd_prev_column[k + 1]))) {
830 /* Advance from k - 1.
831 * From position prev_k, step to the right in the Myers graph: x += 1.
834 int prev_x = kd_prev_column[prev_k];
837 /* The bottom most one.
838 * From position prev_k, step to the bottom in the Myers graph: y += 1.
839 * Incrementing y is achieved by decrementing k while keeping the same x.
840 * (since we're deriving y from y = x - k).
843 int prev_x = kd_prev_column[prev_k];
848 /* Slide down any snake that we might find here. */
849 while (x < left->atoms.len && xk_to_y(x, k) < right->atoms.len
850 && diff_atom_same(&left->atoms.head[x], &right->atoms.head[xk_to_y(x, k)]))
856 for (fi = d; fi >= k; fi-=2) {
857 debug("kd_column[%d] = (%d, %d)\n", fi, kd_column[fi], kd_column[fi] - fi);
859 if (kd_column[fi] >= 0 && kd_column[fi] < left->atoms.len)
860 debug_dump_atom(left, right, &left->atoms.head[kd_column[fi]]);
863 if (kd_column[fi]-fi >= 0 && kd_column[fi]-fi < right->atoms.len)
864 debug_dump_atom(right, left, &right->atoms.head[kd_column[fi]-fi]);
871 if (x == left->atoms.len && xk_to_y(x, k) == right->atoms.len) {
875 debug("Reached the end at d = %d, k = %d\n",
876 backtrack_d, backtrack_k);
881 if (backtrack_d >= 0)
885 debug_dump_myers_graph(left, right, kd_origin);
887 /* backtrack. A matrix spanning from start to end of the file is ready:
890 * ----+---------------------------------
898 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4, backtrack_k = 0
905 * From (4,4) backwards, find the previous position that is the largest, and remember it.
908 for (d = backtrack_d, k = backtrack_k; d >= 0; d--) {
912 /* When the best position is identified, remember it for that kd_column.
913 * That kd_column is no longer needed otherwise, so just re-purpose kd_column[0] = x and kd_column[1] = y,
914 * so that there is no need to allocate more memory.
918 debug("Backtrack d=%d: xy=(%d, %d)\n",
919 d, kd_column[0], kd_column[1]);
921 /* Don't access memory before kd_buf */
924 int *kd_prev_column = kd_column - kd_len;
926 /* When y == 0, backtracking downwards (k-1) is the only way.
927 * When x == 0, backtracking upwards (k+1) is the only way.
930 * ----+---------------------------------
938 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4, backtrack_k = 0
945 debug("prev[k-1] = %d,%d prev[k+1] = %d,%d\n",
946 kd_prev_column[k-1], xk_to_y(kd_prev_column[k-1],k-1),
947 kd_prev_column[k+1], xk_to_y(kd_prev_column[k+1],k+1));
949 || (x > 0 && kd_prev_column[k - 1] >= kd_prev_column[k + 1])) {
951 debug("prev k=k-1=%d x=%d y=%d\n",
952 k, kd_prev_column[k], xk_to_y(kd_prev_column[k], k));
955 debug("prev k=k+1=%d x=%d y=%d\n",
956 k, kd_prev_column[k], xk_to_y(kd_prev_column[k], k));
958 kd_column = kd_prev_column;
961 /* Forwards again, this time recording the diff chunks.
962 * Definitely start from 0,0. kd_column[0] may actually point to the bottom of a snake starting at 0,0 */
966 kd_column = kd_origin;
967 for (d = 0; d <= backtrack_d; d++, kd_column += kd_len) {
968 int next_x = kd_column[0];
969 int next_y = kd_column[1];
970 debug("Forward track from xy(%d,%d) to xy(%d,%d)\n",
971 x, y, next_x, next_y);
973 struct diff_atom *left_atom = &left->atoms.head[x];
974 int left_section_len = next_x - x;
975 struct diff_atom *right_atom = &right->atoms.head[y];
976 int right_section_len = next_y - y;
979 if (left_section_len && right_section_len) {
980 /* This must be a snake slide.
981 * Snake slides have a straight line leading into them (except when starting at (0,0)). Find
982 * out whether the lead-in is horizontal or vertical:
994 * If left_section_len > right_section_len, the lead-in is horizontal, meaning first
995 * remove one atom from the left before sliding down the snake.
996 * If right_section_len > left_section_len, the lead-in is vetical, so add one atom from
997 * the right before sliding down the snake. */
998 if (left_section_len == right_section_len + 1) {
999 if (!diff_state_add_chunk(state, true,
1005 } else if (right_section_len == left_section_len + 1) {
1006 if (!diff_state_add_chunk(state, true,
1011 right_section_len--;
1012 } else if (left_section_len != right_section_len) {
1013 /* The numbers are making no sense. Should never happen. */
1014 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
1018 if (!diff_state_add_chunk(state, true,
1019 left_atom, left_section_len,
1020 right_atom, right_section_len))
1022 } else if (left_section_len && !right_section_len) {
1023 /* Only left atoms and none on the right, they form a "minus" chunk, then. */
1024 if (!diff_state_add_chunk(state, true,
1025 left_atom, left_section_len,
1028 } else if (!left_section_len && right_section_len) {
1029 /* No left atoms, only atoms on the right, they form a "plus" chunk, then. */
1030 if (!diff_state_add_chunk(state, true,
1032 right_atom, right_section_len))
1044 debug("** END %s rc=%d\n", __func__, rc);