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
use core::{
fmt::Debug,
panic::{RefUnwindSafe, UnwindSafe},
};
use alloc::{string::String, sync::Arc, vec::Vec};
use crate::{
automaton::{self, Automaton, OverlappingState},
dfa,
nfa::{contiguous, noncontiguous},
util::{
error::{BuildError, MatchError},
prefilter::Prefilter,
primitives::{PatternID, StateID},
search::{Anchored, Input, Match, MatchKind, StartKind},
},
};
/// An automaton for searching multiple strings in linear time.
///
/// The `AhoCorasick` type supports a few basic ways of constructing an
/// automaton, with the default being [`AhoCorasick::new`]. However, there
/// are a fair number of configurable options that can be set by using
/// [`AhoCorasickBuilder`] instead. Such options include, but are not limited
/// to, how matches are determined, simple case insensitivity, whether to use a
/// DFA or not and various knobs for controlling the space-vs-time trade offs
/// taken when building the automaton.
///
/// # Resource usage
///
/// Aho-Corasick automatons are always constructed in `O(p)` time, where
/// `p` is the combined length of all patterns being searched. With that
/// said, building an automaton can be fairly costly because of high constant
/// factors, particularly when enabling the [DFA](AhoCorasickKind::DFA) option
/// with [`AhoCorasickBuilder::kind`]. For this reason, it's generally a good
/// idea to build an automaton once and reuse it as much as possible.
///
/// Aho-Corasick automatons can also use a fair bit of memory. To get
/// a concrete idea of how much memory is being used, try using the
/// [`AhoCorasick::memory_usage`] method.
///
/// To give a quick idea of the differences between Aho-Corasick
/// implementations and their resource usage, here's a sample of construction
/// times and heap memory used after building an automaton from 100,000
/// randomly selected titles from Wikipedia:
///
/// * 99MB for a [`noncontiguous::NFA`] in 240ms.
/// * 21MB for a [`contiguous::NFA`] in 275ms.
/// * 1.6GB for a [`dfa::DFA`] in 1.88s.
///
/// (Note that the memory usage above reflects the size of each automaton and
/// not peak memory usage. For example, building a contiguous NFA requires
/// first building a noncontiguous NFA. Once the contiguous NFA is built, the
/// noncontiguous NFA is freed.)
///
/// This experiment very strongly argues that a contiguous NFA is often the
/// best balance in terms of resource usage. It takes a little longer to build,
/// but its memory usage is quite small. Its search speed (not listed) is
/// also often faster than a noncontiguous NFA, but a little slower than a
/// DFA. Indeed, when no specific [`AhoCorasickKind`] is used (which is the
/// default), a contiguous NFA is used in most cases.
///
/// The only "catch" to using a contiguous NFA is that, because of its variety
/// of compression tricks, it may not be able to support automatons as large as
/// what the noncontiguous NFA supports. In which case, building a contiguous
/// NFA will fail and (by default) `AhoCorasick` will automatically fall
/// back to a noncontiguous NFA. (This typically only happens when building
/// automatons from millions of patterns.) Otherwise, the small additional time
/// for building a contiguous NFA is almost certainly worth it.
///
/// # Cloning
///
/// The `AhoCorasick` type uses thread safe reference counting internally. It
/// is guaranteed that it is cheap to clone.
///
/// # Search configuration
///
/// Most of the search routines accept anything that can be cheaply converted
/// to an [`Input`]. This includes `&[u8]`, `&str` and `Input` itself.
///
/// # Construction failure
///
/// It is generally possible for building an Aho-Corasick automaton to fail.
/// Construction can fail in generally one way: when the inputs provided are
/// too big. Whether that's a pattern that is too long, too many patterns
/// or some combination of both. A first approximation for the scale at which
/// construction can fail is somewhere around "millions of patterns."
///
/// For that reason, if you're building an Aho-Corasick automaton from
/// untrusted input (or input that doesn't have any reasonable bounds on its
/// size), then it is strongly recommended to handle the possibility of an
/// error.
///
/// If you're constructing an Aho-Corasick automaton from static or trusted
/// data, then it is likely acceptable to panic (by calling `unwrap()` or
/// `expect()`) if construction fails.
///
/// # Fallibility
///
/// The `AhoCorasick` type provides a number of methods for searching, as one
/// might expect. Depending on how the Aho-Corasick automaton was built and
/// depending on the search configuration, it is possible for a search to
/// return an error. Since an error is _never_ dependent on the actual contents
/// of the haystack, this type provides both infallible and fallible methods
/// for searching. The infallible methods panic if an error occurs, and can be
/// used for convenience and when you know the search will never return an
/// error.
///
/// For example, the [`AhoCorasick::find_iter`] method is the infallible
/// version of the [`AhoCorasick::try_find_iter`] method.
///
/// Examples of errors that can occur:
///
/// * Running a search that requires [`MatchKind::Standard`] semantics (such
/// as a stream or overlapping search) with an automaton that was built with
/// [`MatchKind::LeftmostFirst`] or [`MatchKind::LeftmostLongest`] semantics.
/// * Running an anchored search with an automaton that only supports
/// unanchored searches. (By default, `AhoCorasick` only supports unanchored
/// searches. But this can be toggled with [`AhoCorasickBuilder::start_kind`].)
/// * Running an unanchored search with an automaton that only supports
/// anchored searches.
///
/// The common thread between the different types of errors is that they are
/// all rooted in the automaton construction and search configurations. If
/// those configurations are a static property of your program, then it is
/// reasonable to call infallible routines since you know an error will never
/// occur. And if one _does_ occur, then it's a bug in your program.
///
/// To re-iterate, if the patterns, build or search configuration come from
/// user or untrusted data, then you should handle errors at build or search
/// time. If only the haystack comes from user or untrusted data, then there
/// should be no need to handle errors anywhere and it is generally encouraged
/// to `unwrap()` (or `expect()`) both build and search time calls.
///
/// # Examples
///
/// This example shows how to search for occurrences of multiple patterns
/// simultaneously in a case insensitive fashion. Each match includes the
/// pattern that matched along with the byte offsets of the match.
///
/// ```
/// use aho_corasick::{AhoCorasick, PatternID};
///
/// let patterns = &["apple", "maple", "snapple"];
/// let haystack = "Nobody likes maple in their apple flavored Snapple.";
///
/// let ac = AhoCorasick::builder()
/// .ascii_case_insensitive(true)
/// .build(patterns)
/// .unwrap();
/// let mut matches = vec![];
/// for mat in ac.find_iter(haystack) {
/// matches.push((mat.pattern(), mat.start(), mat.end()));
/// }
/// assert_eq!(matches, vec![
/// (PatternID::must(1), 13, 18),
/// (PatternID::must(0), 28, 33),
/// (PatternID::must(2), 43, 50),
/// ]);
/// ```
///
/// This example shows how to replace matches with some other string:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let patterns = &["fox", "brown", "quick"];
/// let haystack = "The quick brown fox.";
/// let replace_with = &["sloth", "grey", "slow"];
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let result = ac.replace_all(haystack, replace_with);
/// assert_eq!(result, "The slow grey sloth.");
/// ```
#[derive(Clone)]
pub struct AhoCorasick {
/// The underlying Aho-Corasick automaton. It's one of
/// nfa::noncontiguous::NFA, nfa::contiguous::NFA or dfa::DFA.
aut: Arc<dyn AcAutomaton>,
/// The specific Aho-Corasick kind chosen. This makes it possible to
/// inspect any `AhoCorasick` and know what kind of search strategy it
/// uses.
kind: AhoCorasickKind,
/// The start kind of this automaton as configured by the caller.
///
/// We don't really *need* to put this here, since the underlying automaton
/// will correctly return errors if the caller requests an unsupported
/// search type. But we do keep this here for API behavior consistency.
/// Namely, the NFAs in this crate support both unanchored and anchored
/// searches unconditionally. There's no way to disable one or the other.
/// They always both work. But the DFA in this crate specifically only
/// supports both unanchored and anchored searches if it's configured to
/// do so. Why? Because for the DFA, supporting both essentially requires
/// two copies of the transition table: one generated by following failure
/// transitions from the original NFA and one generated by not following
/// those failure transitions.
///
/// So why record the start kind here? Well, consider what happens
/// when no specific 'AhoCorasickKind' is selected by the caller and
/// 'StartKind::Unanchored' is used (both are the default). It *might*
/// result in using a DFA or it might pick an NFA. If it picks an NFA, the
/// caller would then be able to run anchored searches, even though the
/// caller only asked for support for unanchored searches. Maybe that's
/// fine, but what if the DFA was chosen instead? Oops, the caller would
/// get an error.
///
/// Basically, it seems bad to return an error or not based on some
/// internal implementation choice. So we smooth things out and ensure
/// anchored searches *always* report an error when only unanchored support
/// was asked for (and vice versa), even if the underlying automaton
/// supports it.
start_kind: StartKind,
}
/// Convenience constructors for an Aho-Corasick searcher. To configure the
/// searcher, use an [`AhoCorasickBuilder`] instead.
impl AhoCorasick {
/// Create a new Aho-Corasick automaton using the default configuration.
///
/// The default configuration optimizes for less space usage, but at the
/// expense of longer search times. To change the configuration, use
/// [`AhoCorasickBuilder`].
///
/// This uses the default [`MatchKind::Standard`] match semantics, which
/// reports a match as soon as it is found. This corresponds to the
/// standard match semantics supported by textbook descriptions of the
/// Aho-Corasick algorithm.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::{AhoCorasick, PatternID};
///
/// let ac = AhoCorasick::new(&["foo", "bar", "baz"]).unwrap();
/// assert_eq!(
/// Some(PatternID::must(1)),
/// ac.find("xxx bar xxx").map(|m| m.pattern()),
/// );
/// ```
pub fn new<I, P>(patterns: I) -> Result<AhoCorasick, BuildError>
where
I: IntoIterator<Item = P>,
P: AsRef<[u8]>,
{
AhoCorasickBuilder::new().build(patterns)
}
/// A convenience method for returning a new Aho-Corasick builder.
///
/// This usually permits one to just import the `AhoCorasick` type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::{AhoCorasick, Match, MatchKind};
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(&["samwise", "sam"])
/// .unwrap();
/// assert_eq!(Some(Match::must(0, 0..7)), ac.find("samwise"));
/// ```
pub fn builder() -> AhoCorasickBuilder {
AhoCorasickBuilder::new()
}
}
/// Infallible search routines. These APIs panic when the underlying search
/// would otherwise fail. Infallible routines are useful because the errors are
/// a result of both search-time configuration and what configuration is used
/// to build the Aho-Corasick searcher. Both of these things are not usually
/// the result of user input, and thus, an error is typically indicative of a
/// programmer error. In cases where callers want errors instead of panics, use
/// the corresponding `try` method in the section below.
impl AhoCorasick {
/// Returns true if and only if this automaton matches the haystack at any
/// position.
///
/// `input` may be any type that is cheaply convertible to an `Input`. This
/// includes, but is not limited to, `&str` and `&[u8]`.
///
/// Aside from convenience, when `AhoCorasick` was built with
/// leftmost-first or leftmost-longest semantics, this might result in a
/// search that visits less of the haystack than [`AhoCorasick::find`]
/// would otherwise. (For standard semantics, matches are always
/// immediately returned once they are seen, so there is no way for this to
/// do less work in that case.)
///
/// Note that there is no corresponding fallible routine for this method.
/// If you need a fallible version of this, then [`AhoCorasick::try_find`]
/// can be used with [`Input::earliest`] enabled.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let ac = AhoCorasick::new(&[
/// "foo", "bar", "quux", "baz",
/// ]).unwrap();
/// assert!(ac.is_match("xxx bar xxx"));
/// assert!(!ac.is_match("xxx qux xxx"));
/// ```
pub fn is_match<'h, I: Into<Input<'h>>>(&self, input: I) -> bool {
self.aut
.try_find(&input.into().earliest(true))
.expect("AhoCorasick::try_find is not expected to fail")
.is_some()
}
/// Returns the location of the first match according to the match
/// semantics that this automaton was constructed with.
///
/// `input` may be any type that is cheaply convertible to an `Input`. This
/// includes, but is not limited to, `&str` and `&[u8]`.
///
/// This is the infallible version of [`AhoCorasick::try_find`].
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_find`] would return an error.
///
/// # Examples
///
/// Basic usage, with standard semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::Standard) // default, not necessary
/// .build(patterns)
/// .unwrap();
/// let mat = ac.find(haystack).expect("should have a match");
/// assert_eq!("b", &haystack[mat.start()..mat.end()]);
/// ```
///
/// Now with leftmost-first semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let mat = ac.find(haystack).expect("should have a match");
/// assert_eq!("abc", &haystack[mat.start()..mat.end()]);
/// ```
///
/// And finally, leftmost-longest semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostLongest)
/// .build(patterns)
/// .unwrap();
/// let mat = ac.find(haystack).expect("should have a match");
/// ```
///
/// # Example: configuring a search
///
/// Because this method accepts anything that can be turned into an
/// [`Input`], it's possible to provide an `Input` directly in order to
/// configure the search. In this example, we show how to use the
/// `earliest` option to force the search to return as soon as it knows
/// a match has occurred.
///
/// ```
/// use aho_corasick::{AhoCorasick, Input, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostLongest)
/// .build(patterns)
/// .unwrap();
/// let mat = ac.find(Input::new(haystack).earliest(true))
/// .expect("should have a match");
/// // The correct leftmost-longest match here is 'abcd', but since we
/// // told the search to quit as soon as it knows a match has occurred,
/// // we get a different match back.
/// assert_eq!("b", &haystack[mat.start()..mat.end()]);
/// ```
pub fn find<'h, I: Into<Input<'h>>>(&self, input: I) -> Option<Match> {
self.try_find(input)
.expect("AhoCorasick::try_find is not expected to fail")
}
/// Returns the location of the first overlapping match in the given
/// input with respect to the current state of the underlying searcher.
///
/// `input` may be any type that is cheaply convertible to an `Input`. This
/// includes, but is not limited to, `&str` and `&[u8]`.
///
/// Overlapping searches do not report matches in their return value.
/// Instead, matches can be accessed via [`OverlappingState::get_match`]
/// after a search call.
///
/// This is the infallible version of
/// [`AhoCorasick::try_find_overlapping`].
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_find_overlapping`] would
/// return an error. For example, when the Aho-Corasick searcher
/// doesn't support overlapping searches. (Only searchers built with
/// [`MatchKind::Standard`] semantics support overlapping searches.)
///
/// # Example
///
/// This shows how we can repeatedly call an overlapping search without
/// ever needing to explicitly re-slice the haystack. Overlapping search
/// works this way because searches depend on state saved during the
/// previous search.
///
/// ```
/// use aho_corasick::{
/// automaton::OverlappingState,
/// AhoCorasick, Input, Match,
/// };
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut state = OverlappingState::start();
///
/// ac.find_overlapping(haystack, &mut state);
/// assert_eq!(Some(Match::must(2, 0..3)), state.get_match());
///
/// ac.find_overlapping(haystack, &mut state);
/// assert_eq!(Some(Match::must(0, 0..6)), state.get_match());
///
/// ac.find_overlapping(haystack, &mut state);
/// assert_eq!(Some(Match::must(2, 11..14)), state.get_match());
///
/// ac.find_overlapping(haystack, &mut state);
/// assert_eq!(Some(Match::must(2, 22..25)), state.get_match());
///
/// ac.find_overlapping(haystack, &mut state);
/// assert_eq!(Some(Match::must(0, 22..28)), state.get_match());
///
/// ac.find_overlapping(haystack, &mut state);
/// assert_eq!(Some(Match::must(1, 22..31)), state.get_match());
///
/// // No more match matches to be found.
/// ac.find_overlapping(haystack, &mut state);
/// assert_eq!(None, state.get_match());
/// ```
pub fn find_overlapping<'h, I: Into<Input<'h>>>(
&self,
input: I,
state: &mut OverlappingState,
) {
self.try_find_overlapping(input, state).expect(
"AhoCorasick::try_find_overlapping is not expected to fail",
)
}
/// Returns an iterator of non-overlapping matches, using the match
/// semantics that this automaton was constructed with.
///
/// `input` may be any type that is cheaply convertible to an `Input`. This
/// includes, but is not limited to, `&str` and `&[u8]`.
///
/// This is the infallible version of [`AhoCorasick::try_find_iter`].
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_find_iter`] would return an error.
///
/// # Examples
///
/// Basic usage, with standard semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::Standard) // default, not necessary
/// .build(patterns)
/// .unwrap();
/// let matches: Vec<PatternID> = ac
/// .find_iter(haystack)
/// .map(|mat| mat.pattern())
/// .collect();
/// assert_eq!(vec![
/// PatternID::must(2),
/// PatternID::must(2),
/// PatternID::must(2),
/// ], matches);
/// ```
///
/// Now with leftmost-first semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let matches: Vec<PatternID> = ac
/// .find_iter(haystack)
/// .map(|mat| mat.pattern())
/// .collect();
/// assert_eq!(vec![
/// PatternID::must(0),
/// PatternID::must(2),
/// PatternID::must(0),
/// ], matches);
/// ```
///
/// And finally, leftmost-longest semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostLongest)
/// .build(patterns)
/// .unwrap();
/// let matches: Vec<PatternID> = ac
/// .find_iter(haystack)
/// .map(|mat| mat.pattern())
/// .collect();
/// assert_eq!(vec![
/// PatternID::must(0),
/// PatternID::must(2),
/// PatternID::must(1),
/// ], matches);
/// ```
pub fn find_iter<'a, 'h, I: Into<Input<'h>>>(
&'a self,
input: I,
) -> FindIter<'a, 'h> {
self.try_find_iter(input)
.expect("AhoCorasick::try_find_iter is not expected to fail")
}
/// Returns an iterator of overlapping matches. Stated differently, this
/// returns an iterator of all possible matches at every position.
///
/// `input` may be any type that is cheaply convertible to an `Input`. This
/// includes, but is not limited to, `&str` and `&[u8]`.
///
/// This is the infallible version of
/// [`AhoCorasick::try_find_overlapping_iter`].
///
/// # Panics
///
/// This panics when `AhoCorasick::try_find_overlapping_iter` would return
/// an error. For example, when the Aho-Corasick searcher is built with
/// either leftmost-first or leftmost-longest match semantics. Stated
/// differently, overlapping searches require one to build the searcher
/// with [`MatchKind::Standard`] (it is the default).
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let matches: Vec<PatternID> = ac
/// .find_overlapping_iter(haystack)
/// .map(|mat| mat.pattern())
/// .collect();
/// assert_eq!(vec![
/// PatternID::must(2),
/// PatternID::must(0),
/// PatternID::must(2),
/// PatternID::must(2),
/// PatternID::must(0),
/// PatternID::must(1),
/// ], matches);
/// ```
pub fn find_overlapping_iter<'a, 'h, I: Into<Input<'h>>>(
&'a self,
input: I,
) -> FindOverlappingIter<'a, 'h> {
self.try_find_overlapping_iter(input).expect(
"AhoCorasick::try_find_overlapping_iter is not expected to fail",
)
}
/// Replace all matches with a corresponding value in the `replace_with`
/// slice given. Matches correspond to the same matches as reported by
/// [`AhoCorasick::find_iter`].
///
/// Replacements are determined by the index of the matching pattern.
/// For example, if the pattern with index `2` is found, then it is
/// replaced by `replace_with[2]`.
///
/// This is the infallible version of [`AhoCorasick::try_replace_all`].
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_replace_all`] would return an
/// error.
///
/// This also panics when `replace_with.len()` does not equal
/// [`AhoCorasick::patterns_len`].
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let result = ac.replace_all(haystack, &["x", "y", "z"]);
/// assert_eq!("x the z to the xage", result);
/// ```
pub fn replace_all<B>(&self, haystack: &str, replace_with: &[B]) -> String
where
B: AsRef<str>,
{
self.try_replace_all(haystack, replace_with)
.expect("AhoCorasick::try_replace_all is not expected to fail")
}
/// Replace all matches using raw bytes with a corresponding value in the
/// `replace_with` slice given. Matches correspond to the same matches as
/// reported by [`AhoCorasick::find_iter`].
///
/// Replacements are determined by the index of the matching pattern.
/// For example, if the pattern with index `2` is found, then it is
/// replaced by `replace_with[2]`.
///
/// This is the infallible version of
/// [`AhoCorasick::try_replace_all_bytes`].
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_replace_all_bytes`] would return an
/// error.
///
/// This also panics when `replace_with.len()` does not equal
/// [`AhoCorasick::patterns_len`].
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = b"append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let result = ac.replace_all_bytes(haystack, &["x", "y", "z"]);
/// assert_eq!(b"x the z to the xage".to_vec(), result);
/// ```
pub fn replace_all_bytes<B>(
&self,
haystack: &[u8],
replace_with: &[B],
) -> Vec<u8>
where
B: AsRef<[u8]>,
{
self.try_replace_all_bytes(haystack, replace_with)
.expect("AhoCorasick::try_replace_all_bytes should not fail")
}
/// Replace all matches using a closure called on each match.
/// Matches correspond to the same matches as reported by
/// [`AhoCorasick::find_iter`].
///
/// The closure accepts three parameters: the match found, the text of
/// the match and a string buffer with which to write the replaced text
/// (if any). If the closure returns `true`, then it continues to the next
/// match. If the closure returns `false`, then searching is stopped.
///
/// Note that any matches with boundaries that don't fall on a valid UTF-8
/// boundary are silently skipped.
///
/// This is the infallible version of
/// [`AhoCorasick::try_replace_all_with`].
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_replace_all_with`] would return an
/// error.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let mut result = String::new();
/// ac.replace_all_with(haystack, &mut result, |mat, _, dst| {
/// dst.push_str(&mat.pattern().as_usize().to_string());
/// true
/// });
/// assert_eq!("0 the 2 to the 0age", result);
/// ```
///
/// Stopping the replacement by returning `false` (continued from the
/// example above):
///
/// ```
/// # use aho_corasick::{AhoCorasick, MatchKind, PatternID};
/// # let patterns = &["append", "appendage", "app"];
/// # let haystack = "append the app to the appendage";
/// # let ac = AhoCorasick::builder()
/// # .match_kind(MatchKind::LeftmostFirst)
/// # .build(patterns)
/// # .unwrap();
/// let mut result = String::new();
/// ac.replace_all_with(haystack, &mut result, |mat, _, dst| {
/// dst.push_str(&mat.pattern().as_usize().to_string());
/// mat.pattern() != PatternID::must(2)
/// });
/// assert_eq!("0 the 2 to the appendage", result);
/// ```
pub fn replace_all_with<F>(
&self,
haystack: &str,
dst: &mut String,
replace_with: F,
) where
F: FnMut(&Match, &str, &mut String) -> bool,
{
self.try_replace_all_with(haystack, dst, replace_with)
.expect("AhoCorasick::try_replace_all_with should not fail")
}
/// Replace all matches using raw bytes with a closure called on each
/// match. Matches correspond to the same matches as reported by
/// [`AhoCorasick::find_iter`].
///
/// The closure accepts three parameters: the match found, the text of
/// the match and a byte buffer with which to write the replaced text
/// (if any). If the closure returns `true`, then it continues to the next
/// match. If the closure returns `false`, then searching is stopped.
///
/// This is the infallible version of
/// [`AhoCorasick::try_replace_all_with_bytes`].
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_replace_all_with_bytes`] would
/// return an error.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = b"append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let mut result = vec![];
/// ac.replace_all_with_bytes(haystack, &mut result, |mat, _, dst| {
/// dst.extend(mat.pattern().as_usize().to_string().bytes());
/// true
/// });
/// assert_eq!(b"0 the 2 to the 0age".to_vec(), result);
/// ```
///
/// Stopping the replacement by returning `false` (continued from the
/// example above):
///
/// ```
/// # use aho_corasick::{AhoCorasick, MatchKind, PatternID};
/// # let patterns = &["append", "appendage", "app"];
/// # let haystack = b"append the app to the appendage";
/// # let ac = AhoCorasick::builder()
/// # .match_kind(MatchKind::LeftmostFirst)
/// # .build(patterns)
/// # .unwrap();
/// let mut result = vec![];
/// ac.replace_all_with_bytes(haystack, &mut result, |mat, _, dst| {
/// dst.extend(mat.pattern().as_usize().to_string().bytes());
/// mat.pattern() != PatternID::must(2)
/// });
/// assert_eq!(b"0 the 2 to the appendage".to_vec(), result);
/// ```
pub fn replace_all_with_bytes<F>(
&self,
haystack: &[u8],
dst: &mut Vec<u8>,
replace_with: F,
) where
F: FnMut(&Match, &[u8], &mut Vec<u8>) -> bool,
{
self.try_replace_all_with_bytes(haystack, dst, replace_with)
.expect("AhoCorasick::try_replace_all_with_bytes should not fail")
}
/// Returns an iterator of non-overlapping matches in the given
/// stream. Matches correspond to the same matches as reported by
/// [`AhoCorasick::find_iter`].
///
/// The matches yielded by this iterator use absolute position offsets in
/// the stream given, where the first byte has index `0`. Matches are
/// yieled until the stream is exhausted.
///
/// Each item yielded by the iterator is an `Result<Match,
/// std::io::Error>`, where an error is yielded if there was a problem
/// reading from the reader given.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible.
///
/// This is the infallible version of
/// [`AhoCorasick::try_stream_find_iter`]. Note that both methods return
/// iterators that produce `Result` values. The difference is that this
/// routine panics if _construction_ of the iterator failed. The `Result`
/// values yield by the iterator come from whether the given reader returns
/// an error or not during the search.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_stream_find_iter`] would return
/// an error. For example, when the Aho-Corasick searcher doesn't support
/// stream searches. (Only searchers built with [`MatchKind::Standard`]
/// semantics support stream searches.)
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut matches = vec![];
/// for result in ac.stream_find_iter(haystack.as_bytes()) {
/// let mat = result?;
/// matches.push(mat.pattern());
/// }
/// assert_eq!(vec![
/// PatternID::must(2),
/// PatternID::must(2),
/// PatternID::must(2),
/// ], matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
pub fn stream_find_iter<'a, R: std::io::Read>(
&'a self,
rdr: R,
) -> StreamFindIter<'a, R> {
self.try_stream_find_iter(rdr)
.expect("AhoCorasick::try_stream_find_iter should not fail")
}
}
/// Fallible search routines. These APIs return an error in cases where the
/// infallible routines would panic.
impl AhoCorasick {
/// Returns the location of the first match according to the match
/// semantics that this automaton was constructed with, and according
/// to the given `Input` configuration.
///
/// This is the fallible version of [`AhoCorasick::find`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the given `Input` configuration.
///
/// For example, if the Aho-Corasick searcher only supports anchored
/// searches or only supports unanchored searches, then providing an
/// `Input` that requests an anchored (or unanchored) search when it isn't
/// supported would result in an error.
///
/// # Example: leftmost-first searching
///
/// Basic usage with leftmost-first semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind, Input};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "foo abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let mat = ac.try_find(haystack)?.expect("should have a match");
/// assert_eq!("abc", &haystack[mat.span()]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: anchored leftmost-first searching
///
/// This shows how to anchor the search, so that even if the haystack
/// contains a match somewhere, a match won't be reported unless one can
/// be found that starts at the beginning of the search:
///
/// ```
/// use aho_corasick::{AhoCorasick, Anchored, Input, MatchKind, StartKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "foo abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .start_kind(StartKind::Anchored)
/// .build(patterns)
/// .unwrap();
/// let input = Input::new(haystack).anchored(Anchored::Yes);
/// assert_eq!(None, ac.try_find(input)?);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// If the beginning of the search is changed to where a match begins, then
/// it will be found:
///
/// ```
/// use aho_corasick::{AhoCorasick, Anchored, Input, MatchKind, StartKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "foo abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .start_kind(StartKind::Anchored)
/// .build(patterns)
/// .unwrap();
/// let input = Input::new(haystack).range(4..).anchored(Anchored::Yes);
/// let mat = ac.try_find(input)?.expect("should have a match");
/// assert_eq!("abc", &haystack[mat.span()]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: earliest leftmost-first searching
///
/// This shows how to run an "earliest" search even when the Aho-Corasick
/// searcher was compiled with leftmost-first match semantics. In this
/// case, the search is stopped as soon as it is known that a match has
/// occurred, even if it doesn't correspond to the leftmost-first match.
///
/// ```
/// use aho_corasick::{AhoCorasick, Input, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "foo abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let input = Input::new(haystack).earliest(true);
/// let mat = ac.try_find(input)?.expect("should have a match");
/// assert_eq!("b", &haystack[mat.span()]);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_find<'h, I: Into<Input<'h>>>(
&self,
input: I,
) -> Result<Option<Match>, MatchError> {
let input = input.into();
enforce_anchored_consistency(self.start_kind, input.get_anchored())?;
self.aut.try_find(&input)
}
/// Returns the location of the first overlapping match in the given
/// input with respect to the current state of the underlying searcher.
///
/// Overlapping searches do not report matches in their return value.
/// Instead, matches can be accessed via [`OverlappingState::get_match`]
/// after a search call.
///
/// This is the fallible version of [`AhoCorasick::find_overlapping`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the given `Input` configuration or if overlapping search is not
/// supported.
///
/// One example is that only Aho-Corasicker searchers built with
/// [`MatchKind::Standard`] semantics support overlapping searches. Using
/// any other match semantics will result in this returning an error.
///
/// # Example: basic usage
///
/// This shows how we can repeatedly call an overlapping search without
/// ever needing to explicitly re-slice the haystack. Overlapping search
/// works this way because searches depend on state saved during the
/// previous search.
///
/// ```
/// use aho_corasick::{
/// automaton::OverlappingState,
/// AhoCorasick, Input, Match,
/// };
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut state = OverlappingState::start();
///
/// ac.try_find_overlapping(haystack, &mut state)?;
/// assert_eq!(Some(Match::must(2, 0..3)), state.get_match());
///
/// ac.try_find_overlapping(haystack, &mut state)?;
/// assert_eq!(Some(Match::must(0, 0..6)), state.get_match());
///
/// ac.try_find_overlapping(haystack, &mut state)?;
/// assert_eq!(Some(Match::must(2, 11..14)), state.get_match());
///
/// ac.try_find_overlapping(haystack, &mut state)?;
/// assert_eq!(Some(Match::must(2, 22..25)), state.get_match());
///
/// ac.try_find_overlapping(haystack, &mut state)?;
/// assert_eq!(Some(Match::must(0, 22..28)), state.get_match());
///
/// ac.try_find_overlapping(haystack, &mut state)?;
/// assert_eq!(Some(Match::must(1, 22..31)), state.get_match());
///
/// // No more match matches to be found.
/// ac.try_find_overlapping(haystack, &mut state)?;
/// assert_eq!(None, state.get_match());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: implementing your own overlapping iteration
///
/// The previous example can be easily adapted to implement your own
/// iteration by repeatedly calling `try_find_overlapping` until either
/// an error occurs or no more matches are reported.
///
/// This is effectively equivalent to the iterator returned by
/// [`AhoCorasick::try_find_overlapping_iter`], with the only difference
/// being that the iterator checks for errors before construction and
/// absolves the caller of needing to check for errors on every search
/// call. (Indeed, if the first `try_find_overlapping` call succeeds and
/// the same `Input` is given to subsequent calls, then all subsequent
/// calls are guaranteed to succeed.)
///
/// ```
/// use aho_corasick::{
/// automaton::OverlappingState,
/// AhoCorasick, Input, Match,
/// };
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut state = OverlappingState::start();
/// let mut matches = vec![];
///
/// loop {
/// ac.try_find_overlapping(haystack, &mut state)?;
/// let mat = match state.get_match() {
/// None => break,
/// Some(mat) => mat,
/// };
/// matches.push(mat);
/// }
/// let expected = vec![
/// Match::must(2, 0..3),
/// Match::must(0, 0..6),
/// Match::must(2, 11..14),
/// Match::must(2, 22..25),
/// Match::must(0, 22..28),
/// Match::must(1, 22..31),
/// ];
/// assert_eq!(expected, matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: anchored iteration
///
/// The previous example can also be adapted to implement
/// iteration over all anchored matches. In particular,
/// [`AhoCorasick::try_find_overlapping_iter`] does not support this
/// because it isn't totally clear what the match semantics ought to be.
///
/// In this example, we will find all overlapping matches that start at
/// the beginning of our search.
///
/// ```
/// use aho_corasick::{
/// automaton::OverlappingState,
/// AhoCorasick, Anchored, Input, Match, StartKind,
/// };
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .start_kind(StartKind::Anchored)
/// .build(patterns)
/// .unwrap();
/// let input = Input::new(haystack).anchored(Anchored::Yes);
/// let mut state = OverlappingState::start();
/// let mut matches = vec![];
///
/// loop {
/// ac.try_find_overlapping(input.clone(), &mut state)?;
/// let mat = match state.get_match() {
/// None => break,
/// Some(mat) => mat,
/// };
/// matches.push(mat);
/// }
/// let expected = vec![
/// Match::must(2, 0..3),
/// Match::must(0, 0..6),
/// ];
/// assert_eq!(expected, matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_find_overlapping<'h, I: Into<Input<'h>>>(
&self,
input: I,
state: &mut OverlappingState,
) -> Result<(), MatchError> {
let input = input.into();
enforce_anchored_consistency(self.start_kind, input.get_anchored())?;
self.aut.try_find_overlapping(&input, state)
}
/// Returns an iterator of non-overlapping matches, using the match
/// semantics that this automaton was constructed with.
///
/// This is the fallible version of [`AhoCorasick::find_iter`].
///
/// Note that the error returned by this method occurs during construction
/// of the iterator. The iterator itself yields `Match` values. That is,
/// once the iterator is constructed, the iteration itself will never
/// report an error.
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the given `Input` configuration.
///
/// For example, if the Aho-Corasick searcher only supports anchored
/// searches or only supports unanchored searches, then providing an
/// `Input` that requests an anchored (or unanchored) search when it isn't
/// supported would result in an error.
///
/// # Example: leftmost-first searching
///
/// Basic usage with leftmost-first semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, Input, MatchKind, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let matches: Vec<PatternID> = ac
/// .try_find_iter(Input::new(haystack))?
/// .map(|mat| mat.pattern())
/// .collect();
/// assert_eq!(vec![
/// PatternID::must(0),
/// PatternID::must(2),
/// PatternID::must(0),
/// ], matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: anchored leftmost-first searching
///
/// This shows how to anchor the search, such that all matches must begin
/// at the starting location of the search. For an iterator, an anchored
/// search implies that all matches are adjacent.
///
/// ```
/// use aho_corasick::{
/// AhoCorasick, Anchored, Input, MatchKind, PatternID, StartKind,
/// };
///
/// let patterns = &["foo", "bar", "quux"];
/// let haystack = "fooquuxbar foo";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .start_kind(StartKind::Anchored)
/// .build(patterns)
/// .unwrap();
/// let matches: Vec<PatternID> = ac
/// .try_find_iter(Input::new(haystack).anchored(Anchored::Yes))?
/// .map(|mat| mat.pattern())
/// .collect();
/// assert_eq!(vec![
/// PatternID::must(0),
/// PatternID::must(2),
/// PatternID::must(1),
/// // The final 'foo' is not found because it is not adjacent to the
/// // 'bar' match. It needs to be adjacent because our search is
/// // anchored.
/// ], matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_find_iter<'a, 'h, I: Into<Input<'h>>>(
&'a self,
input: I,
) -> Result<FindIter<'a, 'h>, MatchError> {
let input = input.into();
enforce_anchored_consistency(self.start_kind, input.get_anchored())?;
Ok(FindIter(self.aut.try_find_iter(input)?))
}
/// Returns an iterator of overlapping matches.
///
/// This is the fallible version of [`AhoCorasick::find_overlapping_iter`].
///
/// Note that the error returned by this method occurs during construction
/// of the iterator. The iterator itself yields `Match` values. That is,
/// once the iterator is constructed, the iteration itself will never
/// report an error.
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the given `Input` configuration or does not support overlapping
/// searches.
///
/// One example is that only Aho-Corasicker searchers built with
/// [`MatchKind::Standard`] semantics support overlapping searches. Using
/// any other match semantics will result in this returning an error.
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, Input, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let matches: Vec<PatternID> = ac
/// .try_find_overlapping_iter(Input::new(haystack))?
/// .map(|mat| mat.pattern())
/// .collect();
/// assert_eq!(vec![
/// PatternID::must(2),
/// PatternID::must(0),
/// PatternID::must(2),
/// PatternID::must(2),
/// PatternID::must(0),
/// PatternID::must(1),
/// ], matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: anchored overlapping search returns an error
///
/// It isn't clear what the match semantics for anchored overlapping
/// iterators *ought* to be, so currently an error is returned. Callers
/// may use [`AhoCorasick::try_find_overlapping`] to implement their own
/// semantics if desired.
///
/// ```
/// use aho_corasick::{AhoCorasick, Anchored, Input, StartKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "appendappendage app";
///
/// let ac = AhoCorasick::builder()
/// .start_kind(StartKind::Anchored)
/// .build(patterns)
/// .unwrap();
/// let input = Input::new(haystack).anchored(Anchored::Yes);
/// assert!(ac.try_find_overlapping_iter(input).is_err());
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_find_overlapping_iter<'a, 'h, I: Into<Input<'h>>>(
&'a self,
input: I,
) -> Result<FindOverlappingIter<'a, 'h>, MatchError> {
let input = input.into();
enforce_anchored_consistency(self.start_kind, input.get_anchored())?;
Ok(FindOverlappingIter(self.aut.try_find_overlapping_iter(input)?))
}
/// Replace all matches with a corresponding value in the `replace_with`
/// slice given. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// Replacements are determined by the index of the matching pattern.
/// For example, if the pattern with index `2` is found, then it is
/// replaced by `replace_with[2]`.
///
/// # Panics
///
/// This panics when `replace_with.len()` does not equal
/// [`AhoCorasick::patterns_len`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this replacement routine always does an unanchored search.
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let result = ac.try_replace_all(haystack, &["x", "y", "z"])?;
/// assert_eq!("x the z to the xage", result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_replace_all<B>(
&self,
haystack: &str,
replace_with: &[B],
) -> Result<String, MatchError>
where
B: AsRef<str>,
{
enforce_anchored_consistency(self.start_kind, Anchored::No)?;
self.aut.try_replace_all(haystack, replace_with)
}
/// Replace all matches using raw bytes with a corresponding value in the
/// `replace_with` slice given. Matches correspond to the same matches as
/// reported by [`AhoCorasick::try_find_iter`].
///
/// Replacements are determined by the index of the matching pattern.
/// For example, if the pattern with index `2` is found, then it is
/// replaced by `replace_with[2]`.
///
/// This is the fallible version of [`AhoCorasick::replace_all_bytes`].
///
/// # Panics
///
/// This panics when `replace_with.len()` does not equal
/// [`AhoCorasick::patterns_len`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this replacement routine always does an unanchored search.
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = b"append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let result = ac.try_replace_all_bytes(haystack, &["x", "y", "z"])?;
/// assert_eq!(b"x the z to the xage".to_vec(), result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_replace_all_bytes<B>(
&self,
haystack: &[u8],
replace_with: &[B],
) -> Result<Vec<u8>, MatchError>
where
B: AsRef<[u8]>,
{
enforce_anchored_consistency(self.start_kind, Anchored::No)?;
self.aut.try_replace_all_bytes(haystack, replace_with)
}
/// Replace all matches using a closure called on each match.
/// Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// The closure accepts three parameters: the match found, the text of
/// the match and a string buffer with which to write the replaced text
/// (if any). If the closure returns `true`, then it continues to the next
/// match. If the closure returns `false`, then searching is stopped.
///
/// Note that any matches with boundaries that don't fall on a valid UTF-8
/// boundary are silently skipped.
///
/// This is the fallible version of [`AhoCorasick::replace_all_with`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this replacement routine always does an unanchored search.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let mut result = String::new();
/// ac.try_replace_all_with(haystack, &mut result, |mat, _, dst| {
/// dst.push_str(&mat.pattern().as_usize().to_string());
/// true
/// })?;
/// assert_eq!("0 the 2 to the 0age", result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Stopping the replacement by returning `false` (continued from the
/// example above):
///
/// ```
/// # use aho_corasick::{AhoCorasick, MatchKind, PatternID};
/// # let patterns = &["append", "appendage", "app"];
/// # let haystack = "append the app to the appendage";
/// # let ac = AhoCorasick::builder()
/// # .match_kind(MatchKind::LeftmostFirst)
/// # .build(patterns)
/// # .unwrap();
/// let mut result = String::new();
/// ac.try_replace_all_with(haystack, &mut result, |mat, _, dst| {
/// dst.push_str(&mat.pattern().as_usize().to_string());
/// mat.pattern() != PatternID::must(2)
/// })?;
/// assert_eq!("0 the 2 to the appendage", result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_replace_all_with<F>(
&self,
haystack: &str,
dst: &mut String,
replace_with: F,
) -> Result<(), MatchError>
where
F: FnMut(&Match, &str, &mut String) -> bool,
{
enforce_anchored_consistency(self.start_kind, Anchored::No)?;
self.aut.try_replace_all_with(haystack, dst, replace_with)
}
/// Replace all matches using raw bytes with a closure called on each
/// match. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// The closure accepts three parameters: the match found, the text of
/// the match and a byte buffer with which to write the replaced text
/// (if any). If the closure returns `true`, then it continues to the next
/// match. If the closure returns `false`, then searching is stopped.
///
/// This is the fallible version of
/// [`AhoCorasick::replace_all_with_bytes`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this replacement routine always does an unanchored search.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = b"append the app to the appendage";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let mut result = vec![];
/// ac.try_replace_all_with_bytes(haystack, &mut result, |mat, _, dst| {
/// dst.extend(mat.pattern().as_usize().to_string().bytes());
/// true
/// })?;
/// assert_eq!(b"0 the 2 to the 0age".to_vec(), result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Stopping the replacement by returning `false` (continued from the
/// example above):
///
/// ```
/// # use aho_corasick::{AhoCorasick, MatchKind, PatternID};
/// # let patterns = &["append", "appendage", "app"];
/// # let haystack = b"append the app to the appendage";
/// # let ac = AhoCorasick::builder()
/// # .match_kind(MatchKind::LeftmostFirst)
/// # .build(patterns)
/// # .unwrap();
/// let mut result = vec![];
/// ac.try_replace_all_with_bytes(haystack, &mut result, |mat, _, dst| {
/// dst.extend(mat.pattern().as_usize().to_string().bytes());
/// mat.pattern() != PatternID::must(2)
/// })?;
/// assert_eq!(b"0 the 2 to the appendage".to_vec(), result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn try_replace_all_with_bytes<F>(
&self,
haystack: &[u8],
dst: &mut Vec<u8>,
replace_with: F,
) -> Result<(), MatchError>
where
F: FnMut(&Match, &[u8], &mut Vec<u8>) -> bool,
{
enforce_anchored_consistency(self.start_kind, Anchored::No)?;
self.aut.try_replace_all_with_bytes(haystack, dst, replace_with)
}
/// Returns an iterator of non-overlapping matches in the given
/// stream. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// The matches yielded by this iterator use absolute position offsets in
/// the stream given, where the first byte has index `0`. Matches are
/// yieled until the stream is exhausted.
///
/// Each item yielded by the iterator is an `Result<Match,
/// std::io::Error>`, where an error is yielded if there was a problem
/// reading from the reader given.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible.
///
/// This is the fallible version of [`AhoCorasick::stream_find_iter`].
/// Note that both methods return iterators that produce `Result` values.
/// The difference is that this routine returns an error if _construction_
/// of the iterator failed. The `Result` values yield by the iterator
/// come from whether the given reader returns an error or not during the
/// search.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this stream searching routine always does an unanchored search.
///
/// This also returns an error if the searcher does not support stream
/// searches. Only searchers built with [`MatchKind::Standard`] semantics
/// support stream searches.
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut matches = vec![];
/// for result in ac.try_stream_find_iter(haystack.as_bytes())? {
/// let mat = result?;
/// matches.push(mat.pattern());
/// }
/// assert_eq!(vec![
/// PatternID::must(2),
/// PatternID::must(2),
/// PatternID::must(2),
/// ], matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
pub fn try_stream_find_iter<'a, R: std::io::Read>(
&'a self,
rdr: R,
) -> Result<StreamFindIter<'a, R>, MatchError> {
enforce_anchored_consistency(self.start_kind, Anchored::No)?;
self.aut.try_stream_find_iter(rdr).map(StreamFindIter)
}
/// Search for and replace all matches of this automaton in
/// the given reader, and write the replacements to the given
/// writer. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// Replacements are determined by the index of the matching pattern. For
/// example, if the pattern with index `2` is found, then it is replaced by
/// `replace_with[2]`.
///
/// After all matches are replaced, the writer is _not_ flushed.
///
/// If there was a problem reading from the given reader or writing to the
/// given writer, then the corresponding `io::Error` is returned and all
/// replacement is stopped.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible. However,
/// callers may want to provide a buffered writer.
///
/// Note that there is currently no infallible version of this routine.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Panics
///
/// This panics when `replace_with.len()` does not equal
/// [`AhoCorasick::patterns_len`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this stream searching routine always does an unanchored search.
///
/// This also returns an error if the searcher does not support stream
/// searches. Only searchers built with [`MatchKind::Standard`] semantics
/// support stream searches.
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let patterns = &["fox", "brown", "quick"];
/// let haystack = "The quick brown fox.";
/// let replace_with = &["sloth", "grey", "slow"];
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut result = vec![];
/// ac.try_stream_replace_all(
/// haystack.as_bytes(),
/// &mut result,
/// replace_with,
/// )?;
/// assert_eq!(b"The slow grey sloth.".to_vec(), result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
pub fn try_stream_replace_all<R, W, B>(
&self,
rdr: R,
wtr: W,
replace_with: &[B],
) -> Result<(), std::io::Error>
where
R: std::io::Read,
W: std::io::Write,
B: AsRef<[u8]>,
{
enforce_anchored_consistency(self.start_kind, Anchored::No)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
self.aut.try_stream_replace_all(rdr, wtr, replace_with)
}
/// Search the given reader and replace all matches of this automaton
/// using the given closure. The result is written to the given
/// writer. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// The closure accepts three parameters: the match found, the text of
/// the match and the writer with which to write the replaced text (if any).
///
/// After all matches are replaced, the writer is _not_ flushed.
///
/// If there was a problem reading from the given reader or writing to the
/// given writer, then the corresponding `io::Error` is returned and all
/// replacement is stopped.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible. However,
/// callers may want to provide a buffered writer.
///
/// Note that there is currently no infallible version of this routine.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this stream searching routine always does an unanchored search.
///
/// This also returns an error if the searcher does not support stream
/// searches. Only searchers built with [`MatchKind::Standard`] semantics
/// support stream searches.
///
/// # Example: basic usage
///
/// ```
/// use std::io::Write;
/// use aho_corasick::AhoCorasick;
///
/// let patterns = &["fox", "brown", "quick"];
/// let haystack = "The quick brown fox.";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut result = vec![];
/// ac.try_stream_replace_all_with(
/// haystack.as_bytes(),
/// &mut result,
/// |mat, _, wtr| {
/// wtr.write_all(mat.pattern().as_usize().to_string().as_bytes())
/// },
/// )?;
/// assert_eq!(b"The 2 1 0.".to_vec(), result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
pub fn try_stream_replace_all_with<R, W, F>(
&self,
rdr: R,
wtr: W,
replace_with: F,
) -> Result<(), std::io::Error>
where
R: std::io::Read,
W: std::io::Write,
F: FnMut(&Match, &[u8], &mut W) -> Result<(), std::io::Error>,
{
enforce_anchored_consistency(self.start_kind, Anchored::No)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
self.aut.try_stream_replace_all_with(rdr, wtr, replace_with)
}
}
/// Routines for querying information about the Aho-Corasick automaton.
impl AhoCorasick {
/// Returns the kind of the Aho-Corasick automaton used by this searcher.
///
/// Knowing the Aho-Corasick kind is principally useful for diagnostic
/// purposes. In particular, if no specific kind was given to
/// [`AhoCorasickBuilder::kind`], then one is automatically chosen and
/// this routine will report which one.
///
/// Note that the heuristics used for choosing which `AhoCorasickKind`
/// may be changed in a semver compatible release.
///
/// # Examples
///
/// ```
/// use aho_corasick::{AhoCorasick, AhoCorasickKind};
///
/// let ac = AhoCorasick::new(&["foo", "bar", "quux", "baz"]).unwrap();
/// // The specific Aho-Corasick kind chosen is not guaranteed!
/// assert_eq!(AhoCorasickKind::DFA, ac.kind());
/// ```
pub fn kind(&self) -> AhoCorasickKind {
self.kind
}
/// Returns the type of starting search configuration supported by this
/// Aho-Corasick automaton.
///
/// # Examples
///
/// ```
/// use aho_corasick::{AhoCorasick, StartKind};
///
/// let ac = AhoCorasick::new(&["foo", "bar", "quux", "baz"]).unwrap();
/// assert_eq!(StartKind::Unanchored, ac.start_kind());
/// ```
pub fn start_kind(&self) -> StartKind {
self.start_kind
}
/// Returns the match kind used by this automaton.
///
/// The match kind is important because it determines what kinds of
/// matches are returned. Also, some operations (such as overlapping
/// search and stream searching) are only supported when using the
/// [`MatchKind::Standard`] match kind.
///
/// # Examples
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let ac = AhoCorasick::new(&["foo", "bar", "quux", "baz"]).unwrap();
/// assert_eq!(MatchKind::Standard, ac.match_kind());
/// ```
pub fn match_kind(&self) -> MatchKind {
self.aut.match_kind()
}
/// Returns the length of the shortest pattern matched by this automaton.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let ac = AhoCorasick::new(&["foo", "bar", "quux", "baz"]).unwrap();
/// assert_eq!(3, ac.min_pattern_len());
/// ```
///
/// Note that an `AhoCorasick` automaton has a minimum length of `0` if
/// and only if it can match the empty string:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let ac = AhoCorasick::new(&["foo", "", "quux", "baz"]).unwrap();
/// assert_eq!(0, ac.min_pattern_len());
/// ```
pub fn min_pattern_len(&self) -> usize {
self.aut.min_pattern_len()
}
/// Returns the length of the longest pattern matched by this automaton.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let ac = AhoCorasick::new(&["foo", "bar", "quux", "baz"]).unwrap();
/// assert_eq!(4, ac.max_pattern_len());
/// ```
pub fn max_pattern_len(&self) -> usize {
self.aut.max_pattern_len()
}
/// Return the total number of patterns matched by this automaton.
///
/// This includes patterns that may never participate in a match. For
/// example, if [`MatchKind::LeftmostFirst`] match semantics are used, and
/// the patterns `Sam` and `Samwise` were used to build the automaton (in
/// that order), then `Samwise` can never participate in a match because
/// `Sam` will always take priority.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let ac = AhoCorasick::new(&["foo", "bar", "baz"]).unwrap();
/// assert_eq!(3, ac.patterns_len());
/// ```
pub fn patterns_len(&self) -> usize {
self.aut.patterns_len()
}
/// Returns the approximate total amount of heap used by this automaton, in
/// units of bytes.
///
/// # Examples
///
/// This example shows the difference in heap usage between a few
/// configurations:
///
/// ```
/// # if !cfg!(target_pointer_width = "64") { return; }
/// use aho_corasick::{AhoCorasick, AhoCorasickKind, MatchKind};
///
/// let ac = AhoCorasick::builder()
/// .kind(None) // default
/// .build(&["foobar", "bruce", "triskaidekaphobia", "springsteen"])
/// .unwrap();
/// assert_eq!(5_632, ac.memory_usage());
///
/// let ac = AhoCorasick::builder()
/// .kind(None) // default
/// .ascii_case_insensitive(true)
/// .build(&["foobar", "bruce", "triskaidekaphobia", "springsteen"])
/// .unwrap();
/// assert_eq!(11_136, ac.memory_usage());
///
/// let ac = AhoCorasick::builder()
/// .kind(Some(AhoCorasickKind::NoncontiguousNFA))
/// .ascii_case_insensitive(true)
/// .build(&["foobar", "bruce", "triskaidekaphobia", "springsteen"])
/// .unwrap();
/// assert_eq!(9_128, ac.memory_usage());
///
/// let ac = AhoCorasick::builder()
/// .kind(Some(AhoCorasickKind::ContiguousNFA))
/// .ascii_case_insensitive(true)
/// .build(&["foobar", "bruce", "triskaidekaphobia", "springsteen"])
/// .unwrap();
/// assert_eq!(2_584, ac.memory_usage());
///
/// let ac = AhoCorasick::builder()
/// .kind(Some(AhoCorasickKind::DFA))
/// .ascii_case_insensitive(true)
/// .build(&["foobar", "bruce", "triskaidekaphobia", "springsteen"])
/// .unwrap();
/// // While this shows the DFA being the biggest here by a small margin,
/// // don't let the difference fool you. With such a small number of
/// // patterns, the difference is small, but a bigger number of patterns
/// // will reveal that the rate of growth of the DFA is far bigger than
/// // the NFAs above. For a large number of patterns, it is easy for the
/// // DFA to take an order of magnitude more heap space (or more!).
/// assert_eq!(11_136, ac.memory_usage());
/// ```
pub fn memory_usage(&self) -> usize {
self.aut.memory_usage()
}
}
// We provide a manual debug impl so that we don't include the 'start_kind',
// principally because it's kind of weird to do so and because it screws with
// the carefully curated debug output for the underlying automaton.
impl core::fmt::Debug for AhoCorasick {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_tuple("AhoCorasick").field(&self.aut).finish()
}
}
/// An iterator of non-overlapping matches in a particular haystack.
///
/// This iterator yields matches according to the [`MatchKind`] used by this
/// automaton.
///
/// This iterator is constructed via the [`AhoCorasick::find_iter`] and
/// [`AhoCorasick::try_find_iter`] methods.
///
/// The lifetime `'a` refers to the lifetime of the `AhoCorasick` automaton.
///
/// The lifetime `'h` refers to the lifetime of the haystack being searched.
#[derive(Debug)]
pub struct FindIter<'a, 'h>(automaton::FindIter<'a, 'h, Arc<dyn AcAutomaton>>);
impl<'a, 'h> Iterator for FindIter<'a, 'h> {
type Item = Match;
#[inline]
fn next(&mut self) -> Option<Match> {
self.0.next()
}
}
/// An iterator of overlapping matches in a particular haystack.
///
/// This iterator will report all possible matches in a particular haystack,
/// even when the matches overlap.
///
/// This iterator is constructed via the [`AhoCorasick::find_overlapping_iter`]
/// and [`AhoCorasick::try_find_overlapping_iter`] methods.
///
/// The lifetime `'a` refers to the lifetime of the `AhoCorasick` automaton.
///
/// The lifetime `'h` refers to the lifetime of the haystack being searched.
#[derive(Debug)]
pub struct FindOverlappingIter<'a, 'h>(
automaton::FindOverlappingIter<'a, 'h, Arc<dyn AcAutomaton>>,
);
impl<'a, 'h> Iterator for FindOverlappingIter<'a, 'h> {
type Item = Match;
#[inline]
fn next(&mut self) -> Option<Match> {
self.0.next()
}
}
/// An iterator that reports Aho-Corasick matches in a stream.
///
/// This iterator yields elements of type `Result<Match, std::io::Error>`,
/// where an error is reported if there was a problem reading from the
/// underlying stream. The iterator terminates only when the underlying stream
/// reaches `EOF`.
///
/// This iterator is constructed via the [`AhoCorasick::stream_find_iter`] and
/// [`AhoCorasick::try_stream_find_iter`] methods.
///
/// The type variable `R` refers to the `io::Read` stream that is being read
/// from.
///
/// The lifetime `'a` refers to the lifetime of the corresponding
/// [`AhoCorasick`] searcher.
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct StreamFindIter<'a, R>(
automaton::StreamFindIter<'a, Arc<dyn AcAutomaton>, R>,
);
#[cfg(feature = "std")]
impl<'a, R: std::io::Read> Iterator for StreamFindIter<'a, R> {
type Item = Result<Match, std::io::Error>;
fn next(&mut self) -> Option<Result<Match, std::io::Error>> {
self.0.next()
}
}
/// A builder for configuring an Aho-Corasick automaton.
///
/// # Quick advice
///
/// * Use [`AhoCorasickBuilder::match_kind`] to configure your searcher
/// with [`MatchKind::LeftmostFirst`] if you want to match how backtracking
/// regex engines execute searches for `pat1|pat2|..|patN`. Use
/// [`MatchKind::LeftmostLongest`] if you want to match how POSIX regex engines
/// do it.
/// * If you need an anchored search, use [`AhoCorasickBuilder::start_kind`] to
/// set the [`StartKind::Anchored`] mode since [`StartKind::Unanchored`] is the
/// default. Or just use [`StartKind::Both`] to support both types of searches.
/// * You might want to use [`AhoCorasickBuilder::kind`] to set your searcher
/// to always use a [`AhoCorasickKind::DFA`] if search speed is critical and
/// memory usage isn't a concern. Otherwise, not setting a kind will probably
/// make the right choice for you. Beware that if you use [`StartKind::Both`]
/// to build a searcher that supports both unanchored and anchored searches
/// _and_ you set [`AhoCorasickKind::DFA`], then the DFA will essentially be
/// duplicated to support both simultaneously. This results in very high memory
/// usage.
/// * For all other options, their defaults are almost certainly what you want.
#[derive(Clone, Debug, Default)]
pub struct AhoCorasickBuilder {
nfa_noncontiguous: noncontiguous::Builder,
nfa_contiguous: contiguous::Builder,
dfa: dfa::Builder,
kind: Option<AhoCorasickKind>,
start_kind: StartKind,
}
impl AhoCorasickBuilder {
/// Create a new builder for configuring an Aho-Corasick automaton.
///
/// The builder provides a way to configure a number of things, including
/// ASCII case insensitivity and what kind of match semantics are used.
pub fn new() -> AhoCorasickBuilder {
AhoCorasickBuilder::default()
}
/// Build an Aho-Corasick automaton using the configuration set on this
/// builder.
///
/// A builder may be reused to create more automatons.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::{AhoCorasickBuilder, PatternID};
///
/// let patterns = &["foo", "bar", "baz"];
/// let ac = AhoCorasickBuilder::new().build(patterns).unwrap();
/// assert_eq!(
/// Some(PatternID::must(1)),
/// ac.find("xxx bar xxx").map(|m| m.pattern()),
/// );
/// ```
pub fn build<I, P>(&self, patterns: I) -> Result<AhoCorasick, BuildError>
where
I: IntoIterator<Item = P>,
P: AsRef<[u8]>,
{
let nfa = self.nfa_noncontiguous.build(patterns)?;
let (aut, kind): (Arc<dyn AcAutomaton>, AhoCorasickKind) =
match self.kind {
None => {
debug!(
"asked for automatic Aho-Corasick implementation, \
criteria: <patterns: {:?}, max pattern len: {:?}, \
start kind: {:?}>",
nfa.patterns_len(),
nfa.max_pattern_len(),
self.start_kind,
);
self.build_auto(nfa)
}
Some(AhoCorasickKind::NoncontiguousNFA) => {
debug!("forcefully chose noncontiguous NFA");
(Arc::new(nfa), AhoCorasickKind::NoncontiguousNFA)
}
Some(AhoCorasickKind::ContiguousNFA) => {
debug!("forcefully chose contiguous NFA");
let cnfa =
self.nfa_contiguous.build_from_noncontiguous(&nfa)?;
(Arc::new(cnfa), AhoCorasickKind::ContiguousNFA)
}
Some(AhoCorasickKind::DFA) => {
debug!("forcefully chose DFA");
let dfa = self.dfa.build_from_noncontiguous(&nfa)?;
(Arc::new(dfa), AhoCorasickKind::DFA)
}
};
Ok(AhoCorasick { aut, kind, start_kind: self.start_kind })
}
/// Implements the automatic selection logic for the Aho-Corasick
/// implementation to use. Since all Aho-Corasick automatons are built
/// from a non-contiguous NFA, the caller is responsible for building
/// that first.
fn build_auto(
&self,
nfa: noncontiguous::NFA,
) -> (Arc<dyn AcAutomaton>, AhoCorasickKind) {
// We try to build a DFA if we have a very small number of patterns,
// otherwise the memory usage just gets too crazy. We also only do it
// when the start kind is unanchored or anchored, but not both, because
// both implies two full copies of the transition table.
let try_dfa = !matches!(self.start_kind, StartKind::Both)
&& nfa.patterns_len() <= 100;
if try_dfa {
match self.dfa.build_from_noncontiguous(&nfa) {
Ok(dfa) => {
debug!("chose a DFA");
return (Arc::new(dfa), AhoCorasickKind::DFA);
}
Err(_err) => {
debug!(
"failed to build DFA, trying something else: {}",
_err
);
}
}
}
// We basically always want a contiguous NFA if the limited
// circumstances in which we use a DFA are not true. It is quite fast
// and has excellent memory usage. The only way we don't use it is if
// there are so many states that it can't fit in a contiguous NFA.
// And the only way to know that is to try to build it. Building a
// contiguous NFA is mostly just reshuffling data from a noncontiguous
// NFA, so it isn't too expensive, especially relative to building a
// noncontiguous NFA in the first place.
match self.nfa_contiguous.build_from_noncontiguous(&nfa) {
Ok(nfa) => {
debug!("chose contiguous NFA");
return (Arc::new(nfa), AhoCorasickKind::ContiguousNFA);
}
#[allow(unused_variables)] // unused when 'logging' is disabled
Err(_err) => {
debug!(
"failed to build contiguous NFA, \
trying something else: {}",
_err
);
}
}
debug!("chose non-contiguous NFA");
(Arc::new(nfa), AhoCorasickKind::NoncontiguousNFA)
}
/// Set the desired match semantics.
///
/// The default is [`MatchKind::Standard`], which corresponds to the match
/// semantics supported by the standard textbook description of the
/// Aho-Corasick algorithm. Namely, matches are reported as soon as they
/// are found. Moreover, this is the only way to get overlapping matches
/// or do stream searching.
///
/// The other kinds of match semantics that are supported are
/// [`MatchKind::LeftmostFirst`] and [`MatchKind::LeftmostLongest`]. The
/// former corresponds to the match you would get if you were to try to
/// match each pattern at each position in the haystack in the same order
/// that you give to the automaton. That is, it returns the leftmost match
/// corresponding to the earliest pattern given to the automaton. The
/// latter corresponds to finding the longest possible match among all
/// leftmost matches.
///
/// For more details on match semantics, see the [documentation for
/// `MatchKind`](MatchKind).
///
/// Note that setting this to [`MatchKind::LeftmostFirst`] or
/// [`MatchKind::LeftmostLongest`] will cause some search routines on
/// [`AhoCorasick`] to return an error (or panic if you're using the
/// infallible API). Notably, this includes stream and overlapping
/// searches.
///
/// # Examples
///
/// In these examples, we demonstrate the differences between match
/// semantics for a particular set of patterns in a specific order:
/// `b`, `abc`, `abcd`.
///
/// Standard semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::Standard) // default, not necessary
/// .build(patterns)
/// .unwrap();
/// let mat = ac.find(haystack).expect("should have a match");
/// assert_eq!("b", &haystack[mat.start()..mat.end()]);
/// ```
///
/// Leftmost-first semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .build(patterns)
/// .unwrap();
/// let mat = ac.find(haystack).expect("should have a match");
/// assert_eq!("abc", &haystack[mat.start()..mat.end()]);
/// ```
///
/// Leftmost-longest semantics:
///
/// ```
/// use aho_corasick::{AhoCorasick, MatchKind};
///
/// let patterns = &["b", "abc", "abcd"];
/// let haystack = "abcd";
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostLongest)
/// .build(patterns)
/// .unwrap();
/// let mat = ac.find(haystack).expect("should have a match");
/// assert_eq!("abcd", &haystack[mat.start()..mat.end()]);
/// ```
pub fn match_kind(&mut self, kind: MatchKind) -> &mut AhoCorasickBuilder {
self.nfa_noncontiguous.match_kind(kind);
self.nfa_contiguous.match_kind(kind);
self.dfa.match_kind(kind);
self
}
/// Sets the starting state configuration for the automaton.
///
/// Every Aho-Corasick automaton is capable of having two start states: one
/// that is used for unanchored searches and one that is used for anchored
/// searches. Some automatons, like the NFAs, support this with almost zero
/// additional cost. Other automatons, like the DFA, require two copies of
/// the underlying transition table to support both simultaneously.
///
/// Because there may be an added non-trivial cost to supporting both, it
/// is possible to configure which starting state configuration is needed.
///
/// Indeed, since anchored searches tend to be somewhat more rare,
/// _only_ unanchored searches are supported by default. Thus,
/// [`StartKind::Unanchored`] is the default.
///
/// Note that when this is set to [`StartKind::Unanchored`], then
/// running an anchored search will result in an error (or a panic
/// if using the infallible APIs). Similarly, when this is set to
/// [`StartKind::Anchored`], then running an unanchored search will
/// result in an error (or a panic if using the infallible APIs). When
/// [`StartKind::Both`] is used, then both unanchored and anchored searches
/// are always supported.
///
/// Also note that even if an `AhoCorasick` searcher is using an NFA
/// internally (which always supports both unanchored and anchored
/// searches), an error will still be reported for a search that isn't
/// supported by the configuration set via this method. This means,
/// for example, that an error is never dependent on which internal
/// implementation of Aho-Corasick is used.
///
/// # Example: anchored search
///
/// This shows how to build a searcher that only supports anchored
/// searches:
///
/// ```
/// use aho_corasick::{
/// AhoCorasick, Anchored, Input, Match, MatchKind, StartKind,
/// };
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .start_kind(StartKind::Anchored)
/// .build(&["b", "abc", "abcd"])
/// .unwrap();
///
/// // An unanchored search is not supported! An error here is guaranteed
/// // given the configuration above regardless of which kind of
/// // Aho-Corasick implementation ends up being used internally.
/// let input = Input::new("foo abcd").anchored(Anchored::No);
/// assert!(ac.try_find(input).is_err());
///
/// let input = Input::new("foo abcd").anchored(Anchored::Yes);
/// assert_eq!(None, ac.try_find(input)?);
///
/// let input = Input::new("abcd").anchored(Anchored::Yes);
/// assert_eq!(Some(Match::must(1, 0..3)), ac.try_find(input)?);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: unanchored and anchored searches
///
/// This shows how to build a searcher that supports both unanchored and
/// anchored searches:
///
/// ```
/// use aho_corasick::{
/// AhoCorasick, Anchored, Input, Match, MatchKind, StartKind,
/// };
///
/// let ac = AhoCorasick::builder()
/// .match_kind(MatchKind::LeftmostFirst)
/// .start_kind(StartKind::Both)
/// .build(&["b", "abc", "abcd"])
/// .unwrap();
///
/// let input = Input::new("foo abcd").anchored(Anchored::No);
/// assert_eq!(Some(Match::must(1, 4..7)), ac.try_find(input)?);
///
/// let input = Input::new("foo abcd").anchored(Anchored::Yes);
/// assert_eq!(None, ac.try_find(input)?);
///
/// let input = Input::new("abcd").anchored(Anchored::Yes);
/// assert_eq!(Some(Match::must(1, 0..3)), ac.try_find(input)?);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn start_kind(&mut self, kind: StartKind) -> &mut AhoCorasickBuilder {
self.dfa.start_kind(kind);
self.start_kind = kind;
self
}
/// Enable ASCII-aware case insensitive matching.
///
/// When this option is enabled, searching will be performed without
/// respect to case for ASCII letters (`a-z` and `A-Z`) only.
///
/// Enabling this option does not change the search algorithm, but it may
/// increase the size of the automaton.
///
/// **NOTE:** It is unlikely that support for Unicode case folding will
/// be added in the future. The ASCII case works via a simple hack to the
/// underlying automaton, but full Unicode handling requires a fair bit of
/// sophistication. If you do need Unicode handling, you might consider
/// using the [`regex` crate](https://docs.rs/regex) or the lower level
/// [`regex-automata` crate](https://docs.rs/regex-automata).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let patterns = &["FOO", "bAr", "BaZ"];
/// let haystack = "foo bar baz";
///
/// let ac = AhoCorasick::builder()
/// .ascii_case_insensitive(true)
/// .build(patterns)
/// .unwrap();
/// assert_eq!(3, ac.find_iter(haystack).count());
/// ```
pub fn ascii_case_insensitive(
&mut self,
yes: bool,
) -> &mut AhoCorasickBuilder {
self.nfa_noncontiguous.ascii_case_insensitive(yes);
self.nfa_contiguous.ascii_case_insensitive(yes);
self.dfa.ascii_case_insensitive(yes);
self
}
/// Choose the type of underlying automaton to use.
///
/// Currently, there are four choices:
///
/// * [`AhoCorasickKind::NoncontiguousNFA`] instructs the searcher to
/// use a [`noncontiguous::NFA`]. A noncontiguous NFA is the fastest to
/// be built, has moderate memory usage and is typically the slowest to
/// execute a search.
/// * [`AhoCorasickKind::ContiguousNFA`] instructs the searcher to use a
/// [`contiguous::NFA`]. A contiguous NFA is a little slower to build than
/// a noncontiguous NFA, has excellent memory usage and is typically a
/// little slower than a DFA for a search.
/// * [`AhoCorasickKind::DFA`] instructs the searcher to use a
/// [`dfa::DFA`]. A DFA is very slow to build, uses exorbitant amounts of
/// memory, but will typically execute searches the fastest.
/// * `None` (the default) instructs the searcher to choose the "best"
/// Aho-Corasick implementation. This choice is typically based primarily
/// on the number of patterns.
///
/// Setting this configuration does not change the time complexity for
/// constructing the Aho-Corasick automaton (which is `O(p)` where `p`
/// is the total number of patterns being compiled). Setting this to
/// [`AhoCorasickKind::DFA`] does however reduce the time complexity of
/// non-overlapping searches from `O(n + p)` to `O(n)`, where `n` is the
/// length of the haystack.
///
/// In general, you should probably stick to the default unless you have
/// some kind of reason to use a specific Aho-Corasick implementation. For
/// example, you might choose `AhoCorasickKind::DFA` if you don't care
/// about memory usage and want the fastest possible search times.
///
/// Setting this guarantees that the searcher returned uses the chosen
/// implementation. If that implementation could not be constructed, then
/// an error will be returned. In contrast, when `None` is used, it is
/// possible for it to attempt to construct, for example, a contiguous
/// NFA and have it fail. In which case, it will fall back to using a
/// noncontiguous NFA.
///
/// If `None` is given, then one may use [`AhoCorasick::kind`] to determine
/// which Aho-Corasick implementation was chosen.
///
/// Note that the heuristics used for choosing which `AhoCorasickKind`
/// may be changed in a semver compatible release.
pub fn kind(
&mut self,
kind: Option<AhoCorasickKind>,
) -> &mut AhoCorasickBuilder {
self.kind = kind;
self
}
/// Enable heuristic prefilter optimizations.
///
/// When enabled, searching will attempt to quickly skip to match
/// candidates using specialized literal search routines. A prefilter
/// cannot always be used, and is generally treated as a heuristic. It
/// can be useful to disable this if the prefilter is observed to be
/// sub-optimal for a particular workload.
///
/// Currently, prefilters are typically only active when building searchers
/// with a small (less than 100) number of patterns.
///
/// This is enabled by default.
pub fn prefilter(&mut self, yes: bool) -> &mut AhoCorasickBuilder {
self.nfa_noncontiguous.prefilter(yes);
self.nfa_contiguous.prefilter(yes);
self.dfa.prefilter(yes);
self
}
/// Set the limit on how many states use a dense representation for their
/// transitions. Other states will generally use a sparse representation.
///
/// A dense representation uses more memory but is generally faster, since
/// the next transition in a dense representation can be computed in a
/// constant number of instructions. A sparse representation uses less
/// memory but is generally slower, since the next transition in a sparse
/// representation requires executing a variable number of instructions.
///
/// This setting is only used when an Aho-Corasick implementation is used
/// that supports the dense versus sparse representation trade off. Not all
/// do.
///
/// This limit is expressed in terms of the depth of a state, i.e., the
/// number of transitions from the starting state of the automaton. The
/// idea is that most of the time searching will be spent near the starting
/// state of the automaton, so states near the start state should use a
/// dense representation. States further away from the start state would
/// then use a sparse representation.
///
/// By default, this is set to a low but non-zero number. Setting this to
/// `0` is almost never what you want, since it is likely to make searches
/// very slow due to the start state itself being forced to use a sparse
/// representation. However, it is unlikely that increasing this number
/// will help things much, since the most active states have a small depth.
/// More to the point, the memory usage increases superlinearly as this
/// number increases.
pub fn dense_depth(&mut self, depth: usize) -> &mut AhoCorasickBuilder {
self.nfa_contiguous.dense_depth(depth);
self
}
/// A debug settting for whether to attempt to shrink the size of the
/// automaton's alphabet or not.
///
/// This option is enabled by default and should never be disabled unless
/// one is debugging the underlying automaton.
///
/// When enabled, some (but not all) Aho-Corasick automatons will use a map
/// from all possible bytes to their corresponding equivalence class. Each
/// equivalence class represents a set of bytes that does not discriminate
/// between a match and a non-match in the automaton.
///
/// The advantage of this map is that the size of the transition table can
/// be reduced drastically from `#states * 256 * sizeof(u32)` to
/// `#states * k * sizeof(u32)` where `k` is the number of equivalence
/// classes (rounded up to the nearest power of 2). As a result, total
/// space usage can decrease substantially. Moreover, since a smaller
/// alphabet is used, automaton compilation becomes faster as well.
///
/// **WARNING:** This is only useful for debugging automatons. Disabling
/// this does not yield any speed advantages. Namely, even when this is
/// disabled, a byte class map is still used while searching. The only
/// difference is that every byte will be forced into its own distinct
/// equivalence class. This is useful for debugging the actual generated
/// transitions because it lets one see the transitions defined on actual
/// bytes instead of the equivalence classes.
pub fn byte_classes(&mut self, yes: bool) -> &mut AhoCorasickBuilder {
self.nfa_contiguous.byte_classes(yes);
self.dfa.byte_classes(yes);
self
}
}
/// The type of Aho-Corasick implementation to use in an [`AhoCorasick`]
/// searcher.
///
/// This is principally used as an input to the
/// [`AhoCorasickBuilder::start_kind`] method. Its documentation goes into more
/// detail about each choice.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AhoCorasickKind {
/// Use a noncontiguous NFA.
NoncontiguousNFA,
/// Use a contiguous NFA.
ContiguousNFA,
/// Use a DFA. Warning: DFAs typically use a large amount of memory.
DFA,
}
/// A trait that effectively gives us practical dynamic dispatch over anything
/// that impls `Automaton`, but without needing to add a bunch of bounds to
/// the core `Automaton` trait. Basically, we provide all of the marker traits
/// that our automatons have, in addition to `Debug` impls and requiring that
/// there is no borrowed data. Without these, the main `AhoCorasick` type would
/// not be able to meaningfully impl `Debug` or the marker traits without also
/// requiring that all impls of `Automaton` do so, which would be not great.
trait AcAutomaton:
Automaton + Debug + Send + Sync + UnwindSafe + RefUnwindSafe + 'static
{
}
impl<A> AcAutomaton for A where
A: Automaton + Debug + Send + Sync + UnwindSafe + RefUnwindSafe + 'static
{
}
impl crate::automaton::private::Sealed for Arc<dyn AcAutomaton> {}
// I'm not sure why this trait impl shows up in the docs, as the AcAutomaton
// trait is not exported. So we forcefully hide it.
//
// SAFETY: This just defers to the underlying 'AcAutomaton' and thus inherits
// its safety properties.
#[doc(hidden)]
unsafe impl Automaton for Arc<dyn AcAutomaton> {
#[inline(always)]
fn start_state(&self, anchored: Anchored) -> Result<StateID, MatchError> {
(**self).start_state(anchored)
}
#[inline(always)]
fn next_state(
&self,
anchored: Anchored,
sid: StateID,
byte: u8,
) -> StateID {
(**self).next_state(anchored, sid, byte)
}
#[inline(always)]
fn is_special(&self, sid: StateID) -> bool {
(**self).is_special(sid)
}
#[inline(always)]
fn is_dead(&self, sid: StateID) -> bool {
(**self).is_dead(sid)
}
#[inline(always)]
fn is_match(&self, sid: StateID) -> bool {
(**self).is_match(sid)
}
#[inline(always)]
fn is_start(&self, sid: StateID) -> bool {
(**self).is_start(sid)
}
#[inline(always)]
fn match_kind(&self) -> MatchKind {
(**self).match_kind()
}
#[inline(always)]
fn match_len(&self, sid: StateID) -> usize {
(**self).match_len(sid)
}
#[inline(always)]
fn match_pattern(&self, sid: StateID, index: usize) -> PatternID {
(**self).match_pattern(sid, index)
}
#[inline(always)]
fn patterns_len(&self) -> usize {
(**self).patterns_len()
}
#[inline(always)]
fn pattern_len(&self, pid: PatternID) -> usize {
(**self).pattern_len(pid)
}
#[inline(always)]
fn min_pattern_len(&self) -> usize {
(**self).min_pattern_len()
}
#[inline(always)]
fn max_pattern_len(&self) -> usize {
(**self).max_pattern_len()
}
#[inline(always)]
fn memory_usage(&self) -> usize {
(**self).memory_usage()
}
#[inline(always)]
fn prefilter(&self) -> Option<&Prefilter> {
(**self).prefilter()
}
// Even though 'try_find' and 'try_find_overlapping' each have their
// own default impls, we explicitly define them here to fix a perf bug.
// Without these explicit definitions, the default impl will wind up using
// dynamic dispatch for all 'Automaton' method calls, including things like
// 'next_state' that absolutely must get inlined or else perf is trashed.
// Defining them explicitly here like this still requires dynamic dispatch
// to call 'try_find' itself, but all uses of 'Automaton' within 'try_find'
// are monomorphized.
//
// We don't need to explicitly impl any other methods, I think, because
// they are all implemented themselves in terms of 'try_find' and
// 'try_find_overlapping'. We still might wind up with an extra virtual
// call here or there, but that's okay since it's outside of any perf
// critical areas.
#[inline(always)]
fn try_find(
&self,
input: &Input<'_>,
) -> Result<Option<Match>, MatchError> {
(**self).try_find(input)
}
#[inline(always)]
fn try_find_overlapping(
&self,
input: &Input<'_>,
state: &mut OverlappingState,
) -> Result<(), MatchError> {
(**self).try_find_overlapping(input, state)
}
}
/// Returns an error if the start state configuration does not support the
/// desired search configuration. See the internal 'AhoCorasick::start_kind'
/// field docs for more details.
fn enforce_anchored_consistency(
have: StartKind,
want: Anchored,
) -> Result<(), MatchError> {
match have {
StartKind::Both => Ok(()),
StartKind::Unanchored if !want.is_anchored() => Ok(()),
StartKind::Unanchored => Err(MatchError::invalid_input_anchored()),
StartKind::Anchored if want.is_anchored() => Ok(()),
StartKind::Anchored => Err(MatchError::invalid_input_unanchored()),
}
}