##// END OF EJS Templates
bdiff: fix latent normalization bug...
Matt Mackall -
r29012:4bd67ae7 stable
parent child Browse files
Show More
@@ -0,0 +1,98
1 # Randomized torture test generation for bdiff
2
3 from __future__ import absolute_import, print_function
4 import random, sys
5 from mercurial import (
6 bdiff,
7 mpatch,
8 )
9
10 def reducetest(a, b):
11 tries = 0
12 reductions = 0
13 print("reducing...")
14 while tries < 1000:
15 a2 = "\n".join(l for l in a.splitlines()
16 if random.randint(0, 100) > 0) + "\n"
17 b2 = "\n".join(l for l in b.splitlines()
18 if random.randint(0, 100) > 0) + "\n"
19 if a2 == a and b2 == b:
20 continue
21 if a2 == b2:
22 continue
23 tries += 1
24
25 try:
26 test1(a, b)
27 except Exception as inst:
28 reductions += 1
29 tries = 0
30 a = a2
31 b = b2
32
33 print("reduced:", reductions, len(a) + len(b),
34 repr(a), repr(b))
35 try:
36 test1(a, b)
37 except Exception as inst:
38 print("failed:", inst)
39
40 sys.exit(0)
41
42 def test1(a, b):
43 d = bdiff.bdiff(a, b)
44 if not d:
45 raise ValueError("empty")
46 c = mpatch.patches(a, [d])
47 if c != b:
48 raise ValueError("bad")
49
50 def testwrap(a, b):
51 try:
52 test1(a, b)
53 return
54 except Exception as inst:
55 pass
56 print("exception:", inst)
57 reducetest(a, b)
58
59 def test(a, b):
60 testwrap(a, b)
61 testwrap(b, a)
62
63 def rndtest(size, noise):
64 a = []
65 src = " aaaaaaaabbbbccd"
66 for x in xrange(size):
67 a.append(src[random.randint(0, len(src) - 1)])
68
69 while True:
70 b = [c for c in a if random.randint(0, 99) > noise]
71 b2 = []
72 for c in b:
73 b2.append(c)
74 while random.randint(0, 99) < noise:
75 b2.append(src[random.randint(0, len(src) - 1)])
76 if b2 != a:
77 break
78
79 a = "\n".join(a) + "\n"
80 b = "\n".join(b2) + "\n"
81
82 test(a, b)
83
84 maxvol = 10000
85 startsize = 2
86 while True:
87 size = startsize
88 count = 0
89 while size < maxvol:
90 print(size)
91 volume = 0
92 while volume < maxvol:
93 rndtest(size, 2)
94 volume += size
95 count += 2
96 size *= 2
97 maxvol *= 4
98 startsize *= 4
@@ -1,472 +1,474
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 = INT_MAX;
107 107 h[i].len = 0;
108 108 }
109 109
110 110 /* add lines to the hash table chains */
111 111 for (i = bn - 1; i >= 0; i--) {
112 112 /* find the equivalence class */
113 113 for (j = b[i].hash & buckets; h[j].pos != INT_MAX;
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 != INT_MAX;
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 = INT_MAX; /* 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 151 int mi = a1, mj = b1, mk = 0, mb = 0, i, j, k;
152 152
153 153 for (i = a1; i < a2; i++) {
154 154 /* skip things before the current block */
155 155 for (j = a[i].n; j < b1; j = b[j].n)
156 156 ;
157 157
158 158 /* loop through all lines match a[i] in b */
159 159 for (; j < b2; 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 168 /* best match so far? */
169 169 if (k > mk) {
170 170 mi = i;
171 171 mj = j;
172 172 mk = k;
173 173 }
174 174 }
175 175 }
176 176
177 177 if (mk) {
178 178 mi = mi - mk + 1;
179 179 mj = mj - mk + 1;
180 180 }
181 181
182 182 /* expand match to include neighboring popular lines */
183 183 while (mi - mb > a1 && mj - mb > b1 &&
184 184 a[mi - mb - 1].e == b[mj - mb - 1].e)
185 185 mb++;
186 186 while (mi + mk < a2 && mj + mk < b2 &&
187 187 a[mi + mk].e == b[mj + mk].e)
188 188 mk++;
189 189
190 190 *omi = mi - mb;
191 191 *omj = mj - mb;
192 192
193 193 return mk + mb;
194 194 }
195 195
196 196 static struct hunk *recurse(struct line *a, struct line *b, struct pos *pos,
197 197 int a1, int a2, int b1, int b2, struct hunk *l)
198 198 {
199 199 int i, j, k;
200 200
201 201 while (1) {
202 202 /* find the longest match in this chunk */
203 203 k = longest_match(a, b, pos, a1, a2, b1, b2, &i, &j);
204 204 if (!k)
205 205 return l;
206 206
207 207 /* and recurse on the remaining chunks on either side */
208 208 l = recurse(a, b, pos, a1, i, b1, j, l);
209 209 if (!l)
210 210 return NULL;
211 211
212 212 l->next = (struct hunk *)malloc(sizeof(struct hunk));
213 213 if (!l->next)
214 214 return NULL;
215 215
216 216 l = l->next;
217 217 l->a1 = i;
218 218 l->a2 = i + k;
219 219 l->b1 = j;
220 220 l->b2 = j + k;
221 221 l->next = NULL;
222 222
223 223 /* tail-recursion didn't happen, so do equivalent iteration */
224 224 a1 = i + k;
225 225 b1 = j + k;
226 226 }
227 227 }
228 228
229 229 static int diff(struct line *a, int an, struct line *b, int bn,
230 230 struct hunk *base)
231 231 {
232 232 struct hunk *curr;
233 233 struct pos *pos;
234 234 int t, count = 0;
235 235
236 236 /* allocate and fill arrays */
237 237 t = equatelines(a, an, b, bn);
238 238 pos = (struct pos *)calloc(bn ? bn : 1, sizeof(struct pos));
239 239
240 240 if (pos && t) {
241 241 /* generate the matching block list */
242 242
243 243 curr = recurse(a, b, pos, 0, an, 0, bn, base);
244 244 if (!curr)
245 245 return -1;
246 246
247 247 /* sentinel end hunk */
248 248 curr->next = (struct hunk *)malloc(sizeof(struct hunk));
249 249 if (!curr->next)
250 250 return -1;
251 251 curr = curr->next;
252 252 curr->a1 = curr->a2 = an;
253 253 curr->b1 = curr->b2 = bn;
254 254 curr->next = NULL;
255 255 }
256 256
257 257 free(pos);
258 258
259 259 /* normalize the hunk list, try to push each hunk towards the end */
260 260 for (curr = base->next; curr; curr = curr->next) {
261 261 struct hunk *next = curr->next;
262 262
263 263 if (!next)
264 264 break;
265 265
266 266 if (curr->a2 == next->a1 || curr->b2 == next->b1)
267 267 while (curr->a2 < an && curr->b2 < bn
268 && next->a1 < next->a2
269 && next->b1 < next->b2
268 270 && !cmp(a + curr->a2, b + curr->b2)) {
269 271 curr->a2++;
270 272 next->a1++;
271 273 curr->b2++;
272 274 next->b1++;
273 275 }
274 276 }
275 277
276 278 for (curr = base->next; curr; curr = curr->next)
277 279 count++;
278 280 return count;
279 281 }
280 282
281 283 static void freehunks(struct hunk *l)
282 284 {
283 285 struct hunk *n;
284 286 for (; l; l = n) {
285 287 n = l->next;
286 288 free(l);
287 289 }
288 290 }
289 291
290 292 static PyObject *blocks(PyObject *self, PyObject *args)
291 293 {
292 294 PyObject *sa, *sb, *rl = NULL, *m;
293 295 struct line *a, *b;
294 296 struct hunk l, *h;
295 297 int an, bn, count, pos = 0;
296 298
297 299 l.next = NULL;
298 300
299 301 if (!PyArg_ParseTuple(args, "SS:bdiff", &sa, &sb))
300 302 return NULL;
301 303
302 304 an = splitlines(PyBytes_AsString(sa), PyBytes_Size(sa), &a);
303 305 bn = splitlines(PyBytes_AsString(sb), PyBytes_Size(sb), &b);
304 306
305 307 if (!a || !b)
306 308 goto nomem;
307 309
308 310 count = diff(a, an, b, bn, &l);
309 311 if (count < 0)
310 312 goto nomem;
311 313
312 314 rl = PyList_New(count);
313 315 if (!rl)
314 316 goto nomem;
315 317
316 318 for (h = l.next; h; h = h->next) {
317 319 m = Py_BuildValue("iiii", h->a1, h->a2, h->b1, h->b2);
318 320 PyList_SetItem(rl, pos, m);
319 321 pos++;
320 322 }
321 323
322 324 nomem:
323 325 free(a);
324 326 free(b);
325 327 freehunks(l.next);
326 328 return rl ? rl : PyErr_NoMemory();
327 329 }
328 330
329 331 static PyObject *bdiff(PyObject *self, PyObject *args)
330 332 {
331 333 char *sa, *sb, *rb;
332 334 PyObject *result = NULL;
333 335 struct line *al, *bl;
334 336 struct hunk l, *h;
335 337 int an, bn, count;
336 338 Py_ssize_t len = 0, la, lb;
337 339 PyThreadState *_save;
338 340
339 341 l.next = NULL;
340 342
341 343 if (!PyArg_ParseTuple(args, "s#s#:bdiff", &sa, &la, &sb, &lb))
342 344 return NULL;
343 345
344 346 if (la > UINT_MAX || lb > UINT_MAX) {
345 347 PyErr_SetString(PyExc_ValueError, "bdiff inputs too large");
346 348 return NULL;
347 349 }
348 350
349 351 _save = PyEval_SaveThread();
350 352 an = splitlines(sa, la, &al);
351 353 bn = splitlines(sb, lb, &bl);
352 354 if (!al || !bl)
353 355 goto nomem;
354 356
355 357 count = diff(al, an, bl, bn, &l);
356 358 if (count < 0)
357 359 goto nomem;
358 360
359 361 /* calculate length of output */
360 362 la = lb = 0;
361 363 for (h = l.next; h; h = h->next) {
362 364 if (h->a1 != la || h->b1 != lb)
363 365 len += 12 + bl[h->b1].l - bl[lb].l;
364 366 la = h->a2;
365 367 lb = h->b2;
366 368 }
367 369 PyEval_RestoreThread(_save);
368 370 _save = NULL;
369 371
370 372 result = PyBytes_FromStringAndSize(NULL, len);
371 373
372 374 if (!result)
373 375 goto nomem;
374 376
375 377 /* build binary patch */
376 378 rb = PyBytes_AsString(result);
377 379 la = lb = 0;
378 380
379 381 for (h = l.next; h; h = h->next) {
380 382 if (h->a1 != la || h->b1 != lb) {
381 383 len = bl[h->b1].l - bl[lb].l;
382 384 putbe32((uint32_t)(al[la].l - al->l), rb);
383 385 putbe32((uint32_t)(al[h->a1].l - al->l), rb + 4);
384 386 putbe32((uint32_t)len, rb + 8);
385 387 memcpy(rb + 12, bl[lb].l, len);
386 388 rb += 12 + len;
387 389 }
388 390 la = h->a2;
389 391 lb = h->b2;
390 392 }
391 393
392 394 nomem:
393 395 if (_save)
394 396 PyEval_RestoreThread(_save);
395 397 free(al);
396 398 free(bl);
397 399 freehunks(l.next);
398 400 return result ? result : PyErr_NoMemory();
399 401 }
400 402
401 403 /*
402 404 * If allws != 0, remove all whitespace (' ', \t and \r). Otherwise,
403 405 * reduce whitespace sequences to a single space and trim remaining whitespace
404 406 * from end of lines.
405 407 */
406 408 static PyObject *fixws(PyObject *self, PyObject *args)
407 409 {
408 410 PyObject *s, *result = NULL;
409 411 char allws, c;
410 412 const char *r;
411 413 Py_ssize_t i, rlen, wlen = 0;
412 414 char *w;
413 415
414 416 if (!PyArg_ParseTuple(args, "Sb:fixws", &s, &allws))
415 417 return NULL;
416 418 r = PyBytes_AsString(s);
417 419 rlen = PyBytes_Size(s);
418 420
419 421 w = (char *)malloc(rlen ? rlen : 1);
420 422 if (!w)
421 423 goto nomem;
422 424
423 425 for (i = 0; i != rlen; i++) {
424 426 c = r[i];
425 427 if (c == ' ' || c == '\t' || c == '\r') {
426 428 if (!allws && (wlen == 0 || w[wlen - 1] != ' '))
427 429 w[wlen++] = ' ';
428 430 } else if (c == '\n' && !allws
429 431 && wlen > 0 && w[wlen - 1] == ' ') {
430 432 w[wlen - 1] = '\n';
431 433 } else {
432 434 w[wlen++] = c;
433 435 }
434 436 }
435 437
436 438 result = PyBytes_FromStringAndSize(w, wlen);
437 439
438 440 nomem:
439 441 free(w);
440 442 return result ? result : PyErr_NoMemory();
441 443 }
442 444
443 445
444 446 static char mdiff_doc[] = "Efficient binary diff.";
445 447
446 448 static PyMethodDef methods[] = {
447 449 {"bdiff", bdiff, METH_VARARGS, "calculate a binary diff\n"},
448 450 {"blocks", blocks, METH_VARARGS, "find a list of matching lines\n"},
449 451 {"fixws", fixws, METH_VARARGS, "normalize diff whitespaces\n"},
450 452 {NULL, NULL}
451 453 };
452 454
453 455 #ifdef IS_PY3K
454 456 static struct PyModuleDef bdiff_module = {
455 457 PyModuleDef_HEAD_INIT,
456 458 "bdiff",
457 459 mdiff_doc,
458 460 -1,
459 461 methods
460 462 };
461 463
462 464 PyMODINIT_FUNC PyInit_bdiff(void)
463 465 {
464 466 return PyModule_Create(&bdiff_module);
465 467 }
466 468 #else
467 469 PyMODINIT_FUNC initbdiff(void)
468 470 {
469 471 Py_InitModule3("bdiff", methods, mdiff_doc);
470 472 }
471 473 #endif
472 474
General Comments 0
You need to be logged in to leave comments. Login now