merge new diff implementation from the git.gameoftrees.org diff.git repository This new diff implementation was started by Neels Hofmeyr during the u2k20 hackathon and now replaces diffreg.c code lifted from the OpenBSD base system. The integration of this code into Got was done by me. Got now uses the patience diff algorithm by default. The diff.git repository will remain the primary repository for the diff code, which already compiles and runs on other operating systems such as Linux. Any fixes and improvements for files inherited from the diff.git repository should be written against that repository and synced to got.git afterwards.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513
diff --git a/Makefile.inc b/Makefile.inc
index cbc7171..328c4a1 100644
--- a/Makefile.inc
+++ b/Makefile.inc
@@ -2,6 +2,7 @@ CPPFLAGS += -DGOT_LIBEXECDIR=${LIBEXECDIR} -DGOT_VERSION=${GOT_VERSION}
#CFLAGS += -DGOT_PACK_NO_MMAP
#CFLAGS += -DGOT_NO_OBJ_CACHE
#CFLAGS += -DGOT_OBJ_CACHE_DEBUG
+#CFLAGS += -DGOT_DIFF_NO_MMAP
.if "${GOT_RELEASE}" == "Yes"
PREFIX ?= /usr/local
diff --git a/got/Makefile b/got/Makefile
index 0eb11ed..29c7f19 100644
--- a/got/Makefile
+++ b/got/Makefile
@@ -9,7 +9,11 @@ SRCS= got.c blame.c commit_graph.c delta.c diff.c \
privsep.c reference.c repository.c sha1.c worktree.c \
inflate.c buf.c rcsutil.c diff3.c lockfile.c \
deflate.c object_create.c delta_cache.c fetch.c \
- gotconfig.c
+ gotconfig.c diff_main.c diff_atomize_text.c \
+ diff_myers.c diff_output.c diff_output_plain.c \
+ diff_output_unidiff.c diff_output_edscript.c \
+ diff_patience.c
+
MAN = ${PROG}.1 got-worktree.5 git-repository.5 got.conf.5
CPPFLAGS = -I${.CURDIR}/../include -I${.CURDIR}/../lib
diff --git a/got/got.c b/got/got.c
index 052e546..dfa05ac 100644
--- a/got/got.c
+++ b/got/got.c
@@ -3141,8 +3141,8 @@ diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
while (path[0] == '/')
path++;
- err = got_diff_blob(blob1, blob2, path, path, diff_context,
- ignore_whitespace, stdout);
+ err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
+ diff_context, ignore_whitespace, stdout);
done:
if (blob1)
got_object_blob_close(blob1);
@@ -3172,6 +3172,8 @@ diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
arg.diff_context = diff_context;
arg.ignore_whitespace = ignore_whitespace;
arg.outfile = stdout;
+ arg.line_offsets = NULL;
+ arg.nlines = 0;
while (path[0] == '/')
path++;
err = got_diff_tree(tree1, tree2, path, path, repo,
@@ -4000,9 +4002,9 @@ print_diff(void *arg, unsigned char status, unsigned char staged_status,
default:
return got_error(GOT_ERR_FILE_STATUS);
}
- return got_diff_objects_as_blobs(blob_id, staged_blob_id,
- label1, label2, a->diff_context, a->ignore_whitespace,
- a->repo, stdout);
+ return got_diff_objects_as_blobs(NULL, NULL, blob_id,
+ staged_blob_id, label1, label2, a->diff_context,
+ a->ignore_whitespace, a->repo, stdout);
}
if (staged_status == GOT_STATUS_ADD ||
@@ -4264,17 +4266,18 @@ cmd_diff(int argc, char *argv[])
switch (type1) {
case GOT_OBJ_TYPE_BLOB:
- error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
- diff_context, ignore_whitespace, repo, stdout);
+ error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
+ NULL, NULL, diff_context, ignore_whitespace, repo,
+ stdout);
break;
case GOT_OBJ_TYPE_TREE:
- error = got_diff_objects_as_trees(id1, id2, "", "",
- diff_context, ignore_whitespace, repo, stdout);
+ error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
+ "", "", diff_context, ignore_whitespace, repo, stdout);
break;
case GOT_OBJ_TYPE_COMMIT:
printf("diff %s %s\n", label1, label2);
- error = got_diff_objects_as_commits(id1, id2, diff_context,
- ignore_whitespace, repo, stdout);
+ error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
+ diff_context, ignore_whitespace, repo, stdout);
break;
default:
error = got_error(GOT_ERR_OBJ_TYPE);
diff --git a/include/got_diff.h b/include/got_diff.h
index fd8185f..6e5a0c4 100644
--- a/include/got_diff.h
+++ b/include/got_diff.h
@@ -21,9 +21,12 @@
* If a label is NULL, use the blob's SHA1 checksum instead.
* The number of context lines to show in the diff must be specified as well.
* Whitespace differences may optionally be ignored.
+ * If not NULL, the two initial output arguments will be populated with an
+ * array of line offsets for, and the number of lines in, the unidiff text.
*/
-const struct got_error *got_diff_blob(struct got_blob_object *,
- struct got_blob_object *, const char *, const char *, int, int, FILE *);
+const struct got_error *got_diff_blob(off_t **, size_t *,
+ struct got_blob_object *, struct got_blob_object *,
+ const char *, const char *, int, int, FILE *);
/*
* Compute the differences between a blob and a file and write unified diff
@@ -61,6 +64,21 @@ struct got_diff_blob_output_unidiff_arg {
FILE *outfile; /* Unidiff text will be written here. */
int diff_context; /* Sets the number of context lines. */
int ignore_whitespace; /* Ignore whitespace differences. */
+
+ /*
+ * The number of lines contained in produced unidiff text output,
+ * and an array of byte offsets to each line. May be initialized to
+ * zero and NULL to ignore line offsets. If not NULL, then the line
+ * offsets array will be populated. Optionally, the array can be
+ * pre-populated with line offsets, with nlines > 0 indicating
+ * the length of the pre-populated array. This is useful if the
+ * output file already contains some lines of text.
+ * The array will be grown as needed to accomodate additional line
+ * offsets, and the last offset found in a pre-populated array will
+ * be added to all subsequent offsets.
+ */
+ size_t nlines;
+ off_t *line_offsets; /* Dispose of with free(3) when done. */
};
const struct got_error *got_diff_blob_output_unidiff(void *,
struct got_blob_object *, struct got_blob_object *,
@@ -105,9 +123,12 @@ const struct got_error *got_diff_tree_collect_changed_paths(void *,
* the diff output. If a label is NULL, use the blob's SHA1 checksum instead.
* The number of context lines to show in the diff must be specified as well.
* Write unified diff text to the provided output FILE.
+ * If not NULL, the two initial output arguments will be populated with an
+ * array of line offsets for, and the number of lines in, the unidiff text.
*/
-const struct got_error *got_diff_objects_as_blobs(struct got_object_id *,
- struct got_object_id *, const char *, const char *, int, int,
+const struct got_error *got_diff_objects_as_blobs(off_t **, size_t *,
+ struct got_object_id *, struct got_object_id *,
+ const char *, const char *, int, int,
struct got_repository *, FILE *);
/*
@@ -116,17 +137,22 @@ const struct got_error *got_diff_objects_as_blobs(struct got_object_id *,
* the trees. If a label is NULL, use the blob's SHA1 checksum instead.
* The number of context lines to show in diffs must be specified.
* Write unified diff text to the provided output FILE.
+ * If not NULL, the two initial output arguments will be populated with an
+ * array of line offsets for, and the number of lines in, the unidiff text.
*/
-const struct got_error *got_diff_objects_as_trees(struct got_object_id *,
- struct got_object_id *, char *, char *, int, int,
- struct got_repository *, FILE *);
+const struct got_error *got_diff_objects_as_trees(off_t **, size_t *,
+ struct got_object_id *, struct got_object_id *, char *, char *,
+ int, int, struct got_repository *, FILE *);
/*
* Diff two objects, assuming both objects are commits.
* The number of context lines to show in diffs must be specified.
* Write unified diff text to the provided output FILE.
+ * If not NULL, the two initial output arguments will be populated with an
+ * array of line offsets for, and the number of lines in, the unidiff text.
*/
-const struct got_error *got_diff_objects_as_commits(struct got_object_id *,
- struct got_object_id *, int, int, struct got_repository *, FILE *);
+const struct got_error *got_diff_objects_as_commits(off_t **, size_t *,
+ struct got_object_id *, struct got_object_id *, int, int,
+ struct got_repository *, FILE *);
#define GOT_DIFF_MAX_CONTEXT 64
diff --git a/lib/arraylist.h b/lib/arraylist.h
new file mode 100644
index 0000000..112da0c
--- /dev/null
+++ b/lib/arraylist.h
@@ -0,0 +1,115 @@
+/* Auto-reallocating array for arbitrary member types. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/* Usage:
+ *
+ * ARRAYLIST(any_type_t) list;
+ * // OR
+ * typedef ARRAYLIST(any_type_t) any_type_list_t;
+ * any_type_list_t list;
+ *
+ * // pass the number of (at first unused) members to add on each realloc:
+ * ARRAYLIST_INIT(list, 128);
+ * any_type_t *x;
+ * while (bar) {
+ * // This enlarges the allocated array as needed;
+ * // list.head may change due to realloc:
+ * ARRAYLIST_ADD(x, list);
+ * if (!x)
+ * return ENOMEM;
+ * *x = random_foo_value;
+ * }
+ * for (i = 0; i < list.len; i++)
+ * printf("%s", foo_to_str(list.head[i]));
+ * ARRAYLIST_FREE(list);
+ */
+#define ARRAYLIST(MEMBER_TYPE) \
+ struct { \
+ MEMBER_TYPE *head; \
+ MEMBER_TYPE *p; \
+ unsigned int len; \
+ unsigned int allocated; \
+ unsigned int alloc_blocksize; \
+ }
+
+#define ARRAYLIST_INIT(ARRAY_LIST, ALLOC_BLOCKSIZE) do { \
+ (ARRAY_LIST).head = NULL; \
+ (ARRAY_LIST).len = 0; \
+ (ARRAY_LIST).allocated = 0; \
+ (ARRAY_LIST).alloc_blocksize = ALLOC_BLOCKSIZE; \
+ } while(0)
+
+#define ARRAYLIST_ADD(NEW_ITEM_P, ARRAY_LIST) do { \
+ if ((ARRAY_LIST).len && !(ARRAY_LIST).allocated) { \
+ NEW_ITEM_P = NULL; \
+ break; \
+ } \
+ if ((ARRAY_LIST).head == NULL \
+ || (ARRAY_LIST).allocated < (ARRAY_LIST).len + 1) { \
+ (ARRAY_LIST).p = recallocarray((ARRAY_LIST).head, \
+ (ARRAY_LIST).len, \
+ (ARRAY_LIST).allocated + \
+ ((ARRAY_LIST).alloc_blocksize ? : 8), \
+ sizeof(*(ARRAY_LIST).head)); \
+ if ((ARRAY_LIST).p == NULL) { \
+ NEW_ITEM_P = NULL; \
+ break; \
+ } \
+ (ARRAY_LIST).allocated += \
+ (ARRAY_LIST).alloc_blocksize ? : 8; \
+ (ARRAY_LIST).head = (ARRAY_LIST).p; \
+ (ARRAY_LIST).p = NULL; \
+ }; \
+ if ((ARRAY_LIST).head == NULL \
+ || (ARRAY_LIST).allocated < (ARRAY_LIST).len + 1) { \
+ NEW_ITEM_P = NULL; \
+ break; \
+ } \
+ (NEW_ITEM_P) = &(ARRAY_LIST).head[(ARRAY_LIST).len]; \
+ (ARRAY_LIST).len++; \
+ } while (0)
+
+#define ARRAYLIST_INSERT(NEW_ITEM_P, ARRAY_LIST, AT_IDX) do { \
+ int _at_idx = (AT_IDX); \
+ ARRAYLIST_ADD(NEW_ITEM_P, ARRAY_LIST); \
+ if ((NEW_ITEM_P) \
+ && _at_idx >= 0 \
+ && _at_idx < (ARRAY_LIST).len) { \
+ memmove(&(ARRAY_LIST).head[_at_idx + 1], \
+ &(ARRAY_LIST).head[_at_idx], \
+ ((ARRAY_LIST).len - 1 - _at_idx) \
+ * sizeof(*(ARRAY_LIST).head)); \
+ (NEW_ITEM_P) = &(ARRAY_LIST).head[_at_idx]; \
+ }; \
+ } while (0)
+
+#define ARRAYLIST_CLEAR(ARRAY_LIST) \
+ (ARRAY_LIST).len = 0
+
+#define ARRAYLIST_FREE(ARRAY_LIST) \
+ do { \
+ if ((ARRAY_LIST).head && (ARRAY_LIST).allocated) \
+ free((ARRAY_LIST).head); \
+ ARRAYLIST_INIT(ARRAY_LIST, (ARRAY_LIST).alloc_blocksize); \
+ } while(0)
+
+#define ARRAYLIST_FOREACH(ITEM_P, ARRAY_LIST) \
+ for ((ITEM_P) = (ARRAY_LIST).head; \
+ (ITEM_P) - (ARRAY_LIST).head < (ARRAY_LIST).len; \
+ (ITEM_P)++)
+
+#define ARRAYLIST_IDX(ITEM_P, ARRAY_LIST) ((ITEM_P) - (ARRAY_LIST).head)
diff --git a/lib/blame.c b/lib/blame.c
index f8f1b5e..6325894 100644
--- a/lib/blame.c
+++ b/lib/blame.c
@@ -15,10 +15,12 @@
*/
#include <sys/queue.h>
+#include <sys/mman.h>
#include <sys/stat.h>
#include <sha1.h>
#include <string.h>
+#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
@@ -38,6 +40,10 @@
#include "got_lib_object.h"
#include "got_lib_diff.h"
+#ifndef MAX
+#define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
+#endif
+
struct got_blame_line {
int annotated;
struct got_object_id id;
@@ -45,6 +51,10 @@ struct got_blame_line {
struct got_blame {
FILE *f;
+ char *map;
+ struct diff_data left_data;
+ struct diff_data right_data;
+ const struct diff_config *cfg;
size_t filesize;
int nlines;
int nannotated;
@@ -77,22 +87,33 @@ annotate_line(struct got_blame *blame, int lineno, struct got_object_id *id,
}
static const struct got_error *
-blame_changes(struct got_blame *blame, struct got_diff_changes *changes,
+blame_changes(struct got_blame *blame, struct diff_result *diff_result,
struct got_object_id *commit_id,
const struct got_error *(*cb)(void *, int, int, struct got_object_id *),
void *arg)
{
const struct got_error *err = NULL;
- struct got_diff_change *change;
+ int i;
- SIMPLEQ_FOREACH(change, &changes->entries, entry) {
- int c = change->cv.c;
- int d = change->cv.d;
- int new_lineno = (c < d ? c : d);
- int new_length = (c < d ? d - c + 1 : (c == d ? 1 : 0));
+ for (i = 0; i < diff_result->chunks.len; i++) {
+ struct diff_chunk *c = diff_chunk_get(diff_result, i);
+ unsigned int right_start, right_count;
+ int lineno, len;
int ln;
- for (ln = new_lineno; ln < new_lineno + new_length; ln++) {
+ if (diff_chunk_get_left_count(c) != 0)
+ continue;
+
+ len = diff_chunk_get_right_count(c);
+ if (len == 0)
+ continue;
+
+ right_start = diff_chunk_get_right_start(c, diff_result, 0);
+ right_count = diff_chunk_get_right_count(c);
+
+ lineno = right_start + 1;
+ len = right_count;
+ for (ln = lineno; ln < lineno + len; ln++) {
err = annotate_line(blame, ln, commit_id, cb, arg);
if (err)
return err;
@@ -115,7 +136,7 @@ blame_commit(struct got_blame *blame, struct got_object_id *parent_id,
struct got_object_id *obj_id = NULL;
struct got_commit_object *commit = NULL;
struct got_blob_object *blob = NULL;
- struct got_diff_changes *changes = NULL;
+ struct got_diffreg_result *diffreg_result = NULL;
err = got_object_open_as_commit(&commit, repo, parent_id);
if (err)
@@ -146,17 +167,25 @@ blame_commit(struct got_blame *blame, struct got_object_id *parent_id,
goto done;
}
- err = got_diff_blob_file_lines_changed(&changes, blob, blame->f,
- blame->filesize);
+ diff_data_free(&blame->left_data);
+ memset(&blame->left_data, 0, sizeof(blame->left_data));
+ err = got_diff_blob_prepared_file(&diffreg_result, &blame->left_data,
+ blob, &blame->right_data, blame->f, blame->map, blame->filesize,
+ blame->cfg, 0);
if (err)
goto done;
- if (changes) {
- err = blame_changes(blame, changes, id, cb, arg);
- got_diff_free_changes(changes);
+ if (diffreg_result->result->chunks.len > 0) {
+ err = blame_changes(blame, diffreg_result->result, id, cb, arg);
} else if (cb)
err = cb(arg, blame->nlines, -1, id);
done:
+ if (diffreg_result) {
+ const struct got_error *free_err;
+ free_err = got_diffreg_result_free_left(diffreg_result);
+ if (free_err && err == NULL)
+ err = free_err;
+ }
if (commit)
got_object_commit_close(commit);
free(obj_id);
@@ -172,7 +201,11 @@ blame_close(struct got_blame *blame)
{
const struct got_error *err = NULL;
- if (blame->f && fclose(blame->f) != 0)
+ diff_data_free(&blame->left_data);
+ diff_data_free(&blame->right_data);
+ if (blame->map && munmap(blame->map, blame->filesize) == -1)
+ err = got_error_from_errno("munmap");
+ if (blame->f && fclose(blame->f) != 0 && err == NULL)
err = got_error_from_errno("fclose");
free(blame->lines);
free(blame);
@@ -191,7 +224,8 @@ blame_open(struct got_blame **blamep, const char *path,
struct got_blob_object *blob = NULL;
struct got_blame *blame = NULL;
struct got_object_id *id = NULL, *pid = NULL;
- int lineno;
+ int lineno, created;
+ size_t size;
struct got_commit_graph *graph = NULL;
*blamep = NULL;
@@ -227,6 +261,12 @@ blame_open(struct got_blame **blamep, const char *path,
if (err || blame->nlines == 0)
goto done;
+ blame->cfg = got_diff_get_config(GOT_DIFF_ALGORITHM_PATIENCE),
+ err = got_diff_prepare_file(&blame->f, &blame->map, &created, &size,
+ &blame->right_data, blame->cfg, 0);
+ if (err)
+ goto done;
+
/* Don't include \n at EOF in the blame line count. */
if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
blame->nlines--;
diff --git a/lib/diff.c b/lib/diff.c
index 7e5ee06..8e431b8 100644
--- a/lib/diff.c
+++ b/lib/diff.c
@@ -17,6 +17,7 @@
#include <sys/queue.h>
#include <sys/stat.h>
+#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -39,27 +40,47 @@
#include "got_lib_object.h"
static const struct got_error *
-diff_blobs(struct got_blob_object *blob1, struct got_blob_object *blob2,
+add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
+{
+ off_t *p;
+
+ p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
+ if (p == NULL)
+ return got_error_from_errno("reallocarray");
+ *line_offsets = p;
+ (*line_offsets)[*nlines] = off;
+ (*nlines)++;
+ return NULL;
+}
+
+static const struct got_error *
+diff_blobs(off_t **line_offsets, size_t *nlines,
+ struct got_diffreg_result **resultp, struct got_blob_object *blob1,
+ struct got_blob_object *blob2,
const char *label1, const char *label2, mode_t mode1, mode_t mode2,
- int diff_context, int ignore_whitespace, FILE *outfile,
- struct got_diff_changes *changes)
+ int diff_context, int ignore_whitespace, FILE *outfile)
{
- struct got_diff_state ds;
- struct got_diff_args args;
- const struct got_error *err = NULL;
+ const struct got_error *err = NULL, *free_err;
FILE *f1 = NULL, *f2 = NULL;
char hex1[SHA1_DIGEST_STRING_LENGTH];
char hex2[SHA1_DIGEST_STRING_LENGTH];
char *idstr1 = NULL, *idstr2 = NULL;
size_t size1, size2;
- int res, flags = 0;
+ struct got_diffreg_result *result;
+ off_t outoff = 0;
+ int n;
+
+ if (line_offsets && *line_offsets && *nlines > 0)
+ outoff = (*line_offsets)[*nlines - 1];
+
+ if (resultp)
+ *resultp = NULL;
if (blob1) {
f1 = got_opentemp();
if (f1 == NULL)
return got_error_from_errno("got_opentemp");
- } else
- flags |= D_EMPTY1;
+ }
if (blob2) {
f2 = got_opentemp();
@@ -68,8 +89,7 @@ diff_blobs(struct got_blob_object *blob1, struct got_blob_object *blob2,
fclose(f1);
return err;
}
- } else
- flags |= D_EMPTY2;
+ }
size1 = 0;
if (blob1) {
@@ -91,27 +111,6 @@ diff_blobs(struct got_blob_object *blob1, struct got_blob_object *blob2,
} else
idstr2 = "/dev/null";
- memset(&ds, 0, sizeof(ds));
- /* XXX should stat buffers be passed in args instead of ds? */
- ds.stb1.st_mode = S_IFREG;
- if (blob1)
- ds.stb1.st_size = size1;
- ds.stb1.st_mtime = 0; /* XXX */
-
- ds.stb2.st_mode = S_IFREG;
- if (blob2)
- ds.stb2.st_size = size2;
- ds.stb2.st_mtime = 0; /* XXX */
-
- memset(&args, 0, sizeof(args));
- args.diff_format = D_UNIFIED;
- args.label[0] = label1 ? label1 : idstr1;
- args.label[1] = label2 ? label2 : idstr2;
- args.diff_context = diff_context;
- flags |= D_PROTOTYPE;
- if (ignore_whitespace)
- flags |= D_IGNOREBLANKS;
-
if (outfile) {
char *modestr1 = NULL, *modestr2 = NULL;
int modebits;
@@ -137,15 +136,52 @@ diff_blobs(struct got_blob_object *blob1, struct got_blob_object *blob2,
goto done;
}
}
- fprintf(outfile, "blob - %s%s\n", idstr1,
+ n = fprintf(outfile, "blob - %s%s\n", idstr1,
modestr1 ? modestr1 : "");
- fprintf(outfile, "blob + %s%s\n", idstr2,
+ if (n < 0)
+ goto done;
+ outoff += n;
+ if (line_offsets) {
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
+ }
+
+ n = fprintf(outfile, "blob + %s%s\n", idstr2,
modestr2 ? modestr2 : "");
+ if (n < 0)
+ goto done;
+ outoff += n;
+ if (line_offsets) {
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
+ }
+
free(modestr1);
free(modestr2);
}
- err = got_diffreg(&res, f1, f2, flags, &args, &ds, outfile, changes);
- got_diff_state_free(&ds);
+ err = got_diffreg(&result, f1, f2, GOT_DIFF_ALGORITHM_PATIENCE,
+ ignore_whitespace);
+ if (err)
+ goto done;
+
+ if (outfile) {
+ err = got_diffreg_output(line_offsets, nlines, result, f1, f2,
+ label1 ? label1 : idstr1,
+ label2 ? label2 : idstr2,
+ GOT_DIFF_OUTPUT_UNIDIFF, diff_context, outfile);
+ if (err)
+ goto done;
+ }
+
+ if (resultp && err == NULL)
+ *resultp = result;
+ else {
+ free_err = got_diffreg_result_free(result);
+ if (free_err && err == NULL)
+ err = free_err;
+ }
done:
if (f1 && fclose(f1) != 0 && err == NULL)
err = got_error_from_errno("fclose");
@@ -162,45 +198,35 @@ got_diff_blob_output_unidiff(void *arg, struct got_blob_object *blob1,
{
struct got_diff_blob_output_unidiff_arg *a = arg;
- return diff_blobs(blob1, blob2, label1, label2, mode1, mode2,
- a->diff_context, a->ignore_whitespace, a->outfile, NULL);
+ return diff_blobs(&a->line_offsets, &a->nlines, NULL,
+ blob1, blob2, label1, label2, mode1, mode2, a->diff_context,
+ a->ignore_whitespace, a->outfile);
}
const struct got_error *
-got_diff_blob(struct got_blob_object *blob1, struct got_blob_object *blob2,
+got_diff_blob(off_t **line_offsets, size_t *nlines,
+ struct got_blob_object *blob1, struct got_blob_object *blob2,
const char *label1, const char *label2, int diff_context,
int ignore_whitespace, FILE *outfile)
{
- return diff_blobs(blob1, blob2, label1, label2, 0, 0, diff_context,
- ignore_whitespace, outfile, NULL);
-}
-
-static const struct got_error *
-alloc_changes(struct got_diff_changes **changes)
-{
- *changes = calloc(1, sizeof(**changes));
- if (*changes == NULL)
- return got_error_from_errno("calloc");
- SIMPLEQ_INIT(&(*changes)->entries);
- return NULL;
+ return diff_blobs(line_offsets, nlines, NULL, blob1, blob2,
+ label1, label2, 0, 0, diff_context, ignore_whitespace, outfile);
}
static const struct got_error *
-diff_blob_file(struct got_diff_changes **changes,
+diff_blob_file(struct got_diffreg_result **resultp,
struct got_blob_object *blob1, const char *label1, FILE *f2, size_t size2,
const char *label2, int diff_context, int ignore_whitespace, FILE *outfile)
{
- struct got_diff_state ds;
- struct got_diff_args args;
- const struct got_error *err = NULL;
+ const struct got_error *err = NULL, *free_err;
FILE *f1 = NULL;
char hex1[SHA1_DIGEST_STRING_LENGTH];
char *idstr1 = NULL;
size_t size1;
- int res, flags = 0;
+ struct got_diffreg_result *result = NULL;
- if (changes)
- *changes = NULL;
+ if (resultp)
+ *resultp = NULL;
size1 = 0;
if (blob1) {
@@ -213,46 +239,35 @@ diff_blob_file(struct got_diff_changes **changes,
if (err)
goto done;
} else {
- flags |= D_EMPTY1;
idstr1 = "/dev/null";
}
- if (f2 == NULL)
- flags |= D_EMPTY2;
-
- memset(&ds, 0, sizeof(ds));
- /* XXX should stat buffers be passed in args instead of ds? */
- ds.stb1.st_mode = S_IFREG;
- if (blob1)
- ds.stb1.st_size = size1;
- ds.stb1.st_mtime = 0; /* XXX */
-
- ds.stb2.st_mode = S_IFREG;
- ds.stb2.st_size = size2;
- ds.stb2.st_mtime = 0; /* XXX */
-
- memset(&args, 0, sizeof(args));
- args.diff_format = D_UNIFIED;
- args.label[0] = label2;
- args.label[1] = label2;
- args.diff_context = diff_context;
- flags |= D_PROTOTYPE;
- if (ignore_whitespace)
- flags |= D_IGNOREBLANKS;
-
if (outfile) {
fprintf(outfile, "blob - %s\n", label1 ? label1 : idstr1);
fprintf(outfile, "file + %s\n",
f2 == NULL ? "/dev/null" : label2);
}
- if (changes) {
- err = alloc_changes(changes);
+
+ err = got_diffreg(&result, f1, f2, GOT_DIFF_ALGORITHM_PATIENCE,
+ ignore_whitespace);
+ if (err)
+ goto done;
+
+ if (outfile) {
+ err = got_diffreg_output(NULL, NULL, result, f1, f2,
+ label2, label2, GOT_DIFF_OUTPUT_UNIDIFF, diff_context,
+ outfile);
if (err)
- return err;
+ goto done;
+ }
+
+ if (resultp && err == NULL)
+ *resultp = result;
+ else if (result) {
+ free_err = got_diffreg_result_free(result);
+ if (free_err && err == NULL)
+ err = free_err;
}
- err = got_diffreg(&res, f1, f2, flags, &args, &ds, outfile,
- changes ? *changes : NULL);
- got_diff_state_free(&ds);
done:
if (f1 && fclose(f1) != 0 && err == NULL)
err = got_error_from_errno("fclose");
@@ -269,43 +284,59 @@ got_diff_blob_file(struct got_blob_object *blob1, const char *label1,
}
const struct got_error *
-got_diff_blob_file_lines_changed(struct got_diff_changes **changes,
- struct got_blob_object *blob1, FILE *f2, size_t size2)
+got_diff_blob_prepared_file(struct got_diffreg_result **resultp,
+ struct diff_data *data1, struct got_blob_object *blob1,
+ struct diff_data *data2, FILE *f2, char *p2, size_t size2,
+ const struct diff_config *cfg, int ignore_whitespace)
{
- return diff_blob_file(changes, blob1, NULL, f2, size2, NULL,
- 0, 0, NULL);
-}
+ const struct got_error *err = NULL, *free_err;
+ FILE *f1 = NULL;
+ char hex1[SHA1_DIGEST_STRING_LENGTH];
+ char *idstr1 = NULL, *p1 = NULL;
+ size_t size1, size;
+ struct got_diffreg_result *result = NULL;
+ int f1_created = 0;
-const struct got_error *
-got_diff_blob_lines_changed(struct got_diff_changes **changes,
- struct got_blob_object *blob1, struct got_blob_object *blob2)
-{
- const struct got_error *err = NULL;
+ *resultp = NULL;
- err = alloc_changes(changes);
+ size1 = 0;
+ if (blob1) {
+ f1 = got_opentemp();
+ if (f1 == NULL)
+ return got_error_from_errno("got_opentemp");
+ idstr1 = got_object_blob_id_str(blob1, hex1, sizeof(hex1));
+ err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
+ blob1);
+ if (err)
+ goto done;
+ } else {
+ idstr1 = "/dev/null";
+ }
+
+ err = got_diff_prepare_file(&f1, &p1, &f1_created, &size,
+ data1, cfg, ignore_whitespace);
if (err)
- return err;
+ goto done;
+
+ err = got_diffreg_prepared_files(&result, cfg, data1, f1,
+ p1, size1, data2, f2, p2, size2);
+ if (err)
+ goto done;
- err = diff_blobs(blob1, blob2, NULL, NULL, 0, 0, 3, 0, NULL, *changes);
+ *resultp = result;
+done:
if (err) {
- got_diff_free_changes(*changes);
- *changes = NULL;
+ if (result)
+ free_err = got_diffreg_result_free_left(result);
+ else
+ free_err = got_diffreg_close(f1, p1, size1, NULL,
+ NULL, 0);
+ if (free_err && err == NULL)
+ err = free_err;
}
return err;
}
-void
-got_diff_free_changes(struct got_diff_changes *changes)
-{
- struct got_diff_change *change;
- while (!SIMPLEQ_EMPTY(&changes->entries)) {
- change = SIMPLEQ_FIRST(&changes->entries);
- SIMPLEQ_REMOVE_HEAD(&changes->entries, entry);
- free(change);
- }
- free(changes);
-}
-
static const struct got_error *
diff_added_blob(struct got_object_id *id, const char *label, mode_t mode,
struct got_repository *repo, got_diff_blob_cb cb, void *cb_arg)
@@ -741,7 +772,8 @@ got_diff_tree(struct got_tree_object *tree1, struct got_tree_object *tree2,
}
const struct got_error *
-got_diff_objects_as_blobs(struct got_object_id *id1, struct got_object_id *id2,
+got_diff_objects_as_blobs(off_t **line_offsets, size_t *nlines,
+ struct got_object_id *id1, struct got_object_id *id2,
const char *label1, const char *label2, int diff_context,
int ignore_whitespace, struct got_repository *repo, FILE *outfile)
{
@@ -761,8 +793,8 @@ got_diff_objects_as_blobs(struct got_object_id *id1, struct got_object_id *id2,
if (err)
goto done;
}
- err = got_diff_blob(blob1, blob2, label1, label2, diff_context,
- ignore_whitespace, outfile);
+ err = got_diff_blob(line_offsets, nlines, blob1, blob2,
+ label1, label2, diff_context, ignore_whitespace, outfile);
done:
if (blob1)
got_object_blob_close(blob1);
@@ -772,13 +804,15 @@ done:
}
const struct got_error *
-got_diff_objects_as_trees(struct got_object_id *id1, struct got_object_id *id2,
+got_diff_objects_as_trees(off_t **line_offsets, size_t *nlines,
+ struct got_object_id *id1, struct got_object_id *id2,
char *label1, char *label2, int diff_context, int ignore_whitespace,
struct got_repository *repo, FILE *outfile)
{
const struct got_error *err;
struct got_tree_object *tree1 = NULL, *tree2 = NULL;
struct got_diff_blob_output_unidiff_arg arg;
+ int want_lineoffsets = (line_offsets != NULL && *line_offsets != NULL);
if (id1 == NULL && id2 == NULL)
return got_error(GOT_ERR_NO_OBJ);
@@ -796,8 +830,20 @@ got_diff_objects_as_trees(struct got_object_id *id1, struct got_object_id *id2,
arg.diff_context = diff_context;
arg.ignore_whitespace = ignore_whitespace;
arg.outfile = outfile;
+ if (want_lineoffsets) {
+ arg.line_offsets = *line_offsets;
+ arg.nlines = *nlines;
+ } else {
+ arg.line_offsets = NULL;
+ arg.nlines = 0;
+ }
err = got_diff_tree(tree1, tree2, label1, label2, repo,
got_diff_blob_output_unidiff, &arg, 1);
+
+ if (want_lineoffsets) {
+ *line_offsets = arg.line_offsets; /* was likely re-allocated */
+ *nlines = arg.nlines;
+ }
done:
if (tree1)
got_object_tree_close(tree1);
@@ -807,8 +853,9 @@ done:
}
const struct got_error *
-got_diff_objects_as_commits(struct got_object_id *id1,
- struct got_object_id *id2, int diff_context, int ignore_whitespace,
+got_diff_objects_as_commits(off_t **line_offsets, size_t *nlines,
+ struct got_object_id *id1, struct got_object_id *id2,
+ int diff_context, int ignore_whitespace,
struct got_repository *repo, FILE *outfile)
{
const struct got_error *err;
@@ -827,7 +874,7 @@ got_diff_objects_as_commits(struct got_object_id *id1,
if (err)
goto done;
- err = got_diff_objects_as_trees(
+ err = got_diff_objects_as_trees(line_offsets, nlines,
commit1 ? got_object_commit_get_tree_id(commit1) : NULL,
got_object_commit_get_tree_id(commit2), "", "", diff_context,
ignore_whitespace, repo, outfile);
@@ -840,50 +887,15 @@ done:
}
const struct got_error *
-got_diff_files(struct got_diff_changes **changes,
- struct got_diff_state **ds,
- struct got_diff_args **args,
- int *flags,
- FILE *f1, size_t size1, const char *label1,
- FILE *f2, size_t size2, const char *label2,
- int diff_context, FILE *outfile)
+got_diff_files(struct got_diffreg_result **resultp,
+ FILE *f1, const char *label1, FILE *f2, const char *label2,
+ int diff_context, int ignore_whitespace, FILE *outfile)
{
const struct got_error *err = NULL;
- int res;
-
- *flags = 0;
- *ds = calloc(1, sizeof(**ds));
- if (*ds == NULL)
- return got_error_from_errno("calloc");
- *args = calloc(1, sizeof(**args));
- if (*args == NULL) {
- err = got_error_from_errno("calloc");
- goto done;
- }
-
- if (changes)
- *changes = NULL;
-
- if (f1 == NULL)
- *flags |= D_EMPTY1;
-
- if (f2 == NULL)
- *flags |= D_EMPTY2;
+ struct got_diffreg_result *diffreg_result = NULL;
- /* XXX should stat buffers be passed in args instead of ds? */
- (*ds)->stb1.st_mode = S_IFREG;
- (*ds)->stb1.st_size = size1;
- (*ds)->stb1.st_mtime = 0; /* XXX */
-
- (*ds)->stb2.st_mode = S_IFREG;
- (*ds)->stb2.st_size = size2;
- (*ds)->stb2.st_mtime = 0; /* XXX */
-
- (*args)->diff_format = D_UNIFIED;
- (*args)->label[0] = label1;
- (*args)->label[1] = label2;
- (*args)->diff_context = diff_context;
- *flags |= D_PROTOTYPE;
+ if (resultp)
+ *resultp = NULL;
if (outfile) {
fprintf(outfile, "file - %s\n",
@@ -891,29 +903,29 @@ got_diff_files(struct got_diff_changes **changes,
fprintf(outfile, "file + %s\n",
f2 == NULL ? "/dev/null" : label2);
}
- if (changes) {
- err = alloc_changes(changes);
+
+ err = got_diffreg(&diffreg_result, f1, f2, GOT_DIFF_ALGORITHM_PATIENCE,
+ ignore_whitespace);
+ if (err)
+ goto done;
+
+ if (outfile) {
+ err = got_diffreg_output(NULL, NULL, diffreg_result,
+ f1, f2, label1, label2, GOT_DIFF_OUTPUT_UNIDIFF,
+ diff_context, outfile);
if (err)
goto done;
}
- err = got_diffreg(&res, f1, f2, *flags, *args, *ds, outfile,
- changes ? *changes : NULL);
+
done:
- if (err) {
- if (*ds) {
- got_diff_state_free(*ds);
- free(*ds);
- *ds = NULL;
- }
- if (*args) {
- free(*args);
- *args = NULL;
- }
- if (changes) {
- if (*changes)
- got_diff_free_changes(*changes);
- *changes = NULL;
- }
+ if (resultp && err == NULL)
+ *resultp = diffreg_result;
+ else if (diffreg_result) {
+ const struct got_error *free_err;
+ free_err = got_diffreg_result_free(diffreg_result);
+ if (free_err && err == NULL)
+ err = free_err;
}
+
return err;
}
diff --git a/lib/diff3.c b/lib/diff3.c
index e8841fa..d685f9e 100644
--- a/lib/diff3.c
+++ b/lib/diff3.c
@@ -202,9 +202,7 @@ diffreg(BUF **d, const char *path1, const char *path2)
const struct got_error *err = NULL;
FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
char *outpath = NULL;
- struct got_diff_state ds;
- struct got_diff_args args;
- int res;
+ struct got_diffreg_result *diffreg_result = NULL;
*d = NULL;
@@ -224,25 +222,13 @@ diffreg(BUF **d, const char *path1, const char *path2)
if (err)
goto done;
- memset(&ds, 0, sizeof(ds));
- /* XXX should stat buffers be passed in args instead of ds? */
- if (stat(path1, &ds.stb1) == -1) {
- err = got_error_from_errno2("stat", path1);
- goto done;
- }
- if (stat(path2, &ds.stb2) == -1) {
- err = got_error_from_errno2("stat", path2);
+ err = got_diffreg(&diffreg_result, f1, f2,
+ GOT_DIFF_ALGORITHM_PATIENCE, 0);
+ if (err)
goto done;
- }
-
- memset(&args, 0, sizeof(args));
- args.diff_format = D_NORMAL;
- args.label[0] = "";
- args.label[1] = "";
- args.diff_context = 0;
- err = got_diffreg(&res, f1, f2, D_FORCEASCII, &args, &ds,
- outfile, NULL);
+ err = got_diffreg_output(NULL, NULL, diffreg_result, f1, f2, "", "",
+ GOT_DIFF_OUTPUT_EDSCRIPT, 0, outfile);
if (err)
goto done;
diff --git a/lib/diff_atomize_text.c b/lib/diff_atomize_text.c
new file mode 100644
index 0000000..a3d25db
--- /dev/null
+++ b/lib/diff_atomize_text.c
@@ -0,0 +1,179 @@
+/* Split source by line breaks, and calculate a simplistic checksum. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <ctype.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+
+#include "diff_internal.h"
+#include "diff_debug.h"
+
+static int
+diff_data_atomize_text_lines_fd(struct diff_data *d)
+{
+ off_t pos = 0;
+ const off_t end = pos + d->len;
+ unsigned int array_size_estimate = d->len / 50;
+ unsigned int pow2 = 1;
+ bool ignore_whitespace = (d->diff_flags & DIFF_FLAG_IGNORE_WHITESPACE);
+
+ while (array_size_estimate >>= 1)
+ pow2++;
+
+ ARRAYLIST_INIT(d->atoms, 1 << pow2);
+
+ if (fseek(d->root->f, 0L, SEEK_SET) == -1)
+ return errno;
+
+ while (pos < end) {
+ off_t line_end = pos;
+ unsigned int hash = 0;
+ unsigned char buf[512];
+ size_t r, i;
+ struct diff_atom *atom;
+ int eol = 0;
+
+ while (eol == 0 && line_end < end) {
+ r = fread(buf, sizeof(char), sizeof(buf), d->root->f);
+ if (r == 0 && ferror(d->root->f))
+ return errno;
+ i = 0;
+ while (eol == 0 && i < r) {
+ if (buf[i] != '\r' && buf[i] != '\n') {
+ if (!ignore_whitespace
+ || !isspace(buf[i]))
+ hash = hash * 23 + buf[i];
+ line_end++;
+ } else
+ eol = buf[i];
+ i++;
+ }
+ }
+
+ /* When not at the end of data, the line ending char ('\r' or
+ * '\n') must follow */
+ if (line_end < end)
+ line_end++;
+ /* If that was an '\r', also pull in any following '\n' */
+ if (line_end < end && eol == '\r') {
+ if (fseeko(d->root->f, line_end, SEEK_SET) == -1)
+ return errno;
+ r = fread(buf, sizeof(char), sizeof(buf), d->root->f);
+ if (r == 0 && ferror(d->root->f))
+ return errno;
+ if (r == 1 && buf[0] == '\n' )
+ line_end++;
+ }
+
+ /* Record the found line as diff atom */
+ ARRAYLIST_ADD(atom, d->atoms);
+ if (!atom)
+ return ENOMEM;
+
+ *atom = (struct diff_atom){
+ .root = d,
+ .pos = pos,
+ .at = NULL, /* atom data is not memory-mapped */
+ .len = line_end - pos,
+ .hash = hash,
+ };
+
+ /* Starting point for next line: */
+ pos = line_end;
+ if (fseeko(d->root->f, pos, SEEK_SET) == -1)
+ return errno;
+ }
+
+ return DIFF_RC_OK;
+}
+
+static int
+diff_data_atomize_text_lines_mmap(struct diff_data *d)
+{
+ const uint8_t *pos = d->data;
+ const uint8_t *end = pos + d->len;
+ bool ignore_whitespace = (d->diff_flags & DIFF_FLAG_IGNORE_WHITESPACE);
+
+ unsigned int array_size_estimate = d->len / 50;
+ unsigned int pow2 = 1;
+ while (array_size_estimate >>= 1)
+ pow2++;
+
+ ARRAYLIST_INIT(d->atoms, 1 << pow2);
+
+ while (pos < end) {
+ const uint8_t *line_end = pos;
+ unsigned int hash = 0;
+
+ while (line_end < end && *line_end != '\r' && *line_end != '\n') {
+ if (!ignore_whitespace
+ || !isspace(*line_end))
+ hash = hash * 23 + *line_end;
+ line_end++;
+ }
+
+ /* When not at the end of data, the line ending char ('\r' or
+ * '\n') must follow */
+ if (line_end < end)
+ line_end++;
+ /* If that was an '\r', also pull in any following '\n' */
+ if (line_end < end - 1 && line_end[0] == '\r' &&
+ line_end[1] == '\n')
+ line_end++;
+
+ /* Record the found line as diff atom */
+ struct diff_atom *atom;
+ ARRAYLIST_ADD(atom, d->atoms);
+ if (!atom)
+ return ENOMEM;
+
+ *atom = (struct diff_atom){
+ .root = d,
+ .pos = (off_t)(pos - d->data),
+ .at = pos,
+ .len = line_end - pos,
+ .hash = hash,
+ };
+
+ /* Starting point for next line: */
+ pos = line_end;
+ }
+
+ return DIFF_RC_OK;
+}
+
+static int
+diff_data_atomize_text_lines(struct diff_data *d)
+{
+ if (d->data == NULL)
+ return diff_data_atomize_text_lines_fd(d);
+ else
+ return diff_data_atomize_text_lines_mmap(d);
+}
+
+int
+diff_atomize_text_by_line(void *func_data, struct diff_data *d)
+{
+ return diff_data_atomize_text_lines(d);
+}
diff --git a/lib/diff_debug.h b/lib/diff_debug.h
new file mode 100644
index 0000000..0ed8a5e
--- /dev/null
+++ b/lib/diff_debug.h
@@ -0,0 +1,228 @@
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#define DEBUG 0
+
+#if DEBUG
+#include <stdio.h>
+#include <unistd.h>
+#define print(args...) fprintf(stderr, ##args)
+#define debug print
+#define debug_dump dump
+#define debug_dump_atom dump_atom
+#define debug_dump_atoms dump_atoms
+
+static inline void
+print_atom_byte(unsigned char c) {
+ if (c == '\r')
+ print("\\r");
+ else if (c == '\n')
+ print("\\n");
+ else if ((c < 32 || c >= 127) && (c != '\t'))
+ print("\\x%02x", c);
+ else
+ print("%c", c);
+}
+
+static inline void
+dump_atom(const struct diff_data *left, const struct diff_data *right,
+ const struct diff_atom *atom)
+{
+ if (!atom) {
+ print("NULL atom\n");
+ return;
+ }
+ if (left)
+ print(" %3u '", diff_atom_root_idx(left, atom));
+
+ if (atom->at == NULL) {
+ off_t remain = atom->len;
+ if (fseek(atom->root->f, atom->pos, SEEK_SET) == -1)
+ abort(); /* cannot return error */
+ while (remain > 0) {
+ char buf[16];
+ size_t r;
+ int i;
+ r = fread(buf, 1, MIN(remain, sizeof(buf)),
+ atom->root->f);
+ if (r == -1)
+ abort(); /* cannot return error */
+ if (r == 0)
+ break;
+ remain -= r;
+ for (i = 0; i < r; i++)
+ print_atom_byte(buf[i]);
+ }
+ } else {
+ const char *s;
+ for (s = atom->at; s < (const char*)(atom->at + atom->len); s++)
+ print_atom_byte(*s);
+ }
+ print("'\n");
+}
+
+static inline void
+dump_atoms(const struct diff_data *d, struct diff_atom *atom,
+ unsigned int count)
+{
+ if (count > 42) {
+ dump_atoms(d, atom, 20);
+ print("[%u lines skipped]\n", count - 20 - 20);
+ dump_atoms(d, atom + count - 20, 20);
+ return;
+ } else {
+ struct diff_atom *i;
+ foreach_diff_atom(i, atom, count) {
+ dump_atom(d, NULL, i);
+ }
+ }
+}
+
+static inline void
+dump(struct diff_data *d)
+{
+ dump_atoms(d, d->atoms.head, d->atoms.len);
+}
+
+/* kd is a quadratic space myers matrix from the original Myers algorithm.
+ * kd_forward and kd_backward are linear slices of a myers matrix from the Myers
+ * Divide algorithm.
+ */
+static inline void
+dump_myers_graph(const struct diff_data *l, const struct diff_data *r,
+ int *kd, int *kd_forward, int kd_forward_d,
+ int *kd_backward, int kd_backward_d)
+{
+ #define COLOR_YELLOW "\033[1;33m"
+ #define COLOR_GREEN "\033[1;32m"
+ #define COLOR_BLUE "\033[1;34m"
+ #define COLOR_RED "\033[1;31m"
+ #define COLOR_END "\033[0;m"
+ int x;
+ int y;
+ print(" ");
+ for (x = 0; x <= l->atoms.len; x++)
+ print("%2d", x % 100);
+ print("\n");
+
+ for (y = 0; y <= r->atoms.len; y++) {
+ print("%3d ", y);
+ for (x = 0; x <= l->atoms.len; x++) {
+
+ /* print d advancements from kd, if any. */
+ char label = 'o';
+ char *color = NULL;
+ if (kd) {
+ int max = l->atoms.len + r->atoms.len;
+ size_t kd_len = max + 1 + max;
+ int *kd_pos = kd;
+ int di;
+#define xk_to_y(X, K) ((X) - (K))
+ for (di = 0; di < max; di++) {
+ int ki;
+ for (ki = di; ki >= -di; ki -= 2) {
+ if (x != kd_pos[ki]
+ || y != xk_to_y(x, ki))
+ continue;
+ label = '0' + (di % 10);
+ color = COLOR_YELLOW;
+ break;
+ }
+ if (label != 'o')
+ break;
+ kd_pos += kd_len;
+ }
+ }
+ if (kd_forward && kd_forward_d >= 0) {
+#define xc_to_y(X, C, DELTA) ((X) - (C) + (DELTA))
+ int ki;
+ for (ki = kd_forward_d;
+ ki >= -kd_forward_d;
+ ki -= 2) {
+ if (x != kd_forward[ki])
+ continue;
+ if (y != xk_to_y(x, ki))
+ continue;
+ label = 'F';
+ color = COLOR_GREEN;
+ break;
+ }
+ }
+ if (kd_backward && kd_backward_d >= 0) {
+ int delta = (int)r->atoms.len
+ - (int)l->atoms.len;
+ int ki;
+ for (ki = kd_backward_d;
+ ki >= -kd_backward_d;
+ ki -= 2) {
+ if (x != kd_backward[ki])
+ continue;
+ if (y != xc_to_y(x, ki, delta))
+ continue;
+ if (label == 'o') {
+ label = 'B';
+ color = COLOR_BLUE;
+ } else {
+ label = 'X';
+ color = COLOR_RED;
+ }
+ break;
+ }
+ }
+ if (color)
+ print("%s", color);
+ print("%c", label);
+ if (color)
+ print("%s", COLOR_END);
+ if (x < l->atoms.len)
+ print("-");
+ }
+ print("\n");
+ if (y == r->atoms.len)
+ break;
+
+ print(" ");
+ for (x = 0; x < l->atoms.len; x++) {
+ bool same;
+ diff_atom_same(&same, &l->atoms.head[x],
+ &r->atoms.head[y]);
+ if (same)
+ print("|\\");
+ else
+ print("| ");
+ }
+ print("|\n");
+ }
+}
+
+static inline void
+debug_dump_myers_graph(const struct diff_data *l, const struct diff_data *r,
+ int *kd, int *kd_forward, int kd_forward_d,
+ int *kd_backward, int kd_backward_d)
+{
+ if (l->atoms.len > 99 || r->atoms.len > 99)
+ return;
+ dump_myers_graph(l, r, kd, kd_forward, kd_forward_d,
+ kd_backward, kd_backward_d);
+}
+
+#else
+#define debug(args...)
+#define debug_dump(args...)
+#define debug_dump_atom(args...)
+#define debug_dump_atoms(args...)
+#define debug_dump_myers_graph(args...)
+#endif
diff --git a/lib/diff_internal.h b/lib/diff_internal.h
new file mode 100644
index 0000000..94ef28c
--- /dev/null
+++ b/lib/diff_internal.h
@@ -0,0 +1,244 @@
+/* Generic infrastructure to implement various diff algorithms. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifndef MAX
+#define MAX(A,B) ((A)>(B)?(A):(B))
+#endif
+#ifndef MIN
+#define MIN(A,B) ((A)<(B)?(A):(B))
+#endif
+
+static inline bool
+diff_range_empty(const struct diff_range *r)
+{
+ return r->start == r->end;
+}
+
+static inline bool
+diff_ranges_touch(const struct diff_range *a, const struct diff_range *b)
+{
+ return (a->end >= b->start) && (a->start <= b->end);
+}
+
+static inline void
+diff_ranges_merge(struct diff_range *a, const struct diff_range *b)
+{
+ *a = (struct diff_range){
+ .start = MIN(a->start, b->start),
+ .end = MAX(a->end, b->end),
+ };
+}
+
+static inline int
+diff_range_len(const struct diff_range *r)
+{
+ if (!r)
+ return 0;
+ return r->end - r->start;
+}
+
+/* List of all possible return codes of a diff invocation. */
+#define DIFF_RC_USE_DIFF_ALGO_FALLBACK -1
+#define DIFF_RC_OK 0
+/* Any positive return values are errno values from sys/errno.h */
+
+struct diff_data;
+
+struct diff_atom {
+ struct diff_data *root; /* back pointer to root diff data */
+
+ off_t pos; /* if not memory-mapped */
+ const uint8_t *at; /* if memory-mapped */
+ off_t len;
+
+ /* This hash is just a very cheap speed up for finding *mismatching*
+ * atoms. When hashes match, we still need to compare entire atoms to
+ * find out whether they are indeed identical or not. */
+ unsigned int hash;
+};
+
+int
+diff_atom_cmp(int *cmp,
+ const struct diff_atom *left,
+ const struct diff_atom *right);
+
+/* Indicate whether two given diff atoms match. */
+int
+diff_atom_same(bool *same,
+ const struct diff_atom *left,
+ const struct diff_atom *right);
+
+/* The atom's index in the entire file. For atoms divided by lines of text, this
+ * yields the line number (starting with 0). Also works for diff_data that
+ * reference only a subsection of a file, always reflecting the global position
+ * in the file (and not the relative position within the subsection). */
+#define diff_atom_root_idx(DIFF_DATA, ATOM) \
+ ((ATOM) && ((ATOM) >= (DIFF_DATA)->root->atoms.head) \
+ ? (unsigned int)((ATOM) - ((DIFF_DATA)->root->atoms.head)) \
+ : (DIFF_DATA)->root->atoms.len)
+
+/* The atom's index within DIFF_DATA. For atoms divided by lines of text, this
+ * yields the line number (starting with 0). */
+#define diff_atom_idx(DIFF_DATA, ATOM) \
+ ((ATOM) && ((ATOM) >= (DIFF_DATA)->atoms.head) \
+ ? (unsigned int)((ATOM) - ((DIFF_DATA)->atoms.head)) \
+ : (DIFF_DATA)->atoms.len)
+
+#define foreach_diff_atom(ATOM, FIRST_ATOM, COUNT) \
+ for ((ATOM) = (FIRST_ATOM); \
+ (ATOM) \
+ && ((ATOM) >= (FIRST_ATOM)) \
+ && ((ATOM) - (FIRST_ATOM) < (COUNT)); \
+ (ATOM)++)
+
+#define diff_data_foreach_atom(ATOM, DIFF_DATA) \
+ foreach_diff_atom(ATOM, (DIFF_DATA)->atoms.head, (DIFF_DATA)->atoms.len)
+
+#define diff_data_foreach_atom_from(FROM, ATOM, DIFF_DATA) \
+ for ((ATOM) = (FROM); \
+ (ATOM) \
+ && ((ATOM) >= (DIFF_DATA)->atoms.head) \
+ && ((ATOM) - (DIFF_DATA)->atoms.head < (DIFF_DATA)->atoms.len); \
+ (ATOM)++)
+
+#define diff_data_foreach_atom_backwards_from(FROM, ATOM, DIFF_DATA) \
+ for ((ATOM) = (FROM); \
+ (ATOM) \
+ && ((ATOM) >= (DIFF_DATA)->atoms.head) \
+ && ((ATOM) - (DIFF_DATA)->atoms.head >= 0); \
+ (ATOM)--)
+
+/* A diff chunk represents a set of atoms on the left and/or a set of atoms on
+ * the right.
+ *
+ * If solved == false:
+ * The diff algorithm has divided the source file, and this is a chunk that the
+ * inner_algo should run on next.
+ * The lines on the left should be diffed against the lines on the right.
+ * (If there are no left lines or no right lines, it implies solved == true,
+ * because there is nothing to diff.)
+ *
+ * If solved == true:
+ * If there are only left atoms, it is a chunk removing atoms from the left ("a
+ * minus chunk").
+ * If there are only right atoms, it is a chunk adding atoms from the right ("a
+ * plus chunk").
+ * If there are both left and right lines, it is a chunk of equal content on
+ * both sides, and left_count == right_count:
+ *
+ * - foo }
+ * - bar }-- diff_chunk{ left_start = &left.atoms.head[0], left_count = 3,
+ * - baz } right_start = NULL, right_count = 0 }
+ * moo }
+ * goo }-- diff_chunk{ left_start = &left.atoms.head[3], left_count = 3,
+ * zoo } right_start = &right.atoms.head[0], right_count = 3 }
+ * +loo }
+ * +roo }-- diff_chunk{ left_start = NULL, left_count = 0,
+ * +too } right_start = &right.atoms.head[3], right_count = 3 }
+ *
+ */
+struct diff_chunk {
+ bool solved;
+ struct diff_atom *left_start;
+ unsigned int left_count;
+ struct diff_atom *right_start;
+ unsigned int right_count;
+};
+
+#define DIFF_RESULT_ALLOC_BLOCKSIZE 128
+
+enum diff_chunk_type {
+ CHUNK_EMPTY,
+ CHUNK_PLUS,
+ CHUNK_MINUS,
+ CHUNK_SAME,
+ CHUNK_ERROR,
+};
+
+static inline enum diff_chunk_type
+diff_chunk_type(const struct diff_chunk *chunk)
+{
+ if (!chunk->left_count && !chunk->right_count)
+ return CHUNK_EMPTY;
+ if (!chunk->solved)
+ return CHUNK_ERROR;
+ if (!chunk->right_count)
+ return CHUNK_MINUS;
+ if (!chunk->left_count)
+ return CHUNK_PLUS;
+ if (chunk->left_count != chunk->right_count)
+ return CHUNK_ERROR;
+ return CHUNK_SAME;
+}
+
+struct diff_chunk_context;
+
+bool
+diff_chunk_context_empty(const struct diff_chunk_context *cc);
+
+bool
+diff_chunk_contexts_touch(const struct diff_chunk_context *cc,
+ const struct diff_chunk_context *other);
+
+void
+diff_chunk_contexts_merge(struct diff_chunk_context *cc,
+ const struct diff_chunk_context *other);
+
+struct diff_state {
+ /* The final result passed to the original diff caller. */
+ struct diff_result *result;
+
+ /* The root diff_data is in result->left,right, these are (possibly)
+ * subsections of the root data. */
+ struct diff_data left;
+ struct diff_data right;
+
+ unsigned int recursion_depth_left;
+
+ /* Remaining chunks from one diff algorithm pass, if any solved == false
+ * chunks came up. */
+ diff_chunk_arraylist_t temp_result;
+
+ /* State buffer used by Myers algorithm. */
+ int *kd_buf;
+ size_t kd_buf_size; /* in units of sizeof(int), not bytes */
+};
+
+struct diff_chunk *diff_state_add_chunk(struct diff_state *state, bool solved,
+ struct diff_atom *left_start,
+ unsigned int left_count,
+ struct diff_atom *right_start,
+ unsigned int right_count);
+
+struct diff_output_info;
+
+int diff_output_lines(struct diff_output_info *output_info, FILE *dest,
+ const char *prefix, struct diff_atom *start_atom,
+ unsigned int count);
+
+int diff_output_trailing_newline_msg(struct diff_output_info *outinfo,
+ FILE *dest,
+ const struct diff_chunk *c);
+int diff_output_match_function_prototype(char **prototype,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc);
+
+struct diff_output_info *diff_output_info_alloc(void);
+
+void
+diff_data_init_subsection(struct diff_data *d, struct diff_data *parent,
+ struct diff_atom *from_atom, unsigned int atoms_count);
diff --git a/lib/diff_main.c b/lib/diff_main.c
new file mode 100644
index 0000000..69aea0a
--- /dev/null
+++ b/lib/diff_main.c
@@ -0,0 +1,629 @@
+/* Generic infrastructure to implement various diff algorithms (implementation). */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+
+#include <sys/queue.h>
+#include <ctype.h>
+#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+#include <unistd.h>
+
+#include <assert.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+
+#include "diff_internal.h"
+#include "diff_debug.h"
+
+static int
+read_at(FILE *f, off_t at_pos, unsigned char *buf, size_t len)
+{
+ int r;
+ if (fseeko(f, at_pos, SEEK_SET) == -1)
+ return errno;
+ r = fread(buf, sizeof(char), len, f);
+ if ((r == 0 || r < len) && ferror(f))
+ return errno;
+ if (r != len)
+ return EIO;
+ return 0;
+}
+
+static int
+buf_cmp(const unsigned char *left, size_t left_len,
+ const unsigned char *right, size_t right_len,
+ bool ignore_whitespace)
+{
+ int cmp;
+
+ if (ignore_whitespace) {
+ int il = 0, ir = 0;
+ while (il < left_len && ir < right_len) {
+ unsigned char cl = left[il];
+ unsigned char cr = right[ir];
+
+ if (isspace(cl) && il < left_len) {
+ il++;
+ continue;
+ }
+ if (isspace(cr) && ir < right_len) {
+ ir++;
+ continue;
+ }
+
+ if (cl > cr)
+ return 1;
+ if (cr > cl)
+ return -1;
+ il++;
+ ir++;
+ }
+ while (il < left_len) {
+ unsigned char cl = left[il++];
+ if (!isspace(cl))
+ return 1;
+ }
+ while (ir < right_len) {
+ unsigned char cr = right[ir++];
+ if (!isspace(cr))
+ return -1;
+ }
+
+ return 0;
+ }
+
+ cmp = memcmp(left, right, MIN(left_len, right_len));
+ if (cmp)
+ return cmp;
+ if (left_len == right_len)
+ return 0;
+ return (left_len > right_len) ? 1 : -1;
+}
+
+int
+diff_atom_cmp(int *cmp,
+ const struct diff_atom *left,
+ const struct diff_atom *right)
+{
+ off_t remain_left, remain_right;
+ int flags = (left->root->diff_flags | right->root->diff_flags);
+ bool ignore_whitespace = (flags & DIFF_FLAG_IGNORE_WHITESPACE);
+
+ if (!left->len && !right->len) {
+ *cmp = 0;
+ return 0;
+ }
+ if (!ignore_whitespace) {
+ if (!right->len) {
+ *cmp = 1;
+ return 0;
+ }
+ if (!left->len) {
+ *cmp = -1;
+ return 0;
+ }
+ }
+
+ if (left->at != NULL && right->at != NULL) {
+ *cmp = buf_cmp(left->at, left->len, right->at, right->len,
+ ignore_whitespace);
+ return 0;
+ }
+
+ remain_left = left->len;
+ remain_right = right->len;
+ while (remain_left > 0 || remain_right > 0) {
+ const size_t chunksz = 8192;
+ unsigned char buf_left[chunksz], buf_right[chunksz];
+ const uint8_t *p_left, *p_right;
+ off_t n_left, n_right;
+ ssize_t r;
+
+ if (!remain_right) {
+ *cmp = 1;
+ return 0;
+ }
+ if (!remain_left) {
+ *cmp = -1;
+ return 0;
+ }
+
+ n_left = MIN(chunksz, remain_left);
+ n_right = MIN(chunksz, remain_right);
+
+ if (left->at == NULL) {
+ r = read_at(left->root->f,
+ left->pos + (left->len - remain_left),
+ buf_left, n_left);
+ if (r) {
+ *cmp = 0;
+ return r;
+ }
+ p_left = buf_left;
+ } else {
+ p_left = left->at + (left->len - remain_left);
+ }
+
+ if (right->at == NULL) {
+ r = read_at(right->root->f,
+ right->pos + (right->len - remain_right),
+ buf_right, n_right);
+ if (r) {
+ *cmp = 0;
+ return r;
+ }
+ p_right = buf_right;
+ } else {
+ p_right = right->at + (right->len - remain_right);
+ }
+
+ r = buf_cmp(p_left, n_left, p_right, n_right,
+ ignore_whitespace);
+ if (r) {
+ *cmp = r;
+ return 0;
+ }
+
+ remain_left -= n_left;
+ remain_right -= n_right;
+ }
+
+ *cmp = 0;
+ return 0;
+}
+
+int
+diff_atom_same(bool *same,
+ const struct diff_atom *left,
+ const struct diff_atom *right)
+{
+ int cmp;
+ int r;
+ if (left->hash != right->hash) {
+ *same = false;
+ return 0;
+ }
+ r = diff_atom_cmp(&cmp, left, right);
+ if (r) {
+ *same = true;
+ return r;
+ }
+ *same = (cmp == 0);
+ return 0;
+}
+
+static struct diff_chunk *
+diff_state_add_solved_chunk(struct diff_state *state,
+ const struct diff_chunk *chunk)
+{
+ diff_chunk_arraylist_t *result;
+ struct diff_chunk *new_chunk;
+ enum diff_chunk_type last_t;
+ enum diff_chunk_type new_t;
+ struct diff_chunk *last;
+
+ /* Append to solved chunks; make sure that adjacent chunks of same type are combined, and that a minus chunk
+ * never directly follows a plus chunk. */
+ result = &state->result->chunks;
+
+ last_t = result->len ? diff_chunk_type(&result->head[result->len - 1])
+ : CHUNK_EMPTY;
+ new_t = diff_chunk_type(chunk);
+
+ debug("ADD %s chunk #%u:\n", chunk->solved ? "solved" : "UNSOLVED",
+ result->len);
+ debug("L\n");
+ debug_dump_atoms(&state->left, chunk->left_start, chunk->left_count);
+ debug("R\n");
+ debug_dump_atoms(&state->right, chunk->right_start, chunk->right_count);
+
+ if (result->len) {
+ last = &result->head[result->len - 1];
+ assert(chunk->left_start
+ == last->left_start + last->left_count);
+ assert(chunk->right_start
+ == last->right_start + last->right_count);
+ }
+
+ if (new_t == last_t) {
+ new_chunk = &result->head[result->len - 1];
+ new_chunk->left_count += chunk->left_count;
+ new_chunk->right_count += chunk->right_count;
+ debug(" - added chunk touches previous one of same type, joined:\n");
+ debug("L\n");
+ debug_dump_atoms(&state->left, new_chunk->left_start, new_chunk->left_count);
+ debug("R\n");
+ debug_dump_atoms(&state->right, new_chunk->right_start, new_chunk->right_count);
+ } else if (last_t == CHUNK_PLUS && new_t == CHUNK_MINUS) {
+ enum diff_chunk_type prev_last_t =
+ result->len > 1 ?
+ diff_chunk_type(&result->head[result->len - 2])
+ : CHUNK_EMPTY;
+ /* If a minus-chunk follows a plus-chunk, place it above the plus-chunk->
+ * Is the one before that also a minus? combine. */
+ if (prev_last_t == CHUNK_MINUS) {
+ new_chunk = &result->head[result->len - 2];
+ new_chunk->left_count += chunk->left_count;
+ new_chunk->right_count += chunk->right_count;
+
+ debug(" - added minus-chunk follows plus-chunk,"
+ " put before that plus-chunk and joined"
+ " with preceding minus-chunk:\n");
+ debug("L\n");
+ debug_dump_atoms(&state->left, new_chunk->left_start, new_chunk->left_count);
+ debug("R\n");
+ debug_dump_atoms(&state->right, new_chunk->right_start, new_chunk->right_count);
+ } else {
+ ARRAYLIST_INSERT(new_chunk, *result, result->len - 1);
+ if (!new_chunk)
+ return NULL;
+ *new_chunk = *chunk;
+
+ /* The new minus chunk indicates to which position on
+ * the right it corresponds, even though it doesn't add
+ * any lines on the right. By moving above a plus chunk,
+ * that position on the right has shifted. */
+ last = &result->head[result->len - 1];
+ new_chunk->right_start = last->right_start;
+
+ debug(" - added minus-chunk follows plus-chunk,"
+ " put before that plus-chunk\n");
+ }
+
+ /* That last_t == CHUNK_PLUS indicates to which position on the
+ * left it corresponds, even though it doesn't add any lines on
+ * the left. By inserting/extending the prev_last_t ==
+ * CHUNK_MINUS, that position on the left has shifted. */
+ last = &result->head[result->len - 1];
+ last->left_start = new_chunk->left_start
+ + new_chunk->left_count;
+
+ } else {
+ ARRAYLIST_ADD(new_chunk, *result);
+ if (!new_chunk)
+ return NULL;
+ *new_chunk = *chunk;
+ }
+ return new_chunk;
+}
+
+/* Even if a left or right side is empty, diff output may need to know the
+ * position in that file.
+ * So left_start or right_start must never be NULL -- pass left_count or
+ * right_count as zero to indicate staying at that position without consuming
+ * any lines. */
+struct diff_chunk *
+diff_state_add_chunk(struct diff_state *state, bool solved,
+ struct diff_atom *left_start, unsigned int left_count,
+ struct diff_atom *right_start, unsigned int right_count)
+{
+ struct diff_chunk *new_chunk;
+ struct diff_chunk chunk = {
+ .solved = solved,
+ .left_start = left_start,
+ .left_count = left_count,
+ .right_start = right_start,
+ .right_count = right_count,
+ };
+
+ /* An unsolved chunk means store as intermediate result for later
+ * re-iteration.
+ * If there already are intermediate results, that means even a
+ * following solved chunk needs to go to intermediate results, so that
+ * it is later put in the final correct position in solved chunks.
+ */
+ if (!solved || state->temp_result.len) {
+ /* Append to temp_result */
+ debug("ADD %s chunk to temp result:\n",
+ chunk.solved ? "solved" : "UNSOLVED");
+ debug("L\n");
+ debug_dump_atoms(&state->left, left_start, left_count);
+ debug("R\n");
+ debug_dump_atoms(&state->right, right_start, right_count);
+ ARRAYLIST_ADD(new_chunk, state->temp_result);
+ if (!new_chunk)
+ return NULL;
+ *new_chunk = chunk;
+ return new_chunk;
+ }
+
+ return diff_state_add_solved_chunk(state, &chunk);
+}
+
+void
+diff_data_init_root(struct diff_data *d, FILE *f, const uint8_t *data,
+ unsigned long long len, int diff_flags)
+{
+ *d = (struct diff_data){
+ .f = f,
+ .pos = 0,
+ .data = data,
+ .len = len,
+ .root = d,
+ .diff_flags = diff_flags,
+ };
+}
+
+void
+diff_data_init_subsection(struct diff_data *d, struct diff_data *parent,
+ struct diff_atom *from_atom, unsigned int atoms_count)
+{
+ struct diff_atom *last_atom;
+
+ debug("diff_data %p parent %p from_atom %p atoms_count %u\n",
+ d, parent, from_atom, atoms_count);
+ debug(" from_atom ");
+ debug_dump_atom(parent, NULL, from_atom);
+
+ if (atoms_count == 0) {
+ *d = (struct diff_data){
+ .f = NULL,
+ .pos = 0,
+ .data = NULL,
+ .len = 0,
+ .root = parent->root,
+ .atoms.head = NULL,
+ .atoms.len = atoms_count,
+ };
+
+ return;
+ }
+
+ last_atom = from_atom + atoms_count - 1;
+ *d = (struct diff_data){
+ .f = NULL,
+ .pos = from_atom->pos,
+ .data = from_atom->at,
+ .len = (last_atom->pos + last_atom->len) - from_atom->pos,
+ .root = parent->root,
+ .atoms.head = from_atom,
+ .atoms.len = atoms_count,
+ };
+
+ debug("subsection:\n");
+ debug_dump(d);
+}
+
+void
+diff_data_free(struct diff_data *diff_data)
+{
+ if (!diff_data)
+ return;
+ if (diff_data->atoms.allocated)
+ ARRAYLIST_FREE(diff_data->atoms);
+}
+
+int
+diff_algo_none(const struct diff_algo_config *algo_config,
+ struct diff_state *state)
+{
+ debug("\n** %s\n", __func__);
+ debug("left:\n");
+ debug_dump(&state->left);
+ debug("right:\n");
+ debug_dump(&state->right);
+ debug_dump_myers_graph(&state->left, &state->right, NULL, NULL, 0, NULL,
+ 0);
+
+ /* Add a chunk of equal lines, if any */
+ struct diff_atom *l = state->left.atoms.head;
+ unsigned int l_len = state->left.atoms.len;
+ struct diff_atom *r = state->right.atoms.head;
+ unsigned int r_len = state->right.atoms.len;
+ unsigned int equal_atoms_start = 0;
+ unsigned int equal_atoms_end = 0;
+ unsigned int l_idx = 0;
+ unsigned int r_idx = 0;
+
+ while (equal_atoms_start < l_len
+ && equal_atoms_start < r_len) {
+ int err;
+ bool same;
+ err = diff_atom_same(&same, &l[equal_atoms_start],
+ &r[equal_atoms_start]);
+ if (err)
+ return err;
+ if (!same)
+ break;
+ equal_atoms_start++;
+ }
+ while (equal_atoms_end < (l_len - equal_atoms_start)
+ && equal_atoms_end < (r_len - equal_atoms_start)) {
+ int err;
+ bool same;
+ err = diff_atom_same(&same, &l[l_len - 1 - equal_atoms_end],
+ &r[r_len - 1 - equal_atoms_end]);
+ if (err)
+ return err;
+ if (!same)
+ break;
+ equal_atoms_end++;
+ }
+
+ /* Add a chunk of equal lines at the start */
+ if (equal_atoms_start) {
+ if (!diff_state_add_chunk(state, true,
+ l, equal_atoms_start,
+ r, equal_atoms_start))
+ return ENOMEM;
+ l_idx += equal_atoms_start;
+ r_idx += equal_atoms_start;
+ }
+
+ /* Add a "minus" chunk with all lines from the left. */
+ if (equal_atoms_start + equal_atoms_end < l_len) {
+ unsigned int add_len = l_len - equal_atoms_start - equal_atoms_end;
+ if (!diff_state_add_chunk(state, true,
+ &l[l_idx], add_len,
+ &r[r_idx], 0))
+ return ENOMEM;
+ l_idx += add_len;
+ }
+
+ /* Add a "plus" chunk with all lines from the right. */
+ if (equal_atoms_start + equal_atoms_end < r_len) {
+ unsigned int add_len = r_len - equal_atoms_start - equal_atoms_end;
+ if (!diff_state_add_chunk(state, true,
+ &l[l_idx], 0,
+ &r[r_idx], add_len))
+ return ENOMEM;
+ r_idx += add_len;
+ }
+
+ /* Add a chunk of equal lines at the end */
+ if (equal_atoms_end) {
+ if (!diff_state_add_chunk(state, true,
+ &l[l_idx], equal_atoms_end,
+ &r[r_idx], equal_atoms_end))
+ return ENOMEM;
+ }
+
+ return DIFF_RC_OK;
+}
+
+int
+diff_run_algo(const struct diff_algo_config *algo_config,
+ struct diff_state *state)
+{
+ int rc;
+
+ if (!algo_config || !algo_config->impl
+ || !state->recursion_depth_left
+ || !state->left.atoms.len || !state->right.atoms.len) {
+ debug("Fall back to diff_algo_none():%s%s%s\n",
+ (!algo_config || !algo_config->impl) ? " no-cfg" : "",
+ (!state->recursion_depth_left) ? " max-depth" : "",
+ (!state->left.atoms.len || !state->right.atoms.len)?
+ " trivial" : "");
+ return diff_algo_none(algo_config, state);
+ }
+
+ ARRAYLIST_FREE(state->temp_result);
+ ARRAYLIST_INIT(state->temp_result, DIFF_RESULT_ALLOC_BLOCKSIZE);
+ rc = algo_config->impl(algo_config, state);
+ switch (rc) {
+ case DIFF_RC_USE_DIFF_ALGO_FALLBACK:
+ debug("Got DIFF_RC_USE_DIFF_ALGO_FALLBACK (%p)\n",
+ algo_config->fallback_algo);
+ rc = diff_run_algo(algo_config->fallback_algo, state);
+ goto return_rc;
+
+ case DIFF_RC_OK:
+ /* continue below */
+ break;
+
+ default:
+ /* some error happened */
+ goto return_rc;
+ }
+
+ /* Pick up any diff chunks that are still unsolved and feed to
+ * inner_algo. inner_algo will solve unsolved chunks and append to
+ * result, and subsequent solved chunks on this level are then appended
+ * to result afterwards. */
+ int i;
+ for (i = 0; i < state->temp_result.len; i++) {
+ struct diff_chunk *c = &state->temp_result.head[i];
+ if (c->solved) {
+ diff_state_add_solved_chunk(state, c);
+ continue;
+ }
+
+ /* c is an unsolved chunk, feed to inner_algo */
+ struct diff_state inner_state = {
+ .result = state->result,
+ .recursion_depth_left = state->recursion_depth_left - 1,
+ .kd_buf = state->kd_buf,
+ .kd_buf_size = state->kd_buf_size,
+ };
+ diff_data_init_subsection(&inner_state.left, &state->left,
+ c->left_start, c->left_count);
+ diff_data_init_subsection(&inner_state.right, &state->right,
+ c->right_start, c->right_count);
+
+ rc = diff_run_algo(algo_config->inner_algo, &inner_state);
+ state->kd_buf = inner_state.kd_buf;
+ state->kd_buf_size = inner_state.kd_buf_size;
+ if (rc != DIFF_RC_OK)
+ goto return_rc;
+ }
+
+ rc = DIFF_RC_OK;
+return_rc:
+ ARRAYLIST_FREE(state->temp_result);
+ return rc;
+}
+
+int
+diff_atomize_file(struct diff_data *d,
+ const struct diff_config *config,
+ FILE *f, const uint8_t *data, off_t len, int diff_flags)
+{
+ if (!config->atomize_func)
+ return EINVAL;
+
+ diff_data_init_root(d, f, data, len, diff_flags);
+
+ return config->atomize_func(config->atomize_func_data, d);
+
+}
+
+struct diff_result *
+diff_main(const struct diff_config *config, struct diff_data *left,
+ struct diff_data *right)
+{
+ struct diff_result *result = malloc(sizeof(struct diff_result));
+ if (!result)
+ return NULL;
+
+ *result = (struct diff_result){};
+ result->left = left;
+ result->right = right;
+
+ struct diff_state state = {
+ .result = result,
+ .recursion_depth_left = config->max_recursion_depth ? : 32,
+ .kd_buf = NULL,
+ .kd_buf_size = 0,
+ };
+ diff_data_init_subsection(&state.left, left,
+ left->atoms.head,
+ left->atoms.len);
+ diff_data_init_subsection(&state.right, right,
+ right->atoms.head,
+ right->atoms.len);
+
+ result->rc = diff_run_algo(config->algo, &state);
+ free(state.kd_buf);
+
+ return result;
+}
+
+void
+diff_result_free(struct diff_result *result)
+{
+ if (!result)
+ return;
+ ARRAYLIST_FREE(result->chunks);
+ free(result);
+}
diff --git a/lib/diff_main.h b/lib/diff_main.h
new file mode 100644
index 0000000..4014216
--- /dev/null
+++ b/lib/diff_main.h
@@ -0,0 +1,182 @@
+/* Generic infrastructure to implement various diff algorithms. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+struct diff_range {
+ int start;
+ int end;
+};
+
+/* List of all possible return codes of a diff invocation. */
+#define DIFF_RC_USE_DIFF_ALGO_FALLBACK -1
+#define DIFF_RC_OK 0
+/* Any positive return values are errno values from sys/errno.h */
+
+struct diff_atom;
+
+/* For each file, there is a "root" struct diff_data referencing the entire
+ * file, which the atoms are parsed from. In recursion of diff algorithm, there
+ * may be "child" struct diff_data only referencing a subsection of the file,
+ * re-using the atoms parsing. For "root" structs, atoms_allocated will be
+ * nonzero, indicating that the array of atoms is owned by that struct. For
+ * "child" structs, atoms_allocated == 0, to indicate that the struct is
+ * referencing a subset of atoms. */
+struct diff_data {
+ FILE *f; /* if root diff_data and not memory-mapped */
+ off_t pos; /* if not memory-mapped */
+ const uint8_t *data; /* if memory-mapped */
+ off_t len;
+
+ ARRAYLIST(struct diff_atom) atoms;
+ struct diff_data *root;
+ struct diff_data *current;
+ void *algo_data;
+
+ int diff_flags;
+
+ int err;
+};
+
+#define DIFF_FLAG_IGNORE_WHITESPACE 0x00000001
+#define DIFF_FLAG_SHOW_PROTOTYPES 0x00000002
+
+void diff_data_free(struct diff_data *diff_data);
+
+struct diff_chunk;
+typedef ARRAYLIST(struct diff_chunk) diff_chunk_arraylist_t;
+
+struct diff_result {
+ int rc;
+
+ /*
+ * Pointers to diff data passed in via diff_main.
+ * Do not free these diff_data before freeing the diff_result struct.
+ */
+ struct diff_data *left;
+ struct diff_data *right;
+
+ diff_chunk_arraylist_t chunks;
+};
+
+struct diff_state;
+
+/* Signature of a utility function to divide a file into diff atoms.
+ * An example is diff_atomize_text_by_line() in diff_atomize_text.c.
+ *
+ * func_data: context pointer (free to be used by implementation).
+ * d: struct diff_data with d->data and d->len already set up, and
+ * d->atoms to be created.
+ */
+typedef int (*diff_atomize_func_t)(void *func_data, struct diff_data *d);
+
+extern int diff_atomize_text_by_line(void *func_data, struct diff_data *d);
+
+struct diff_algo_config;
+typedef int (*diff_algo_impl_t)(
+ const struct diff_algo_config *algo_config, struct diff_state *state);
+
+/* Form a result with all left-side removed and all right-side added, i.e. no
+ * actual diff algorithm involved. */
+int diff_algo_none(const struct diff_algo_config *algo_config,
+ struct diff_state *state);
+
+/* Myers Diff tracing from the start all the way through to the end, requiring
+ * quadratic amounts of memory. This can fail if the required space surpasses
+ * algo_config->permitted_state_size. */
+extern int diff_algo_myers(const struct diff_algo_config *algo_config,
+ struct diff_state *state);
+
+/* Myers "Divide et Impera": tracing forwards from the start and backwards from
+ * the end to find a midpoint that divides the problem into smaller chunks.
+ * Requires only linear amounts of memory. */
+extern int diff_algo_myers_divide(
+ const struct diff_algo_config *algo_config, struct diff_state *state);
+
+/* Patience Diff algorithm, which divides a larger diff into smaller chunks. For
+ * very specific scenarios, it may lead to a complete diff result by itself, but
+ * needs a fallback algo to solve chunks that don't have common-unique atoms. */
+extern int diff_algo_patience(
+ const struct diff_algo_config *algo_config, struct diff_state *state);
+
+/* Diff algorithms to use, possibly nested. For example:
+ *
+ * struct diff_algo_config myers, patience, myers_divide;
+ *
+ * myers = (struct diff_algo_config){
+ * .impl = diff_algo_myers,
+ * .permitted_state_size = 32 * 1024 * 1024,
+ * // When too large, do diff_algo_patience:
+ * .fallback_algo = &patience,
+ * };
+ *
+ * const struct diff_algo_config patience = (struct diff_algo_config){
+ * .impl = diff_algo_patience,
+ * // After subdivision, do Patience again:
+ * .inner_algo = &patience,
+ * // If subdivision failed, do Myers Divide et Impera:
+ * .fallback_algo = &myers_then_myers_divide,
+ * };
+ *
+ * const struct diff_algo_config myers_divide = (struct diff_algo_config){
+ * .impl = diff_algo_myers_divide,
+ * // When division succeeded, start from the top:
+ * .inner_algo = &myers_then_myers_divide,
+ * // (fallback_algo = NULL implies diff_algo_none).
+ * };
+ * struct diff_config config = {
+ * .algo = &myers,
+ * ...
+ * };
+ * diff_main(&config, ...);
+ */
+struct diff_algo_config {
+ diff_algo_impl_t impl;
+
+ /* Fail this algo if it would use more than this amount of memory, and
+ * instead use fallback_algo (diff_algo_myers). permitted_state_size ==
+ * 0 means no limitation. */
+ size_t permitted_state_size;
+
+ /* For algorithms that divide into smaller chunks, use this algorithm to
+ * solve the divided chunks. */
+ const struct diff_algo_config *inner_algo;
+
+ /* If the algorithm fails (e.g. diff_algo_myers_if_small needs too large
+ * state, or diff_algo_patience can't find any common-unique atoms),
+ * then use this algorithm instead. */
+ const struct diff_algo_config *fallback_algo;
+};
+
+struct diff_config {
+ diff_atomize_func_t atomize_func;
+ void *atomize_func_data;
+
+ const struct diff_algo_config *algo;
+
+ /* How deep to step into subdivisions of a source file, a paranoia /
+ * safety measure to guard against infinite loops through diff
+ * algorithms. When the maximum recursion is reached, employ
+ * diff_algo_none (i.e. remove all left atoms and add all right atoms).
+ */
+ unsigned int max_recursion_depth;
+};
+
+int diff_atomize_file(struct diff_data *d, const struct diff_config *config,
+ FILE *f, const uint8_t *data, off_t len, int diff_flags);
+struct diff_result *diff_main(const struct diff_config *config,
+ struct diff_data *left,
+ struct diff_data *right);
+void diff_result_free(struct diff_result *result);
diff --git a/lib/diff_myers.c b/lib/diff_myers.c
new file mode 100644
index 0000000..a286036
--- /dev/null
+++ b/lib/diff_myers.c
@@ -0,0 +1,1419 @@
+/* Myers diff algorithm implementation, invented by Eugene W. Myers [1].
+ * Implementations of both the Myers Divide Et Impera (using linear space)
+ * and the canonical Myers algorithm (using quadratic space). */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+
+#include "diff_internal.h"
+#include "diff_debug.h"
+
+/* Myers' diff algorithm [1] is nicely explained in [2].
+ * [1] http://www.xmailserver.org/diff2.pdf
+ * [2] https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/ ff.
+ *
+ * Myers approaches finding the smallest diff as a graph problem.
+ * The crux is that the original algorithm requires quadratic amount of memory:
+ * both sides' lengths added, and that squared. So if we're diffing lines of
+ * text, two files with 1000 lines each would blow up to a matrix of about
+ * 2000 * 2000 ints of state, about 16 Mb of RAM to figure out 2 kb of text.
+ * The solution is using Myers' "divide and conquer" extension algorithm, which
+ * does the original traversal from both ends of the files to reach a middle
+ * where these "snakes" touch, hence does not need to backtrace the traversal,
+ * and so gets away with only keeping a single column of that huge state matrix
+ * in memory.
+ */
+
+struct diff_box {
+ unsigned int left_start;
+ unsigned int left_end;
+ unsigned int right_start;
+ unsigned int right_end;
+};
+
+/* If the two contents of a file are A B C D E and X B C Y,
+ * the Myers diff graph looks like:
+ *
+ * k0 k1
+ * \ \
+ * k-1 0 1 2 3 4 5
+ * \ A B C D E
+ * 0 o-o-o-o-o-o
+ * X | | | | | |
+ * 1 o-o-o-o-o-o
+ * B | |\| | | |
+ * 2 o-o-o-o-o-o
+ * C | | |\| | |
+ * 3 o-o-o-o-o-o
+ * Y | | | | | |\
+ * 4 o-o-o-o-o-o c1
+ * \ \
+ * c-1 c0
+ *
+ * Moving right means delete an atom from the left-hand-side,
+ * Moving down means add an atom from the right-hand-side.
+ * Diagonals indicate identical atoms on both sides, the challenge is to use as
+ * many diagonals as possible.
+ *
+ * The original Myers algorithm walks all the way from the top left to the
+ * bottom right, remembers all steps, and then backtraces to find the shortest
+ * path. However, that requires keeping the entire graph in memory, which needs
+ * quadratic space.
+ *
+ * Myers adds a variant that uses linear space -- note, not linear time, only
+ * linear space: walk forward and backward, find a meeting point in the middle,
+ * and recurse on the two separate sections. This is called "divide and
+ * conquer".
+ *
+ * d: the step number, starting with 0, a.k.a. the distance from the starting
+ * point.
+ * k: relative index in the state array for the forward scan, indicating on
+ * which diagonal through the diff graph we currently are.
+ * c: relative index in the state array for the backward scan, indicating the
+ * diagonal number from the bottom up.
+ *
+ * The "divide and conquer" traversal through the Myers graph looks like this:
+ *
+ * | d= 0 1 2 3 2 1 0
+ * ----+--------------------------------------------
+ * k= | c=
+ * 4 | 3
+ * |
+ * 3 | 3,0 5,2 2
+ * | / \
+ * 2 | 2,0 5,3 1
+ * | / \
+ * 1 | 1,0 4,3 >= 4,3 5,4<-- 0
+ * | / / \ /
+ * 0 | -->0,0 3,3 4,4 -1
+ * | \ / /
+ * -1 | 0,1 1,2 3,4 -2
+ * | \ /
+ * -2 | 0,2 -3
+ * | \
+ * | 0,3
+ * | forward-> <-backward
+ *
+ * x,y pairs here are the coordinates in the Myers graph:
+ * x = atom index in left-side source, y = atom index in the right-side source.
+ *
+ * Only one forward column and one backward column are kept in mem, each need at
+ * most left.len + 1 + right.len items. Note that each d step occupies either
+ * the even or the odd items of a column: if e.g. the previous column is in the
+ * odd items, the next column is formed in the even items, without overwriting
+ * the previous column's results.
+ *
+ * Also note that from the diagonal index k and the x coordinate, the y
+ * coordinate can be derived:
+ * y = x - k
+ * Hence the state array only needs to keep the x coordinate, i.e. the position
+ * in the left-hand file, and the y coordinate, i.e. position in the right-hand
+ * file, is derived from the index in the state array.
+ *
+ * The two traces meet at 4,3, the first step (here found in the forward
+ * traversal) where a forward position is on or past a backward traced position
+ * on the same diagonal.
+ *
+ * This divides the problem space into:
+ *
+ * 0 1 2 3 4 5
+ * A B C D E
+ * 0 o-o-o-o-o
+ * X | | | | |
+ * 1 o-o-o-o-o
+ * B | |\| | |
+ * 2 o-o-o-o-o
+ * C | | |\| |
+ * 3 o-o-o-o-*-o *: forward and backward meet here
+ * Y | |
+ * 4 o-o
+ *
+ * Doing the same on each section lead to:
+ *
+ * 0 1 2 3 4 5
+ * A B C D E
+ * 0 o-o
+ * X | |
+ * 1 o-b b: backward d=1 first reaches here (sliding up the snake)
+ * B \ f: then forward d=2 reaches here (sliding down the snake)
+ * 2 o As result, the box from b to f is found to be identical;
+ * C \ leaving a top box from 0,0 to 1,1 and a bottom trivial
+ * 3 f-o tail 3,3 to 4,3.
+ *
+ * 3 o-*
+ * Y |
+ * 4 o *: forward and backward meet here
+ *
+ * and solving the last top left box gives:
+ *
+ * 0 1 2 3 4 5
+ * A B C D E -A
+ * 0 o-o +X
+ * X | B
+ * 1 o C
+ * B \ -D
+ * 2 o -E
+ * C \ +Y
+ * 3 o-o-o
+ * Y |
+ * 4 o
+ *
+ */
+
+#define xk_to_y(X, K) ((X) - (K))
+#define xc_to_y(X, C, DELTA) ((X) - (C) + (DELTA))
+#define k_to_c(K, DELTA) ((K) + (DELTA))
+#define c_to_k(C, DELTA) ((C) - (DELTA))
+
+/* Do one forwards step in the "divide and conquer" graph traversal.
+ * left: the left side to diff.
+ * right: the right side to diff against.
+ * kd_forward: the traversal state for forwards traversal, modified by this
+ * function.
+ * This is carried over between invocations with increasing d.
+ * kd_forward points at the center of the state array, allowing
+ * negative indexes.
+ * kd_backward: the traversal state for backwards traversal, to find a meeting
+ * point.
+ * Since forwards is done first, kd_backward will be valid for d -
+ * 1, not d.
+ * kd_backward points at the center of the state array, allowing
+ * negative indexes.
+ * d: Step or distance counter, indicating for what value of d the kd_forward
+ * should be populated.
+ * For d == 0, kd_forward[0] is initialized, i.e. the first invocation should
+ * be for d == 0.
+ * meeting_snake: resulting meeting point, if any.
+ * Return true when a meeting point has been identified.
+ */
+static int
+diff_divide_myers_forward(bool *found_midpoint,
+ struct diff_data *left, struct diff_data *right,
+ int *kd_forward, int *kd_backward, int d,
+ struct diff_box *meeting_snake)
+{
+ int delta = (int)right->atoms.len - (int)left->atoms.len;
+ int k;
+ int x;
+ int prev_x;
+ int prev_y;
+ int x_before_slide;
+ *found_midpoint = false;
+
+ for (k = d; k >= -d; k -= 2) {
+ if (k < -(int)right->atoms.len || k > (int)left->atoms.len) {
+ /* This diagonal is completely outside of the Myers
+ * graph, don't calculate it. */
+ if (k < 0) {
+ /* We are traversing negatively, and already
+ * below the entire graph, nothing will come of
+ * this. */
+ debug(" break\n");
+ break;
+ }
+ debug(" continue\n");
+ continue;
+ }
+ if (d == 0) {
+ /* This is the initializing step. There is no prev_k
+ * yet, get the initial x from the top left of the Myers
+ * graph. */
+ x = 0;
+ prev_x = x;
+ prev_y = xk_to_y(x, k);
+ }
+ /* Favoring "-" lines first means favoring moving rightwards in
+ * the Myers graph.
+ * For this, all k should derive from k - 1, only the bottom
+ * most k derive from k + 1:
+ *
+ * | d= 0 1 2
+ * ----+----------------
+ * k= |
+ * 2 | 2,0 <-- from prev_k = 2 - 1 = 1
+ * | /
+ * 1 | 1,0
+ * | /
+ * 0 | -->0,0 3,3
+ * | \\ /
+ * -1 | 0,1 <-- bottom most for d=1 from
+ * | \\ prev_k = -1 + 1 = 0
+ * -2 | 0,2 <-- bottom most for d=2 from
+ * prev_k = -2 + 1 = -1
+ *
+ * Except when a k + 1 from a previous run already means a
+ * further advancement in the graph.
+ * If k == d, there is no k + 1 and k - 1 is the only option.
+ * If k < d, use k + 1 in case that yields a larger x. Also use
+ * k + 1 if k - 1 is outside the graph.
+ */
+ else if (k > -d
+ && (k == d
+ || (k - 1 >= -(int)right->atoms.len
+ && kd_forward[k - 1] >= kd_forward[k + 1]))) {
+ /* Advance from k - 1.
+ * From position prev_k, step to the right in the Myers
+ * graph: x += 1.
+ */
+ int prev_k = k - 1;
+ prev_x = kd_forward[prev_k];
+ prev_y = xk_to_y(prev_x, prev_k);
+ x = prev_x + 1;
+ } else {
+ /* The bottom most one.
+ * From position prev_k, step to the bottom in the Myers
+ * graph: y += 1.
+ * Incrementing y is achieved by decrementing k while
+ * keeping the same x.
+ * (since we're deriving y from y = x - k).
+ */
+ int prev_k = k + 1;
+ prev_x = kd_forward[prev_k];
+ prev_y = xk_to_y(prev_x, prev_k);
+ x = prev_x;
+ }
+
+ x_before_slide = x;
+ /* Slide down any snake that we might find here. */
+ while (x < left->atoms.len && xk_to_y(x, k) < right->atoms.len) {
+ bool same;
+ int r = diff_atom_same(&same,
+ &left->atoms.head[x],
+ &right->atoms.head[
+ xk_to_y(x, k)]);
+ if (r)
+ return r;
+ if (!same)
+ break;
+ x++;
+ }
+ kd_forward[k] = x;
+#if 0
+ if (x_before_slide != x) {
+ debug(" down %d similar lines\n", x - x_before_slide);
+ }
+
+#if DEBUG
+ {
+ int fi;
+ for (fi = d; fi >= k; fi--) {
+ debug("kd_forward[%d] = (%d, %d)\n", fi,
+ kd_forward[fi], kd_forward[fi] - fi);
+ }
+ }
+#endif
+#endif
+
+ if (x < 0 || x > left->atoms.len
+ || xk_to_y(x, k) < 0 || xk_to_y(x, k) > right->atoms.len)
+ continue;
+
+ /* Figured out a new forwards traversal, see if this has gone
+ * onto or even past a preceding backwards traversal.
+ *
+ * If the delta in length is odd, then d and backwards_d hit the
+ * same state indexes:
+ * | d= 0 1 2 1 0
+ * ----+---------------- ----------------
+ * k= | c=
+ * 4 | 3
+ * |
+ * 3 | 2
+ * | same
+ * 2 | 2,0====5,3 1
+ * | / \
+ * 1 | 1,0 5,4<-- 0
+ * | / /
+ * 0 | -->0,0 3,3====4,4 -1
+ * | \ /
+ * -1 | 0,1 -2
+ * | \
+ * -2 | 0,2 -3
+ * |
+ *
+ * If the delta is even, they end up off-by-one, i.e. on
+ * different diagonals:
+ *
+ * | d= 0 1 2 1 0
+ * ----+---------------- ----------------
+ * | c=
+ * 3 | 3
+ * |
+ * 2 | 2,0 off 2
+ * | / \\
+ * 1 | 1,0 4,3 1
+ * | / // \
+ * 0 | -->0,0 3,3 4,4<-- 0
+ * | \ / /
+ * -1 | 0,1 3,4 -1
+ * | \ //
+ * -2 | 0,2 -2
+ * |
+ *
+ * So in the forward path, we can only match up diagonals when
+ * the delta is odd.
+ */
+ if ((delta & 1) == 0)
+ continue;
+ /* Forwards is done first, so the backwards one was still at
+ * d - 1. Can't do this for d == 0. */
+ int backwards_d = d - 1;
+ if (backwards_d < 0)
+ continue;
+
+ /* If both sides have the same length, forward and backward
+ * start on the same diagonal, meaning the backwards state index
+ * c == k.
+ * As soon as the lengths are not the same, the backwards
+ * traversal starts on a different diagonal, and c = k shifted
+ * by the difference in length.
+ */
+ int c = k_to_c(k, delta);
+
+ /* When the file sizes are very different, the traversal trees
+ * start on far distant diagonals.
+ * They don't necessarily meet straight on. See whether this
+ * forward value is on a diagonal that is also valid in
+ * kd_backward[], and match them if so. */
+ if (c >= -backwards_d && c <= backwards_d) {
+ /* Current k is on a diagonal that exists in
+ * kd_backward[]. If the two x positions have met or
+ * passed (forward walked onto or past backward), then
+ * we've found a midpoint / a mid-box.
+ *
+ * When forwards and backwards traversals meet, the
+ * endpoints of the mid-snake are not the two points in
+ * kd_forward and kd_backward, but rather the section
+ * that was slid (if any) of the current
+ * forward/backward traversal only.
+ *
+ * For example:
+ *
+ * o
+ * \
+ * o
+ * \
+ * o
+ * \
+ * o
+ * \
+ * X o o
+ * | | |
+ * o-o-o o
+ * \|
+ * M
+ * \
+ * o
+ * \
+ * A o
+ * | |
+ * o-o-o
+ *
+ * The forward traversal reached M from the top and slid
+ * downwards to A. The backward traversal already
+ * reached X, which is not a straight line from M
+ * anymore, so picking a mid-snake from M to X would
+ * yield a mistake.
+ *
+ * The correct mid-snake is between M and A. M is where
+ * the forward traversal hit the diagonal that the
+ * backward traversal has already passed, and A is what
+ * it reaches when sliding down identical lines.
+ */
+ int backward_x = kd_backward[c];
+ if (x >= backward_x) {
+ if (x_before_slide != x) {
+ /* met after sliding up a mid-snake */
+ *meeting_snake = (struct diff_box){
+ .left_start = x_before_slide,
+ .left_end = x,
+ .right_start = xc_to_y(x_before_slide,
+ c, delta),
+ .right_end = xk_to_y(x, k),
+ };
+ } else {
+ /* met after a side step, non-identical
+ * line. Mark that as box divider
+ * instead. This makes sure that
+ * myers_divide never returns the same
+ * box that came as input, avoiding
+ * "infinite" looping. */
+ *meeting_snake = (struct diff_box){
+ .left_start = prev_x,
+ .left_end = x,
+ .right_start = prev_y,
+ .right_end = xk_to_y(x, k),
+ };
+ }
+ debug("HIT x=(%u,%u) - y=(%u,%u)\n",
+ meeting_snake->left_start,
+ meeting_snake->right_start,
+ meeting_snake->left_end,
+ meeting_snake->right_end);
+ debug_dump_myers_graph(left, right, NULL,
+ kd_forward, d,
+ kd_backward, d-1);
+ *found_midpoint = true;
+ return 0;
+ }
+ }
+ }
+
+ return 0;
+}
+
+/* Do one backwards step in the "divide and conquer" graph traversal.
+ * left: the left side to diff.
+ * right: the right side to diff against.
+ * kd_forward: the traversal state for forwards traversal, to find a meeting
+ * point.
+ * Since forwards is done first, after this, both kd_forward and
+ * kd_backward will be valid for d.
+ * kd_forward points at the center of the state array, allowing
+ * negative indexes.
+ * kd_backward: the traversal state for backwards traversal, to find a meeting
+ * point.
+ * This is carried over between invocations with increasing d.
+ * kd_backward points at the center of the state array, allowing
+ * negative indexes.
+ * d: Step or distance counter, indicating for what value of d the kd_backward
+ * should be populated.
+ * Before the first invocation, kd_backward[0] shall point at the bottom
+ * right of the Myers graph (left.len, right.len).
+ * The first invocation will be for d == 1.
+ * meeting_snake: resulting meeting point, if any.
+ * Return true when a meeting point has been identified.
+ */
+static int
+diff_divide_myers_backward(bool *found_midpoint,
+ struct diff_data *left, struct diff_data *right,
+ int *kd_forward, int *kd_backward, int d,
+ struct diff_box *meeting_snake)
+{
+ int delta = (int)right->atoms.len - (int)left->atoms.len;
+ int c;
+ int x;
+ int prev_x;
+ int prev_y;
+ int x_before_slide;
+
+ *found_midpoint = false;
+
+ for (c = d; c >= -d; c -= 2) {
+ if (c < -(int)left->atoms.len || c > (int)right->atoms.len) {
+ /* This diagonal is completely outside of the Myers
+ * graph, don't calculate it. */
+ if (c < 0) {
+ /* We are traversing negatively, and already
+ * below the entire graph, nothing will come of
+ * this. */
+ break;
+ }
+ continue;
+ }
+ if (d == 0) {
+ /* This is the initializing step. There is no prev_c
+ * yet, get the initial x from the bottom right of the
+ * Myers graph. */
+ x = left->atoms.len;
+ prev_x = x;
+ prev_y = xc_to_y(x, c, delta);
+ }
+ /* Favoring "-" lines first means favoring moving rightwards in
+ * the Myers graph.
+ * For this, all c should derive from c - 1, only the bottom
+ * most c derive from c + 1:
+ *
+ * 2 1 0
+ * ---------------------------------------------------
+ * c=
+ * 3
+ *
+ * from prev_c = c - 1 --> 5,2 2
+ * \
+ * 5,3 1
+ * \
+ * 4,3 5,4<-- 0
+ * \ /
+ * bottom most for d=1 from c + 1 --> 4,4 -1
+ * /
+ * bottom most for d=2 --> 3,4 -2
+ *
+ * Except when a c + 1 from a previous run already means a
+ * further advancement in the graph.
+ * If c == d, there is no c + 1 and c - 1 is the only option.
+ * If c < d, use c + 1 in case that yields a larger x.
+ * Also use c + 1 if c - 1 is outside the graph.
+ */
+ else if (c > -d && (c == d
+ || (c - 1 >= -(int)right->atoms.len
+ && kd_backward[c - 1] <= kd_backward[c + 1]))) {
+ /* A top one.
+ * From position prev_c, step upwards in the Myers
+ * graph: y -= 1.
+ * Decrementing y is achieved by incrementing c while
+ * keeping the same x. (since we're deriving y from
+ * y = x - c + delta).
+ */
+ int prev_c = c - 1;
+ prev_x = kd_backward[prev_c];
+ prev_y = xc_to_y(prev_x, prev_c, delta);
+ x = prev_x;
+ } else {
+ /* The bottom most one.
+ * From position prev_c, step to the left in the Myers
+ * graph: x -= 1.
+ */
+ int prev_c = c + 1;
+ prev_x = kd_backward[prev_c];
+ prev_y = xc_to_y(prev_x, prev_c, delta);
+ x = prev_x - 1;
+ }
+
+ /* Slide up any snake that we might find here (sections of
+ * identical lines on both sides). */
+#if 0
+ debug("c=%d x-1=%d Yb-1=%d-1=%d\n", c, x-1, xc_to_y(x, c,
+ delta),
+ xc_to_y(x, c, delta)-1);
+ if (x > 0) {
+ debug(" l=");
+ debug_dump_atom(left, right, &left->atoms.head[x-1]);
+ }
+ if (xc_to_y(x, c, delta) > 0) {
+ debug(" r=");
+ debug_dump_atom(right, left,
+ &right->atoms.head[xc_to_y(x, c, delta)-1]);
+ }
+#endif
+ x_before_slide = x;
+ while (x > 0 && xc_to_y(x, c, delta) > 0) {
+ bool same;
+ int r = diff_atom_same(&same,
+ &left->atoms.head[x-1],
+ &right->atoms.head[
+ xc_to_y(x, c, delta)-1]);
+ if (r)
+ return r;
+ if (!same)
+ break;
+ x--;
+ }
+ kd_backward[c] = x;
+#if 0
+ if (x_before_slide != x) {
+ debug(" up %d similar lines\n", x_before_slide - x);
+ }
+
+ if (DEBUG) {
+ int fi;
+ for (fi = d; fi >= c; fi--) {
+ debug("kd_backward[%d] = (%d, %d)\n",
+ fi,
+ kd_backward[fi],
+ kd_backward[fi] - fi + delta);
+ }
+ }
+#endif
+
+ if (x < 0 || x > left->atoms.len
+ || xc_to_y(x, c, delta) < 0
+ || xc_to_y(x, c, delta) > right->atoms.len)
+ continue;
+
+ /* Figured out a new backwards traversal, see if this has gone
+ * onto or even past a preceding forwards traversal.
+ *
+ * If the delta in length is even, then d and backwards_d hit
+ * the same state indexes -- note how this is different from in
+ * the forwards traversal, because now both d are the same:
+ *
+ * | d= 0 1 2 2 1 0
+ * ----+---------------- --------------------
+ * k= | c=
+ * 4 |
+ * |
+ * 3 | 3
+ * | same
+ * 2 | 2,0====5,2 2
+ * | / \
+ * 1 | 1,0 5,3 1
+ * | / / \
+ * 0 | -->0,0 3,3====4,3 5,4<-- 0
+ * | \ / /
+ * -1 | 0,1 4,4 -1
+ * | \
+ * -2 | 0,2 -2
+ * |
+ * -3
+ * If the delta is odd, they end up off-by-one, i.e. on
+ * different diagonals.
+ * So in the backward path, we can only match up diagonals when
+ * the delta is even.
+ */
+ if ((delta & 1) != 0)
+ continue;
+ /* Forwards was done first, now both d are the same. */
+ int forwards_d = d;
+
+ /* As soon as the lengths are not the same, the
+ * backwards traversal starts on a different diagonal,
+ * and c = k shifted by the difference in length.
+ */
+ int k = c_to_k(c, delta);
+
+ /* When the file sizes are very different, the traversal trees
+ * start on far distant diagonals.
+ * They don't necessarily meet straight on. See whether this
+ * backward value is also on a valid diagonal in kd_forward[],
+ * and match them if so. */
+ if (k >= -forwards_d && k <= forwards_d) {
+ /* Current c is on a diagonal that exists in
+ * kd_forward[]. If the two x positions have met or
+ * passed (backward walked onto or past forward), then
+ * we've found a midpoint / a mid-box.
+ *
+ * When forwards and backwards traversals meet, the
+ * endpoints of the mid-snake are not the two points in
+ * kd_forward and kd_backward, but rather the section
+ * that was slid (if any) of the current
+ * forward/backward traversal only.
+ *
+ * For example:
+ *
+ * o-o-o
+ * | |
+ * o A
+ * | \
+ * o o
+ * \
+ * M
+ * |\
+ * o o-o-o
+ * | | |
+ * o o X
+ * \
+ * o
+ * \
+ * o
+ * \
+ * o
+ *
+ * The backward traversal reached M from the bottom and
+ * slid upwards. The forward traversal already reached
+ * X, which is not a straight line from M anymore, so
+ * picking a mid-snake from M to X would yield a
+ * mistake.
+ *
+ * The correct mid-snake is between M and A. M is where
+ * the backward traversal hit the diagonal that the
+ * forwards traversal has already passed, and A is what
+ * it reaches when sliding up identical lines.
+ */
+
+ int forward_x = kd_forward[k];
+ if (forward_x >= x) {
+ if (x_before_slide != x) {
+ /* met after sliding down a mid-snake */
+ *meeting_snake = (struct diff_box){
+ .left_start = x,
+ .left_end = x_before_slide,
+ .right_start = xc_to_y(x, c, delta),
+ .right_end = xk_to_y(x_before_slide, k),
+ };
+ } else {
+ /* met after a side step, non-identical
+ * line. Mark that as box divider
+ * instead. This makes sure that
+ * myers_divide never returns the same
+ * box that came as input, avoiding
+ * "infinite" looping. */
+ *meeting_snake = (struct diff_box){
+ .left_start = x,
+ .left_end = prev_x,
+ .right_start = xc_to_y(x, c, delta),
+ .right_end = prev_y,
+ };
+ }
+ debug("HIT x=%u,%u - y=%u,%u\n",
+ meeting_snake->left_start,
+ meeting_snake->right_start,
+ meeting_snake->left_end,
+ meeting_snake->right_end);
+ debug_dump_myers_graph(left, right, NULL,
+ kd_forward, d,
+ kd_backward, d);
+ *found_midpoint = true;
+ return 0;
+ }
+ }
+ }
+ return 0;
+}
+
+/* Integer square root approximation */
+static int
+shift_sqrt(int val)
+{
+ int i;
+ for (i = 1; val > 0; val >>= 2)
+ i <<= 1;
+ return i;
+}
+
+/* Myers "Divide et Impera": tracing forwards from the start and backwards from
+ * the end to find a midpoint that divides the problem into smaller chunks.
+ * Requires only linear amounts of memory. */
+int
+diff_algo_myers_divide(const struct diff_algo_config *algo_config,
+ struct diff_state *state)
+{
+ int rc = ENOMEM;
+ struct diff_data *left = &state->left;
+ struct diff_data *right = &state->right;
+ int *kd_buf;
+
+ debug("\n** %s\n", __func__);
+ debug("left:\n");
+ debug_dump(left);
+ debug("right:\n");
+ debug_dump(right);
+
+ /* Allocate two columns of a Myers graph, one for the forward and one
+ * for the backward traversal. */
+ unsigned int max = left->atoms.len + right->atoms.len;
+ size_t kd_len = max + 1;
+ size_t kd_buf_size = kd_len << 1;
+
+ if (state->kd_buf_size < kd_buf_size) {
+ kd_buf = reallocarray(state->kd_buf, kd_buf_size,
+ sizeof(int));
+ if (!kd_buf)
+ return ENOMEM;
+ state->kd_buf = kd_buf;
+ state->kd_buf_size = kd_buf_size;
+ } else
+ kd_buf = state->kd_buf;
+ int i;
+ for (i = 0; i < kd_buf_size; i++)
+ kd_buf[i] = -1;
+ int *kd_forward = kd_buf;
+ int *kd_backward = kd_buf + kd_len;
+ int max_effort = shift_sqrt(max/2);
+
+ /* The 'k' axis in Myers spans positive and negative indexes, so point
+ * the kd to the middle.
+ * It is then possible to index from -max/2 .. max/2. */
+ kd_forward += max/2;
+ kd_backward += max/2;
+
+ int d;
+ struct diff_box mid_snake = {};
+ bool found_midpoint = false;
+ for (d = 0; d <= (max/2); d++) {
+ int r;
+ r = diff_divide_myers_forward(&found_midpoint, left, right,
+ kd_forward, kd_backward, d,
+ &mid_snake);
+ if (r)
+ return r;
+ if (found_midpoint)
+ break;
+ r = diff_divide_myers_backward(&found_midpoint, left, right,
+ kd_forward, kd_backward, d,
+ &mid_snake);
+ if (r)
+ return r;
+ if (found_midpoint)
+ break;
+
+ /* Limit the effort spent looking for a mid snake. If files have
+ * very few lines in common, the effort spent to find nice mid
+ * snakes is just not worth it, the diff result will still be
+ * essentially minus everything on the left, plus everything on
+ * the right, with a few useless matches here and there. */
+ if (d > max_effort) {
+ /* pick the furthest reaching point from
+ * kd_forward and kd_backward, and use that as a
+ * midpoint, to not step into another diff algo
+ * recursion with unchanged box. */
+ int delta = (int)right->atoms.len - (int)left->atoms.len;
+ int x = 0;
+ int y;
+ int i;
+ int best_forward_i = 0;
+ int best_forward_distance = 0;
+ int best_backward_i = 0;
+ int best_backward_distance = 0;
+ int distance;
+ int best_forward_x;
+ int best_forward_y;
+ int best_backward_x;
+ int best_backward_y;
+
+ debug("~~~ HIT d = %d > max_effort = %d\n", d, max_effort);
+ debug_dump_myers_graph(left, right, NULL,
+ kd_forward, d,
+ kd_backward, d);
+
+ for (i = d; i >= -d; i -= 2) {
+ if (i >= -(int)right->atoms.len && i <= (int)left->atoms.len) {
+ x = kd_forward[i];
+ y = xk_to_y(x, i);
+ distance = x + y;
+ if (distance > best_forward_distance) {
+ best_forward_distance = distance;
+ best_forward_i = i;
+ }
+ }
+
+ if (i >= -(int)left->atoms.len && i <= (int)right->atoms.len) {
+ x = kd_backward[i];
+ y = xc_to_y(x, i, delta);
+ distance = (right->atoms.len - x)
+ + (left->atoms.len - y);
+ if (distance >= best_backward_distance) {
+ best_backward_distance = distance;
+ best_backward_i = i;
+ }
+ }
+ }
+
+ /* The myers-divide didn't meet in the middle. We just
+ * figured out the places where the forward path
+ * advanced the most, and the backward path advanced the
+ * most. Just divide at whichever one of those two is better.
+ *
+ * o-o
+ * |
+ * o
+ * \
+ * o
+ * \
+ * F <-- cut here
+ *
+ *
+ *
+ * or here --> B
+ * \
+ * o
+ * \
+ * o
+ * |
+ * o-o
+ */
+ best_forward_x = kd_forward[best_forward_i];
+ best_forward_y = xk_to_y(best_forward_x, best_forward_i);
+ best_backward_x = kd_backward[best_backward_i];
+ best_backward_y = xc_to_y(best_backward_x, best_backward_i, delta);
+
+ if (best_forward_distance >= best_backward_distance) {
+ x = best_forward_x;
+ y = best_forward_y;
+ } else {
+ x = best_backward_x;
+ y = best_backward_y;
+ }
+
+ debug("max_effort cut at x=%d y=%d\n", x, y);
+ if (x < 0 || y < 0
+ || x > left->atoms.len || y > right->atoms.len)
+ break;
+
+ found_midpoint = true;
+ mid_snake = (struct diff_box){
+ .left_start = x,
+ .left_end = x,
+ .right_start = y,
+ .right_end = y,
+ };
+ break;
+ }
+ }
+
+ if (!found_midpoint) {
+ /* Divide and conquer failed to find a meeting point. Use the
+ * fallback_algo defined in the algo_config (leave this to the
+ * caller). This is just paranoia/sanity, we normally should
+ * always find a midpoint.
+ */
+ debug(" no midpoint \n");
+ rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
+ goto return_rc;
+ } else {
+ debug(" mid snake L: %u to %u of %u R: %u to %u of %u\n",
+ mid_snake.left_start, mid_snake.left_end, left->atoms.len,
+ mid_snake.right_start, mid_snake.right_end,
+ right->atoms.len);
+
+ /* Section before the mid-snake. */
+ debug("Section before the mid-snake\n");
+
+ struct diff_atom *left_atom = &left->atoms.head[0];
+ unsigned int left_section_len = mid_snake.left_start;
+ struct diff_atom *right_atom = &right->atoms.head[0];
+ unsigned int right_section_len = mid_snake.right_start;
+
+ if (left_section_len && right_section_len) {
+ /* Record an unsolved chunk, the caller will apply
+ * inner_algo() on this chunk. */
+ if (!diff_state_add_chunk(state, false,
+ left_atom, left_section_len,
+ right_atom,
+ right_section_len))
+ goto return_rc;
+ } else if (left_section_len && !right_section_len) {
+ /* Only left atoms and none on the right, they form a
+ * "minus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, left_section_len,
+ right_atom, 0))
+ goto return_rc;
+ } else if (!left_section_len && right_section_len) {
+ /* No left atoms, only atoms on the right, they form a
+ * "plus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, 0,
+ right_atom,
+ right_section_len))
+ goto return_rc;
+ }
+ /* else: left_section_len == 0 and right_section_len == 0, i.e.
+ * nothing before the mid-snake. */
+
+ if (mid_snake.left_end > mid_snake.left_start
+ || mid_snake.right_end > mid_snake.right_start) {
+ /* The midpoint is a section of identical data on both
+ * sides, or a certain differing line: that section
+ * immediately becomes a solved chunk. */
+ debug("the mid-snake\n");
+ if (!diff_state_add_chunk(state, true,
+ &left->atoms.head[mid_snake.left_start],
+ mid_snake.left_end - mid_snake.left_start,
+ &right->atoms.head[mid_snake.right_start],
+ mid_snake.right_end - mid_snake.right_start))
+ goto return_rc;
+ }
+
+ /* Section after the mid-snake. */
+ debug("Section after the mid-snake\n");
+ debug(" left_end %u right_end %u\n",
+ mid_snake.left_end, mid_snake.right_end);
+ debug(" left_count %u right_count %u\n",
+ left->atoms.len, right->atoms.len);
+ left_atom = &left->atoms.head[mid_snake.left_end];
+ left_section_len = left->atoms.len - mid_snake.left_end;
+ right_atom = &right->atoms.head[mid_snake.right_end];
+ right_section_len = right->atoms.len - mid_snake.right_end;
+
+ if (left_section_len && right_section_len) {
+ /* Record an unsolved chunk, the caller will apply
+ * inner_algo() on this chunk. */
+ if (!diff_state_add_chunk(state, false,
+ left_atom, left_section_len,
+ right_atom,
+ right_section_len))
+ goto return_rc;
+ } else if (left_section_len && !right_section_len) {
+ /* Only left atoms and none on the right, they form a
+ * "minus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, left_section_len,
+ right_atom, 0))
+ goto return_rc;
+ } else if (!left_section_len && right_section_len) {
+ /* No left atoms, only atoms on the right, they form a
+ * "plus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, 0,
+ right_atom,
+ right_section_len))
+ goto return_rc;
+ }
+ /* else: left_section_len == 0 and right_section_len == 0, i.e.
+ * nothing after the mid-snake. */
+ }
+
+ rc = DIFF_RC_OK;
+
+return_rc:
+ debug("** END %s\n", __func__);
+ return rc;
+}
+
+/* Myers Diff tracing from the start all the way through to the end, requiring
+ * quadratic amounts of memory. This can fail if the required space surpasses
+ * algo_config->permitted_state_size. */
+int
+diff_algo_myers(const struct diff_algo_config *algo_config,
+ struct diff_state *state)
+{
+ /* do a diff_divide_myers_forward() without a _backward(), so that it
+ * walks forward across the entire files to reach the end. Keep each
+ * run's state, and do a final backtrace. */
+ int rc = ENOMEM;
+ struct diff_data *left = &state->left;
+ struct diff_data *right = &state->right;
+ int *kd_buf;
+
+ debug("\n** %s\n", __func__);
+ debug("left:\n");
+ debug_dump(left);
+ debug("right:\n");
+ debug_dump(right);
+ debug_dump_myers_graph(left, right, NULL, NULL, 0, NULL, 0);
+
+ /* Allocate two columns of a Myers graph, one for the forward and one
+ * for the backward traversal. */
+ unsigned int max = left->atoms.len + right->atoms.len;
+ size_t kd_len = max + 1 + max;
+ size_t kd_buf_size = kd_len * kd_len;
+ size_t kd_state_size = kd_buf_size * sizeof(int);
+ debug("state size: %zu\n", kd_state_size);
+ if (kd_buf_size < kd_len /* overflow? */
+ || kd_state_size > algo_config->permitted_state_size) {
+ debug("state size %zu > permitted_state_size %zu, use fallback_algo\n",
+ kd_state_size, algo_config->permitted_state_size);
+ return DIFF_RC_USE_DIFF_ALGO_FALLBACK;
+ }
+
+ if (state->kd_buf_size < kd_buf_size) {
+ kd_buf = reallocarray(state->kd_buf, kd_buf_size,
+ sizeof(int));
+ if (!kd_buf)
+ return ENOMEM;
+ state->kd_buf = kd_buf;
+ state->kd_buf_size = kd_buf_size;
+ } else
+ kd_buf = state->kd_buf;
+
+ int i;
+ for (i = 0; i < kd_buf_size; i++)
+ kd_buf[i] = -1;
+
+ /* The 'k' axis in Myers spans positive and negative indexes, so point
+ * the kd to the middle.
+ * It is then possible to index from -max .. max. */
+ int *kd_origin = kd_buf + max;
+ int *kd_column = kd_origin;
+
+ int d;
+ int backtrack_d = -1;
+ int backtrack_k = 0;
+ int k;
+ int x, y;
+ for (d = 0; d <= max; d++, kd_column += kd_len) {
+ debug("-- %s d=%d\n", __func__, d);
+
+ for (k = d; k >= -d; k -= 2) {
+ if (k < -(int)right->atoms.len
+ || k > (int)left->atoms.len) {
+ /* This diagonal is completely outside of the
+ * Myers graph, don't calculate it. */
+ if (k < -(int)right->atoms.len)
+ debug(" %d k <"
+ " -(int)right->atoms.len %d\n",
+ k, -(int)right->atoms.len);
+ else
+ debug(" %d k > left->atoms.len %d\n", k,
+ left->atoms.len);
+ if (k < 0) {
+ /* We are traversing negatively, and
+ * already below the entire graph,
+ * nothing will come of this. */
+ debug(" break\n");
+ break;
+ }
+ debug(" continue\n");
+ continue;
+ }
+
+ if (d == 0) {
+ /* This is the initializing step. There is no
+ * prev_k yet, get the initial x from the top
+ * left of the Myers graph. */
+ x = 0;
+ } else {
+ int *kd_prev_column = kd_column - kd_len;
+
+ /* Favoring "-" lines first means favoring
+ * moving rightwards in the Myers graph.
+ * For this, all k should derive from k - 1,
+ * only the bottom most k derive from k + 1:
+ *
+ * | d= 0 1 2
+ * ----+----------------
+ * k= |
+ * 2 | 2,0 <-- from
+ * | / prev_k = 2 - 1 = 1
+ * 1 | 1,0
+ * | /
+ * 0 | -->0,0 3,3
+ * | \\ /
+ * -1 | 0,1 <-- bottom most for d=1
+ * | \\ from prev_k = -1+1 = 0
+ * -2 | 0,2 <-- bottom most for
+ * d=2 from
+ * prev_k = -2+1 = -1
+ *
+ * Except when a k + 1 from a previous run
+ * already means a further advancement in the
+ * graph.
+ * If k == d, there is no k + 1 and k - 1 is the
+ * only option.
+ * If k < d, use k + 1 in case that yields a
+ * larger x. Also use k + 1 if k - 1 is outside
+ * the graph.
+ */
+ if (k > -d
+ && (k == d
+ || (k - 1 >= -(int)right->atoms.len
+ && kd_prev_column[k - 1]
+ >= kd_prev_column[k + 1]))) {
+ /* Advance from k - 1.
+ * From position prev_k, step to the
+ * right in the Myers graph: x += 1.
+ */
+ int prev_k = k - 1;
+ int prev_x = kd_prev_column[prev_k];
+ x = prev_x + 1;
+ } else {
+ /* The bottom most one.
+ * From position prev_k, step to the
+ * bottom in the Myers graph: y += 1.
+ * Incrementing y is achieved by
+ * decrementing k while keeping the same
+ * x. (since we're deriving y from y =
+ * x - k).
+ */
+ int prev_k = k + 1;
+ int prev_x = kd_prev_column[prev_k];
+ x = prev_x;
+ }
+ }
+
+ /* Slide down any snake that we might find here. */
+ while (x < left->atoms.len
+ && xk_to_y(x, k) < right->atoms.len) {
+ bool same;
+ int r = diff_atom_same(&same,
+ &left->atoms.head[x],
+ &right->atoms.head[
+ xk_to_y(x, k)]);
+ if (r)
+ return r;
+ if (!same)
+ break;
+ x++;
+ }
+ kd_column[k] = x;
+
+ if (x == left->atoms.len
+ && xk_to_y(x, k) == right->atoms.len) {
+ /* Found a path */
+ backtrack_d = d;
+ backtrack_k = k;
+ debug("Reached the end at d = %d, k = %d\n",
+ backtrack_d, backtrack_k);
+ break;
+ }
+ }
+
+ if (backtrack_d >= 0)
+ break;
+ }
+
+ debug_dump_myers_graph(left, right, kd_origin, NULL, 0, NULL, 0);
+
+ /* backtrack. A matrix spanning from start to end of the file is ready:
+ *
+ * | d= 0 1 2 3 4
+ * ----+---------------------------------
+ * k= |
+ * 3 |
+ * |
+ * 2 | 2,0
+ * | /
+ * 1 | 1,0 4,3
+ * | / / \
+ * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4, backtrack_k = 0
+ * | \ / \
+ * -1 | 0,1 3,4
+ * | \
+ * -2 | 0,2
+ * |
+ *
+ * From (4,4) backwards, find the previous position that is the largest, and remember it.
+ *
+ */
+ for (d = backtrack_d, k = backtrack_k; d >= 0; d--) {
+ x = kd_column[k];
+ y = xk_to_y(x, k);
+
+ /* When the best position is identified, remember it for that
+ * kd_column.
+ * That kd_column is no longer needed otherwise, so just
+ * re-purpose kd_column[0] = x and kd_column[1] = y,
+ * so that there is no need to allocate more memory.
+ */
+ kd_column[0] = x;
+ kd_column[1] = y;
+ debug("Backtrack d=%d: xy=(%d, %d)\n",
+ d, kd_column[0], kd_column[1]);
+
+ /* Don't access memory before kd_buf */
+ if (d == 0)
+ break;
+ int *kd_prev_column = kd_column - kd_len;
+
+ /* When y == 0, backtracking downwards (k-1) is the only way.
+ * When x == 0, backtracking upwards (k+1) is the only way.
+ *
+ * | d= 0 1 2 3 4
+ * ----+---------------------------------
+ * k= |
+ * 3 |
+ * | ..y == 0
+ * 2 | 2,0
+ * | /
+ * 1 | 1,0 4,3
+ * | / / \
+ * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4,
+ * | \ / \ backtrack_k = 0
+ * -1 | 0,1 3,4
+ * | \
+ * -2 | 0,2__
+ * | x == 0
+ */
+ if (y == 0
+ || (x > 0
+ && kd_prev_column[k - 1] >= kd_prev_column[k + 1])) {
+ k = k - 1;
+ debug("prev k=k-1=%d x=%d y=%d\n",
+ k, kd_prev_column[k],
+ xk_to_y(kd_prev_column[k], k));
+ } else {
+ k = k + 1;
+ debug("prev k=k+1=%d x=%d y=%d\n",
+ k, kd_prev_column[k],
+ xk_to_y(kd_prev_column[k], k));
+ }
+ kd_column = kd_prev_column;
+ }
+
+ /* Forwards again, this time recording the diff chunks.
+ * Definitely start from 0,0. kd_column[0] may actually point to the
+ * bottom of a snake starting at 0,0 */
+ x = 0;
+ y = 0;
+
+ kd_column = kd_origin;
+ for (d = 0; d <= backtrack_d; d++, kd_column += kd_len) {
+ int next_x = kd_column[0];
+ int next_y = kd_column[1];
+ debug("Forward track from xy(%d,%d) to xy(%d,%d)\n",
+ x, y, next_x, next_y);
+
+ struct diff_atom *left_atom = &left->atoms.head[x];
+ int left_section_len = next_x - x;
+ struct diff_atom *right_atom = &right->atoms.head[y];
+ int right_section_len = next_y - y;
+
+ rc = ENOMEM;
+ if (left_section_len && right_section_len) {
+ /* This must be a snake slide.
+ * Snake slides have a straight line leading into them
+ * (except when starting at (0,0)). Find out whether the
+ * lead-in is horizontal or vertical:
+ *
+ * left
+ * ---------->
+ * |
+ * r| o-o o
+ * i| \ |
+ * g| o o
+ * h| \ \
+ * t| o o
+ * v
+ *
+ * If left_section_len > right_section_len, the lead-in
+ * is horizontal, meaning first remove one atom from the
+ * left before sliding down the snake.
+ * If right_section_len > left_section_len, the lead-in
+ * is vetical, so add one atom from the right before
+ * sliding down the snake. */
+ if (left_section_len == right_section_len + 1) {
+ if (!diff_state_add_chunk(state, true,
+ left_atom, 1,
+ right_atom, 0))
+ goto return_rc;
+ left_atom++;
+ left_section_len--;
+ } else if (right_section_len == left_section_len + 1) {
+ if (!diff_state_add_chunk(state, true,
+ left_atom, 0,
+ right_atom, 1))
+ goto return_rc;
+ right_atom++;
+ right_section_len--;
+ } else if (left_section_len != right_section_len) {
+ /* The numbers are making no sense. Should never
+ * happen. */
+ rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
+ goto return_rc;
+ }
+
+ if (!diff_state_add_chunk(state, true,
+ left_atom, left_section_len,
+ right_atom,
+ right_section_len))
+ goto return_rc;
+ } else if (left_section_len && !right_section_len) {
+ /* Only left atoms and none on the right, they form a
+ * "minus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, left_section_len,
+ right_atom, 0))
+ goto return_rc;
+ } else if (!left_section_len && right_section_len) {
+ /* No left atoms, only atoms on the right, they form a
+ * "plus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, 0,
+ right_atom,
+ right_section_len))
+ goto return_rc;
+ }
+
+ x = next_x;
+ y = next_y;
+ }
+
+ rc = DIFF_RC_OK;
+
+return_rc:
+ debug("** END %s rc=%d\n", __func__, rc);
+ return rc;
+}
diff --git a/lib/diff_output.c b/lib/diff_output.c
new file mode 100644
index 0000000..92c42e1
--- /dev/null
+++ b/lib/diff_output.c
@@ -0,0 +1,328 @@
+/* Common parts for printing diff output */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <ctype.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+#include <diff_output.h>
+
+#include "diff_internal.h"
+
+static int
+get_atom_byte(int *ch, struct diff_atom *atom, off_t off)
+{
+ off_t cur;
+
+ if (atom->at != NULL) {
+ *ch = atom->at[off];
+ return 0;
+ }
+
+ cur = ftello(atom->root->f);
+ if (cur == -1)
+ return errno;
+
+ if (cur != atom->pos + off &&
+ fseeko(atom->root->f, atom->pos + off, SEEK_SET) == -1)
+ return errno;
+
+ *ch = fgetc(atom->root->f);
+ if (*ch == EOF && ferror(atom->root->f))
+ return errno;
+
+ return 0;
+}
+
+int
+diff_output_lines(struct diff_output_info *outinfo, FILE *dest,
+ const char *prefix, struct diff_atom *start_atom,
+ unsigned int count)
+{
+ struct diff_atom *atom;
+ off_t outoff = 0, *offp;
+ int rc;
+
+ if (outinfo && outinfo->line_offsets.len > 0) {
+ unsigned int idx = outinfo->line_offsets.len - 1;
+ outoff = outinfo->line_offsets.head[idx];
+ }
+
+ foreach_diff_atom(atom, start_atom, count) {
+ off_t outlen = 0;
+ int i, ch;
+ unsigned int len = atom->len;
+ rc = fprintf(dest, "%s", prefix);
+ if (rc < 0)
+ return errno;
+ outlen += rc;
+ if (len) {
+ rc = get_atom_byte(&ch, atom, len - 1);
+ if (rc)
+ return rc;
+ if (ch == '\n')
+ len--;
+ if (len) {
+ rc = get_atom_byte(&ch, atom, len - 1);
+ if (rc)
+ return rc;
+ if (ch == '\r')
+ len--;
+ }
+ }
+
+ for (i = 0; i < len; i++) {
+ rc = get_atom_byte(&ch, atom, i);
+ if (rc)
+ return rc;
+ rc = fprintf(dest, "%c", (unsigned char)ch);
+ if (rc < 0)
+ return errno;
+ outlen += rc;
+ }
+ rc = fprintf(dest, "\n");
+ if (rc < 0)
+ return errno;
+ outlen += rc;
+ if (outinfo) {
+ ARRAYLIST_ADD(offp, outinfo->line_offsets);
+ if (offp == NULL)
+ return ENOMEM;
+ outoff += outlen;
+ *offp = outoff;
+ }
+ }
+
+ return DIFF_RC_OK;
+}
+
+int
+diff_output_chunk_left_version(struct diff_output_info **output_info,
+ FILE *dest,
+ const struct diff_input_info *info,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc)
+{
+ int rc, c_idx;
+ struct diff_output_info *outinfo = NULL;
+
+ if (diff_range_empty(&cc->left))
+ return DIFF_RC_OK;
+
+ if (output_info) {
+ *output_info = diff_output_info_alloc();
+ if (*output_info == NULL)
+ return ENOMEM;
+ outinfo = *output_info;
+ }
+
+ /* Write out all chunks on the left side. */
+ for (c_idx = cc->chunk.start; c_idx < cc->chunk.end; c_idx++) {
+ const struct diff_chunk *c = &result->chunks.head[c_idx];
+
+ if (c->left_count) {
+ rc = diff_output_lines(outinfo, dest, "",
+ c->left_start, c->left_count);
+ if (rc)
+ return rc;
+ }
+ }
+
+ return DIFF_RC_OK;
+}
+
+int
+diff_output_chunk_right_version(struct diff_output_info **output_info,
+ FILE *dest,
+ const struct diff_input_info *info,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc)
+{
+ int rc, c_idx;
+ struct diff_output_info *outinfo = NULL;
+
+ if (diff_range_empty(&cc->right))
+ return DIFF_RC_OK;
+
+ if (output_info) {
+ *output_info = diff_output_info_alloc();
+ if (*output_info == NULL)
+ return ENOMEM;
+ outinfo = *output_info;
+ }
+
+ /* Write out all chunks on the right side. */
+ for (c_idx = cc->chunk.start; c_idx < cc->chunk.end; c_idx++) {
+ const struct diff_chunk *c = &result->chunks.head[c_idx];
+
+ if (c->right_count) {
+ rc = diff_output_lines(outinfo, dest, "", c->right_start,
+ c->right_count);
+ if (rc)
+ return rc;
+ }
+ }
+
+ return DIFF_RC_OK;
+}
+
+int
+diff_output_trailing_newline_msg(struct diff_output_info *outinfo, FILE *dest,
+ const struct diff_chunk *c)
+{
+ enum diff_chunk_type chunk_type = diff_chunk_type(c);
+ struct diff_atom *atom, *start_atom;
+ unsigned int atom_count;
+ int rc, ch;
+ off_t outoff = 0, *offp;
+
+ if (chunk_type == CHUNK_MINUS || chunk_type == CHUNK_SAME) {
+ start_atom = c->left_start;
+ atom_count = c->left_count;
+ } else if (chunk_type == CHUNK_PLUS) {
+ start_atom = c->right_start;
+ atom_count = c->right_count;
+ } else
+ return EINVAL;
+
+ /* Locate the last atom. */
+ if (atom_count == 0)
+ return EINVAL;
+ atom = &start_atom[atom_count - 1];
+
+ rc = get_atom_byte(&ch, atom, atom->len - 1);
+ if (rc != DIFF_RC_OK)
+ return rc;
+
+ if (ch != '\n') {
+ if (outinfo && outinfo->line_offsets.len > 0) {
+ unsigned int idx = outinfo->line_offsets.len - 1;
+ outoff = outinfo->line_offsets.head[idx];
+ }
+ rc = fprintf(dest, "\\ No newline at end of file\n");
+ if (rc < 0)
+ return errno;
+ if (outinfo) {
+ ARRAYLIST_ADD(offp, outinfo->line_offsets);
+ if (offp == NULL)
+ return ENOMEM;
+ outoff += rc;
+ *offp = outoff;
+ }
+ }
+
+ return DIFF_RC_OK;
+}
+
+static bool
+is_function_prototype(const char *buf)
+{
+ return isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$';
+}
+
+#define FUNCTION_CONTEXT_SIZE 55
+#define begins_with(s, pre) (strncmp(s, pre, sizeof(pre)-1) == 0)
+
+int
+diff_output_match_function_prototype(char **prototype,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc)
+{
+ struct diff_atom *start_atom, *atom;
+ const struct diff_data *data;
+ unsigned char buf[FUNCTION_CONTEXT_SIZE];
+ char *state = NULL;
+ int rc, i;
+
+ *prototype = NULL;
+
+ if (result->left->atoms.len > 0 && cc->left.start > 0) {
+ data = result->left;
+ start_atom = &data->atoms.head[cc->left.start - 1];
+ } else if (result->right->atoms.len > 0 && cc->right.start > 0) {
+ data = result->right;
+ start_atom = &data->atoms.head[cc->right.start - 1];
+ } else
+ return DIFF_RC_OK;
+
+ diff_data_foreach_atom_backwards_from(start_atom, atom, data) {
+ for (i = 0; i < atom->len && i < sizeof(buf) - 1; i++) {
+ unsigned int ch;
+ rc = get_atom_byte(&ch, atom, i);
+ if (rc)
+ return rc;
+ if (ch == '\n')
+ break;
+ buf[i] = ch;
+ }
+ buf[i] = '\0';
+ if (is_function_prototype(buf)) {
+ if (begins_with(buf, "private:")) {
+ if (!state)
+ state = " (private)";
+ } else if (begins_with(buf, "protected:")) {
+ if (!state)
+ state = " (protected)";
+ } else if (begins_with(buf, "public:")) {
+ if (!state)
+ state = " (public)";
+ } else {
+ if (state) /* don't care about truncation */
+ strlcat(buf, state, sizeof(buf));
+ *prototype = strdup(buf);
+ if (*prototype == NULL)
+ return ENOMEM;
+ return DIFF_RC_OK;
+ }
+ }
+ }
+
+ return DIFF_RC_OK;
+}
+
+struct diff_output_info *
+diff_output_info_alloc(void)
+{
+ struct diff_output_info *output_info;
+ off_t *offp;
+
+ output_info = malloc(sizeof(*output_info));
+ if (output_info != NULL) {
+ ARRAYLIST_INIT(output_info->line_offsets, 128);
+ ARRAYLIST_ADD(offp, output_info->line_offsets);
+ if (offp == NULL) {
+ diff_output_info_free(output_info);
+ return NULL;
+ }
+ *offp = 0;
+ }
+ return output_info;
+}
+
+void
+diff_output_info_free(struct diff_output_info *output_info)
+{
+ ARRAYLIST_FREE(output_info->line_offsets);
+ free(output_info);
+}
diff --git a/lib/diff_output.h b/lib/diff_output.h
new file mode 100644
index 0000000..e507bbb
--- /dev/null
+++ b/lib/diff_output.h
@@ -0,0 +1,91 @@
+/* Diff output generators and invocation shims. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+struct diff_input_info {
+ const char *left_path;
+ const char *right_path;
+};
+
+struct diff_output_info {
+ /*
+ * Byte offset to each line in the generated output file.
+ * The total number of lines in the file is line_offsets.len - 1.
+ * The last offset in this array corresponds to end-of-file.
+ */
+ ARRAYLIST(off_t) line_offsets;
+};
+
+void diff_output_info_free(struct diff_output_info *output_info);
+
+struct diff_chunk_context {
+ struct diff_range chunk;
+ struct diff_range left, right;
+};
+
+int diff_output_plain(struct diff_output_info **output_info, FILE *dest,
+ const struct diff_input_info *info,
+ const struct diff_result *result);
+int diff_output_unidiff(struct diff_output_info **output_info,
+ FILE *dest, const struct diff_input_info *info,
+ const struct diff_result *result,
+ unsigned int context_lines);
+int diff_output_edscript(struct diff_output_info **output_info,
+ FILE *dest, const struct diff_input_info *info,
+ const struct diff_result *result);
+int diff_chunk_get_left_start(const struct diff_chunk *c,
+ const struct diff_result *r,
+ int context_lines);
+int diff_chunk_get_left_end(const struct diff_chunk *c,
+ const struct diff_result *r,
+ int context_lines);
+int diff_chunk_get_right_start(const struct diff_chunk *c,
+ const struct diff_result *r,
+ int context_lines);
+int diff_chunk_get_right_end(const struct diff_chunk *c,
+ const struct diff_result *r,
+ int context_lines);
+struct diff_chunk *diff_chunk_get(const struct diff_result *r, int chunk_idx);
+int diff_chunk_get_left_count(struct diff_chunk *c);
+int diff_chunk_get_right_count(struct diff_chunk *c);
+void diff_chunk_context_get(struct diff_chunk_context *cc,
+ const struct diff_result *r,
+ int chunk_idx, int context_lines);
+void diff_chunk_context_load_change(struct diff_chunk_context *cc,
+ int *nchunks_used,
+ struct diff_result *result,
+ int start_chunk_idx,
+ int context_lines);
+
+struct diff_output_unidiff_state;
+struct diff_output_unidiff_state *diff_output_unidiff_state_alloc(void);
+void diff_output_unidiff_state_reset(struct diff_output_unidiff_state *state);
+void diff_output_unidiff_state_free(struct diff_output_unidiff_state *state);
+int diff_output_unidiff_chunk(struct diff_output_info **output_info, FILE *dest,
+ struct diff_output_unidiff_state *state,
+ const struct diff_input_info *info,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc);
+int diff_output_chunk_left_version(struct diff_output_info **output_info,
+ FILE *dest,
+ const struct diff_input_info *info,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc);
+int diff_output_chunk_right_version(struct diff_output_info **output_info,
+ FILE *dest,
+ const struct diff_input_info *info,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc);
diff --git a/lib/diff_output_edscript.c b/lib/diff_output_edscript.c
new file mode 100644
index 0000000..b6e9089
--- /dev/null
+++ b/lib/diff_output_edscript.c
@@ -0,0 +1,162 @@
+/* Produce ed(1) script output from a diff_result. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ * Copyright (c) 2020 Stefan Sperling <stsp@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+#include <diff_output.h>
+
+#include "diff_internal.h"
+
+static int
+output_edscript_chunk(struct diff_output_info *outinfo,
+ FILE *dest, const struct diff_input_info *info,
+ const struct diff_result *result,
+ struct diff_chunk_context *cc)
+{
+ off_t outoff = 0, *offp;
+ int left_start, left_len, right_start, right_len;
+ int rc;
+
+ left_len = cc->left.end - cc->left.start;
+ if (left_len < 0)
+ return EINVAL;
+ else if (result->left->atoms.len == 0)
+ left_start = 0;
+ else if (left_len == 0 && cc->left.start > 0)
+ left_start = cc->left.start;
+ else
+ left_start = cc->left.start + 1;
+
+ right_len = cc->right.end - cc->right.start;
+ if (right_len < 0)
+ return EINVAL;
+ else if (result->right->atoms.len == 0)
+ right_start = 0;
+ else if (right_len == 0 && cc->right.start > 0)
+ right_start = cc->right.start;
+ else
+ right_start = cc->right.start + 1;
+
+ if (left_len == 0) {
+ /* addition */
+ if (right_len == 1) {
+ rc = fprintf(dest, "%da%d\n", left_start, right_start);
+ } else {
+ rc = fprintf(dest, "%da%d,%d\n", left_start,
+ right_start, cc->right.end);
+ }
+ } else if (right_len == 0) {
+ /* deletion */
+ if (left_len == 1) {
+ rc = fprintf(dest, "%dd%d\n", left_start,
+ right_start);
+ } else {
+ rc = fprintf(dest, "%d,%dd%d\n", left_start,
+ cc->left.end, right_start);
+ }
+ } else {
+ /* change */
+ if (left_len == 1 && right_len == 1) {
+ rc = fprintf(dest, "%dc%d\n", left_start, right_start);
+ } else if (left_len == 1) {
+ rc = fprintf(dest, "%dc%d,%d\n", left_start,
+ right_start, cc->right.end);
+ } else if (right_len == 1) {
+ rc = fprintf(dest, "%d,%dc%d\n", left_start,
+ cc->left.end, right_start);
+ } else {
+ rc = fprintf(dest, "%d,%dc%d,%d\n", left_start,
+ cc->left.end, right_start, cc->right.end);
+ }
+ }
+ if (rc < 0)
+ return errno;
+ if (outinfo) {
+ ARRAYLIST_ADD(offp, outinfo->line_offsets);
+ if (offp == NULL)
+ return ENOMEM;
+ outoff += rc;
+ *offp = outoff;
+ }
+
+ return DIFF_RC_OK;
+}
+
+int
+diff_output_edscript(struct diff_output_info **output_info,
+ FILE *dest, const struct diff_input_info *info,
+ const struct diff_result *result)
+{
+ struct diff_output_info *outinfo = NULL;
+ struct diff_chunk_context cc = {};
+ int i, rc;
+
+ if (!result)
+ return EINVAL;
+ if (result->rc != DIFF_RC_OK)
+ return result->rc;
+
+ if (output_info) {
+ *output_info = diff_output_info_alloc();
+ if (*output_info == NULL)
+ return ENOMEM;
+ outinfo = *output_info;
+ }
+
+ for (i = 0; i < result->chunks.len; i++) {
+ struct diff_chunk *chunk = &result->chunks.head[i];
+ enum diff_chunk_type t = diff_chunk_type(chunk);
+ struct diff_chunk_context next;
+
+ if (t != CHUNK_MINUS && t != CHUNK_PLUS)
+ continue;
+
+ if (diff_chunk_context_empty(&cc)) {
+ /* Note down the start point, any number of subsequent
+ * chunks may be joined up to this chunk by being
+ * directly adjacent. */
+ diff_chunk_context_get(&cc, result, i, 0);
+ continue;
+ }
+
+ /* There already is a previous chunk noted down for being
+ * printed. Does it join up with this one? */
+ diff_chunk_context_get(&next, result, i, 0);
+
+ if (diff_chunk_contexts_touch(&cc, &next)) {
+ /* This next context touches or overlaps the previous
+ * one, join. */
+ diff_chunk_contexts_merge(&cc, &next);
+ continue;
+ }
+
+ rc = output_edscript_chunk(outinfo, dest, info, result, &cc);
+ if (rc != DIFF_RC_OK)
+ return rc;
+ cc = next;
+ }
+
+ if (!diff_chunk_context_empty(&cc))
+ return output_edscript_chunk(outinfo, dest, info, result, &cc);
+ return DIFF_RC_OK;
+}
diff --git a/lib/diff_output_plain.c b/lib/diff_output_plain.c
new file mode 100644
index 0000000..cc478ba
--- /dev/null
+++ b/lib/diff_output_plain.c
@@ -0,0 +1,68 @@
+/* Output all lines of a diff_result. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdbool.h>
+#include <stdlib.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+#include <diff_output.h>
+
+#include "diff_internal.h"
+
+int
+diff_output_plain(struct diff_output_info **output_info, FILE *dest,
+ const struct diff_input_info *info,
+ const struct diff_result *result)
+{
+ struct diff_output_info *outinfo = NULL;
+ int i, rc;
+
+ if (!result)
+ return EINVAL;
+ if (result->rc != DIFF_RC_OK)
+ return result->rc;
+
+ if (output_info) {
+ *output_info = diff_output_info_alloc();
+ if (*output_info == NULL)
+ return errno;
+ outinfo = *output_info;
+ }
+
+ for (i = 0; i < result->chunks.len; i++) {
+ struct diff_chunk *c = &result->chunks.head[i];
+ if (c->left_count && c->right_count)
+ rc = diff_output_lines(outinfo, dest,
+ c->solved ? " " : "?",
+ c->left_start, c->left_count);
+ else if (c->left_count && !c->right_count)
+ rc = diff_output_lines(outinfo, dest,
+ c->solved ? "-" : "?",
+ c->left_start, c->left_count);
+ else if (c->right_count && !c->left_count)
+ rc = diff_output_lines(outinfo, dest,
+ c->solved ? "+" : "?",
+ c->right_start, c->right_count);
+ if (rc)
+ return rc;
+ }
+ return DIFF_RC_OK;
+}
diff --git a/lib/diff_output_unidiff.c b/lib/diff_output_unidiff.c
new file mode 100644
index 0000000..96cecea
--- /dev/null
+++ b/lib/diff_output_unidiff.c
@@ -0,0 +1,527 @@
+/* Produce a unidiff output from a diff_result. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+#include <diff_output.h>
+
+#include "diff_internal.h"
+#include "diff_debug.h"
+
+bool
+diff_chunk_context_empty(const struct diff_chunk_context *cc)
+{
+ return diff_range_empty(&cc->chunk);
+}
+
+int
+diff_chunk_get_left_start(const struct diff_chunk *c,
+ const struct diff_result *r, int context_lines)
+{
+ int left_start = diff_atom_root_idx(r->left, c->left_start);
+ return MAX(0, left_start - context_lines);
+}
+
+int
+diff_chunk_get_left_end(const struct diff_chunk *c,
+ const struct diff_result *r, int context_lines)
+{
+ int left_start = diff_chunk_get_left_start(c, r, 0);
+ return MIN(r->left->atoms.len,
+ left_start + c->left_count + context_lines);
+}
+
+int
+diff_chunk_get_right_start(const struct diff_chunk *c,
+ const struct diff_result *r, int context_lines)
+{
+ int right_start = diff_atom_root_idx(r->right, c->right_start);
+ return MAX(0, right_start - context_lines);
+}
+
+int
+diff_chunk_get_right_end(const struct diff_chunk *c,
+ const struct diff_result *r, int context_lines)
+{
+ int right_start = diff_chunk_get_right_start(c, r, 0);
+ return MIN(r->right->atoms.len,
+ right_start + c->right_count + context_lines);
+}
+
+struct diff_chunk *
+diff_chunk_get(const struct diff_result *r, int chunk_idx)
+{
+ return &r->chunks.head[chunk_idx];
+}
+
+int
+diff_chunk_get_left_count(struct diff_chunk *c)
+{
+ return c->left_count;
+}
+
+int
+diff_chunk_get_right_count(struct diff_chunk *c)
+{
+ return c->right_count;
+}
+
+void
+diff_chunk_context_get(struct diff_chunk_context *cc, const struct diff_result *r,
+ int chunk_idx, int context_lines)
+{
+ const struct diff_chunk *c = &r->chunks.head[chunk_idx];
+ int left_start = diff_chunk_get_left_start(c, r, context_lines);
+ int left_end = diff_chunk_get_left_end(c, r, context_lines);
+ int right_start = diff_chunk_get_right_start(c, r, context_lines);
+ int right_end = diff_chunk_get_right_end(c, r, context_lines);
+
+ *cc = (struct diff_chunk_context){
+ .chunk = {
+ .start = chunk_idx,
+ .end = chunk_idx + 1,
+ },
+ .left = {
+ .start = left_start,
+ .end = left_end,
+ },
+ .right = {
+ .start = right_start,
+ .end = right_end,
+ },
+ };
+}
+
+bool
+diff_chunk_contexts_touch(const struct diff_chunk_context *cc,
+ const struct diff_chunk_context *other)
+{
+ return diff_ranges_touch(&cc->chunk, &other->chunk)
+ || diff_ranges_touch(&cc->left, &other->left)
+ || diff_ranges_touch(&cc->right, &other->right);
+}
+
+void
+diff_chunk_contexts_merge(struct diff_chunk_context *cc,
+ const struct diff_chunk_context *other)
+{
+ diff_ranges_merge(&cc->chunk, &other->chunk);
+ diff_ranges_merge(&cc->left, &other->left);
+ diff_ranges_merge(&cc->right, &other->right);
+}
+
+void
+diff_chunk_context_load_change(struct diff_chunk_context *cc,
+ int *nchunks_used,
+ struct diff_result *result,
+ int start_chunk_idx,
+ int context_lines)
+{
+ int i;
+ int seen_minus = 0, seen_plus = 0;
+
+ if (nchunks_used)
+ *nchunks_used = 0;
+
+ for (i = start_chunk_idx; i < result->chunks.len; i++) {
+ struct diff_chunk *chunk = &result->chunks.head[i];
+ enum diff_chunk_type t = diff_chunk_type(chunk);
+ struct diff_chunk_context next;
+
+ if (t != CHUNK_MINUS && t != CHUNK_PLUS) {
+ if (nchunks_used)
+ (*nchunks_used)++;
+ if (seen_minus || seen_plus)
+ break;
+ else
+ continue;
+ } else if (t == CHUNK_MINUS)
+ seen_minus = 1;
+ else if (t == CHUNK_PLUS)
+ seen_plus = 1;
+
+ if (diff_chunk_context_empty(cc)) {
+ /* Note down the start point, any number of subsequent
+ * chunks may be joined up to this chunk by being
+ * directly adjacent. */
+ diff_chunk_context_get(cc, result, i, context_lines);
+ if (nchunks_used)
+ (*nchunks_used)++;
+ continue;
+ }
+
+ /* There already is a previous chunk noted down for being
+ * printed. Does it join up with this one? */
+ diff_chunk_context_get(&next, result, i, context_lines);
+
+ if (diff_chunk_contexts_touch(cc, &next)) {
+ /* This next context touches or overlaps the previous
+ * one, join. */
+ diff_chunk_contexts_merge(cc, &next);
+ if (nchunks_used)
+ (*nchunks_used)++;
+ continue;
+ } else
+ break;
+ }
+}
+
+struct diff_output_unidiff_state {
+ bool header_printed;
+};
+
+struct diff_output_unidiff_state *
+diff_output_unidiff_state_alloc(void)
+{
+ struct diff_output_unidiff_state *state;
+
+ state = calloc(1, sizeof(struct diff_output_unidiff_state));
+ if (state != NULL)
+ diff_output_unidiff_state_reset(state);
+ return state;
+}
+
+void
+diff_output_unidiff_state_reset(struct diff_output_unidiff_state *state)
+{
+ state->header_printed = false;
+}
+
+void
+diff_output_unidiff_state_free(struct diff_output_unidiff_state *state)
+{
+ free(state);
+}
+
+static int
+output_unidiff_chunk(struct diff_output_info *outinfo, FILE *dest,
+ struct diff_output_unidiff_state *state,
+ const struct diff_input_info *info,
+ const struct diff_result *result,
+ bool print_header, bool show_function_prototypes,
+ const struct diff_chunk_context *cc)
+{
+ int rc, left_start, left_len, right_start, right_len;
+ off_t outoff = 0, *offp;
+ char *prototype = NULL;
+
+ if (diff_range_empty(&cc->left) && diff_range_empty(&cc->right))
+ return DIFF_RC_OK;
+
+ if (outinfo && outinfo->line_offsets.len > 0) {
+ unsigned int idx = outinfo->line_offsets.len - 1;
+ outoff = outinfo->line_offsets.head[idx];
+ }
+
+ if (print_header && !(state->header_printed)) {
+ rc = fprintf(dest, "--- %s\n", info->left_path ? : "a");
+ if (rc < 0)
+ return errno;
+ if (outinfo) {
+ ARRAYLIST_ADD(offp, outinfo->line_offsets);
+ if (offp == NULL)
+ return ENOMEM;
+ outoff += rc;
+ *offp = outoff;
+
+ }
+ rc = fprintf(dest, "+++ %s\n", info->right_path ? : "b");
+ if (rc < 0)
+ return errno;
+ if (outinfo) {
+ ARRAYLIST_ADD(offp, outinfo->line_offsets);
+ if (offp == NULL)
+ return ENOMEM;
+ outoff += rc;
+ *offp = outoff;
+
+ }
+ state->header_printed = true;
+ }
+
+ left_len = cc->left.end - cc->left.start;
+ if (result->left->atoms.len == 0)
+ left_start = 0;
+ else if (left_len == 0 && cc->left.start > 0)
+ left_start = cc->left.start;
+ else
+ left_start = cc->left.start + 1;
+
+ right_len = cc->right.end - cc->right.start;
+ if (result->right->atoms.len == 0)
+ right_start = 0;
+ else if (right_len == 0 && cc->right.start > 0)
+ right_start = cc->right.start;
+ else
+ right_start = cc->right.start + 1;
+
+ if (show_function_prototypes) {
+ rc = diff_output_match_function_prototype(&prototype,
+ result, cc);
+ if (rc)
+ return rc;
+ }
+
+ if (left_len == 1 && right_len == 1) {
+ rc = fprintf(dest, "@@ -%d +%d @@%s%s\n",
+ left_start, right_start,
+ prototype ? " " : "",
+ prototype ? : "");
+ } else if (left_len == 1 && right_len != 1) {
+ rc = fprintf(dest, "@@ -%d +%d,%d @@%s%s\n",
+ left_start, right_start, right_len,
+ prototype ? " " : "",
+ prototype ? : "");
+ } else if (left_len != 1 && right_len == 1) {
+ rc = fprintf(dest, "@@ -%d,%d +%d @@%s%s\n",
+ left_start, left_len, right_start,
+ prototype ? " " : "",
+ prototype ? : "");
+ } else {
+ rc = fprintf(dest, "@@ -%d,%d +%d,%d @@%s%s\n",
+ left_start, left_len, right_start, right_len,
+ prototype ? " " : "",
+ prototype ? : "");
+ }
+ free(prototype);
+ if (rc < 0)
+ return errno;
+ if (outinfo) {
+ ARRAYLIST_ADD(offp, outinfo->line_offsets);
+ if (offp == NULL)
+ return ENOMEM;
+ outoff += rc;
+ *offp = outoff;
+
+ }
+
+ /* Got the absolute line numbers where to start printing, and the index
+ * of the interesting (non-context) chunk.
+ * To print context lines above the interesting chunk, nipping on the
+ * previous chunk index may be necessary.
+ * It is guaranteed to be only context lines where left == right, so it
+ * suffices to look on the left. */
+ const struct diff_chunk *first_chunk;
+ int chunk_start_line;
+ first_chunk = &result->chunks.head[cc->chunk.start];
+ chunk_start_line = diff_atom_root_idx(result->left,
+ first_chunk->left_start);
+ if (cc->left.start < chunk_start_line) {
+ rc = diff_output_lines(outinfo, dest, " ",
+ &result->left->atoms.head[cc->left.start],
+ chunk_start_line - cc->left.start);
+ if (rc)
+ return rc;
+ }
+
+ /* Now write out all the joined chunks and contexts between them */
+ int c_idx;
+ for (c_idx = cc->chunk.start; c_idx < cc->chunk.end; c_idx++) {
+ const struct diff_chunk *c = &result->chunks.head[c_idx];
+
+ if (c->left_count && c->right_count)
+ rc = diff_output_lines(outinfo, dest,
+ c->solved ? " " : "?",
+ c->left_start, c->left_count);
+ else if (c->left_count && !c->right_count)
+ rc = diff_output_lines(outinfo, dest,
+ c->solved ? "-" : "?",
+ c->left_start, c->left_count);
+ else if (c->right_count && !c->left_count)
+ rc = diff_output_lines(outinfo, dest,
+ c->solved ? "+" : "?",
+ c->right_start, c->right_count);
+ if (rc)
+ return rc;
+
+ if (cc->chunk.end == result->chunks.len) {
+ rc = diff_output_trailing_newline_msg(outinfo, dest, c);
+ if (rc != DIFF_RC_OK)
+ return rc;
+ }
+ }
+
+ /* Trailing context? */
+ const struct diff_chunk *last_chunk;
+ int chunk_end_line;
+ last_chunk = &result->chunks.head[cc->chunk.end - 1];
+ chunk_end_line = diff_atom_root_idx(result->left,
+ last_chunk->left_start
+ + last_chunk->left_count);
+ if (cc->left.end > chunk_end_line) {
+ rc = diff_output_lines(outinfo, dest, " ",
+ &result->left->atoms.head[chunk_end_line],
+ cc->left.end - chunk_end_line);
+ if (rc)
+ return rc;
+ }
+
+ return DIFF_RC_OK;
+}
+
+int
+diff_output_unidiff_chunk(struct diff_output_info **output_info, FILE *dest,
+ struct diff_output_unidiff_state *state,
+ const struct diff_input_info *info,
+ const struct diff_result *result,
+ const struct diff_chunk_context *cc)
+{
+ struct diff_output_info *outinfo = NULL;
+ int flags = (result->left->root->diff_flags |
+ result->right->root->diff_flags);
+ bool show_function_prototypes = (flags & DIFF_FLAG_SHOW_PROTOTYPES);
+
+ if (output_info) {
+ *output_info = diff_output_info_alloc();
+ if (*output_info == NULL)
+ return ENOMEM;
+ outinfo = *output_info;
+ }
+
+ return output_unidiff_chunk(outinfo, dest, state, info,
+ result, false, show_function_prototypes, cc);
+}
+
+int
+diff_output_unidiff(struct diff_output_info **output_info,
+ FILE *dest, const struct diff_input_info *info,
+ const struct diff_result *result,
+ unsigned int context_lines)
+{
+ struct diff_output_unidiff_state *state;
+ struct diff_chunk_context cc = {};
+ struct diff_output_info *outinfo = NULL;
+ int flags = (result->left->root->diff_flags |
+ result->right->root->diff_flags);
+ bool show_function_prototypes = (flags & DIFF_FLAG_SHOW_PROTOTYPES);
+ int i;
+
+ if (!result)
+ return EINVAL;
+ if (result->rc != DIFF_RC_OK)
+ return result->rc;
+
+ if (output_info) {
+ *output_info = diff_output_info_alloc();
+ if (*output_info == NULL)
+ return ENOMEM;
+ outinfo = *output_info;
+ }
+
+ state = diff_output_unidiff_state_alloc();
+ if (state == NULL) {
+ if (output_info) {
+ diff_output_info_free(*output_info);
+ *output_info = NULL;
+ }
+ return ENOMEM;
+ }
+
+#if DEBUG
+ unsigned int check_left_pos, check_right_pos;
+ check_left_pos = 0;
+ check_right_pos = 0;
+ for (i = 0; i < result->chunks.len; i++) {
+ struct diff_chunk *c = &result->chunks.head[i];
+ enum diff_chunk_type t = diff_chunk_type(c);
+
+ debug("[%d] %s lines L%d R%d @L %d @R %d\n",
+ i, (t == CHUNK_MINUS ? "minus" :
+ (t == CHUNK_PLUS ? "plus" :
+ (t == CHUNK_SAME ? "same" : "?"))),
+ c->left_count,
+ c->right_count,
+ c->left_start ? diff_atom_root_idx(result->left, c->left_start) : -1,
+ c->right_start ? diff_atom_root_idx(result->right, c->right_start) : -1);
+ assert(check_left_pos == diff_atom_root_idx(result->left, c->left_start));
+ assert(check_right_pos == diff_atom_root_idx(result->right, c->right_start));
+ check_left_pos += c->left_count;
+ check_right_pos += c->right_count;
+
+ }
+ assert(check_left_pos == result->left->atoms.len);
+ assert(check_right_pos == result->right->atoms.len);
+#endif
+
+ for (i = 0; i < result->chunks.len; i++) {
+ struct diff_chunk *c = &result->chunks.head[i];
+ enum diff_chunk_type t = diff_chunk_type(c);
+ struct diff_chunk_context next;
+
+ if (t != CHUNK_MINUS && t != CHUNK_PLUS)
+ continue;
+
+ if (diff_chunk_context_empty(&cc)) {
+ /* These are the first lines being printed.
+ * Note down the start point, any number of subsequent
+ * chunks may be joined up to this unidiff chunk by
+ * context lines or by being directly adjacent. */
+ diff_chunk_context_get(&cc, result, i, context_lines);
+ debug("new chunk to be printed:"
+ " chunk %d-%d left %d-%d right %d-%d\n",
+ cc.chunk.start, cc.chunk.end,
+ cc.left.start, cc.left.end,
+ cc.right.start, cc.right.end);
+ continue;
+ }
+
+ /* There already is a previous chunk noted down for being
+ * printed. Does it join up with this one? */
+ diff_chunk_context_get(&next, result, i, context_lines);
+ debug("new chunk to be printed:"
+ " chunk %d-%d left %d-%d right %d-%d\n",
+ next.chunk.start, next.chunk.end,
+ next.left.start, next.left.end,
+ next.right.start, next.right.end);
+
+ if (diff_chunk_contexts_touch(&cc, &next)) {
+ /* This next context touches or overlaps the previous
+ * one, join. */
+ diff_chunk_contexts_merge(&cc, &next);
+ debug("new chunk to be printed touches previous chunk,"
+ " now: left %d-%d right %d-%d\n",
+ cc.left.start, cc.left.end,
+ cc.right.start, cc.right.end);
+ continue;
+ }
+
+ /* No touching, so the previous context is complete with a gap
+ * between it and this next one. Print the previous one and
+ * start fresh here. */
+ debug("new chunk to be printed does not touch previous chunk;"
+ " print left %d-%d right %d-%d\n",
+ cc.left.start, cc.left.end, cc.right.start, cc.right.end);
+ output_unidiff_chunk(outinfo, dest, state, info, result,
+ true, show_function_prototypes, &cc);
+ cc = next;
+ debug("new unprinted chunk is left %d-%d right %d-%d\n",
+ cc.left.start, cc.left.end, cc.right.start, cc.right.end);
+ }
+
+ if (!diff_chunk_context_empty(&cc))
+ output_unidiff_chunk(outinfo, dest, state, info, result,
+ true, show_function_prototypes, &cc);
+ diff_output_unidiff_state_free(state);
+ return DIFF_RC_OK;
+}
diff --git a/lib/diff_patience.c b/lib/diff_patience.c
new file mode 100644
index 0000000..6fcac65
--- /dev/null
+++ b/lib/diff_patience.c
@@ -0,0 +1,784 @@
+/* Implementation of the Patience Diff algorithm invented by Bram Cohen:
+ * Divide a diff problem into smaller chunks by an LCS (Longest Common Sequence)
+ * of common-unique lines. */
+/*
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <assert.h>
+#include <inttypes.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <arraylist.h>
+#include <diff_main.h>
+
+#include "diff_internal.h"
+#include "diff_debug.h"
+
+/* Algorithm to find unique lines:
+ * 0: stupidly iterate atoms
+ * 1: qsort
+ * 2: mergesort
+ */
+#define UNIQUE_STRATEGY 1
+
+/* Per-atom state for the Patience Diff algorithm */
+struct atom_patience {
+#if UNIQUE_STRATEGY == 0
+ bool unique_here;
+#endif
+ bool unique_in_both;
+ struct diff_atom *pos_in_other;
+ struct diff_atom *prev_stack;
+ struct diff_range identical_lines;
+};
+
+/* A diff_atom has a backpointer to the root diff_data. That points to the
+ * current diff_data, a possibly smaller section of the root. That current
+ * diff_data->algo_data is a pointer to an array of struct atom_patience. The
+ * atom's index in current diff_data gives the index in the atom_patience array.
+ */
+#define PATIENCE(ATOM) \
+ (((struct atom_patience*)((ATOM)->root->current->algo_data))\
+ [diff_atom_idx((ATOM)->root->current, ATOM)])
+
+#if UNIQUE_STRATEGY == 0
+
+/* Stupid iteration and comparison of all atoms */
+static int
+diff_atoms_mark_unique(struct diff_data *d, unsigned int *unique_count)
+{
+ struct diff_atom *i;
+ unsigned int count = 0;
+ diff_data_foreach_atom(i, d) {
+ PATIENCE(i).unique_here = true;
+ PATIENCE(i).unique_in_both = true;
+ count++;
+ }
+ diff_data_foreach_atom(i, d) {
+ struct diff_atom *j;
+
+ if (!PATIENCE(i).unique_here)
+ continue;
+
+ diff_data_foreach_atom_from(i + 1, j, d) {
+ bool same;
+ int r = diff_atom_same(&same, i, j);
+ if (r)
+ return r;
+ if (!same)
+ continue;
+ if (PATIENCE(i).unique_here) {
+ PATIENCE(i).unique_here = false;
+ PATIENCE(i).unique_in_both = false;
+ count--;
+ }
+ PATIENCE(j).unique_here = false;
+ PATIENCE(j).unique_in_both = false;
+ count--;
+ }
+ }
+ if (unique_count)
+ *unique_count = count;
+ return 0;
+}
+
+/* Mark those lines as PATIENCE(atom).unique_in_both = true that appear exactly
+ * once in each side. */
+static int
+diff_atoms_mark_unique_in_both(struct diff_data *left, struct diff_data *right,
+ unsigned int *unique_in_both_count)
+{
+ /* Derive the final unique_in_both count without needing an explicit
+ * iteration. So this is just some optimiziation to save one iteration
+ * in the end. */
+ unsigned int unique_in_both;
+ int r;
+
+ r = diff_atoms_mark_unique(left, &unique_in_both);
+ if (r)
+ return r;
+ r = diff_atoms_mark_unique(right, NULL);
+ if (r)
+ return r;
+
+ debug("unique_in_both %u\n", unique_in_both);
+
+ struct diff_atom *i;
+ diff_data_foreach_atom(i, left) {
+ if (!PATIENCE(i).unique_here)
+ continue;
+ struct diff_atom *j;
+ int found_in_b = 0;
+ diff_data_foreach_atom(j, right) {
+ bool same;
+ int r = diff_atom_same(&same, i, j);
+ if (r)
+ return r;
+ if (!same)
+ continue;
+ if (!PATIENCE(j).unique_here) {
+ found_in_b = 2; /* or more */
+ break;
+ } else {
+ found_in_b = 1;
+ PATIENCE(j).pos_in_other = i;
+ PATIENCE(i).pos_in_other = j;
+ }
+ }
+
+ if (found_in_b == 0 || found_in_b > 1) {
+ PATIENCE(i).unique_in_both = false;
+ unique_in_both--;
+ debug("unique_in_both %u (%d) ", unique_in_both,
+ found_in_b);
+ debug_dump_atom(left, NULL, i);
+ }
+ }
+
+ /* Still need to unmark right[*]->patience.unique_in_both for atoms that
+ * don't exist in left */
+ diff_data_foreach_atom(i, right) {
+ if (!PATIENCE(i).unique_here
+ || !PATIENCE(i).unique_in_both)
+ continue;
+ struct diff_atom *j;
+ bool found_in_a = false;
+ diff_data_foreach_atom(j, left) {
+ bool same;
+ int r;
+ if (!PATIENCE(j).unique_in_both)
+ continue;
+ r = diff_atom_same(&same, i, j);
+ if (r)
+ return r;
+ if (!same)
+ continue;
+ found_in_a = true;
+ break;
+ }
+
+ if (!found_in_a)
+ PATIENCE(i).unique_in_both = false;
+ }
+
+ if (unique_in_both_count)
+ *unique_in_both_count = unique_in_both;
+ return 0;
+}
+
+#else /* UNIQUE_STRATEGY != 0 */
+
+/* Use an optimized sorting algorithm (qsort, mergesort) to find unique lines */
+
+int diff_atoms_compar(const void *_a, const void *_b)
+{
+ const struct diff_atom *a = *(struct diff_atom**)_a;
+ const struct diff_atom *b = *(struct diff_atom**)_b;
+ int cmp;
+ int rc = 0;
+
+ /* If there's been an error (e.g. I/O error) in a previous compar, we
+ * have no way to abort the sort but just report the rc and stop
+ * comparing. Make sure to catch errors on either side. If atoms are
+ * from more than one diff_data, make sure the error, if any, spreads
+ * to all of them, so we can cut short all future comparisons. */
+ if (a->root->err)
+ rc = a->root->err;
+ if (b->root->err)
+ rc = b->root->err;
+ if (rc) {
+ a->root->err = rc;
+ b->root->err = rc;
+ /* just return 'equal' to not swap more positions */
+ return 0;
+ }
+
+ /* Sort by the simplistic hash */
+ if (a->hash < b->hash)
+ return -1;
+ if (a->hash > b->hash)
+ return 1;
+
+ /* If hashes are the same, the lines may still differ. Do a full cmp. */
+ rc = diff_atom_cmp(&cmp, a, b);
+
+ if (rc) {
+ /* Mark the I/O error so that the caller can find out about it.
+ * For the case atoms are from more than one diff_data, mark in
+ * both. */
+ a->root->err = rc;
+ if (a->root != b->root)
+ b->root->err = rc;
+ return 0;
+ }
+
+ return cmp;
+}
+
+/* Sort an array of struct diff_atom* in-place. */
+static int diff_atoms_sort(struct diff_atom *atoms[],
+ size_t atoms_count)
+{
+#if UNIQUE_STRATEGY == 1
+ qsort(atoms, atoms_count, sizeof(struct diff_atom*), diff_atoms_compar);
+#else
+ mergesort(atoms, atoms_count, sizeof(struct diff_atom*),
+ diff_atoms_compar);
+#endif
+ return atoms[0]->root->err;
+}
+
+static int
+diff_atoms_mark_unique_in_both(struct diff_data *left, struct diff_data *right,
+ unsigned int *unique_in_both_count_p)
+{
+ struct diff_atom *a;
+ struct diff_atom *b;
+ struct diff_atom **all_atoms;
+ unsigned int len = 0;
+ unsigned int i;
+ unsigned int unique_in_both_count = 0;
+ int rc;
+
+ all_atoms = calloc(left->atoms.len + right->atoms.len,
+ sizeof(struct diff_atom *));
+ if (all_atoms == NULL)
+ return ENOMEM;
+
+ left->err = 0;
+ right->err = 0;
+ left->root->err = 0;
+ right->root->err = 0;
+ diff_data_foreach_atom(a, left) {
+ all_atoms[len++] = a;
+ }
+ diff_data_foreach_atom(b, right) {
+ all_atoms[len++] = b;
+ }
+
+ rc = diff_atoms_sort(all_atoms, len);
+ if (rc)
+ goto free_and_exit;
+
+ /* Now we have a sorted array of atom pointers. All similar lines are
+ * adjacent. Walk through the array and mark those that are unique on
+ * each side, but exist once in both sources. */
+ for (i = 0; i < len; i++) {
+ bool same;
+ unsigned int next_differing_i;
+ unsigned int last_identical_i;
+ unsigned int j;
+ unsigned int count_first_side = 1;
+ unsigned int count_other_side = 0;
+ a = all_atoms[i];
+ debug("a: ");
+ debug_dump_atom(a->root, NULL, a);
+
+ /* Do as few diff_atom_cmp() as possible: first walk forward
+ * only using the cheap hash as indicator for differing atoms;
+ * then walk backwards until hitting an identical atom. */
+ for (next_differing_i = i + 1; next_differing_i < len;
+ next_differing_i++) {
+ b = all_atoms[next_differing_i];
+ if (a->hash != b->hash)
+ break;
+ }
+ for (last_identical_i = next_differing_i - 1;
+ last_identical_i > i;
+ last_identical_i--) {
+ b = all_atoms[last_identical_i];
+ rc = diff_atom_same(&same, a, b);
+ if (rc)
+ goto free_and_exit;
+ if (same)
+ break;
+ }
+ next_differing_i = last_identical_i + 1;
+
+ for (j = i+1; j < next_differing_i; j++) {
+ b = all_atoms[j];
+ /* A following atom is the same. See on which side the
+ * repetition counts. */
+ if (a->root == b->root)
+ count_first_side ++;
+ else
+ count_other_side ++;
+ debug("b: ");
+ debug_dump_atom(b->root, NULL, b);
+ debug(" count_first_side=%d count_other_side=%d\n",
+ count_first_side, count_other_side);
+ }
+
+ /* Counted a section of similar atoms, put the results back to
+ * the atoms. */
+ if ((count_first_side == 1)
+ && (count_other_side == 1)) {
+ b = all_atoms[i+1];
+ PATIENCE(a).unique_in_both = true;
+ PATIENCE(a).pos_in_other = b;
+ PATIENCE(b).unique_in_both = true;
+ PATIENCE(b).pos_in_other = a;
+ unique_in_both_count++;
+ }
+
+ /* j now points at the first atom after 'a' that is not
+ * identical to 'a'. j is always > i. */
+ i = j - 1;
+ }
+ *unique_in_both_count_p = unique_in_both_count;
+ rc = 0;
+free_and_exit:
+ free(all_atoms);
+ return rc;
+}
+#endif /* UNIQUE_STRATEGY != 0 */
+
+static int
+diff_atoms_swallow_identical_neighbors(struct diff_data *left,
+ struct diff_data *right,
+ unsigned int *unique_in_both_count)
+{
+ debug("trivially combine identical lines"
+ " around unique_in_both lines\n");
+
+ unsigned int l_idx;
+ unsigned int next_l_idx;
+ /* Only checking against identical-line overlaps on the left; overlaps
+ * on the right are tolerated and ironed out later. See also the other
+ * place marked with (1). */
+ unsigned int l_min = 0;
+ for (l_idx = 0; l_idx < left->atoms.len; l_idx = next_l_idx) {
+ next_l_idx = l_idx + 1;
+ struct diff_atom *l = &left->atoms.head[l_idx];
+ struct diff_atom *r;
+
+ if (!PATIENCE(l).unique_in_both)
+ continue;
+
+ debug("check identical lines around\n");
+ debug(" L "); debug_dump_atom(left, right, l);
+
+ unsigned int r_idx = diff_atom_idx(right, PATIENCE(l).pos_in_other);
+ r = &right->atoms.head[r_idx];
+ debug(" R "); debug_dump_atom(right, left, r);
+
+ struct diff_range identical_l;
+ struct diff_range identical_r;
+
+ /* Swallow upwards.
+ * Each common-unique line swallows identical lines upwards and
+ * downwards.
+ * Will never hit another identical common-unique line above on
+ * the left, because those would already have swallowed this
+ * common-unique line in a previous iteration.
+ */
+ for (identical_l.start = l_idx, identical_r.start = r_idx;
+ identical_l.start > (l_min+1) && identical_r.start > 0;
+ identical_l.start--, identical_r.start--) {
+ bool same;
+ int rc = diff_atom_same(&same,
+ &left->atoms.head[identical_l.start - 1],
+ &right->atoms.head[identical_r.start - 1]);
+ if (rc)
+ return rc;
+ if (!same)
+ break;
+ }
+
+ /* Swallow downwards. Join any common-unique lines in a block of
+ * matching L/R lines with this one. */
+ for (identical_l.end = l_idx + 1, identical_r.end = r_idx + 1;
+ identical_l.end < left->atoms.len
+ && identical_r.end < right->atoms.len;
+ identical_l.end++, identical_r.end++,
+ next_l_idx++) {
+ struct diff_atom *l_end;
+ struct diff_atom *r_end;
+ bool same;
+ int rc = diff_atom_same(&same,
+ &left->atoms.head[identical_l.end],
+ &right->atoms.head[identical_r.end]);
+ if (rc)
+ return rc;
+ if (!same)
+ break;
+ l_end = &left->atoms.head[identical_l.end];
+ r_end = &right->atoms.head[identical_r.end];
+ if (!PATIENCE(l_end).unique_in_both)
+ continue;
+ /* A unique_in_both atom is joined with a preceding
+ * unique_in_both atom, remove the joined atom from
+ * listing of unique_in_both atoms */
+ PATIENCE(l_end).unique_in_both = false;
+ PATIENCE(r_end).unique_in_both = false;
+ (*unique_in_both_count)--;
+ }
+
+ PATIENCE(l).identical_lines = identical_l;
+ PATIENCE(r).identical_lines = identical_r;
+
+ l_min = identical_l.end;
+
+ if (!diff_range_empty(&PATIENCE(l).identical_lines)) {
+ debug("common-unique line at l=%u r=%u swallowed"
+ " identical lines l=%u-%u r=%u-%u\n",
+ l_idx, r_idx,
+ identical_l.start, identical_l.end,
+ identical_r.start, identical_r.end);
+ }
+ debug("next_l_idx = %u\n", next_l_idx);
+ }
+ return 0;
+}
+
+/* binary search to find the stack to put this atom "card" on. */
+static int
+find_target_stack(struct diff_atom *atom,
+ struct diff_atom **patience_stacks,
+ unsigned int patience_stacks_count)
+{
+ unsigned int lo = 0;
+ unsigned int hi = patience_stacks_count;
+ while (lo < hi) {
+ unsigned int mid = (lo + hi) >> 1;
+
+ if (PATIENCE(patience_stacks[mid]).pos_in_other
+ < PATIENCE(atom).pos_in_other)
+ lo = mid + 1;
+ else
+ hi = mid;
+ }
+ return lo;
+}
+
+/* Among the lines that appear exactly once in each side, find the longest
+ * streak that appear in both files in the same order (with other stuff allowed
+ * to interleave). Use patience sort for that, as in the Patience Diff
+ * algorithm.
+ * See https://bramcohen.livejournal.com/73318.html and, for a much more
+ * detailed explanation,
+ * https://blog.jcoglan.com/2017/09/19/the-patience-diff-algorithm/ */
+int
+diff_algo_patience(const struct diff_algo_config *algo_config,
+ struct diff_state *state)
+{
+ int rc;
+ struct diff_data *left = &state->left;
+ struct diff_data *right = &state->right;
+ struct atom_patience *atom_patience_left =
+ calloc(left->atoms.len, sizeof(struct atom_patience));
+ struct atom_patience *atom_patience_right =
+ calloc(right->atoms.len, sizeof(struct atom_patience));
+ unsigned int unique_in_both_count;
+ struct diff_atom **lcs = NULL;
+
+ debug("\n** %s\n", __func__);
+
+ left->root->current = left;
+ right->root->current = right;
+ left->algo_data = atom_patience_left;
+ right->algo_data = atom_patience_right;
+
+ /* Find those lines that appear exactly once in 'left' and exactly once
+ * in 'right'. */
+ rc = diff_atoms_mark_unique_in_both(left, right, &unique_in_both_count);
+ if (rc)
+ goto free_and_exit;
+
+ debug("unique_in_both_count %u\n", unique_in_both_count);
+ debug("left:\n");
+ debug_dump(left);
+ debug("right:\n");
+ debug_dump(right);
+
+ if (!unique_in_both_count) {
+ /* Cannot apply Patience, tell the caller to use fallback_algo
+ * instead. */
+ rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
+ goto free_and_exit;
+ }
+
+ rc = diff_atoms_swallow_identical_neighbors(left, right,
+ &unique_in_both_count);
+ if (rc)
+ goto free_and_exit;
+ debug("After swallowing identical neighbors: unique_in_both = %u\n",
+ unique_in_both_count);
+
+ rc = ENOMEM;
+
+ /* An array of Longest Common Sequence is the result of the below
+ * subscope: */
+ unsigned int lcs_count = 0;
+ struct diff_atom *lcs_tail = NULL;
+
+ {
+ /* This subscope marks the lifetime of the atom_pointers
+ * allocation */
+
+ /* One chunk of storage for atom pointers */
+ struct diff_atom **atom_pointers;
+ atom_pointers = recallocarray(NULL, 0, unique_in_both_count * 2,
+ sizeof(struct diff_atom*));
+ if (atom_pointers == NULL)
+ return ENOMEM;
+ /* Half for the list of atoms that still need to be put on
+ * stacks */
+ struct diff_atom **uniques = atom_pointers;
+
+ /* Half for the patience sort state's "card stacks" -- we
+ * remember only each stack's topmost "card" */
+ struct diff_atom **patience_stacks;
+ patience_stacks = atom_pointers + unique_in_both_count;
+ unsigned int patience_stacks_count = 0;
+
+ /* Take all common, unique items from 'left' ... */
+
+ struct diff_atom *atom;
+ struct diff_atom **uniques_end = uniques;
+ diff_data_foreach_atom(atom, left) {
+ if (!PATIENCE(atom).unique_in_both)
+ continue;
+ *uniques_end = atom;
+ uniques_end++;
+ }
+
+ /* ...and sort them to the order found in 'right'.
+ * The idea is to find the leftmost stack that has a higher line
+ * number and add it to the stack's top.
+ * If there is no such stack, open a new one on the right. The
+ * line number is derived from the atom*, which are array items
+ * and hence reflect the relative position in the source file.
+ * So we got the common-uniques from 'left' and sort them
+ * according to PATIENCE(atom).pos_in_other. */
+ unsigned int i;
+ for (i = 0; i < unique_in_both_count; i++) {
+ atom = uniques[i];
+ unsigned int target_stack;
+ target_stack = find_target_stack(atom, patience_stacks,
+ patience_stacks_count);
+ assert(target_stack <= patience_stacks_count);
+ patience_stacks[target_stack] = atom;
+ if (target_stack == patience_stacks_count)
+ patience_stacks_count++;
+
+ /* Record a back reference to the next stack on the
+ * left, which will form the final longest sequence
+ * later. */
+ PATIENCE(atom).prev_stack = target_stack ?
+ patience_stacks[target_stack - 1] : NULL;
+
+ {
+ int xx;
+ for (xx = 0; xx < patience_stacks_count; xx++) {
+ debug(" %s%d",
+ (xx == target_stack) ? ">" : "",
+ diff_atom_idx(right,
+ PATIENCE(patience_stacks[xx]).pos_in_other));
+ }
+ debug("\n");
+ }
+ }
+
+ /* backtrace through prev_stack references to form the final
+ * longest common sequence */
+ lcs_tail = patience_stacks[patience_stacks_count - 1];
+ lcs_count = patience_stacks_count;
+
+ /* uniques and patience_stacks are no longer needed.
+ * Backpointers are in PATIENCE(atom).prev_stack */
+ free(atom_pointers);
+ }
+
+ lcs = recallocarray(NULL, 0, lcs_count, sizeof(struct diff_atom*));
+ struct diff_atom **lcs_backtrace_pos = &lcs[lcs_count - 1];
+ struct diff_atom *atom;
+ for (atom = lcs_tail; atom; atom = PATIENCE(atom).prev_stack, lcs_backtrace_pos--) {
+ assert(lcs_backtrace_pos >= lcs);
+ *lcs_backtrace_pos = atom;
+ }
+
+ unsigned int i;
+ if (DEBUG) {
+ debug("\npatience LCS:\n");
+ for (i = 0; i < lcs_count; i++) {
+ debug("\n L "); debug_dump_atom(left, right, lcs[i]);
+ debug(" R "); debug_dump_atom(right, left,
+ PATIENCE(lcs[i]).pos_in_other);
+ }
+ }
+
+
+ /* TODO: For each common-unique line found (now listed in lcs), swallow
+ * lines upwards and downwards that are identical on each side. Requires
+ * a way to represent atoms being glued to adjacent atoms. */
+
+ debug("\ntraverse LCS, possibly recursing:\n");
+
+ /* Now we have pinned positions in both files at which it makes sense to
+ * divide the diff problem into smaller chunks. Go into the next round:
+ * look at each section in turn, trying to again find common-unique
+ * lines in those smaller sections. As soon as no more are found, the
+ * remaining smaller sections are solved by Myers. */
+ /* left_pos and right_pos are indexes in left/right->atoms.head until
+ * which the atoms are already handled (added to result chunks). */
+ unsigned int left_pos = 0;
+ unsigned int right_pos = 0;
+ for (i = 0; i <= lcs_count; i++) {
+ struct diff_atom *atom;
+ struct diff_atom *atom_r;
+ /* left_idx and right_idx are indexes of the start of this
+ * section of identical lines on both sides.
+ * left_pos marks the index of the first still unhandled line,
+ * left_idx is the start of an identical section some way
+ * further down, and this loop adds an unsolved chunk of
+ * [left_pos..left_idx[ and a solved chunk of
+ * [left_idx..identical_lines.end[. */
+ unsigned int left_idx;
+ unsigned int right_idx;
+ int already_done_count = 0;
+
+ debug("iteration %u of %u left_pos %u right_pos %u\n",
+ i, lcs_count, left_pos, right_pos);
+
+ if (i < lcs_count) {
+ atom = lcs[i];
+ atom_r = PATIENCE(atom).pos_in_other;
+ debug("lcs[%u] = left[%u] = right[%u]\n", i,
+ diff_atom_idx(left, atom), diff_atom_idx(right, atom_r));
+ left_idx = PATIENCE(atom).identical_lines.start;
+ right_idx = PATIENCE(atom_r).identical_lines.start;
+ debug(" identical lines l %u-%u r %u-%u\n",
+ PATIENCE(atom).identical_lines.start, PATIENCE(atom).identical_lines.end,
+ PATIENCE(atom_r).identical_lines.start, PATIENCE(atom_r).identical_lines.end);
+ } else {
+ /* There are no more identical lines until the end of
+ * left and right. */
+ atom = NULL;
+ atom_r = NULL;
+ left_idx = left->atoms.len;
+ right_idx = right->atoms.len;
+ }
+
+ if (right_idx < right_pos) {
+ /* This may happen if common-unique lines were in a
+ * different order on the right, and then ended up
+ * consuming the same identical atoms around a pair of
+ * common-unique atoms more than once.
+ * See also marker the other place marked with (1). */
+ already_done_count = right_pos - right_idx;
+ left_idx += already_done_count;
+ right_idx += already_done_count;
+ /* Paranoia: make sure we're skipping just an
+ * additionally joined identical line around it, and not
+ * the common-unique line itself. */
+ assert(left_idx <= diff_atom_idx(left, atom));
+ }
+
+ /* 'atom' (if not NULL) now marks an atom that matches on both
+ * sides according to patience-diff (a common-unique identical
+ * atom in both files).
+ * Handle the section before and the atom itself; the section
+ * after will be handled by the next loop iteration -- note that
+ * i loops to last element + 1 ("i <= lcs_count"), so that there
+ * will be another final iteration to pick up the last remaining
+ * items after the last LCS atom.
+ */
+
+ debug("iteration %u left_pos %u left_idx %u"
+ " right_pos %u right_idx %u\n",
+ i, left_pos, left_idx, right_pos, right_idx);
+
+ /* Section before the matching atom */
+ struct diff_atom *left_atom = &left->atoms.head[left_pos];
+ unsigned int left_section_len = left_idx - left_pos;
+
+ struct diff_atom *right_atom = &(right->atoms.head[right_pos]);
+ unsigned int right_section_len = right_idx - right_pos;
+
+ if (left_section_len && right_section_len) {
+ /* Record an unsolved chunk, the caller will apply
+ * inner_algo() on this chunk. */
+ if (!diff_state_add_chunk(state, false,
+ left_atom, left_section_len,
+ right_atom,
+ right_section_len))
+ goto free_and_exit;
+ } else if (left_section_len && !right_section_len) {
+ /* Only left atoms and none on the right, they form a
+ * "minus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, left_section_len,
+ right_atom, 0))
+ goto free_and_exit;
+ } else if (!left_section_len && right_section_len) {
+ /* No left atoms, only atoms on the right, they form a
+ * "plus" chunk, then. */
+ if (!diff_state_add_chunk(state, true,
+ left_atom, 0,
+ right_atom, right_section_len))
+ goto free_and_exit;
+ }
+ /* else: left_section_len == 0 and right_section_len == 0, i.e.
+ * nothing here. */
+
+ /* The atom found to match on both sides forms a chunk of equals
+ * on each side. In the very last iteration of this loop, there
+ * is no matching atom, we were just cleaning out the remaining
+ * lines. */
+ if (atom) {
+ void *ok;
+ unsigned int left_start = PATIENCE(atom).identical_lines.start;
+ unsigned int left_len = diff_range_len(&PATIENCE(atom).identical_lines);
+ unsigned int right_start = PATIENCE(atom_r).identical_lines.start;
+ unsigned int right_len = diff_range_len(&PATIENCE(atom_r).identical_lines);
+
+ left_start += already_done_count;
+ left_len -= already_done_count;
+ right_start += already_done_count;
+ right_len -= already_done_count;
+
+ ok = diff_state_add_chunk(state, true,
+ left->atoms.head + left_start, left_len,
+ right->atoms.head + right_start, right_len);
+ if (!ok)
+ goto free_and_exit;
+ left_pos = PATIENCE(atom).identical_lines.end;
+ right_pos = PATIENCE(atom_r).identical_lines.end;
+ } else {
+ left_pos = left_idx + 1;
+ right_pos = right_idx + 1;
+ }
+ debug("end of iteration %u left_pos %u left_idx %u"
+ " right_pos %u right_idx %u\n",
+ i, left_pos, left_idx, right_pos, right_idx);
+ }
+ debug("** END %s\n", __func__);
+
+ rc = DIFF_RC_OK;
+
+free_and_exit:
+ left->root->current = NULL;
+ right->root->current = NULL;
+ free(atom_patience_left);
+ free(atom_patience_right);
+ if (lcs)
+ free(lcs);
+ return rc;
+}
diff --git a/lib/diffreg.c b/lib/diffreg.c
index 6ababe7..c631824 100644
--- a/lib/diffreg.c
+++ b/lib/diffreg.c
@@ -1,1254 +1,390 @@
-/* $OpenBSD: diffreg.c,v 1.91 2016/03/01 20:57:35 natano Exp $ */
-
/*
- * Copyright (C) Caldera International Inc. 2001-2002.
- * All rights reserved.
+ * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
+ * Copyright (c) 2020 Stefan Sperling <stsp@openbsd.org>
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code and documentation must retain the above
- * copyright notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed or owned by Caldera
- * International, Inc.
- * 4. Neither the name of Caldera International, Inc. nor the names of other
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
*
- * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
- * INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE FOR ANY DIRECT,
- * INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-/*-
- * Copyright (c) 1991, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)diffreg.c 8.1 (Berkeley) 6/6/93
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
-#include <sys/types.h>
+#include <sys/mman.h>
#include <sys/stat.h>
-#include <sys/wait.h>
#include <sys/queue.h>
-#include <ctype.h>
-#include <err.h>
#include <errno.h>
-#include <fcntl.h>
-#include <paths.h>
-#include <stdarg.h>
-#include <stddef.h>
-#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <time.h>
-#include <unistd.h>
-#include <limits.h>
-#include <sha1.h>
-#include <zlib.h>
-#include "got_error.h"
#include "got_object.h"
-#include "got_diff.h"
+#include "got_opentemp.h"
+#include "got_error.h"
#include "got_lib_diff.h"
-#define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
-#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
-
-/*
- * diff - compare two files.
- */
-
-/*
- * Uses an algorithm due to Harold Stone, which finds
- * a pair of longest identical subsequences in the two
- * files.
- *
- * The major goal is to generate the match vector J.
- * J[i] is the index of the line in file1 corresponding
- * to line i file0. J[i] = 0 if there is no
- * such line in file1.
- *
- * Lines are hashed so as to work in core. All potential
- * matches are located by sorting the lines of each file
- * on the hash (called ``value''). In particular, this
- * collects the equivalence classes in file1 together.
- * Subroutine equiv replaces the value of each line in
- * file0 by the index of the first element of its
- * matching equivalence in (the reordered) file1.
- * To save space equiv squeezes file1 into a single
- * array member in which the equivalence classes
- * are simply concatenated, except that their first
- * members are flagged by changing sign.
- *
- * Next the indices that point into member are unsorted into
- * array class according to the original order of file0.
- *
- * The cleverness lies in routine stone. This marches
- * through the lines of file0, developing a vector klist
- * of "k-candidates". At step i a k-candidate is a matched
- * pair of lines x,y (x in file0 y in file1) such that
- * there is a common subsequence of length k
- * between the first i lines of file0 and the first y
- * lines of file1, but there is no such subsequence for
- * any smaller y. x is the earliest possible mate to y
- * that occurs in such a subsequence.
- *
- * Whenever any of the members of the equivalence class of
- * lines in file1 matable to a line in file0 has serial number
- * less than the y of some k-candidate, that k-candidate
- * with the smallest such y is replaced. The new
- * k-candidate is chained (via pred) to the current
- * k-1 candidate so that the actual subsequence can
- * be recovered. When a member has serial number greater
- * that the y of all k-candidates, the klist is extended.
- * At the end, the longest subsequence is pulled out
- * and placed in the array J by unravel
- *
- * With J in hand, the matches there recorded are
- * check'ed against reality to assure that no spurious
- * matches have crept in due to hashing. If they have,
- * they are broken, and "jackpot" is recorded--a harmless
- * matter except that a true match for a spuriously
- * mated line may now be unnecessarily reported as a change.
- *
- * Much of the complexity of the program comes simply
- * from trying to minimize core utilization and
- * maximize the range of doable problems by dynamically
- * allocating what is needed and reusing what is not.
- * The core requirements for problems larger than somewhat
- * are (in words) 2*length(file0) + length(file1) +
- * 3*(number of k-candidates installed), typically about
- * 6n words for files of length n.
- */
+const struct diff_algo_config myers_then_patience;
+const struct diff_algo_config myers_then_myers_divide;
+const struct diff_algo_config patience;
+const struct diff_algo_config myers_divide;
-struct cand {
- int x;
- int y;
- int pred;
+const struct diff_algo_config myers_then_patience = (struct diff_algo_config){
+ .impl = diff_algo_myers,
+ .permitted_state_size = 1024 * 1024 * sizeof(int),
+ .fallback_algo = &patience,
};
-struct line {
- int serial;
- int value;
+const struct diff_algo_config myers_then_myers_divide =
+ (struct diff_algo_config){
+ .impl = diff_algo_myers,
+ .permitted_state_size = 1024 * 1024 * sizeof(int),
+ .fallback_algo = &myers_divide,
};
-static void diff_output(FILE *, const char *, ...);
-static int output(FILE *, struct got_diff_changes *, struct got_diff_state *, struct got_diff_args *, const char *, FILE *, const char *, FILE *, int);
-static void check(struct got_diff_state *, FILE *, FILE *, int);
-static void range(FILE *, int, int, char *);
-static void uni_range(FILE *, int, int);
-static void dump_unified_vec(FILE *, struct got_diff_changes *, struct got_diff_state *, struct got_diff_args *, FILE *, FILE *, int);
-static int prepare(struct got_diff_state *, int, FILE *, off_t, int);
-static void prune(struct got_diff_state *);
-static void equiv(struct line *, int, struct line *, int, int *);
-static void unravel(struct got_diff_state *, int);
-static int unsort(struct line *, int, int *);
-static int change(FILE *, struct got_diff_changes *, struct got_diff_state *, struct got_diff_args *, const char *, FILE *, const char *, FILE *, int, int, int, int, int *);
-static void sort(struct line *, int);
-static void print_header(FILE *, struct got_diff_state *, struct got_diff_args *, const char *, const char *);
-static int asciifile(FILE *);
-static void fetch(FILE *, struct got_diff_state *, struct got_diff_args *, long *, int, int, FILE *, int, int);
-static int newcand(struct got_diff_state *, int, int, int, int *);
-static int search(struct got_diff_state *, int *, int, int);
-static int skipline(FILE *);
-static int isqrt(int);
-static int stone(struct got_diff_state *, int *, int, int *, int *, int);
-static int readhash(struct got_diff_state *, FILE *, int);
-static int files_differ(struct got_diff_state *, FILE *, FILE *);
-static char *match_function(struct got_diff_state *, const long *, int, FILE *);
-
-/*
- * chrtran points to one of 2 translation tables: cup2low if folding upper to
- * lower case clow2low if not folding case
- */
-u_char clow2low[256] = {
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
- 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
- 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
- 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
- 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41,
- 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c,
- 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
- 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
- 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d,
- 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
- 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83,
- 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e,
- 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
- 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,
- 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
- 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba,
- 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5,
- 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0,
- 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb,
- 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
- 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1,
- 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc,
- 0xfd, 0xfe, 0xff
+const struct diff_algo_config patience = (struct diff_algo_config){
+ .impl = diff_algo_patience,
+ /* After subdivision, do Patience again: */
+ .inner_algo = &patience,
+ /* If subdivision failed, do Myers Divide et Impera: */
+ .fallback_algo = &myers_then_myers_divide,
};
-u_char cup2low[256] = {
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
- 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
- 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
- 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
- 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x60, 0x61,
- 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c,
- 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
- 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x60, 0x61, 0x62,
- 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d,
- 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
- 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83,
- 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e,
- 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
- 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,
- 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
- 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba,
- 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5,
- 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0,
- 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb,
- 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
- 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1,
- 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc,
- 0xfd, 0xfe, 0xff
+const struct diff_algo_config myers_divide = (struct diff_algo_config){
+ .impl = diff_algo_myers_divide,
+ /* When division succeeded, start from the top: */
+ .inner_algo = &myers_then_myers_divide,
+ /* (fallback_algo = NULL implies diff_algo_none). */
};
-static void
-diff_output(FILE *outfile, const char *fmt, ...)
-{
- va_list ap;
+/* If the state for a forward-Myers is small enough, use Myers, otherwise first
+ * do a Myers-divide. */
+const struct diff_config diff_config_myers_then_myers_divide = {
+ .atomize_func = diff_atomize_text_by_line,
+ .algo = &myers_then_myers_divide,
+};
- if (outfile == NULL)
- return;
+/* If the state for a forward-Myers is small enough, use Myers, otherwise first
+ * do a Patience. */
+const struct diff_config diff_config_myers_then_patience = {
+ .atomize_func = diff_atomize_text_by_line,
+ .algo = &myers_then_patience,
+};
- va_start(ap, fmt);
- vfprintf(outfile, fmt, ap);
- va_end(ap);
-}
+/* Directly force Patience as a first divider of the source file. */
+const struct diff_config diff_config_patience = {
+ .atomize_func = diff_atomize_text_by_line,
+ .algo = &patience,
+};
-void
-got_diff_state_free(struct got_diff_state *ds)
-{
- free(ds->J);
- free(ds->member);
- free(ds->class);
- free(ds->clist);
- free(ds->klist);
- free(ds->ixold);
- free(ds->ixnew);
-}
+/* Directly force Patience as a first divider of the source file. */
+const struct diff_config diff_config_no_algo = {
+ .atomize_func = diff_atomize_text_by_line,
+};
const struct got_error *
-got_diffreg(int *rval, FILE *f1, FILE *f2, int flags,
- struct got_diff_args *args, struct got_diff_state *ds, FILE *outfile,
- struct got_diff_changes *changes)
+got_diffreg_close(FILE *f1, char *p1, size_t size1,
+ FILE *f2, char *p2, size_t size2)
{
const struct got_error *err = NULL;
- int i, *p;
- long *lp;
-
- *rval = D_SAME;
- ds->anychange = 0;
- ds->lastline = 0;
- ds->lastmatchline = 0;
- ds->context_vec_ptr = ds->context_vec_start - 1;
- ds->max_context = GOT_DIFF_MAX_CONTEXT;
- if (flags & D_IGNORECASE)
- ds->chrtran = cup2low;
- else
- ds->chrtran = clow2low;
- if (S_ISDIR(ds->stb1.st_mode) != S_ISDIR(ds->stb2.st_mode)) {
- *rval = (S_ISDIR(ds->stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
- return NULL;
- }
- if (!(flags & D_EMPTY1) && f1 == NULL) {
- args->status |= 2;
- goto closem;
- }
-
- if (!(flags & D_EMPTY2) && f2 == NULL) {
- args->status |= 2;
- goto closem;
- }
-
- switch (files_differ(ds, f1, f2)) {
- case 0:
- goto closem;
- case 1:
- break;
- default:
- /* error */
- args->status |= 2;
- goto closem;
- }
-
- if ((flags & D_FORCEASCII) == 0 &&
- (!asciifile(f1) || !asciifile(f2))) {
- *rval = D_BINARY;
- args->status |= 1;
- goto closem;
- }
- if (prepare(ds, 0, f1, ds->stb1.st_size, flags)) {
- err = got_error_from_errno("prepare");
- goto closem;
- }
- if (prepare(ds, 1, f2, ds->stb2.st_size, flags)) {
- err = got_error_from_errno("prepare");
- goto closem;
- }
-
- prune(ds);
- sort(ds->sfile[0], ds->slen[0]);
- sort(ds->sfile[1], ds->slen[1]);
-
- ds->member = (int *)ds->file[1];
- equiv(ds->sfile[0], ds->slen[0], ds->sfile[1], ds->slen[1], ds->member);
- p = reallocarray(ds->member, ds->slen[1] + 2, sizeof(*ds->member));
- if (p == NULL) {
- err = got_error_from_errno("reallocarray");
- goto closem;
- }
- ds->member = p;
-
- ds->class = (int *)ds->file[0];
- if (unsort(ds->sfile[0], ds->slen[0], ds->class)) {
- err = got_error_from_errno("unsort");
- goto closem;
- }
- p = reallocarray(ds->class, ds->slen[0] + 2, sizeof(*ds->class));
- if (p == NULL) {
- err = got_error_from_errno("reallocarray");
- goto closem;
- }
- ds->class = p;
- ds->klist = calloc(ds->slen[0] + 2, sizeof(*ds->klist));
- if (ds->klist == NULL) {
- err = got_error_from_errno("calloc");
- goto closem;
- }
- ds->clen = 0;
- ds->clistlen = 100;
- ds->clist = calloc(ds->clistlen, sizeof(*ds->clist));
- if (ds->clist == NULL) {
- err = got_error_from_errno("calloc");
- goto closem;
- }
- i = stone(ds, ds->class, ds->slen[0], ds->member, ds->klist, flags);
- if (i < 0) {
- err = got_error_from_errno("stone");
- goto closem;
- }
-
- p = reallocarray(ds->J, ds->len[0] + 2, sizeof(*ds->J));
- if (p == NULL) {
- err = got_error_from_errno("reallocarray");
- goto closem;
- }
- ds->J = p;
- unravel(ds, ds->klist[i]);
-
- lp = reallocarray(ds->ixold, ds->len[0] + 2, sizeof(*ds->ixold));
- if (lp == NULL) {
- err = got_error_from_errno("reallocarray");
- goto closem;
- }
- ds->ixold = lp;
- lp = reallocarray(ds->ixnew, ds->len[1] + 2, sizeof(*ds->ixnew));
- if (lp == NULL) {
- err = got_error_from_errno("reallocarray");
- goto closem;
- }
- ds->ixnew = lp;
- check(ds, f1, f2, flags);
- if (output(outfile, changes, ds, args, args->label[0], f1,
- args->label[1], f2, flags))
- err = got_error_from_errno("output");
-closem:
- if (ds->anychange) {
- args->status |= 1;
- if (*rval == D_SAME)
- *rval = D_DIFFER;
- }
- return (err);
+ if (p1 && munmap(p1, size1) == -1 && err == NULL)
+ err = got_error_from_errno("munmap");
+ if (p2 && munmap(p2, size2) == -1 && err == NULL)
+ err = got_error_from_errno("munmap");
+ if (f1 && fclose(f1) != 0 && err == NULL)
+ err = got_error_from_errno("fclose");
+ if (f2 && fclose(f2) != 0 && err == NULL)
+ err = got_error_from_errno("fclose");
+ return err;
}
-/*
- * Check to see if the given files differ.
- * Returns 0 if they are the same, 1 if different, and -1 on error.
- * XXX - could use code from cmp(1) [faster]
- */
-static int
-files_differ(struct got_diff_state *ds, FILE *f1, FILE *f2)
+const struct diff_config *
+got_diff_get_config(enum got_diff_algorithm algorithm)
{
- char buf1[BUFSIZ], buf2[BUFSIZ];
- size_t i, j;
-
- if (f1 == NULL || f2 == NULL || ds->stb1.st_size != ds->stb2.st_size ||
- (ds->stb1.st_mode & S_IFMT) != (ds->stb2.st_mode & S_IFMT))
- return (1);
- for (;;) {
- i = fread(buf1, 1, sizeof(buf1), f1);
- j = fread(buf2, 1, sizeof(buf2), f2);
- if ((!i && ferror(f1)) || (!j && ferror(f2)))
- return (-1);
- if (i != j)
- return (1);
- if (i == 0)
- return (0);
- if (memcmp(buf1, buf2, i) != 0)
- return (1);
+ switch (algorithm) {
+ case GOT_DIFF_ALGORITHM_PATIENCE:
+ return &diff_config_patience;
+ case GOT_DIFF_ALGORITHM_MYERS:
+ return &diff_config_myers_then_myers_divide;
}
+ return NULL; /* should not happen */
}
-static int
-prepare(struct got_diff_state *ds, int i, FILE *fd, off_t filesize, int flags)
+const struct got_error *
+got_diff_prepare_file(FILE **f, char **p, int *f_created, size_t *size,
+ struct diff_data *diff_data, const struct diff_config *cfg,
+ int ignore_whitespace)
{
- struct line *p, *q;
- int j, h;
- size_t sz;
+ const struct got_error *err = NULL;
+ struct stat st;
+ int diff_flags = 0, rc;
- if (fd != NULL)
- rewind(fd);
+ *size = 0;
- sz = (filesize <= SIZE_MAX ? filesize : SIZE_MAX) / 25;
- if (sz < 100)
- sz = 100;
+ diff_flags |= DIFF_FLAG_SHOW_PROTOTYPES;
+ if (ignore_whitespace)
+ diff_flags |= DIFF_FLAG_IGNORE_WHITESPACE;
- p = calloc(sz + 3, sizeof(*p));
- if (p == NULL)
- return (-1);
- for (j = 0; fd != NULL && (h = readhash(ds, fd, flags));) {
- if (j == sz) {
- sz = sz * 3 / 2;
- q = reallocarray(p, sz + 3, sizeof(*p));
- if (q == NULL) {
- free(p);
- return (-1);
- }
- p = q;
+ if (f && *f) {
+ if (fstat(fileno(*f), &st) == -1) {
+ err = got_error_from_errno("fstat");
+ goto done;
+ }
+ #ifndef GOT_DIFF_NO_MMAP
+ *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE,
+ fileno(*f), 0);
+ if (*p == MAP_FAILED)
+ #endif
+ *p = NULL; /* fall back on file I/O */
+ } else {
+ *f_created = 1;
+ st.st_size = 0;
+ *f = got_opentemp();
+ if (*f == NULL) {
+ err = got_error_from_errno("got_opentemp");
+ goto done;
}
- p[++j].value = h;
}
- ds->len[i] = j;
- ds->file[i] = p;
-
- return (0);
-}
-static void
-prune(struct got_diff_state *ds)
-{
- int i, j;
-
- for (ds->pref = 0; ds->pref < ds->len[0] && ds->pref < ds->len[1] &&
- ds->file[0][ds->pref + 1].value == ds->file[1][ds->pref + 1].value;
- ds->pref++)
- ;
- for (ds->suff = 0; ds->suff < ds->len[0] - ds->pref && ds->suff < ds->len[1] - ds->pref &&
- ds->file[0][ds->len[0] - ds->suff].value == ds->file[1][ds->len[1] - ds->suff].value;
- ds->suff++)
- ;
- for (j = 0; j < 2; j++) {
- ds->sfile[j] = ds->file[j] + ds->pref;
- ds->slen[j] = ds->len[j] - ds->pref - ds->suff;
- for (i = 0; i <= ds->slen[j]; i++)
- ds->sfile[j][i].serial = i;
+ rc = diff_atomize_file(diff_data, cfg, *f, *p, st.st_size, diff_flags);
+ if (rc) {
+ err = got_error_set_errno(rc, "diff_atomize_file");
+ goto done;
}
+done:
+ if (err)
+ diff_data_free(diff_data);
+ else
+ *size = st.st_size;
+ return err;
}
-static void
-equiv(struct line *a, int n, struct line *b, int m, int *c)
+const struct got_error *
+got_diffreg_prepared_files(struct got_diffreg_result **diffreg_result,
+ const struct diff_config *cfg,
+ struct diff_data *left, FILE *f1, char *p1, size_t size1,
+ struct diff_data *right, FILE *f2, char *p2, size_t size2)
{
- int i, j;
-
- i = j = 1;
- while (i <= n && j <= m) {
- if (a[i].value < b[j].value)
- a[i++].value = 0;
- else if (a[i].value == b[j].value)
- a[i++].value = j;
- else
- j++;
- }
- while (i <= n)
- a[i++].value = 0;
- b[m + 1].value = 0;
- j = 0;
- while (++j <= m) {
- c[j] = -b[j].serial;
- while (b[j + 1].value == b[j].value) {
- j++;
- c[j] = b[j].serial;
+ const struct got_error *err = NULL;
+ struct diff_result *diff_result;
+
+ *diffreg_result = calloc(1, sizeof(**diffreg_result));
+ if (*diffreg_result == NULL)
+ return got_error_from_errno("calloc");
+
+ diff_result = diff_main(cfg, left, right);
+ if (diff_result == NULL) {
+ err = got_error_set_errno(ENOMEM, "malloc");
+ goto done;
+ }
+ if (diff_result->rc != DIFF_RC_OK) {
+ err = got_error_set_errno(diff_result->rc, "diff");
+ goto done;
+ }
+
+ (*diffreg_result)->result = diff_result;
+ (*diffreg_result)->f1 = f1;
+ (*diffreg_result)->map1 = p1;
+ (*diffreg_result)->size1 = size1;
+ (*diffreg_result)->f2 = f2;
+ (*diffreg_result)->map2 = p2;
+ (*diffreg_result)->size2 = size2;
+done:
+ if (err) {
+ if (diffreg_result) {
+ free(*diffreg_result);
+ *diffreg_result = NULL;
}
}
- c[j] = -1;
-}
-
-/* Code taken from ping.c */
-static int
-isqrt(int n)
-{
- int y, x = 1;
-
- if (n == 0)
- return (0);
-
- do { /* newton was a stinker */
- y = x;
- x = n / x;
- x += y;
- x /= 2;
- } while ((x - y) > 1 || (x - y) < -1);
-
- return (x);
+
+ return err;
}
-static int
-stone(struct got_diff_state *ds, int *a, int n, int *b, int *c, int flags)
-{
- int i, k, y, j, l;
- int oldc, tc, oldl, sq;
- u_int numtries, bound;
- int error;
-
- if (flags & D_MINIMAL)
- bound = UINT_MAX;
- else {
- sq = isqrt(n);
- bound = MAXIMUM(256, sq);
- }
-
- k = 0;
- c[0] = newcand(ds, 0, 0, 0, &error);
- if (error)
- return -1;
- for (i = 1; i <= n; i++) {
- j = a[i];
- if (j == 0)
- continue;
- y = -b[j];
- oldl = 0;
- oldc = c[0];
- numtries = 0;
- do {
- if (y <= ds->clist[oldc].y)
- continue;
- l = search(ds, c, k, y);
- if (l != oldl + 1)
- oldc = c[l - 1];
- if (l <= k) {
- if (ds->clist[c[l]].y <= y)
- continue;
- tc = c[l];
- c[l] = newcand(ds, i, y, oldc, &error);
- if (error)
- return -1;
- oldc = tc;
- oldl = l;
- numtries++;
- } else {
- c[l] = newcand(ds, i, y, oldc, &error);
- if (error)
- return -1;
- k++;
- break;
- }
- } while ((y = b[++j]) > 0 && numtries < bound);
- }
- return (k);
-}
-
-static int
-newcand(struct got_diff_state *ds, int x, int y, int pred, int *errorp)
+const struct got_error *
+got_diffreg(struct got_diffreg_result **diffreg_result, FILE *f1, FILE *f2,
+ enum got_diff_algorithm algorithm, int ignore_whitespace)
{
- struct cand *q;
-
- if (ds->clen == ds->clistlen) {
- ds->clistlen = ds->clistlen * 11 / 10;
- q = reallocarray(ds->clist, ds->clistlen, sizeof(*ds->clist));
- if (q == NULL) {
- *errorp = -1;
- free(ds->clist);
- ds->clist = NULL;
- return 0;
+ const struct got_error *err = NULL;
+ const struct diff_config *cfg;
+ char *p1 = NULL, *p2 = NULL;
+ int f1_created = 0, f2_created = 0;
+ size_t size1, size2;
+ struct diff_data d_left, d_right;
+ struct diff_data *left, *right;
+ struct diff_result *diff_result;
+
+ if (diffreg_result) {
+ *diffreg_result = calloc(1, sizeof(**diffreg_result));
+ if (*diffreg_result == NULL)
+ return got_error_from_errno("calloc");
+ left = &(*diffreg_result)->left;
+ right = &(*diffreg_result)->right;
+ } else {
+ memset(&d_left, 0, sizeof(d_left));
+ memset(&d_right, 0, sizeof(d_right));
+ left = &d_left;
+ right = &d_right;
+ }
+
+ cfg = got_diff_get_config(algorithm);
+ if (cfg == NULL) {
+ err = got_error(GOT_ERR_NOT_IMPL);
+ goto done;
+ }
+
+ err = got_diff_prepare_file(&f1, &p1, &f1_created, &size1,
+ left, cfg, ignore_whitespace);
+ if (err)
+ goto done;
+
+ err = got_diff_prepare_file(&f2, &p2, &f2_created, &size2,
+ right, cfg, ignore_whitespace);
+ if (err)
+ goto done;
+
+ diff_result = diff_main(cfg, left, right);
+ if (diff_result == NULL) {
+ err = got_error_set_errno(ENOMEM, "malloc");
+ goto done;
+ }
+ if (diff_result->rc != DIFF_RC_OK) {
+ err = got_error_set_errno(diff_result->rc, "diff");
+ goto done;
+ }
+
+ if (diffreg_result) {
+ (*diffreg_result)->result = diff_result;
+ if (f1_created)
+ (*diffreg_result)->f1 = f1;
+ (*diffreg_result)->map1 = p1;
+ (*diffreg_result)->size1 = size1;
+ if (f2_created)
+ (*diffreg_result)->f2 = f2;
+ (*diffreg_result)->map2 = p2;
+ (*diffreg_result)->size2 = size2;
+ }
+done:
+ if (diffreg_result == NULL) {
+ diff_data_free(left);
+ diff_data_free(right);
+ }
+ if (err) {
+ got_diffreg_close(f1_created ? f1 : NULL, p1, size1,
+ f2_created ? f2 : NULL, p2, size2);
+ if (diffreg_result) {
+ diff_data_free(left);
+ diff_data_free(right);
+ free(*diffreg_result);
+ *diffreg_result = NULL;
}
- ds->clist = q;
}
- q = ds->clist + ds->clen;
- q->x = x;
- q->y = y;
- q->pred = pred;
- *errorp = 0;
- return (ds->clen++);
+
+ return err;
}
-static int
-search(struct got_diff_state *ds, int *c, int k, int y)
+const struct got_error *
+got_diffreg_output(off_t **line_offsets, size_t *nlines,
+ struct got_diffreg_result *diff_result, FILE *f1, FILE *f2,
+ const char *path1, const char *path2,
+ enum got_diff_output_format output_format, int context_lines, FILE *outfile)
{
- int i, j, l, t;
+ struct diff_input_info info = {
+ .left_path = path1,
+ .right_path = path2,
+ };
+ int rc;
+ struct diff_output_info *output_info;
+
+ switch (output_format) {
+ case GOT_DIFF_OUTPUT_UNIDIFF:
+ rc = diff_output_unidiff(
+ line_offsets ? &output_info : NULL, outfile, &info,
+ diff_result->result, context_lines);
+ if (rc != DIFF_RC_OK)
+ return got_error_set_errno(rc, "diff_output_unidiff");
+ break;
+ case GOT_DIFF_OUTPUT_EDSCRIPT:
+ rc = diff_output_edscript(line_offsets ? &output_info : NULL,
+ outfile, &info, diff_result->result);
+ if (rc != DIFF_RC_OK)
+ return got_error_set_errno(rc, "diff_output_edscript");
+ break;
- if (ds->clist[c[k]].y < y) /* quick look for typical case */
- return (k + 1);
- i = 0;
- j = k + 1;
- for (;;) {
- l = (i + j) / 2;
- if (l <= i)
- break;
- t = ds->clist[c[l]].y;
- if (t > y)
- j = l;
- else if (t < y)
- i = l;
- else
- return (l);
}
- return (l + 1);
-}
-
-static void
-unravel(struct got_diff_state *ds, int p)
-{
- struct cand *q;
- int i;
-
- for (i = 0; i <= ds->len[0]; i++)
- ds->J[i] = i <= ds->pref ? i :
- i > ds->len[0] - ds->suff ? i + ds->len[1] - ds->len[0] : 0;
- for (q = ds->clist + p; q->y != 0; q = ds->clist + q->pred)
- ds->J[q->x + ds->pref] = q->y + ds->pref;
-}
-
-/*
- * Check does double duty:
- * 1. ferret out any fortuitous correspondences due
- * to confounding by hashing (which result in "jackpot")
- * 2. collect random access indexes to the two files
- */
-static void
-check(struct got_diff_state *ds, FILE *f1, FILE *f2, int flags)
-{
- int i, j, jackpot, c, d;
- long ctold, ctnew;
- if (f1 != NULL)
- rewind(f1);
- if (f2 != NULL)
- rewind(f2);
- j = 1;
- ds->ixold[0] = ds->ixnew[0] = 0;
- jackpot = 0;
- ctold = ctnew = 0;
- for (i = 1; i <= ds->len[0]; i++) {
- if (ds->J[i] == 0) {
- ds->ixold[i] = ctold += skipline(f1);
- continue;
- }
- while (j < ds->J[i]) {
- ds->ixnew[j] = ctnew += skipline(f2);
- j++;
- }
- if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE)) {
- for (;;) {
- c = (f1 == NULL ? EOF : getc(f1));
- d = (f2 == NULL ? EOF : getc(f2));
+ if (line_offsets && *line_offsets) {
+ if (output_info->line_offsets.len > 0) {
+ off_t prev_offset = 0, *p, *o;
+ int i, len;
+ if (*nlines > 0) {
+ prev_offset = (*line_offsets)[*nlines - 1];
/*
- * GNU diff ignores a missing newline
- * in one file for -b or -w.
+ * First line offset is always zero. Skip it
+ * when appending to a pre-populated array.
*/
- if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) {
- if (c == EOF && d == '\n') {
- ctnew++;
- break;
- } else if (c == '\n' && d == EOF) {
- ctold++;
- break;
- }
- }
- ctold++;
- ctnew++;
- if ((flags & D_FOLDBLANKS) && isspace(c) &&
- isspace(d)) {
- do {
- if (c == '\n')
- break;
- ctold++;
- } while (f1 && isspace(c = getc(f1)));
- do {
- if (d == '\n')
- break;
- ctnew++;
- } while (f2 && isspace(d = getc(f2)));
- } else if ((flags & D_IGNOREBLANKS)) {
- while (f1 && isspace(c) && c != '\n') {
- c = getc(f1);
- ctold++;
- }
- while (f2 && isspace(d) && d != '\n') {
- d = getc(f2);
- ctnew++;
- }
- }
- if (ds->chrtran[c] != ds->chrtran[d]) {
- jackpot++;
- ds->J[i] = 0;
- if (c != '\n' && c != EOF)
- ctold += skipline(f1);
- if (d != '\n' && c != EOF)
- ctnew += skipline(f2);
- break;
- }
- if (c == '\n' || c == EOF)
- break;
- }
- } else {
- for (;;) {
- ctold++;
- ctnew++;
- c = (f1 == NULL ? EOF : getc(f1));
- d = (f2 == NULL ? EOF : getc(f2));
- if (c != d) {
- /* jackpot++; */
- ds->J[i] = 0;
- if (c != '\n' && c != EOF)
- ctold += skipline(f1);
- if (d != '\n' && c != EOF)
- ctnew += skipline(f2);
- break;
- }
- if (c == '\n' || c == EOF)
- break;
- }
- }
- ds->ixold[i] = ctold;
- ds->ixnew[j] = ctnew;
- j++;
- }
- for (; j <= ds->len[1]; j++)
- ds->ixnew[j] = ctnew += skipline(f2);
- /*
- * if (jackpot)
- * fprintf(stderr, "jackpot\n");
- */
-}
-
-/* shellsort CACM #201 */
-static void
-sort(struct line *a, int n)
-{
- struct line *ai, *aim, w;
- int j, m = 0, k;
-
- if (n == 0)
- return;
- for (j = 1; j <= n; j *= 2)
- m = 2 * j - 1;
- for (m /= 2; m != 0; m /= 2) {
- k = n - m;
- for (j = 1; j <= k; j++) {
- for (ai = &a[j]; ai > a; ai -= m) {
- aim = &ai[m];
- if (aim < ai)
- break; /* wraparound */
- if (aim->value > ai[0].value ||
- (aim->value == ai[0].value &&
- aim->serial > ai[0].serial))
- break;
- w.value = ai[0].value;
- ai[0].value = aim->value;
- aim->value = w.value;
- w.serial = ai[0].serial;
- ai[0].serial = aim->serial;
- aim->serial = w.serial;
- }
- }
- }
-}
-
-static int
-unsort(struct line *f, int l, int *b)
-{
- int *a, i;
-
- a = calloc(l + 1, sizeof(*a));
- if (a == NULL)
- return (-1);
- for (i = 1; i <= l; i++)
- a[f[i].serial] = f[i].value;
- for (i = 1; i <= l; i++)
- b[i] = a[i];
- free(a);
-
- return (0);
-}
-
-static int
-skipline(FILE *f)
-{
- int i, c;
-
- for (i = 1; f != NULL && (c = getc(f)) != '\n' && c != EOF; i++)
- continue;
- return (i);
-}
-
-static int
-output(FILE *outfile, struct got_diff_changes *changes,
- struct got_diff_state *ds, struct got_diff_args *args,
- const char *file1, FILE *f1, const char *file2, FILE *f2, int flags)
-{
- int m, i0, i1, j0, j1;
- int error = 0;
-
- if (f1 != NULL)
- rewind(f1);
- if (f2 != NULL)
- rewind(f2);
- m = ds->len[0];
- ds->J[0] = 0;
- ds->J[m + 1] = ds->len[1] + 1;
- for (i0 = 1; i0 <= m; i0 = i1 + 1) {
- while (i0 <= m && ds->J[i0] == ds->J[i0 - 1] + 1)
- i0++;
- j0 = ds->J[i0 - 1] + 1;
- i1 = i0 - 1;
- while (i1 < m && ds->J[i1 + 1] == 0)
- i1++;
- j1 = ds->J[i1 + 1] - 1;
- ds->J[i1] = j1;
- error = change(outfile, changes, ds, args, file1, f1, file2, f2,
- i0, i1, j0, j1, &flags);
- if (error)
- return (error);
- }
- if (m == 0) {
- error = change(outfile, changes, ds, args, file1, f1, file2, f2,
- 1, 0, 1, ds->len[1], &flags);
- if (error)
- return (error);
- }
- if (ds->anychange != 0 && args->diff_format == D_UNIFIED)
- dump_unified_vec(outfile, changes, ds, args, f1, f2, flags);
-
- return (0);
-}
-
-static void
-range(FILE *outfile, int a, int b, char *separator)
-{
- diff_output(outfile, "%d", a > b ? b : a);
- if (a < b)
- diff_output(outfile, "%s%d", separator, b);
-}
-
-static void
-uni_range(FILE *outfile, int a, int b)
-{
- if (a < b)
- diff_output(outfile, "%d,%d", a, b - a + 1);
- else if (a == b)
- diff_output(outfile, "%d", b);
- else
- diff_output(outfile, "%d,0", b);
-}
-
-/*
- * Indicate that there is a difference between lines a and b of the from file
- * to get to lines c to d of the to file. If a is greater then b then there
- * are no lines in the from file involved and this means that there were
- * lines appended (beginning at b). If c is greater than d then there are
- * lines missing from the to file.
- */
-static int
-change(FILE *outfile, struct got_diff_changes *changes,
- struct got_diff_state *ds, struct got_diff_args *args,
- const char *file1, FILE *f1, const char *file2, FILE *f2,
- int a, int b, int c, int d, int *pflags)
-{
- if (a > b && c > d)
- return (0);
-
- if (*pflags & D_HEADER) {
- diff_output(outfile, "%s %s %s\n", args->diffargs, file1, file2);
- *pflags &= ~D_HEADER;
- }
- if (args->diff_format == D_UNIFIED) {
- /*
- * Allocate change records as needed.
- */
- if (ds->context_vec_ptr == ds->context_vec_end - 1) {
- struct context_vec *cvp;
- ptrdiff_t offset;
- offset = ds->context_vec_ptr - ds->context_vec_start;
- ds->max_context <<= 1;
- cvp = reallocarray(ds->context_vec_start,
- ds->max_context, sizeof(*ds->context_vec_start));
- if (cvp == NULL) {
- free(ds->context_vec_start);
- return (-1);
- }
- ds->context_vec_start = cvp;
- ds->context_vec_end = ds->context_vec_start +
- ds->max_context;
- ds->context_vec_ptr = ds->context_vec_start + offset;
- }
- if (ds->anychange == 0) {
- /*
- * Print the context/unidiff header first time through.
- */
- print_header(outfile, ds, args, file1, file2);
- ds->anychange = 1;
- } else if (a > ds->context_vec_ptr->b + (2 * args->diff_context) + 1 &&
- c > ds->context_vec_ptr->d + (2 * args->diff_context) + 1) {
- /*
- * If this change is more than 'diff_context' lines from the
- * previous change, dump the record and reset it.
- */
- dump_unified_vec(outfile, changes, ds, args, f1, f2,
- *pflags);
- }
- ds->context_vec_ptr++;
- ds->context_vec_ptr->a = a;
- ds->context_vec_ptr->b = b;
- ds->context_vec_ptr->c = c;
- ds->context_vec_ptr->d = d;
- return (0);
- }
- if (ds->anychange == 0)
- ds->anychange = 1;
- if (args->diff_format == D_BRIEF)
- return (0);
- if (args->diff_format == D_NORMAL) {
- range(outfile, a, b, ",");
- diff_output(outfile, "%c", a > b ? 'a' : c > d ? 'd' : 'c');
- range(outfile, c, d, ",");
- diff_output(outfile, "\n");
- fetch(outfile, ds, args, ds->ixold, a, b, f1, '<', *pflags);
- if (a <= b && c <= d)
- diff_output(outfile, "---\n");
- }
- fetch(outfile, ds, args, ds->ixnew, c, d, f2,
- args->diff_format == D_NORMAL ? '>' : '\0', *pflags);
- return (0);
-}
-
-static void
-fetch(FILE *outfile, struct got_diff_state *ds, struct got_diff_args *args,
- long *f, int a, int b, FILE *lb, int ch, int flags)
-{
- int i, j, c, col, nc;
-
- if (lb == NULL || a > b)
- return;
- for (i = a; i <= b; i++) {
- fseek(lb, f[i - 1], SEEK_SET);
- nc = f[i] - f[i - 1];
- if (ch != '\0') {
- diff_output(outfile, "%c", ch);
- if (args->Tflag && (args->diff_format == D_UNIFIED ||
- args->diff_format == D_NORMAL))
- diff_output(outfile, "\t");
- else if (args->diff_format != D_UNIFIED)
- diff_output(outfile, " ");
- }
- col = 0;
- for (j = 0; j < nc; j++) {
- if ((c = getc(lb)) == EOF) {
- diff_output(outfile, "\n\\ No newline at end of "
- "file\n");
- return;
- }
- if (c == '\t' && (flags & D_EXPANDTABS)) {
- do {
- diff_output(outfile, " ");
- } while (++col & 7);
+ o = &output_info->line_offsets.head[1];
+ len = output_info->line_offsets.len - 1;
} else {
- diff_output(outfile, "%c", c);
- col++;
+ o = &output_info->line_offsets.head[0];
+ len = output_info->line_offsets.len;
}
+ p = reallocarray(*line_offsets, *nlines + len,
+ sizeof(off_t));
+ if (p == NULL)
+ return got_error_from_errno("calloc");
+ for (i = 0; i < len; i++)
+ p[*nlines + i] = o[i] + prev_offset;
+ *line_offsets = p;
+ *nlines += len;
}
+ diff_output_info_free(output_info);
}
-}
-/*
- * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
- */
-static int
-readhash(struct got_diff_state *ds, FILE *f, int flags)
-{
- int i, t, space;
- int sum;
-
- sum = 1;
- space = 0;
- if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) == 0) {
- if (flags & D_IGNORECASE)
- for (i = 0; (t = getc(f)) != '\n'; i++) {
- if (t == EOF) {
- if (i == 0)
- return (0);
- break;
- }
- sum = sum * 127 + ds->chrtran[t];
- }
- else
- for (i = 0; (t = getc(f)) != '\n'; i++) {
- if (t == EOF) {
- if (i == 0)
- return (0);
- break;
- }
- sum = sum * 127 + t;
- }
- } else {
- for (i = 0;;) {
- switch (t = getc(f)) {
- case '\t':
- case '\r':
- case '\v':
- case '\f':
- case ' ':
- space++;
- continue;
- default:
- if (space && (flags & D_IGNOREBLANKS) == 0) {
- i++;
- space = 0;
- }
- sum = sum * 127 + ds->chrtran[t];
- i++;
- continue;
- case EOF:
- if (i == 0)
- return (0);
- /* FALLTHROUGH */
- case '\n':
- break;
- }
- break;
- }
- }
- /*
- * There is a remote possibility that we end up with a zero sum.
- * Zero is used as an EOF marker, so return 1 instead.
- */
- return (sum == 0 ? 1 : sum);
+ return NULL;
}
-static int
-asciifile(FILE *f)
+const struct got_error *
+got_diffreg_result_free(struct got_diffreg_result *diffreg_result)
{
- unsigned char buf[BUFSIZ];
- size_t cnt;
-
- if (f == NULL)
- return (1);
-
- rewind(f);
- cnt = fread(buf, 1, sizeof(buf), f);
- return (memchr(buf, '\0', cnt) == NULL);
+ const struct got_error *err;
+
+ diff_result_free(diffreg_result->result);
+ diff_data_free(&diffreg_result->left);
+ diff_data_free(&diffreg_result->right);
+ err = got_diffreg_close(diffreg_result->f1, diffreg_result->map1,
+ diffreg_result->size1, diffreg_result->f2,
+ diffreg_result->map2, diffreg_result->size2);
+ free(diffreg_result);
+ return err;
}
-#define begins_with(s, pre) (strncmp(s, pre, sizeof(pre)-1) == 0)
-
-static char *
-match_function(struct got_diff_state *ds, const long *f, int pos, FILE *fp)
+const struct got_error *
+got_diffreg_result_free_left(struct got_diffreg_result *diffreg_result)
{
- unsigned char buf[FUNCTION_CONTEXT_SIZE];
- size_t nc;
- int last = ds->lastline;
- char *state = NULL;
-
- ds->lastline = pos;
- while (pos > last) {
- fseek(fp, f[pos - 1], SEEK_SET);
- nc = f[pos] - f[pos - 1];
- if (nc >= sizeof(buf))
- nc = sizeof(buf) - 1;
- nc = fread(buf, 1, nc, fp);
- if (nc > 0) {
- buf[nc] = '\0';
- buf[strcspn(buf, "\n")] = '\0';
- if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$') {
- if (begins_with(buf, "private:")) {
- if (!state)
- state = " (private)";
- } else if (begins_with(buf, "protected:")) {
- if (!state)
- state = " (protected)";
- } else if (begins_with(buf, "public:")) {
- if (!state)
- state = " (public)";
- } else {
- strlcpy(ds->lastbuf, buf, sizeof ds->lastbuf);
- if (state)
- strlcat(ds->lastbuf, state,
- sizeof ds->lastbuf);
- ds->lastmatchline = pos;
- return ds->lastbuf;
- }
- }
- }
- pos--;
- }
- return ds->lastmatchline > 0 ? ds->lastbuf : NULL;
+ diff_data_free(&diffreg_result->left);
+ memset(&diffreg_result->left, 0, sizeof(diffreg_result->left));
+ return got_diffreg_close(diffreg_result->f1, diffreg_result->map1,
+ diffreg_result->size1, NULL, NULL, 0);
}
-/* dump accumulated "unified" diff changes */
-static void
-dump_unified_vec(FILE *outfile, struct got_diff_changes *changes,
- struct got_diff_state *ds, struct got_diff_args *args,
- FILE *f1, FILE *f2, int flags)
+const struct got_error *
+got_diffreg_result_free_right(struct got_diffreg_result *diffreg_result)
{
- struct context_vec *cvp = ds->context_vec_start;
- int lowa, upb, lowc, upd;
- int a, b, c, d;
- char ch, *f;
-
- if (ds->context_vec_start > ds->context_vec_ptr)
- return;
-
- b = d = 0; /* gcc */
- lowa = MAXIMUM(1, cvp->a - args->diff_context);
- upb = MINIMUM(ds->len[0], ds->context_vec_ptr->b + args->diff_context);
- lowc = MAXIMUM(1, cvp->c - args->diff_context);
- upd = MINIMUM(ds->len[1], ds->context_vec_ptr->d + args->diff_context);
-
- diff_output(outfile, "@@ -");
- uni_range(outfile, lowa, upb);
- diff_output(outfile, " +");
- uni_range(outfile, lowc, upd);
- diff_output(outfile, " @@");
- if (f1 != NULL && (flags & D_PROTOTYPE)) {
- f = match_function(ds, ds->ixold, lowa-1, f1);
- if (f != NULL)
- diff_output(outfile, " %s", f);
- }
- diff_output(outfile, "\n");
-
- /*
- * Output changes in "unified" diff format--the old and new lines
- * are printed together.
- */
- for (; cvp <= ds->context_vec_ptr; cvp++) {
- if (changes) {
- struct got_diff_change *change;
- change = calloc(1, sizeof(*change));
- if (change) {
- memcpy(&change->cv, cvp, sizeof(change->cv));
- SIMPLEQ_INSERT_TAIL(&changes->entries, change,
- entry);
- changes->nchanges++;
- }
- }
-
- a = cvp->a;
- b = cvp->b;
- c = cvp->c;
- d = cvp->d;
-
- /*
- * c: both new and old changes
- * d: only changes in the old file
- * a: only changes in the new file
- */
- if (a <= b && c <= d)
- ch = 'c';
- else
- ch = (a <= b) ? 'd' : 'a';
-
- switch (ch) {
- case 'c':
- fetch(outfile, ds, args, ds->ixold, lowa, a - 1, f1, ' ', flags);
- fetch(outfile, ds, args, ds->ixold, a, b, f1, '-', flags);
- fetch(outfile, ds, args, ds->ixnew, c, d, f2, '+', flags);
- break;
- case 'd':
- fetch(outfile, ds, args, ds->ixold, lowa, a - 1, f1, ' ', flags);
- fetch(outfile, ds, args, ds->ixold, a, b, f1, '-', flags);
- break;
- case 'a':
- fetch(outfile, ds, args, ds->ixnew, lowc, c - 1, f2, ' ', flags);
- fetch(outfile, ds, args, ds->ixnew, c, d, f2, '+', flags);
- break;
- }
- lowa = b + 1;
- lowc = d + 1;
- }
- fetch(outfile, ds, args, ds->ixnew, d + 1, upd, f2, ' ', flags);
-
- ds->context_vec_ptr = ds->context_vec_start - 1;
+ diff_data_free(&diffreg_result->right);
+ memset(&diffreg_result->right, 0, sizeof(diffreg_result->right));
+ return got_diffreg_close(NULL, NULL, 0, diffreg_result->f2,
+ diffreg_result->map2, diffreg_result->size2);
}
void
-got_diff_dump_change(FILE *outfile, struct got_diff_change *change,
- struct got_diff_state *ds, struct got_diff_args *args,
- FILE *f1, FILE *f2, int diff_flags)
+got_diff_dump_change(FILE *outfile, struct diff_chunk *change,
+ FILE *f1, FILE *f2)
{
- ds->context_vec_ptr = &change->cv;
- ds->context_vec_start = &change->cv;
- ds->context_vec_end = &change->cv;
-
- /* XXX TODO needs error checking */
- dump_unified_vec(outfile, NULL, ds, args, f1, f2, diff_flags);
-}
-
-static void
-print_header(FILE *outfile, struct got_diff_state *ds, struct got_diff_args *args,
- const char *file1, const char *file2)
-{
- if (args->label[0] != NULL)
- diff_output(outfile, "--- %s\n", args->label[0]);
- else
- diff_output(outfile, "--- %s\t%s", file1,
- ctime(&ds->stb1.st_mtime));
- if (args->label[1] != NULL)
- diff_output(outfile, "+++ %s\n", args->label[1]);
- else
- diff_output(outfile, "+++ %s\t%s", file2,
- ctime(&ds->stb2.st_mtime));
}
diff --git a/lib/got_lib_diff.h b/lib/got_lib_diff.h
index ace2137..6a04918 100644
--- a/lib/got_lib_diff.h
+++ b/lib/got_lib_diff.h
@@ -1,137 +1,43 @@
-
-
-/*ROR
- * Copyright (c) 1991, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
+/*
+ * Copyright (c) 2020 Stefan Sperling <stsp@openbsd.org>
*
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
*
- * @(#)diff.h 8.1 (Berkeley) 6/6/93
- */
-
-#include <sys/types.h>
-#include <regex.h>
-
-/*
- * Output format options
- */
-#define D_NORMAL 0 /* Normal output */
-#define D_UNIFIED 3 /* Unified context diff */
-#define D_BRIEF 6 /* Say if the files differ */
-
-/*
- * Output flags
- */
-#define D_HEADER 0x001 /* Print a header/footer between files */
-#define D_EMPTY1 0x002 /* Treat first file as empty (/dev/null) */
-#define D_EMPTY2 0x004 /* Treat second file as empty (/dev/null) */
-
-/*
- * Command line flags
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
-#define D_FORCEASCII 0x008 /* Treat file as ascii regardless of content */
-#define D_FOLDBLANKS 0x010 /* Treat all white space as equal */
-#define D_MINIMAL 0x020 /* Make diff as small as possible */
-#define D_IGNORECASE 0x040 /* Case-insensitive matching */
-#define D_PROTOTYPE 0x080 /* Display C function prototype */
-#define D_EXPANDTABS 0x100 /* Expand tabs to spaces */
-#define D_IGNOREBLANKS 0x200 /* Ignore white space changes */
-/*
- * Status values for got_diffreg() return values
- */
-#define D_SAME 0 /* Files are the same */
-#define D_DIFFER 1 /* Files are different */
-#define D_BINARY 2 /* Binary files are different */
-#define D_MISMATCH1 3 /* path1 was a dir, path2 a file */
-#define D_MISMATCH2 4 /* path1 was a file, path2 a dir */
-#define D_SKIPPED1 5 /* path1 was a special file */
-#define D_SKIPPED2 6 /* path2 was a special file */
+#include "arraylist.h"
+#include "diff_main.h"
+#include "diff_output.h"
-struct excludes {
- char *pattern;
- struct excludes *next;
-};
-
-/*
- * The following struct is used to record change information when
- * doing a "context" or "unified" diff. (see routine "change" to
- * understand the highly mnemonic field names)
- */
-struct context_vec {
- int a; /* start line in old file */
- int b; /* end line in old file */
- int c; /* start line in new file */
- int d; /* end line in new file */
+enum got_diff_algorithm {
+ GOT_DIFF_ALGORITHM_MYERS,
+ GOT_DIFF_ALGORITHM_PATIENCE,
};
-struct got_diff_change {
- SIMPLEQ_ENTRY(got_diff_change) entry;
- struct context_vec cv;
+enum got_diff_output_format {
+ GOT_DIFF_OUTPUT_UNIDIFF,
+ GOT_DIFF_OUTPUT_EDSCRIPT,
};
-struct got_diff_changes {
- int nchanges;
- SIMPLEQ_HEAD(, got_diff_change) entries;
-};
-
-struct got_diff_state {
- int *J; /* will be overlaid on class */
- int *class; /* will be overlaid on file[0] */
- int *klist; /* will be overlaid on file[0] after class */
- int *member; /* will be overlaid on file[1] */
- int clen;
- int len[2];
- int pref, suff; /* length of prefix and suffix */
- int slen[2];
- int anychange;
- long *ixnew; /* will be overlaid on file[1] */
- long *ixold; /* will be overlaid on klist */
- struct cand *clist; /* merely a free storage pot for candidates */
- int clistlen; /* the length of clist */
- struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
- u_char *chrtran; /* translation table for case-folding */
- struct context_vec *context_vec_start;
- struct context_vec *context_vec_end;
- struct context_vec *context_vec_ptr;
- struct line *file[2];
-#define FUNCTION_CONTEXT_SIZE 55
- char lastbuf[FUNCTION_CONTEXT_SIZE];
- int lastline;
- int lastmatchline;
- struct stat stb1, stb2;
- size_t max_context;
-};
-
-void got_diff_state_free(struct got_diff_state *);
-
-struct got_diff_args {
- int Tflag;
- int diff_format, diff_context, status;
- char *diffargs;
- const char *label[2];
+struct got_diffreg_result {
+ struct diff_result *result;
+ FILE *f1;
+ char *map1;
+ size_t size1;
+ FILE *f2;
+ char *map2;
+ size_t size2;
+ struct diff_data left;
+ struct diff_data right;
};
#define GOT_DIFF_CONFLICT_MARKER_BEGIN "<<<<<<<"
@@ -139,22 +45,33 @@ struct got_diff_args {
#define GOT_DIFF_CONFLICT_MARKER_SEP "======="
#define GOT_DIFF_CONFLICT_MARKER_END ">>>>>>>"
-const struct got_error *got_diffreg(int *, FILE *,
- FILE *, int, struct got_diff_args *, struct got_diff_state *, FILE *,
- struct got_diff_changes *);
-
-const struct got_error *got_diff_blob_lines_changed(struct got_diff_changes **,
- struct got_blob_object *, struct got_blob_object *);
-const struct got_error *got_diff_blob_file_lines_changed(struct got_diff_changes **,
- struct got_blob_object *, FILE *, size_t);
-void got_diff_free_changes(struct got_diff_changes *);
+const struct diff_config *got_diff_get_config(enum got_diff_algorithm);
+const struct got_error *got_diff_prepare_file(FILE **, char **, int *,
+ size_t *, struct diff_data *, const struct diff_config *, int);
+const struct got_error *got_diffreg_prepared_files(struct got_diffreg_result **,
+ const struct diff_config *, struct diff_data *, FILE *, char *, size_t,
+ struct diff_data *, FILE *, char *, size_t);
+const struct got_error *got_diff_blob_prepared_file(
+ struct got_diffreg_result **, struct diff_data *, struct got_blob_object *,
+ struct diff_data *, FILE *, char *, size_t, const struct diff_config *,
+ int);
+const struct got_error *got_diffreg(struct got_diffreg_result **, FILE *, FILE *,
+ enum got_diff_algorithm, int);
+const struct got_error *got_diffreg_output(off_t **, size_t *,
+ struct got_diffreg_result *, FILE *, FILE *, const char *, const char *,
+ enum got_diff_output_format, int, FILE *);
+const struct got_error *got_diffreg_result_free(struct got_diffreg_result *);
+const struct got_error *got_diffreg_result_free_left(
+ struct got_diffreg_result *);
+const struct got_error *got_diffreg_result_free_right(
+ struct got_diffreg_result *);
+const struct got_error *got_diffreg_close(FILE *, char *, size_t,
+ FILE *, char *, size_t);
const struct got_error *got_merge_diff3(int *, int, const char *, const char *,
const char *, const char *, const char *, const char *);
-const struct got_error *got_diff_files(struct got_diff_changes **,
- struct got_diff_state **, struct got_diff_args **, int *, FILE *, size_t,
- const char *, FILE *, size_t, const char *, int, FILE *);
+const struct got_error *got_diff_files(struct got_diffreg_result **, FILE *,
+ const char *, FILE *, const char *, int, int, FILE *);
-void got_diff_dump_change(FILE *, struct got_diff_change *,
- struct got_diff_state *, struct got_diff_args *, FILE *, FILE *, int);
+void got_diff_dump_change(FILE *, struct diff_chunk *, FILE *, FILE *);
diff --git a/lib/worktree.c b/lib/worktree.c
index 498ebaa..b012446 100644
--- a/lib/worktree.c
+++ b/lib/worktree.c
@@ -4136,47 +4136,62 @@ copy_remaining_content(FILE *f1, FILE *f2, int *line_cur1, int *line_cur2,
}
static const struct got_error *
-apply_or_reject_change(int *choice, struct got_diff_change *change, int n,
- int nchanges, struct got_diff_state *ds, struct got_diff_args *args,
- int diff_flags, const char *relpath, FILE *f1, FILE *f2, int *line_cur1,
- int *line_cur2, FILE *outfile, FILE *rejectfile,
+apply_or_reject_change(int *choice, int *nchunks_used,
+ struct diff_result *diff_result, int n,
+ const char *relpath, FILE *f1, FILE *f2, int *line_cur1, int *line_cur2,
+ FILE *outfile, FILE *rejectfile, int changeno, int nchanges,
got_worktree_patch_cb patch_cb, void *patch_arg)
{
const struct got_error *err = NULL;
- int start_old = change->cv.a;
- int end_old = change->cv.b;
- int start_new = change->cv.c;
- int end_new = change->cv.d;
- long pos1, pos2;
+ struct diff_chunk_context cc = {};
+ int start_old, end_old, start_new, end_new;
FILE *hunkfile;
+ struct diff_output_unidiff_state *diff_state;
+ struct diff_input_info diff_info;
+ int rc;
*choice = GOT_PATCH_CHOICE_NONE;
- hunkfile = got_opentemp();
- if (hunkfile == NULL)
- return got_error_from_errno("got_opentemp");
+ /* Get changed line numbers without context lines for copy_change(). */
+ diff_chunk_context_load_change(&cc, NULL, diff_result, n, 0);
+ start_old = cc.left.start;
+ end_old = cc.left.end;
+ start_new = cc.right.start;
+ end_new = cc.right.end;
- pos1 = ftell(f1);
- pos2 = ftell(f2);
+ /* Get the same change with context lines for display. */
+ memset(&cc, 0, sizeof(cc));
+ diff_chunk_context_load_change(&cc, nchunks_used, diff_result, n, 3);
- /* XXX TODO needs error checking */
- got_diff_dump_change(hunkfile, change, ds, args, f1, f2, diff_flags);
+ memset(&diff_info, 0, sizeof(diff_info));
+ diff_info.left_path = relpath;
+ diff_info.right_path = relpath;
- if (fseek(f1, pos1, SEEK_SET) == -1) {
- err = got_ferror(f1, GOT_ERR_IO);
+ diff_state = diff_output_unidiff_state_alloc();
+ if (diff_state == NULL)
+ return got_error_set_errno(ENOMEM,
+ "diff_output_unidiff_state_alloc");
+
+ hunkfile = got_opentemp();
+ if (hunkfile == NULL) {
+ err = got_error_from_errno("got_opentemp");
goto done;
}
- if (fseek(f2, pos2, SEEK_SET) == -1) {
- err = got_ferror(f1, GOT_ERR_IO);
+
+ rc = diff_output_unidiff_chunk(NULL, hunkfile, diff_state, &diff_info,
+ diff_result, &cc);
+ if (rc != DIFF_RC_OK) {
+ err = got_error_set_errno(rc, "diff_output_unidiff_chunk");
goto done;
}
+
if (fseek(hunkfile, 0L, SEEK_SET) == -1) {
err = got_ferror(hunkfile, GOT_ERR_IO);
goto done;
}
err = (*patch_cb)(choice, patch_arg, GOT_STATUS_MODIFY, relpath,
- hunkfile, n, nchanges);
+ hunkfile, changeno, nchanges);
if (err)
goto done;
@@ -4196,6 +4211,7 @@ apply_or_reject_change(int *choice, struct got_diff_change *change, int n,
break;
}
done:
+ diff_output_unidiff_state_free(diff_state);
if (hunkfile && fclose(hunkfile) == EOF && err == NULL)
err = got_error_from_errno("fclose");
return err;
@@ -4218,20 +4234,17 @@ create_patched_content(char **path_outfile, int reverse_patch,
const char *relpath, struct got_repository *repo,
got_worktree_patch_cb patch_cb, void *patch_arg)
{
- const struct got_error *err;
+ const struct got_error *err, *free_err;
struct got_blob_object *blob = NULL;
FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
int fd2 = -1;
char link_target[PATH_MAX];
ssize_t link_len = 0;
char *path1 = NULL, *id_str = NULL;
- struct stat sb1, sb2;
- struct got_diff_changes *changes = NULL;
- struct got_diff_state *ds = NULL;
- struct got_diff_args *args = NULL;
- struct got_diff_change *change;
- int diff_flags = 0, line_cur1 = 1, line_cur2 = 1, have_content = 0;
- int n = 0;
+ struct stat sb2;
+ struct got_diffreg_result *diffreg_result = NULL;
+ int line_cur1 = 1, line_cur2 = 1, have_content = 0;
+ int i = 0, n = 0, nchunks_used = 0, nchanges = 0;
*path_outfile = NULL;
@@ -4311,13 +4324,8 @@ create_patched_content(char **path_outfile, int reverse_patch,
if (err)
goto done;
- if (stat(path1, &sb1) == -1) {
- err = got_error_from_errno2("stat", path1);
- goto done;
- }
-
- err = got_diff_files(&changes, &ds, &args, &diff_flags,
- f1, sb1.st_size, id_str, f2, sb2.st_size, path2, 3, NULL);
+ err = got_diff_files(&diffreg_result, f1, id_str, f2, path2, 3, 0,
+ NULL);
if (err)
goto done;
@@ -4329,14 +4337,22 @@ create_patched_content(char **path_outfile, int reverse_patch,
return got_ferror(f1, GOT_ERR_IO);
if (fseek(f2, 0L, SEEK_SET) == -1)
return got_ferror(f2, GOT_ERR_IO);
- SIMPLEQ_FOREACH(change, &changes->entries, entry) {
+
+ /* Count the number of actual changes in the diff result. */
+ for (n = 0; n < diffreg_result->result->chunks.len; n += nchunks_used) {
+ struct diff_chunk_context cc = {};
+ diff_chunk_context_load_change(&cc, &nchunks_used,
+ diffreg_result->result, n, 0);
+ nchanges++;
+ }
+ for (n = 0; n < diffreg_result->result->chunks.len; n += nchunks_used) {
int choice;
- err = apply_or_reject_change(&choice, change, ++n,
- changes->nchanges, ds, args, diff_flags, relpath,
- f1, f2, &line_cur1, &line_cur2,
+ err = apply_or_reject_change(&choice, &nchunks_used,
+ diffreg_result->result, n, relpath, f1, f2,
+ &line_cur1, &line_cur2,
reverse_patch ? NULL : outfile,
reverse_patch ? outfile : NULL,
- patch_cb, patch_arg);
+ ++i, nchanges, patch_cb, patch_arg);
if (err)
goto done;
if (choice == GOT_PATCH_CHOICE_YES)
@@ -4362,6 +4378,9 @@ done:
free(id_str);
if (blob)
got_object_blob_close(blob);
+ free_err = got_diffreg_result_free(diffreg_result);
+ if (err == NULL)
+ err = free_err;
if (f1 && fclose(f1) == EOF && err == NULL)
err = got_error_from_errno2("fclose", path1);
if (f2 && fclose(f2) == EOF && err == NULL)
@@ -4378,13 +4397,6 @@ done:
free(*path_outfile);
*path_outfile = NULL;
}
- free(args);
- if (ds) {
- got_diff_state_free(ds);
- free(ds);
- }
- if (changes)
- got_diff_free_changes(changes);
free(path1);
return err;
}
@@ -7399,17 +7411,13 @@ create_unstaged_content(char **path_unstaged_content,
struct got_repository *repo,
got_worktree_patch_cb patch_cb, void *patch_arg)
{
- const struct got_error *err;
+ const struct got_error *err, *free_err;
struct got_blob_object *blob = NULL, *staged_blob = NULL;
FILE *f1 = NULL, *f2 = NULL, *outfile = NULL, *rejectfile = NULL;
char *path1 = NULL, *path2 = NULL, *label1 = NULL;
- struct stat sb1, sb2;
- struct got_diff_changes *changes = NULL;
- struct got_diff_state *ds = NULL;
- struct got_diff_args *args = NULL;
- struct got_diff_change *change;
- int diff_flags = 0, line_cur1 = 1, line_cur2 = 1, n = 0;
- int have_content = 0, have_rejected_content = 0;
+ struct got_diffreg_result *diffreg_result = NULL;
+ int line_cur1 = 1, line_cur2 = 1, n = 0, nchunks_used = 0;
+ int have_content = 0, have_rejected_content = 0, i = 0, nchanges = 0;
*path_unstaged_content = NULL;
*path_new_staged_content = NULL;
@@ -7441,18 +7449,8 @@ create_unstaged_content(char **path_unstaged_content,
if (err)
goto done;
- if (stat(path1, &sb1) == -1) {
- err = got_error_from_errno2("stat", path1);
- goto done;
- }
-
- if (stat(path2, &sb2) == -1) {
- err = got_error_from_errno2("stat", path2);
- goto done;
- }
-
- err = got_diff_files(&changes, &ds, &args, &diff_flags,
- f1, sb1.st_size, label1, f2, sb2.st_size, path2, 3, NULL);
+ err = got_diff_files(&diffreg_result, f1, label1, f2,
+ path2, 3, 0, NULL);
if (err)
goto done;
@@ -7473,12 +7471,19 @@ create_unstaged_content(char **path_unstaged_content,
err = got_ferror(f2, GOT_ERR_IO);
goto done;
}
- SIMPLEQ_FOREACH(change, &changes->entries, entry) {
+ /* Count the number of actual changes in the diff result. */
+ for (n = 0; n < diffreg_result->result->chunks.len; n += nchunks_used) {
+ struct diff_chunk_context cc = {};
+ diff_chunk_context_load_change(&cc, &nchunks_used,
+ diffreg_result->result, n, 0);
+ nchanges++;
+ }
+ for (n = 0; n < diffreg_result->result->chunks.len; n += nchunks_used) {
int choice;
- err = apply_or_reject_change(&choice, change, ++n,
- changes->nchanges, ds, args, diff_flags, relpath,
- f1, f2, &line_cur1, &line_cur2,
- outfile, rejectfile, patch_cb, patch_arg);
+ err = apply_or_reject_change(&choice, &nchunks_used,
+ diffreg_result->result, n, relpath, f1, f2,
+ &line_cur1, &line_cur2,
+ outfile, rejectfile, ++i, nchanges, patch_cb, patch_arg);
if (err)
goto done;
if (choice == GOT_PATCH_CHOICE_YES)
@@ -7497,6 +7502,9 @@ done:
got_object_blob_close(blob);
if (staged_blob)
got_object_blob_close(staged_blob);
+ free_err = got_diffreg_result_free(diffreg_result);
+ if (free_err && err == NULL)
+ err = free_err;
if (f1 && fclose(f1) == EOF && err == NULL)
err = got_error_from_errno2("fclose", path1);
if (f2 && fclose(f2) == EOF && err == NULL)
@@ -7525,13 +7533,6 @@ done:
free(*path_new_staged_content);
*path_new_staged_content = NULL;
}
- free(args);
- if (ds) {
- got_diff_state_free(ds);
- free(ds);
- }
- if (changes)
- got_diff_free_changes(changes);
free(path1);
free(path2);
return err;
diff --git a/regress/cmdline/stage.sh b/regress/cmdline/stage.sh
index 4c63c93..529ce0b 100755
--- a/regress/cmdline/stage.sh
+++ b/regress/cmdline/stage.sh
@@ -1799,7 +1799,7 @@ EOF
cat > $testroot/stdout.expected <<EOF
-----------------------------------------------
-@@ -1,5 +1,5 @@ b
+@@ -1,5 +1,5 @@
1
-2
+a
diff --git a/tog/Makefile b/tog/Makefile
index 41af3be..0c38c99 100644
--- a/tog/Makefile
+++ b/tog/Makefile
@@ -9,7 +9,10 @@ SRCS= tog.c blame.c commit_graph.c delta.c diff.c \
privsep.c reference.c repository.c sha1.c worktree.c \
utf8.c inflate.c buf.c rcsutil.c diff3.c \
lockfile.c deflate.c object_create.c delta_cache.c \
- gotconfig.c
+ gotconfig.c diff_main.c diff_atomize_text.c \
+ diff_myers.c diff_output.c diff_output_plain.c \
+ diff_output_unidiff.c diff_output_edscript.c \
+ diff_patience.c
MAN = ${PROG}.1
CPPFLAGS = -I${.CURDIR}/../include -I${.CURDIR}/../lib
diff --git a/tog/tog.c b/tog/tog.c
index 1b0d1ec..5c342d0 100644
--- a/tog/tog.c
+++ b/tog/tog.c
@@ -252,11 +252,10 @@ struct tog_diff_view_state {
struct got_repository *repo;
struct got_reflist_head *refs;
struct tog_colors colors;
- int nlines;
+ size_t nlines;
off_t *line_offsets;
int matched_line;
int selected_line;
- size_t filesize;
/* passed from log view; may be NULL */
struct tog_view *log_view;
@@ -2796,19 +2795,23 @@ match_color(struct tog_colors *colors, const char *line)
}
static const struct got_error *
-draw_file(struct tog_view *view, FILE *f, int *first_displayed_line, int nlines,
- int selected_line, int max_lines, int *last_displayed_line, int *eof,
- char *header, struct tog_colors *colors)
+draw_file(struct tog_view *view, FILE *f, int first_displayed_line, int nlines,
+ off_t *line_offsets, int selected_line, int max_lines,
+ int *last_displayed_line, int *eof, char *header, struct tog_colors *colors)
{
const struct got_error *err;
- int lineno = 0, nprinted = 0;
+ int nprinted = 0;
char *line;
struct tog_color *tc;
size_t len;
wchar_t *wline;
int width;
+ off_t line_offset;
+
+ line_offset = line_offsets[first_displayed_line - 1];
+ if (fseeko(f, line_offset, SEEK_SET) == -1)
+ return got_error_from_errno("fseek");
- rewind(f);
werase(view->window);
if (header) {
@@ -2831,17 +2834,12 @@ draw_file(struct tog_view *view, FILE *f, int *first_displayed_line, int nlines,
}
*eof = 0;
- while (nprinted < max_lines) {
+ while (max_lines > 0 && nprinted < max_lines) {
line = parse_next_line(f, &len);
if (line == NULL) {
*eof = 1;
break;
}
- if (++lineno < *first_displayed_line) {
- free(line);
- continue;
- }
-
err = format_line(&wline, &width, line, view->ncols, 0);
if (err) {
free(line);
@@ -2858,13 +2856,15 @@ draw_file(struct tog_view *view, FILE *f, int *first_displayed_line, int nlines,
COLOR_PAIR(tc->colorpair), NULL);
if (width <= view->ncols - 1)
waddch(view->window, '\n');
- if (++nprinted == 1)
- *first_displayed_line = lineno;
+ nprinted++;
free(line);
free(wline);
wline = NULL;
}
- *last_displayed_line = lineno;
+ if (nprinted >= 1)
+ *last_displayed_line = first_displayed_line + (nprinted - 1);
+ else
+ *last_displayed_line = first_displayed_line;
view_vborder(view);
@@ -2949,18 +2949,35 @@ done:
}
static const struct got_error *
-write_commit_info(struct got_object_id *commit_id,
- struct got_reflist_head *refs, struct got_repository *repo, FILE *outfile)
+add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
+{
+ off_t *p;
+
+ p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
+ if (p == NULL)
+ return got_error_from_errno("reallocarray");
+ *line_offsets = p;
+ (*line_offsets)[*nlines] = off;
+ (*nlines)++;
+ return NULL;
+}
+
+static const struct got_error *
+write_commit_info(off_t **line_offsets, size_t *nlines,
+ struct got_object_id *commit_id, struct got_reflist_head *refs,
+ struct got_repository *repo, FILE *outfile)
{
const struct got_error *err = NULL;
char datebuf[26], *datestr;
struct got_commit_object *commit;
- char *id_str = NULL, *logmsg = NULL;
+ char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
time_t committer_time;
const char *author, *committer;
char *refs_str = NULL;
struct got_pathlist_head changed_paths;
struct got_pathlist_entry *pe;
+ off_t outoff = 0;
+ int n;
TAILQ_INIT(&changed_paths);
@@ -2980,152 +2997,107 @@ write_commit_info(struct got_object_id *commit_id,
goto done;
}
- if (fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
- refs_str ? refs_str : "", refs_str ? ")" : "") < 0) {
+ err = add_line_offset(line_offsets, nlines, 0);
+ if (err)
+ goto done;
+
+ n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
+ refs_str ? refs_str : "", refs_str ? ")" : "");
+ if (n < 0) {
err = got_error_from_errno("fprintf");
goto done;
}
- if (fprintf(outfile, "from: %s\n",
- got_object_commit_get_author(commit)) < 0) {
+ outoff += n;
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
+
+ n = fprintf(outfile, "from: %s\n",
+ got_object_commit_get_author(commit));
+ if (n < 0) {
err = got_error_from_errno("fprintf");
goto done;
}
+ outoff += n;
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
+
committer_time = got_object_commit_get_committer_time(commit);
datestr = get_datestr(&committer_time, datebuf);
- if (datestr && fprintf(outfile, "date: %s UTC\n", datestr) < 0) {
- err = got_error_from_errno("fprintf");
- goto done;
+ if (datestr) {
+ n = fprintf(outfile, "date: %s UTC\n", datestr);
+ if (n < 0) {
+ err = got_error_from_errno("fprintf");
+ goto done;
+ }
+ outoff += n;
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
}
author = got_object_commit_get_author(commit);
committer = got_object_commit_get_committer(commit);
- if (strcmp(author, committer) != 0 &&
- fprintf(outfile, "via: %s\n", committer) < 0) {
- err = got_error_from_errno("fprintf");
- goto done;
+ if (strcmp(author, committer) != 0) {
+ n = fprintf(outfile, "via: %s\n", committer);
+ if (n < 0) {
+ err = got_error_from_errno("fprintf");
+ goto done;
+ }
+ outoff += n;
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
}
err = got_object_commit_get_logmsg(&logmsg, commit);
if (err)
goto done;
- if (fprintf(outfile, "%s\n", logmsg) < 0) {
- err = got_error_from_errno("fprintf");
- goto done;
+ s = logmsg;
+ while ((line = strsep(&s, "\n")) != NULL) {
+ n = fprintf(outfile, "%s\n", line);
+ if (n < 0) {
+ err = got_error_from_errno("fprintf");
+ goto done;
+ }
+ outoff += n;
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
}
+
err = get_changed_paths(&changed_paths, commit, repo);
if (err)
goto done;
TAILQ_FOREACH(pe, &changed_paths, entry) {
struct got_diff_changed_path *cp = pe->data;
- fprintf(outfile, "%c %s\n", cp->status, pe->path);
+ n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
+ if (n < 0) {
+ err = got_error_from_errno("fprintf");
+ goto done;
+ }
+ outoff += n;
+ err = add_line_offset(line_offsets, nlines, outoff);
+ if (err)
+ goto done;
free((char *)pe->path);
free(pe->data);
}
+
fputc('\n', outfile);
+ outoff++;
+ err = add_line_offset(line_offsets, nlines, outoff);
done:
got_pathlist_free(&changed_paths);
free(id_str);
free(logmsg);
free(refs_str);
got_object_commit_close(commit);
- return err;
-}
-
-const struct got_error *
-get_filestream_info(size_t *filesize, int *nlines, off_t **line_offsets,
- FILE *infile)
-{
- const struct got_error *err = NULL;
- size_t len, remain;
- char buf[32768];
- int i;
- size_t nalloc = 0;
- off_t off = 0;
-
- *line_offsets = NULL;
- *filesize = 0;
- *nlines = 0;
-
- if (fseek(infile, 0, SEEK_END) == -1)
- return got_error_from_errno("fseek");
- len = ftell(infile) + 1;
- if (ferror(infile))
- return got_error_from_errno("ftell");
- if (fseek(infile, 0, SEEK_SET) == -1)
- return got_error_from_errno("fseek");
-
- if (len == 0)
- return NULL;
-
- remain = len;
- while (remain > 0) {
- size_t r, n = MIN(remain, sizeof(buf));
- r = fread(buf, 1, n, infile);
- if (r == 0) {
- if (ferror(infile)) {
- err = got_error_from_errno("fread");
- goto done;
- }
- break;
- }
- i = 0;
- remain -= r;
-
- if (*line_offsets == NULL) {
- /* Have some data but perhaps no '\n'. */
- *nlines = 1;
- nalloc = len / 40; /* 40-char average line length */
- *line_offsets = calloc(nalloc, sizeof(**line_offsets));
- if (*line_offsets == NULL) {
- err = got_error_from_errno("calloc");
- goto done;
- }
- /* Skip forward over end of first line. */
- while (i < len) {
- if (buf[i] == '\n')
- break;
- i++;
- }
- }
-
- /* Scan '\n' offsets in remaining chunk of data. */
- while (i < r) {
- if (buf[i] != '\n') {
- i++;
- continue;
- }
- (*nlines)++;
- if (nalloc < *nlines) {
- size_t nallocnew = *nlines + (remain / 40);
- off_t *o = recallocarray(*line_offsets,
- nalloc, nallocnew, sizeof(**line_offsets));
- if (o == NULL) {
- err = got_error_from_errno(
- "recallocarray");
- goto done;
- }
- *line_offsets = o;
- nalloc = nallocnew;
- }
- off = i + 1;
- (*line_offsets)[*nlines - 1] = off;
- i++;
- }
- }
-
- if (fflush(infile) != 0) {
- err = got_error_from_errno("fflush");
- goto done;
- }
- rewind(infile);
-
- *filesize = len;
-done:
if (err) {
free(*line_offsets);
*line_offsets = NULL;
- *filesize = 0;
*nlines = 0;
}
- return NULL;
+ return err;
}
static const struct got_error *
@@ -3135,6 +3107,12 @@ create_diff(struct tog_diff_view_state *s)
FILE *f = NULL;
int obj_type;
+ free(s->line_offsets);
+ s->line_offsets = malloc(sizeof(off_t));
+ if (s->line_offsets == NULL)
+ return got_error_from_errno("malloc");
+ s->nlines = 0;
+
f = got_opentemp();
if (f == NULL) {
err = got_error_from_errno("got_opentemp");
@@ -3155,12 +3133,13 @@ create_diff(struct tog_diff_view_state *s)
switch (obj_type) {
case GOT_OBJ_TYPE_BLOB:
- err = got_diff_objects_as_blobs(s->id1, s->id2, NULL, NULL,
- s->diff_context, 0, s->repo, s->f);
+ err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
+ s->id1, s->id2, NULL, NULL, s->diff_context, 0,
+ s->repo, s->f);
break;
case GOT_OBJ_TYPE_TREE:
- err = got_diff_objects_as_trees(s->id1, s->id2, "", "",
- s->diff_context, 0, s->repo, s->f);
+ err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
+ s->id1, s->id2, "", "", s->diff_context, 0, s->repo, s->f);
break;
case GOT_OBJ_TYPE_COMMIT: {
const struct got_object_id_queue *parent_ids;
@@ -3172,15 +3151,17 @@ create_diff(struct tog_diff_view_state *s)
goto done;
/* Show commit info if we're diffing to a parent/root commit. */
if (s->id1 == NULL) {
- err = write_commit_info(s->id2, s->refs, s->repo, s->f);
+ err = write_commit_info(&s->line_offsets, &s->nlines,
+ s->id2, s->refs, s->repo, s->f);
if (err)
goto done;
} else {
parent_ids = got_object_commit_get_parent_ids(commit2);
SIMPLEQ_FOREACH(pid, parent_ids, entry) {
if (got_object_id_cmp(s->id1, pid->id) == 0) {
- err = write_commit_info(s->id2, s->refs,
- s->repo, s->f);
+ err = write_commit_info(
+ &s->line_offsets, &s->nlines,
+ s->id2, s->refs, s->repo, s->f);
if (err)
goto done;
break;
@@ -3189,8 +3170,8 @@ create_diff(struct tog_diff_view_state *s)
}
got_object_commit_close(commit2);
- err = got_diff_objects_as_commits(s->id1, s->id2,
- s->diff_context, 0, s->repo, s->f);
+ err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
+ s->id1, s->id2, s->diff_context, 0, s->repo, s->f);
break;
}
default:
@@ -3199,8 +3180,6 @@ create_diff(struct tog_diff_view_state *s)
}
if (err)
goto done;
- err = get_filestream_info(&s->filesize, &s->nlines, &s->line_offsets,
- s->f);
done:
if (s->f && fflush(s->f) != 0 && err == NULL)
err = got_error_from_errno("fflush");
@@ -3394,6 +3373,8 @@ open_diff_view(struct tog_view *view, struct got_object_id *id1,
show_log_view(log_view); /* draw vborder */
diff_view_indicate_progress(view);
+ s->line_offsets = NULL;
+ s->nlines = 0;
err = create_diff(s);
if (err) {
free(s->id1);
@@ -3426,6 +3407,8 @@ close_diff_view(struct tog_view *view)
err = got_error_from_errno("fclose");
free_colors(&s->colors);
free(s->line_offsets);
+ s->line_offsets = NULL;
+ s->nlines = 0;
return err;
}
@@ -3455,9 +3438,9 @@ show_diff_view(struct tog_view *view)
free(id_str1);
free(id_str2);
- return draw_file(view, s->f, &s->first_displayed_line, s->nlines,
- s->selected_line, view->nlines, &s->last_displayed_line, &s->eof,
- header, &s->colors);
+ return draw_file(view, s->f, s->first_displayed_line, s->nlines,
+ s->line_offsets, s->selected_line, view->nlines,
+ &s->last_displayed_line, &s->eof, header, &s->colors);
}
static const struct got_error *