##// END OF EJS Templates
bdiff: balance recursion to avoid quadratic behavior (issue4704)...
Matt Mackall -
r29014:f1ca2496 stable
parent child Browse files
Show More
@@ -0,0 +1,29
1 #require no-pure
2
3 A script to generate nasty diff worst-case scenarios:
4
5 $ cat > s.py <<EOF
6 > import random
7 > for x in xrange(100000):
8 > print
9 > if random.randint(0, 100) >= 50:
10 > x += 1
11 > print hex(x)
12 > EOF
13
14 $ hg init a
15 $ cd a
16
17 Check in a big file:
18
19 $ python ../s.py > a
20 $ hg ci -qAm0
21
22 Modify it:
23
24 $ python ../s.py > a
25
26 Time a check-in, should never take more than 10 seconds user time:
27
28 $ hg ci --time -m1
29 time: real .* secs .user [0-9][.].* sys .* (re)
@@ -1,474 +1,475
1 1 /*
2 2 bdiff.c - efficient binary diff extension for Mercurial
3 3
4 4 Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
5 5
6 6 This software may be used and distributed according to the terms of
7 7 the GNU General Public License, incorporated herein by reference.
8 8
9 9 Based roughly on Python difflib
10 10 */
11 11
12 12 #define PY_SSIZE_T_CLEAN
13 13 #include <Python.h>
14 14 #include <stdlib.h>
15 15 #include <string.h>
16 16 #include <limits.h>
17 17
18 18 #include "util.h"
19 19
20 20 struct line {
21 21 int hash, n, e;
22 22 Py_ssize_t len;
23 23 const char *l;
24 24 };
25 25
26 26 struct pos {
27 27 int pos, len;
28 28 };
29 29
30 30 struct hunk;
31 31 struct hunk {
32 32 int a1, a2, b1, b2;
33 33 struct hunk *next;
34 34 };
35 35
36 36 static int splitlines(const char *a, Py_ssize_t len, struct line **lr)
37 37 {
38 38 unsigned hash;
39 39 int i;
40 40 const char *p, *b = a;
41 41 const char * const plast = a + len - 1;
42 42 struct line *l;
43 43
44 44 /* count the lines */
45 45 i = 1; /* extra line for sentinel */
46 46 for (p = a; p < a + len; p++)
47 47 if (*p == '\n' || p == plast)
48 48 i++;
49 49
50 50 *lr = l = (struct line *)malloc(sizeof(struct line) * i);
51 51 if (!l)
52 52 return -1;
53 53
54 54 /* build the line array and calculate hashes */
55 55 hash = 0;
56 56 for (p = a; p < a + len; p++) {
57 57 /* Leonid Yuriev's hash */
58 58 hash = (hash * 1664525) + (unsigned char)*p + 1013904223;
59 59
60 60 if (*p == '\n' || p == plast) {
61 61 l->hash = hash;
62 62 hash = 0;
63 63 l->len = p - b + 1;
64 64 l->l = b;
65 65 l->n = INT_MAX;
66 66 l++;
67 67 b = p + 1;
68 68 }
69 69 }
70 70
71 71 /* set up a sentinel */
72 72 l->hash = 0;
73 73 l->len = 0;
74 74 l->l = a + len;
75 75 return i - 1;
76 76 }
77 77
78 78 static inline int cmp(struct line *a, struct line *b)
79 79 {
80 80 return a->hash != b->hash || a->len != b->len || memcmp(a->l, b->l, a->len);
81 81 }
82 82
83 83 static int equatelines(struct line *a, int an, struct line *b, int bn)
84 84 {
85 85 int i, j, buckets = 1, t, scale;
86 86 struct pos *h = NULL;
87 87
88 88 /* build a hash table of the next highest power of 2 */
89 89 while (buckets < bn + 1)
90 90 buckets *= 2;
91 91
92 92 /* try to allocate a large hash table to avoid collisions */
93 93 for (scale = 4; scale; scale /= 2) {
94 94 h = (struct pos *)malloc(scale * buckets * sizeof(struct pos));
95 95 if (h)
96 96 break;
97 97 }
98 98
99 99 if (!h)
100 100 return 0;
101 101
102 102 buckets = buckets * scale - 1;
103 103
104 104 /* clear the hash table */
105 105 for (i = 0; i <= buckets; i++) {
106 106 h[i].pos = -1;
107 107 h[i].len = 0;
108 108 }
109 109
110 110 /* add lines to the hash table chains */
111 111 for (i = 0; i < bn; i++) {
112 112 /* find the equivalence class */
113 113 for (j = b[i].hash & buckets; h[j].pos != -1;
114 114 j = (j + 1) & buckets)
115 115 if (!cmp(b + i, b + h[j].pos))
116 116 break;
117 117
118 118 /* add to the head of the equivalence class */
119 119 b[i].n = h[j].pos;
120 120 b[i].e = j;
121 121 h[j].pos = i;
122 122 h[j].len++; /* keep track of popularity */
123 123 }
124 124
125 125 /* compute popularity threshold */
126 126 t = (bn >= 31000) ? bn / 1000 : 1000000 / (bn + 1);
127 127
128 128 /* match items in a to their equivalence class in b */
129 129 for (i = 0; i < an; i++) {
130 130 /* find the equivalence class */
131 131 for (j = a[i].hash & buckets; h[j].pos != -1;
132 132 j = (j + 1) & buckets)
133 133 if (!cmp(a + i, b + h[j].pos))
134 134 break;
135 135
136 136 a[i].e = j; /* use equivalence class for quick compare */
137 137 if (h[j].len <= t)
138 138 a[i].n = h[j].pos; /* point to head of match list */
139 139 else
140 140 a[i].n = -1; /* too popular */
141 141 }
142 142
143 143 /* discard hash tables */
144 144 free(h);
145 145 return 1;
146 146 }
147 147
148 148 static int longest_match(struct line *a, struct line *b, struct pos *pos,
149 149 int a1, int a2, int b1, int b2, int *omi, int *omj)
150 150 {
151 int mi = a1, mj = b1, mk = 0, mb = 0, i, j, k;
151 int mi = a1, mj = b1, mk = 0, mb = 0, i, j, k, half = (a1 + a2) / 2;
152 152
153 153 for (i = a1; i < a2; i++) {
154 154 /* skip all lines in b after the current block */
155 155 for (j = a[i].n; j >= b2; j = b[j].n)
156 156 ;
157 157
158 158 /* loop through all lines match a[i] in b */
159 159 for (; j >= b1; j = b[j].n) {
160 160 /* does this extend an earlier match? */
161 161 if (i > a1 && j > b1 && pos[j - 1].pos == i - 1)
162 162 k = pos[j - 1].len + 1;
163 163 else
164 164 k = 1;
165 165 pos[j].pos = i;
166 166 pos[j].len = k;
167 167
168 /* best match so far? */
169 if (k > mk || (k == mk && i <= mi)) {
168 /* best match so far? we prefer matches closer
169 to the middle to balance recursion */
170 if (k > mk || (k == mk && (i <= mi || i < half))) {
170 171 mi = i;
171 172 mj = j;
172 173 mk = k;
173 174 }
174 175 }
175 176 }
176 177
177 178 if (mk) {
178 179 mi = mi - mk + 1;
179 180 mj = mj - mk + 1;
180 181 }
181 182
182 183 /* expand match to include neighboring popular lines */
183 184 while (mi - mb > a1 && mj - mb > b1 &&
184 185 a[mi - mb - 1].e == b[mj - mb - 1].e)
185 186 mb++;
186 187 while (mi + mk < a2 && mj + mk < b2 &&
187 188 a[mi + mk].e == b[mj + mk].e)
188 189 mk++;
189 190
190 191 *omi = mi - mb;
191 192 *omj = mj - mb;
192 193
193 194 return mk + mb;
194 195 }
195 196
196 197 static struct hunk *recurse(struct line *a, struct line *b, struct pos *pos,
197 198 int a1, int a2, int b1, int b2, struct hunk *l)
198 199 {
199 200 int i, j, k;
200 201
201 202 while (1) {
202 203 /* find the longest match in this chunk */
203 204 k = longest_match(a, b, pos, a1, a2, b1, b2, &i, &j);
204 205 if (!k)
205 206 return l;
206 207
207 208 /* and recurse on the remaining chunks on either side */
208 209 l = recurse(a, b, pos, a1, i, b1, j, l);
209 210 if (!l)
210 211 return NULL;
211 212
212 213 l->next = (struct hunk *)malloc(sizeof(struct hunk));
213 214 if (!l->next)
214 215 return NULL;
215 216
216 217 l = l->next;
217 218 l->a1 = i;
218 219 l->a2 = i + k;
219 220 l->b1 = j;
220 221 l->b2 = j + k;
221 222 l->next = NULL;
222 223
223 224 /* tail-recursion didn't happen, so do equivalent iteration */
224 225 a1 = i + k;
225 226 b1 = j + k;
226 227 }
227 228 }
228 229
229 230 static int diff(struct line *a, int an, struct line *b, int bn,
230 231 struct hunk *base)
231 232 {
232 233 struct hunk *curr;
233 234 struct pos *pos;
234 235 int t, count = 0;
235 236
236 237 /* allocate and fill arrays */
237 238 t = equatelines(a, an, b, bn);
238 239 pos = (struct pos *)calloc(bn ? bn : 1, sizeof(struct pos));
239 240
240 241 if (pos && t) {
241 242 /* generate the matching block list */
242 243
243 244 curr = recurse(a, b, pos, 0, an, 0, bn, base);
244 245 if (!curr)
245 246 return -1;
246 247
247 248 /* sentinel end hunk */
248 249 curr->next = (struct hunk *)malloc(sizeof(struct hunk));
249 250 if (!curr->next)
250 251 return -1;
251 252 curr = curr->next;
252 253 curr->a1 = curr->a2 = an;
253 254 curr->b1 = curr->b2 = bn;
254 255 curr->next = NULL;
255 256 }
256 257
257 258 free(pos);
258 259
259 260 /* normalize the hunk list, try to push each hunk towards the end */
260 261 for (curr = base->next; curr; curr = curr->next) {
261 262 struct hunk *next = curr->next;
262 263
263 264 if (!next)
264 265 break;
265 266
266 267 if (curr->a2 == next->a1 || curr->b2 == next->b1)
267 268 while (curr->a2 < an && curr->b2 < bn
268 269 && next->a1 < next->a2
269 270 && next->b1 < next->b2
270 271 && !cmp(a + curr->a2, b + curr->b2)) {
271 272 curr->a2++;
272 273 next->a1++;
273 274 curr->b2++;
274 275 next->b1++;
275 276 }
276 277 }
277 278
278 279 for (curr = base->next; curr; curr = curr->next)
279 280 count++;
280 281 return count;
281 282 }
282 283
283 284 static void freehunks(struct hunk *l)
284 285 {
285 286 struct hunk *n;
286 287 for (; l; l = n) {
287 288 n = l->next;
288 289 free(l);
289 290 }
290 291 }
291 292
292 293 static PyObject *blocks(PyObject *self, PyObject *args)
293 294 {
294 295 PyObject *sa, *sb, *rl = NULL, *m;
295 296 struct line *a, *b;
296 297 struct hunk l, *h;
297 298 int an, bn, count, pos = 0;
298 299
299 300 l.next = NULL;
300 301
301 302 if (!PyArg_ParseTuple(args, "SS:bdiff", &sa, &sb))
302 303 return NULL;
303 304
304 305 an = splitlines(PyBytes_AsString(sa), PyBytes_Size(sa), &a);
305 306 bn = splitlines(PyBytes_AsString(sb), PyBytes_Size(sb), &b);
306 307
307 308 if (!a || !b)
308 309 goto nomem;
309 310
310 311 count = diff(a, an, b, bn, &l);
311 312 if (count < 0)
312 313 goto nomem;
313 314
314 315 rl = PyList_New(count);
315 316 if (!rl)
316 317 goto nomem;
317 318
318 319 for (h = l.next; h; h = h->next) {
319 320 m = Py_BuildValue("iiii", h->a1, h->a2, h->b1, h->b2);
320 321 PyList_SetItem(rl, pos, m);
321 322 pos++;
322 323 }
323 324
324 325 nomem:
325 326 free(a);
326 327 free(b);
327 328 freehunks(l.next);
328 329 return rl ? rl : PyErr_NoMemory();
329 330 }
330 331
331 332 static PyObject *bdiff(PyObject *self, PyObject *args)
332 333 {
333 334 char *sa, *sb, *rb;
334 335 PyObject *result = NULL;
335 336 struct line *al, *bl;
336 337 struct hunk l, *h;
337 338 int an, bn, count;
338 339 Py_ssize_t len = 0, la, lb;
339 340 PyThreadState *_save;
340 341
341 342 l.next = NULL;
342 343
343 344 if (!PyArg_ParseTuple(args, "s#s#:bdiff", &sa, &la, &sb, &lb))
344 345 return NULL;
345 346
346 347 if (la > UINT_MAX || lb > UINT_MAX) {
347 348 PyErr_SetString(PyExc_ValueError, "bdiff inputs too large");
348 349 return NULL;
349 350 }
350 351
351 352 _save = PyEval_SaveThread();
352 353 an = splitlines(sa, la, &al);
353 354 bn = splitlines(sb, lb, &bl);
354 355 if (!al || !bl)
355 356 goto nomem;
356 357
357 358 count = diff(al, an, bl, bn, &l);
358 359 if (count < 0)
359 360 goto nomem;
360 361
361 362 /* calculate length of output */
362 363 la = lb = 0;
363 364 for (h = l.next; h; h = h->next) {
364 365 if (h->a1 != la || h->b1 != lb)
365 366 len += 12 + bl[h->b1].l - bl[lb].l;
366 367 la = h->a2;
367 368 lb = h->b2;
368 369 }
369 370 PyEval_RestoreThread(_save);
370 371 _save = NULL;
371 372
372 373 result = PyBytes_FromStringAndSize(NULL, len);
373 374
374 375 if (!result)
375 376 goto nomem;
376 377
377 378 /* build binary patch */
378 379 rb = PyBytes_AsString(result);
379 380 la = lb = 0;
380 381
381 382 for (h = l.next; h; h = h->next) {
382 383 if (h->a1 != la || h->b1 != lb) {
383 384 len = bl[h->b1].l - bl[lb].l;
384 385 putbe32((uint32_t)(al[la].l - al->l), rb);
385 386 putbe32((uint32_t)(al[h->a1].l - al->l), rb + 4);
386 387 putbe32((uint32_t)len, rb + 8);
387 388 memcpy(rb + 12, bl[lb].l, len);
388 389 rb += 12 + len;
389 390 }
390 391 la = h->a2;
391 392 lb = h->b2;
392 393 }
393 394
394 395 nomem:
395 396 if (_save)
396 397 PyEval_RestoreThread(_save);
397 398 free(al);
398 399 free(bl);
399 400 freehunks(l.next);
400 401 return result ? result : PyErr_NoMemory();
401 402 }
402 403
403 404 /*
404 405 * If allws != 0, remove all whitespace (' ', \t and \r). Otherwise,
405 406 * reduce whitespace sequences to a single space and trim remaining whitespace
406 407 * from end of lines.
407 408 */
408 409 static PyObject *fixws(PyObject *self, PyObject *args)
409 410 {
410 411 PyObject *s, *result = NULL;
411 412 char allws, c;
412 413 const char *r;
413 414 Py_ssize_t i, rlen, wlen = 0;
414 415 char *w;
415 416
416 417 if (!PyArg_ParseTuple(args, "Sb:fixws", &s, &allws))
417 418 return NULL;
418 419 r = PyBytes_AsString(s);
419 420 rlen = PyBytes_Size(s);
420 421
421 422 w = (char *)malloc(rlen ? rlen : 1);
422 423 if (!w)
423 424 goto nomem;
424 425
425 426 for (i = 0; i != rlen; i++) {
426 427 c = r[i];
427 428 if (c == ' ' || c == '\t' || c == '\r') {
428 429 if (!allws && (wlen == 0 || w[wlen - 1] != ' '))
429 430 w[wlen++] = ' ';
430 431 } else if (c == '\n' && !allws
431 432 && wlen > 0 && w[wlen - 1] == ' ') {
432 433 w[wlen - 1] = '\n';
433 434 } else {
434 435 w[wlen++] = c;
435 436 }
436 437 }
437 438
438 439 result = PyBytes_FromStringAndSize(w, wlen);
439 440
440 441 nomem:
441 442 free(w);
442 443 return result ? result : PyErr_NoMemory();
443 444 }
444 445
445 446
446 447 static char mdiff_doc[] = "Efficient binary diff.";
447 448
448 449 static PyMethodDef methods[] = {
449 450 {"bdiff", bdiff, METH_VARARGS, "calculate a binary diff\n"},
450 451 {"blocks", blocks, METH_VARARGS, "find a list of matching lines\n"},
451 452 {"fixws", fixws, METH_VARARGS, "normalize diff whitespaces\n"},
452 453 {NULL, NULL}
453 454 };
454 455
455 456 #ifdef IS_PY3K
456 457 static struct PyModuleDef bdiff_module = {
457 458 PyModuleDef_HEAD_INIT,
458 459 "bdiff",
459 460 mdiff_doc,
460 461 -1,
461 462 methods
462 463 };
463 464
464 465 PyMODINIT_FUNC PyInit_bdiff(void)
465 466 {
466 467 return PyModule_Create(&bdiff_module);
467 468 }
468 469 #else
469 470 PyMODINIT_FUNC initbdiff(void)
470 471 {
471 472 Py_InitModule3("bdiff", methods, mdiff_doc);
472 473 }
473 474 #endif
474 475
General Comments 0
You need to be logged in to leave comments. Login now