@matheusbsbs / matheus-bagliano / commits / fcb77bc57b
Fork 0

builtin-apply.c: restructure "offset" matching

This restructures code to find matching location with offset in find_offset() function, so that there is need for only one call site of match_fragment() function. There still isn't a change in the logic of the program. Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Jan 19, 2008 at 02:16 UTC fcb77bc57b4d2f63bd4d0c2fd36498f308d28cbe
1 file changed +25 -24
builtin-apply.c
+25 -24
@@ -1452,8 +1452,8 @@ static int find_offset(const char *buf, unsigned long size,
1452 const char *fragment, unsigned long fragsize,
1453 int line, int *lines)
1454 {
1455 - int i;
1456 - unsigned long start, backwards, forwards;
1455 + int i, no_more_backwards, no_more_forwards;
1456 + unsigned long start, backwards, forwards, try;
1457
1458 if (fragsize > size)
1459 return -1;
@@ -1471,32 +1471,44 @@ static int find_offset(const char *buf, unsigned long size,
1471 }
1472 }
1473
1474 - /* Exact line number? */
1475 - if (match_fragment(buf, size, start, fragment, fragsize))
1476 - return start;
1477 -
1474 /*
1475 * There's probably some smart way to do this, but I'll leave
1476 * that to the smart and beautiful people. I'm simple and stupid.
1477 */
1478 backwards = start;
1479 forwards = start;
1480 + try = start;
1481 +
1482 for (i = 0; ; i++) {
1485 - unsigned long try;
1486 - int n;
1483 + no_more_backwards = !backwards;
1484 + no_more_forwards = (forwards + fragsize > size);
1485 +
1486 + if (match_fragment(buf, size, try, fragment, fragsize)) {
1487 + int shift = ((i+1) >> 1);
1488 + if (i & 1)
1489 + shift = -shift;
1490 + *lines = shift;
1491 + return try;
1492 + }
1493 +
1494 + again:
1495 + if (no_more_backwards && no_more_forwards)
1496 + break;
1497
1488 - /* "backward" */
1498 if (i & 1) {
1490 - if (!backwards) {
1491 - if (forwards + fragsize > size)
1492 - break;
1493 - continue;
1499 + if (no_more_backwards) {
1500 + i++;
1501 + goto again;
1502 }
1503 do {
1504 --backwards;
1505 } while (backwards && buf[backwards-1] != '\n');
1506 try = backwards;
1507 } else {
1508 + if (no_more_forwards) {
1509 + i++;
1510 + goto again;
1511 + }
1512 while (forwards + fragsize <= size) {
1513 if (buf[forwards++] == '\n')
1514 break;
@@ -1504,18 +1516,7 @@ static int find_offset(const char *buf, unsigned long size,
1516 try = forwards;
1517 }
1518
1507 - if (!match_fragment(buf, size, try, fragment, fragsize))
1508 - continue;
1509 - n = (i >> 1)+1;
1510 - if (i & 1)
1511 - n = -n;
1512 - *lines = n;
1513 - return try;
1519 }
1515 -
1516 - /*
1517 - * We should start searching forward and backward.
1518 - */
1520 return -1;
1521 }
1522