1 /* Analyze differences between two vectors.
3 Copyright (C) 1988-1989, 1992-1995, 2001-2004, 2006, 2007 Free
4 Software Foundation, Inc.
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* The basic idea is to consider two vectors as similar if, when
21 transforming the first vector into the second vector through a
22 sequence of edits (inserts and deletes of one element each),
23 this sequence is short - or equivalently, if the ordered list
24 of elements that are untouched by these edits is long. For a
25 good introduction to the subject, read about the "Levenshtein
26 distance" in Wikipedia.
28 The basic algorithm is described in:
29 "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
30 Algorithmica Vol. 1 No. 2, 1986, pp. 251-266;
31 see especially section 4.2, which describes the variation used below.
33 The basic algorithm was independently discovered as described in:
34 "Algorithms for Approximate String Matching", E. Ukkonen,
35 Information and Control Vol. 64, 1985, pp. 100-118.
37 Unless the 'find_minimal' flag is set, this code uses the TOO_EXPENSIVE
38 heuristic, by Paul Eggert, to limit the cost to O(N**1.5 log N)
39 at the price of producing suboptimal output for large inputs with
42 /* Before including this file, you need to define:
43 ELEMENT The element type of the vectors being compared.
44 EQUAL A two-argument macro that tests two elements for
46 OFFSET A signed integer type sufficient to hold the
47 difference between two indices. Usually
48 something like ssize_t.
49 EXTRA_CONTEXT_FIELDS Declarations of fields for 'struct context'.
50 NOTE_DELETE(ctxt, xoff) Record the removal of the object xvec[xoff].
51 NOTE_INSERT(ctxt, yoff) Record the insertion of the object yvec[yoff].
52 USE_HEURISTIC (Optional) Define if you want to support the
53 heuristic for large vectors. */
55 /* Maximum value of type OFFSET. */
57 ((((OFFSET)1 << (sizeof (OFFSET) * CHAR_BIT - 2)) - 1) * 2 + 1)
59 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
62 # define IF_LINT(Code) Code
64 # define IF_LINT(Code) /* empty */
69 * Context of comparison operation.
73 /* Vectors being compared. */
80 /* Vector, indexed by diagonal, containing 1 + the X coordinate of the point
81 furthest along the given diagonal in the forward search of the edit
85 /* Vector, indexed by diagonal, containing the X coordinate of the point
86 furthest along the given diagonal in the backward search of the edit
91 /* This corresponds to the diff -H flag. With this heuristic, for
92 vectors with a constant small density of changes, the algorithm is
93 linear in the vectors size. */
97 /* Edit scripts longer than this are too expensive to compute. */
100 /* Snakes bigger than this are considered `big'. */
101 #define SNAKE_LIMIT 20
106 /* Midpoints of this partition. */
110 /* True if low half will be analyzed minimally. */
113 /* Likewise for high half. */
118 /* Find the midpoint of the shortest edit script for a specified portion
121 Scan from the beginnings of the vectors, and simultaneously from the ends,
122 doing a breadth-first search through the space of edit-sequence.
123 When the two searches meet, we have found the midpoint of the shortest
126 If FIND_MINIMAL is true, find the minimal edit script regardless of
127 expense. Otherwise, if the search is too expensive, use heuristics to
128 stop the search and report a suboptimal answer.
130 Set PART->(xmid,ymid) to the midpoint (XMID,YMID). The diagonal number
131 XMID - YMID equals the number of inserted elements minus the number
132 of deleted elements (counting only elements before the midpoint).
134 Set PART->lo_minimal to true iff the minimal edit script for the
135 left half of the partition is known; similarly for PART->hi_minimal.
137 This function assumes that the first elements of the specified portions
138 of the two vectors do not match, and likewise that the last elements do not
139 match. The caller must trim matching elements from the beginning and end
140 of the portions it is going to specify.
142 If we return the "wrong" partitions, the worst this can do is cause
143 suboptimal diff output. It cannot cause incorrect diff output. */
146 diag (OFFSET xoff, OFFSET xlim, OFFSET yoff, OFFSET ylim, bool find_minimal,
147 struct partition *part, struct context *ctxt)
149 OFFSET *const fd = ctxt->fdiag; /* Give the compiler a chance. */
150 OFFSET *const bd = ctxt->bdiag; /* Additional help for the compiler. */
151 const ELEMENT *const xv = ctxt->xvec; /* Still more help for the compiler. */
152 const ELEMENT *const yv = ctxt->yvec; /* And more and more . . . */
153 const OFFSET dmin = xoff - ylim; /* Minimum valid diagonal. */
154 const OFFSET dmax = xlim - yoff; /* Maximum valid diagonal. */
155 const OFFSET fmid = xoff - yoff; /* Center diagonal of top-down search. */
156 const OFFSET bmid = xlim - ylim; /* Center diagonal of bottom-up search. */
158 OFFSET fmax = fmid; /* Limits of top-down search. */
160 OFFSET bmax = bmid; /* Limits of bottom-up search. */
161 OFFSET c; /* Cost. */
162 bool odd = (fmid - bmid) & 1; /* True if southeast corner is on an odd
163 diagonal with respect to the northwest. */
170 OFFSET d; /* Active diagonal. */
171 bool big_snake = false;
173 /* Extend the top-down search by an edit step in each diagonal. */
182 for (d = fmax; d >= fmin; d -= 2)
186 OFFSET tlo = fd[d - 1];
187 OFFSET thi = fd[d + 1];
188 OFFSET x0 = tlo < thi ? thi : tlo + 1;
190 for (x = x0, y = x0 - d;
191 x < xlim && y < ylim && EQUAL (xv[x], yv[y]);
194 if (x - x0 > SNAKE_LIMIT)
197 if (odd && bmin <= d && d <= bmax && bd[d] <= x)
201 part->lo_minimal = part->hi_minimal = true;
206 /* Similarly extend the bottom-up search. */
208 bd[--bmin - 1] = OFFSET_MAX;
212 bd[++bmax + 1] = OFFSET_MAX;
215 for (d = bmax; d >= bmin; d -= 2)
219 OFFSET tlo = bd[d - 1];
220 OFFSET thi = bd[d + 1];
221 OFFSET x0 = tlo < thi ? tlo : thi - 1;
223 for (x = x0, y = x0 - d;
224 xoff < x && yoff < y && EQUAL (xv[x - 1], yv[y - 1]);
227 if (x0 - x > SNAKE_LIMIT)
230 if (!odd && fmin <= d && d <= fmax && x <= fd[d])
234 part->lo_minimal = part->hi_minimal = true;
243 /* Heuristic: check occasionally for a diagonal that has made lots
244 of progress compared with the edit distance. If we have any
245 such, find the one that has made the most progress and return it
246 as if it had succeeded.
248 With this heuristic, for vectors with a constant small density
249 of changes, the algorithm is linear in the vector size. */
251 if (200 < c && big_snake && ctxt->heuristic)
255 for (d = fmax; d >= fmin; d -= 2)
257 OFFSET dd = d - fmid;
260 OFFSET v = (x - xoff) * 2 - dd;
262 if (v > 12 * (c + (dd < 0 ? -dd : dd)))
265 && xoff + SNAKE_LIMIT <= x && x < xlim
266 && yoff + SNAKE_LIMIT <= y && y < ylim)
268 /* We have a good enough best diagonal; now insist
269 that it end with a significant snake. */
272 for (k = 1; EQUAL (xv[x - k], yv[y - k]); k++)
273 if (k == SNAKE_LIMIT)
285 part->lo_minimal = true;
286 part->hi_minimal = false;
291 for (d = bmax; d >= bmin; d -= 2)
293 OFFSET dd = d - bmid;
296 OFFSET v = (xlim - x) * 2 + dd;
298 if (v > 12 * (c + (dd < 0 ? -dd : dd)))
301 && xoff < x && x <= xlim - SNAKE_LIMIT
302 && yoff < y && y <= ylim - SNAKE_LIMIT)
304 /* We have a good enough best diagonal; now insist
305 that it end with a significant snake. */
308 for (k = 0; EQUAL (xv[x + k], yv[y + k]); k++)
309 if (k == SNAKE_LIMIT - 1)
321 part->lo_minimal = false;
322 part->hi_minimal = true;
326 #endif /* USE_HEURISTIC */
328 /* Heuristic: if we've gone well beyond the call of duty, give up
329 and report halfway between our best results so far. */
330 if (c >= ctxt->too_expensive)
333 OFFSET fxbest IF_LINT (= 0);
335 OFFSET bxbest IF_LINT (= 0);
337 /* Find forward diagonal that maximizes X + Y. */
339 for (d = fmax; d >= fmin; d -= 2)
341 OFFSET x = MIN (fd[d], xlim);
355 /* Find backward diagonal that minimizes X + Y. */
356 bxybest = OFFSET_MAX;
357 for (d = bmax; d >= bmin; d -= 2)
359 OFFSET x = MAX (xoff, bd[d]);
373 /* Use the better of the two diagonals. */
374 if ((xlim + ylim) - bxybest < fxybest - (xoff + yoff))
377 part->ymid = fxybest - fxbest;
378 part->lo_minimal = true;
379 part->hi_minimal = false;
384 part->ymid = bxybest - bxbest;
385 part->lo_minimal = false;
386 part->hi_minimal = true;
394 /* Compare in detail contiguous subsequences of the two vectors
395 which are known, as a whole, to match each other.
397 The subsequence of vector 0 is [XOFF, XLIM) and likewise for vector 1.
399 Note that XLIM, YLIM are exclusive bounds. All indices into the vectors
402 If FIND_MINIMAL, find a minimal difference no matter how
405 The results are recorded by invoking NOTE_DELETE and NOTE_INSERT. */
408 compareseq (OFFSET xoff, OFFSET xlim, OFFSET yoff, OFFSET ylim,
409 bool find_minimal, struct context *ctxt)
411 ELEMENT const *xv = ctxt->xvec; /* Help the compiler. */
412 ELEMENT const *yv = ctxt->yvec;
414 /* Slide down the bottom initial diagonal. */
415 while (xoff < xlim && yoff < ylim && EQUAL (xv[xoff], yv[yoff]))
421 /* Slide up the top initial diagonal. */
422 while (xoff < xlim && yoff < ylim && EQUAL (xv[xlim - 1], yv[ylim - 1]))
428 /* Handle simple cases. */
432 NOTE_INSERT (ctxt, yoff);
435 else if (yoff == ylim)
438 NOTE_DELETE (ctxt, xoff);
443 struct partition part;
445 /* Find a point of correspondence in the middle of the vectors. */
446 diag (xoff, xlim, yoff, ylim, find_minimal, &part, ctxt);
448 /* Use the partitions to split this problem into subproblems. */
449 compareseq (xoff, part.xmid, yoff, part.ymid, part.lo_minimal, ctxt);
450 compareseq (part.xmid, xlim, part.ymid, ylim, part.hi_minimal, ctxt);
457 #undef EXTRA_CONTEXT_FIELDS