##// END OF EJS Templates
bdiff: further restrain potential quadratic performance...
Matt Mackall -
r29015:87d4a6c5 stable
parent child Browse files
Show More
@@ -1,475 +1,483 b''
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, half = (a1 + a2) / 2;
151 int mi = a1, mj = b1, mk = 0, mb = 0, i, j, k, half;
152
153 /* window our search on large regions to better bound
154 worst-case performance. by choosing a window at the end, we
155 reduce skipping overhead on the b chains. */
156 if (a2 - a1 > 30000)
157 a1 = a2 - 30000;
158
159 half = (a1 + a2) / 2;
152 160
153 161 for (i = a1; i < a2; i++) {
154 162 /* skip all lines in b after the current block */
155 163 for (j = a[i].n; j >= b2; j = b[j].n)
156 164 ;
157 165
158 166 /* loop through all lines match a[i] in b */
159 167 for (; j >= b1; j = b[j].n) {
160 168 /* does this extend an earlier match? */
161 169 if (i > a1 && j > b1 && pos[j - 1].pos == i - 1)
162 170 k = pos[j - 1].len + 1;
163 171 else
164 172 k = 1;
165 173 pos[j].pos = i;
166 174 pos[j].len = k;
167 175
168 176 /* best match so far? we prefer matches closer
169 177 to the middle to balance recursion */
170 178 if (k > mk || (k == mk && (i <= mi || i < half))) {
171 179 mi = i;
172 180 mj = j;
173 181 mk = k;
174 182 }
175 183 }
176 184 }
177 185
178 186 if (mk) {
179 187 mi = mi - mk + 1;
180 188 mj = mj - mk + 1;
181 189 }
182 190
183 191 /* expand match to include neighboring popular lines */
184 192 while (mi - mb > a1 && mj - mb > b1 &&
185 193 a[mi - mb - 1].e == b[mj - mb - 1].e)
186 194 mb++;
187 195 while (mi + mk < a2 && mj + mk < b2 &&
188 196 a[mi + mk].e == b[mj + mk].e)
189 197 mk++;
190 198
191 199 *omi = mi - mb;
192 200 *omj = mj - mb;
193 201
194 202 return mk + mb;
195 203 }
196 204
197 205 static struct hunk *recurse(struct line *a, struct line *b, struct pos *pos,
198 206 int a1, int a2, int b1, int b2, struct hunk *l)
199 207 {
200 208 int i, j, k;
201 209
202 210 while (1) {
203 211 /* find the longest match in this chunk */
204 212 k = longest_match(a, b, pos, a1, a2, b1, b2, &i, &j);
205 213 if (!k)
206 214 return l;
207 215
208 216 /* and recurse on the remaining chunks on either side */
209 217 l = recurse(a, b, pos, a1, i, b1, j, l);
210 218 if (!l)
211 219 return NULL;
212 220
213 221 l->next = (struct hunk *)malloc(sizeof(struct hunk));
214 222 if (!l->next)
215 223 return NULL;
216 224
217 225 l = l->next;
218 226 l->a1 = i;
219 227 l->a2 = i + k;
220 228 l->b1 = j;
221 229 l->b2 = j + k;
222 230 l->next = NULL;
223 231
224 232 /* tail-recursion didn't happen, so do equivalent iteration */
225 233 a1 = i + k;
226 234 b1 = j + k;
227 235 }
228 236 }
229 237
230 238 static int diff(struct line *a, int an, struct line *b, int bn,
231 239 struct hunk *base)
232 240 {
233 241 struct hunk *curr;
234 242 struct pos *pos;
235 243 int t, count = 0;
236 244
237 245 /* allocate and fill arrays */
238 246 t = equatelines(a, an, b, bn);
239 247 pos = (struct pos *)calloc(bn ? bn : 1, sizeof(struct pos));
240 248
241 249 if (pos && t) {
242 250 /* generate the matching block list */
243 251
244 252 curr = recurse(a, b, pos, 0, an, 0, bn, base);
245 253 if (!curr)
246 254 return -1;
247 255
248 256 /* sentinel end hunk */
249 257 curr->next = (struct hunk *)malloc(sizeof(struct hunk));
250 258 if (!curr->next)
251 259 return -1;
252 260 curr = curr->next;
253 261 curr->a1 = curr->a2 = an;
254 262 curr->b1 = curr->b2 = bn;
255 263 curr->next = NULL;
256 264 }
257 265
258 266 free(pos);
259 267
260 268 /* normalize the hunk list, try to push each hunk towards the end */
261 269 for (curr = base->next; curr; curr = curr->next) {
262 270 struct hunk *next = curr->next;
263 271
264 272 if (!next)
265 273 break;
266 274
267 275 if (curr->a2 == next->a1 || curr->b2 == next->b1)
268 276 while (curr->a2 < an && curr->b2 < bn
269 277 && next->a1 < next->a2
270 278 && next->b1 < next->b2
271 279 && !cmp(a + curr->a2, b + curr->b2)) {
272 280 curr->a2++;
273 281 next->a1++;
274 282 curr->b2++;
275 283 next->b1++;
276 284 }
277 285 }
278 286
279 287 for (curr = base->next; curr; curr = curr->next)
280 288 count++;
281 289 return count;
282 290 }
283 291
284 292 static void freehunks(struct hunk *l)
285 293 {
286 294 struct hunk *n;
287 295 for (; l; l = n) {
288 296 n = l->next;
289 297 free(l);
290 298 }
291 299 }
292 300
293 301 static PyObject *blocks(PyObject *self, PyObject *args)
294 302 {
295 303 PyObject *sa, *sb, *rl = NULL, *m;
296 304 struct line *a, *b;
297 305 struct hunk l, *h;
298 306 int an, bn, count, pos = 0;
299 307
300 308 l.next = NULL;
301 309
302 310 if (!PyArg_ParseTuple(args, "SS:bdiff", &sa, &sb))
303 311 return NULL;
304 312
305 313 an = splitlines(PyBytes_AsString(sa), PyBytes_Size(sa), &a);
306 314 bn = splitlines(PyBytes_AsString(sb), PyBytes_Size(sb), &b);
307 315
308 316 if (!a || !b)
309 317 goto nomem;
310 318
311 319 count = diff(a, an, b, bn, &l);
312 320 if (count < 0)
313 321 goto nomem;
314 322
315 323 rl = PyList_New(count);
316 324 if (!rl)
317 325 goto nomem;
318 326
319 327 for (h = l.next; h; h = h->next) {
320 328 m = Py_BuildValue("iiii", h->a1, h->a2, h->b1, h->b2);
321 329 PyList_SetItem(rl, pos, m);
322 330 pos++;
323 331 }
324 332
325 333 nomem:
326 334 free(a);
327 335 free(b);
328 336 freehunks(l.next);
329 337 return rl ? rl : PyErr_NoMemory();
330 338 }
331 339
332 340 static PyObject *bdiff(PyObject *self, PyObject *args)
333 341 {
334 342 char *sa, *sb, *rb;
335 343 PyObject *result = NULL;
336 344 struct line *al, *bl;
337 345 struct hunk l, *h;
338 346 int an, bn, count;
339 347 Py_ssize_t len = 0, la, lb;
340 348 PyThreadState *_save;
341 349
342 350 l.next = NULL;
343 351
344 352 if (!PyArg_ParseTuple(args, "s#s#:bdiff", &sa, &la, &sb, &lb))
345 353 return NULL;
346 354
347 355 if (la > UINT_MAX || lb > UINT_MAX) {
348 356 PyErr_SetString(PyExc_ValueError, "bdiff inputs too large");
349 357 return NULL;
350 358 }
351 359
352 360 _save = PyEval_SaveThread();
353 361 an = splitlines(sa, la, &al);
354 362 bn = splitlines(sb, lb, &bl);
355 363 if (!al || !bl)
356 364 goto nomem;
357 365
358 366 count = diff(al, an, bl, bn, &l);
359 367 if (count < 0)
360 368 goto nomem;
361 369
362 370 /* calculate length of output */
363 371 la = lb = 0;
364 372 for (h = l.next; h; h = h->next) {
365 373 if (h->a1 != la || h->b1 != lb)
366 374 len += 12 + bl[h->b1].l - bl[lb].l;
367 375 la = h->a2;
368 376 lb = h->b2;
369 377 }
370 378 PyEval_RestoreThread(_save);
371 379 _save = NULL;
372 380
373 381 result = PyBytes_FromStringAndSize(NULL, len);
374 382
375 383 if (!result)
376 384 goto nomem;
377 385
378 386 /* build binary patch */
379 387 rb = PyBytes_AsString(result);
380 388 la = lb = 0;
381 389
382 390 for (h = l.next; h; h = h->next) {
383 391 if (h->a1 != la || h->b1 != lb) {
384 392 len = bl[h->b1].l - bl[lb].l;
385 393 putbe32((uint32_t)(al[la].l - al->l), rb);
386 394 putbe32((uint32_t)(al[h->a1].l - al->l), rb + 4);
387 395 putbe32((uint32_t)len, rb + 8);
388 396 memcpy(rb + 12, bl[lb].l, len);
389 397 rb += 12 + len;
390 398 }
391 399 la = h->a2;
392 400 lb = h->b2;
393 401 }
394 402
395 403 nomem:
396 404 if (_save)
397 405 PyEval_RestoreThread(_save);
398 406 free(al);
399 407 free(bl);
400 408 freehunks(l.next);
401 409 return result ? result : PyErr_NoMemory();
402 410 }
403 411
404 412 /*
405 413 * If allws != 0, remove all whitespace (' ', \t and \r). Otherwise,
406 414 * reduce whitespace sequences to a single space and trim remaining whitespace
407 415 * from end of lines.
408 416 */
409 417 static PyObject *fixws(PyObject *self, PyObject *args)
410 418 {
411 419 PyObject *s, *result = NULL;
412 420 char allws, c;
413 421 const char *r;
414 422 Py_ssize_t i, rlen, wlen = 0;
415 423 char *w;
416 424
417 425 if (!PyArg_ParseTuple(args, "Sb:fixws", &s, &allws))
418 426 return NULL;
419 427 r = PyBytes_AsString(s);
420 428 rlen = PyBytes_Size(s);
421 429
422 430 w = (char *)malloc(rlen ? rlen : 1);
423 431 if (!w)
424 432 goto nomem;
425 433
426 434 for (i = 0; i != rlen; i++) {
427 435 c = r[i];
428 436 if (c == ' ' || c == '\t' || c == '\r') {
429 437 if (!allws && (wlen == 0 || w[wlen - 1] != ' '))
430 438 w[wlen++] = ' ';
431 439 } else if (c == '\n' && !allws
432 440 && wlen > 0 && w[wlen - 1] == ' ') {
433 441 w[wlen - 1] = '\n';
434 442 } else {
435 443 w[wlen++] = c;
436 444 }
437 445 }
438 446
439 447 result = PyBytes_FromStringAndSize(w, wlen);
440 448
441 449 nomem:
442 450 free(w);
443 451 return result ? result : PyErr_NoMemory();
444 452 }
445 453
446 454
447 455 static char mdiff_doc[] = "Efficient binary diff.";
448 456
449 457 static PyMethodDef methods[] = {
450 458 {"bdiff", bdiff, METH_VARARGS, "calculate a binary diff\n"},
451 459 {"blocks", blocks, METH_VARARGS, "find a list of matching lines\n"},
452 460 {"fixws", fixws, METH_VARARGS, "normalize diff whitespaces\n"},
453 461 {NULL, NULL}
454 462 };
455 463
456 464 #ifdef IS_PY3K
457 465 static struct PyModuleDef bdiff_module = {
458 466 PyModuleDef_HEAD_INIT,
459 467 "bdiff",
460 468 mdiff_doc,
461 469 -1,
462 470 methods
463 471 };
464 472
465 473 PyMODINIT_FUNC PyInit_bdiff(void)
466 474 {
467 475 return PyModule_Create(&bdiff_module);
468 476 }
469 477 #else
470 478 PyMODINIT_FUNC initbdiff(void)
471 479 {
472 480 Py_InitModule3("bdiff", methods, mdiff_doc);
473 481 }
474 482 #endif
475 483
General Comments 0
You need to be logged in to leave comments. Login now