1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
//! Bitap algorithm for fast fuzzy string matching.
//!
//! The Bitap algorithm (also known as shift-or or shift-and) uses bitwise
//! operations to perform fuzzy matching very efficiently for short patterns
//! (up to 64 characters).
//!
//! Time complexity: O(n × k) where n = text length, k = max edits
//! Each step involves only a few bitwise operations.
#![allow(
clippy::needless_range_loop,
clippy::items_after_statements,
clippy::too_many_lines,
clippy::inline_always
)]
use super::damlev::{DamLevMatch, EditLimits};
use super::hash::FxHashMap;
/// Fast UTF-8 character decoder - avoids `str::from_utf8` + `chars().next()` overhead.
/// Returns (char, `byte_length`).
///
/// # Safety
/// Assumes input is valid UTF-8. Invalid sequences return replacement char.
#[inline(always)]
fn decode_utf8_char_fast(bytes: &[u8], pos: usize) -> (char, usize) {
let b0 = bytes[pos];
if b0 < 128 {
// ASCII: single byte
(b0 as char, 1)
} else if b0 < 224 {
// 2-byte UTF-8 (Latin Extended, Cyrillic, etc.)
if pos + 1 < bytes.len() {
let b1 = bytes[pos + 1];
let codepoint = ((u32::from(b0) & 0x1F) << 6) | (u32::from(b1) & 0x3F);
// SAFETY: Valid 2-byte UTF-8 always produces valid codepoint in 0x80-0x7FF range
(unsafe { char::from_u32_unchecked(codepoint) }, 2)
} else {
('\u{FFFD}', 1)
}
} else if b0 < 240 {
// 3-byte UTF-8 (CJK, etc.)
if pos + 2 < bytes.len() {
let b1 = bytes[pos + 1];
let b2 = bytes[pos + 2];
let codepoint = ((u32::from(b0) & 0x0F) << 12)
| ((u32::from(b1) & 0x3F) << 6)
| (u32::from(b2) & 0x3F);
// SAFETY: Valid 3-byte UTF-8 produces valid codepoint (excluding surrogates handled by validation)
(unsafe { char::from_u32_unchecked(codepoint) }, 3)
} else {
('\u{FFFD}', 1)
}
} else {
// 4-byte UTF-8 (Emoji, etc.)
if pos + 3 < bytes.len() {
let b1 = bytes[pos + 1];
let b2 = bytes[pos + 2];
let b3 = bytes[pos + 3];
let codepoint = ((u32::from(b0) & 0x07) << 18)
| ((u32::from(b1) & 0x3F) << 12)
| ((u32::from(b2) & 0x3F) << 6)
| (u32::from(b3) & 0x3F);
// SAFETY: Valid 4-byte UTF-8 always produces valid codepoint
(unsafe { char::from_u32_unchecked(codepoint) }, 4)
} else {
('\u{FFFD}', 1)
}
}
}
/// Maximum pattern length supported by Bitap (using u64 bitmasks).
pub const MAX_PATTERN_LEN: usize = 64;
/// Bitap matcher for fuzzy string matching.
#[derive(Debug)]
pub struct BitapMatcher {
pattern: String,
pattern_chars: Vec<char>,
pattern_len: usize,
limits: EditLimits,
case_insensitive: bool,
/// Character masks: for each character, a bitmask where bit i is 0
/// if pattern[i] == character.
char_masks: FxHashMap<char, u64>,
/// ASCII byte masks for O(1) lookup (all 1s = no match).
byte_masks: [u64; 128],
/// Boyer-Moore style skip table: how far to skip when a byte is NOT in pattern.
/// For bytes in pattern: 0 (can't skip). For bytes not in pattern: `pattern_len` - `max_edits`.
skip_table: [u8; 256],
/// Whether the pattern is pure ASCII.
is_ascii: bool,
/// Mask with 1 in the position of the last pattern character.
accept_mask: u64,
/// Unicode block masks for O(1) lookup of non-ASCII characters.
/// If all pattern chars are in the same 256-codepoint block, we use this instead of `HashMap`.
/// `block_base` is the start codepoint (e.g., 0x0400 for Cyrillic).
unicode_block_base: u32,
unicode_block_masks: Option<Box<[u64; 256]>>,
}
impl BitapMatcher {
/// Create a new Bitap matcher.
///
/// Returns None if the pattern is too long (> 64 chars).
pub fn new(pattern: &str, limits: EditLimits, case_insensitive: bool) -> Option<Self> {
let pattern_chars: Vec<char> = if case_insensitive {
pattern.to_lowercase().chars().collect()
} else {
pattern.chars().collect()
};
if pattern_chars.len() > MAX_PATTERN_LEN || pattern_chars.is_empty() {
return None;
}
let pattern_len = pattern_chars.len();
let is_ascii = pattern_chars.iter().all(char::is_ascii);
// Build character masks
// For each character in the alphabet, create a bitmask where bit i is 0
// if pattern[i] matches the character, 1 otherwise.
// We use the "shift-or" variant where 0 means match.
let mut char_masks: FxHashMap<char, u64> = FxHashMap::default();
let mut byte_masks = [!0u64; 128]; // All 1s = no match
for (i, &ch) in pattern_chars.iter().enumerate() {
// Set bit i to 0 for this character (start with all 1s, clear bit i)
let mask = char_masks.entry(ch).or_insert(!0u64);
*mask &= !(1u64 << i);
// Also update byte_masks for ASCII characters
if ch.is_ascii() {
let byte = ch as u8;
byte_masks[byte as usize] &= !(1u64 << i);
// Handle case insensitivity for ASCII
if case_insensitive {
if byte.is_ascii_lowercase() {
byte_masks[byte.to_ascii_uppercase() as usize] &= !(1u64 << i);
} else if byte.is_ascii_uppercase() {
byte_masks[byte.to_ascii_lowercase() as usize] &= !(1u64 << i);
}
}
}
}
// Accept mask: 1 in position (pattern_len - 1)
let accept_mask = 1u64 << (pattern_len - 1);
// Build Boyer-Moore style skip table
// If a byte is not in the pattern, we can skip ahead when we see it
let max_edits = limits.max_edits as usize;
let skip_distance = pattern_len.saturating_sub(max_edits).max(1) as u8;
let mut skip_table = [skip_distance; 256];
// Bytes that ARE in the pattern can't be skipped
for &ch in &pattern_chars {
if ch.is_ascii() {
skip_table[ch as usize] = 0;
// Also mark case variants
if case_insensitive {
if ch.is_ascii_lowercase() {
skip_table[ch.to_ascii_uppercase() as usize] = 0;
} else if ch.is_ascii_uppercase() {
skip_table[ch.to_ascii_lowercase() as usize] = 0;
}
}
}
}
// Build Unicode block lookup table for non-ASCII patterns.
// If all pattern chars fall within a single 256-codepoint block, we can use O(1) array lookup.
let (unicode_block_base, unicode_block_masks) =
Self::build_unicode_block_masks(&pattern_chars, &char_masks);
Some(BitapMatcher {
pattern: pattern.to_string(),
pattern_chars,
pattern_len,
limits,
case_insensitive,
char_masks,
byte_masks,
skip_table,
is_ascii,
accept_mask,
unicode_block_base,
unicode_block_masks,
})
}
/// Returns the original pattern string.
#[must_use]
pub fn pattern(&self) -> &str {
&self.pattern
}
/// Returns the pattern as a slice of characters.
#[must_use]
pub fn pattern_chars(&self) -> &[char] {
&self.pattern_chars
}
/// Build Unicode block lookup table for O(1) character mask access.
/// Returns (`block_base`, `Some(masks)`) if all non-ASCII chars are in a single 256-codepoint block.
fn build_unicode_block_masks(
pattern_chars: &[char],
char_masks: &FxHashMap<char, u64>,
) -> (u32, Option<Box<[u64; 256]>>) {
// Find non-ASCII characters
let non_ascii: Vec<char> = pattern_chars
.iter()
.filter(|c| !c.is_ascii())
.copied()
.collect();
if non_ascii.is_empty() {
return (0, None);
}
// Check if all non-ASCII chars are in the same 256-codepoint block
let first_cp = non_ascii[0] as u32;
let block_base = first_cp & !0xFF; // Round down to block start (e.g., 0x0400 for Cyrillic)
let all_in_block = non_ascii.iter().all(|&ch| {
let cp = ch as u32;
(cp & !0xFF) == block_base
});
if !all_in_block {
return (0, None);
}
// Build the lookup table
let mut masks = Box::new([!0u64; 256]);
for (&ch, &mask) in char_masks {
let cp = ch as u32;
if (cp & !0xFF) == block_base {
let idx = (cp & 0xFF) as usize;
masks[idx] = mask;
}
}
(block_base, Some(masks))
}
/// Get character mask for a character (all 1s if not in pattern).
#[inline(always)]
fn get_mask(&self, ch: char) -> u64 {
let cp = ch as u32;
// Fast path: check Unicode block lookup table
if let Some(ref masks) = self.unicode_block_masks
&& (cp & !0xFF) == self.unicode_block_base
{
return masks[(cp & 0xFF) as usize];
}
// Fallback to HashMap
*self.char_masks.get(&ch).unwrap_or(&!0u64)
}
/// Get mask directly from 2-byte UTF-8 sequence (avoids char decode).
/// Returns (mask, 2) if successful, or falls back to `decode_utf8_char_fast`.
#[inline(always)]
fn get_mask_2byte(&self, b0: u8, b1: u8) -> u64 {
if let Some(ref masks) = self.unicode_block_masks {
// Compute codepoint index directly from UTF-8 bytes
// For 2-byte UTF-8: codepoint = ((b0 & 0x1F) << 6) | (b1 & 0x3F)
// Block check: (codepoint & !0xFF) == block_base
// Index: codepoint & 0xFF
let codepoint_low6 = (u32::from(b0) & 0x1F) << 6;
let codepoint = codepoint_low6 | (u32::from(b1) & 0x3F);
if (codepoint & !0xFF) == self.unicode_block_base {
return masks[(codepoint & 0xFF) as usize];
}
}
// Fallback: decode to char and lookup
let codepoint = ((u32::from(b0) & 0x1F) << 6) | (u32::from(b1) & 0x3F);
let ch = unsafe { char::from_u32_unchecked(codepoint) };
*self.char_masks.get(&ch).unwrap_or(&!0u64)
}
/// Get Boyer-Moore skip distance for a byte.
/// Returns 0 if byte is in pattern, otherwise returns skip distance.
#[inline(always)]
#[must_use]
pub fn get_skip(&self, byte: u8) -> usize {
self.skip_table[byte as usize] as usize
}
/// Find the next position worth checking using Boyer-Moore skipping.
/// Scans from `start` looking for a byte that's in the pattern.
/// Returns the position of the first pattern-relevant byte, or `text.len()` if none.
#[inline]
#[must_use]
pub fn find_next_candidate(&self, text: &[u8], start: usize) -> usize {
let mut pos = start;
while pos < text.len() {
let skip = self.skip_table[text[pos] as usize];
if skip == 0 {
return pos;
}
pos += skip as usize;
}
text.len()
}
/// Calculate similarity score.
fn calc_similarity(&self, edits: u8, insertions: u8, deletions: u8) -> f32 {
let pattern_len = self.pattern_len as f32;
if pattern_len == 0.0 {
return 1.0;
}
let edit_distance = f32::from(edits);
let matched_len = pattern_len + f32::from(insertions) - f32::from(deletions);
let max_len = pattern_len.max(matched_len).max(1.0);
(1.0 - edit_distance / max_len).max(0.0)
}
/// Myers' bit-vector algorithm for fast O(n) edit distance computation.
/// Returns the edit distance between pattern and text.
///
/// This is much faster than full DP (O(n) vs O(m×n)) but doesn't give
/// breakdown of edit types. Use for fast verification.
#[inline]
fn compute_edit_distance_myers(&self, text_chars: &[char]) -> u8 {
let m = self.pattern_len;
let n = text_chars.len();
if m == 0 {
return n as u8;
}
if n == 0 {
return m as u8;
}
// Myers' algorithm using our precomputed masks
// Note: Our masks have bit=0 for match, which is the inverse of typical Myers
// We adapt by inverting the eq mask
let mut pv = !0u64; // positive vertical delta (all 1s)
let mut mv = 0u64; // negative vertical delta (all 0s)
let mut score = m as u8;
let mask = 1u64 << (m - 1);
for &text_char in text_chars {
// Get pattern equality mask (bit i is 1 if pattern[i] matches text_char)
// Our stored masks have 0 for match, so we invert
let eq = if text_char.is_ascii() {
!self.byte_masks[text_char as usize]
} else {
!self.get_mask(text_char)
};
let xv = eq | mv;
let xh = ((eq & pv).wrapping_add(pv)) ^ pv | eq;
let ph = mv | !(xh | pv);
let mh = pv & xh;
// Update score
if (ph & mask) != 0 {
score = score.saturating_add(1);
}
if (mh & mask) != 0 {
score = score.saturating_sub(1);
}
// Shift for next column
let ph_shift = (ph << 1) | 1;
let mh_shift = mh << 1;
pv = mh_shift | !(xv | ph_shift);
mv = ph_shift & xv;
}
score
}
/// Fast edit breakdown using Myers for distance + length heuristic for breakdown.
/// Returns (insertions, deletions, substitutions, swaps).
///
/// This approximates the breakdown based on:
/// - Total distance from Myers (exact)
/// - Length difference (insertions - deletions = `text_len` - `pattern_len`)
///
/// Transpositions are counted as substitutions in this fast version.
#[inline]
#[allow(dead_code)]
fn compute_edit_breakdown_fast(&self, text_chars: &[char]) -> (u8, u8, u8, u8) {
let m = self.pattern_len;
let n = text_chars.len();
if m == 0 {
return (n as u8, 0, 0, 0);
}
if n == 0 {
return (0, m as u8, 0, 0);
}
let distance = self.compute_edit_distance_myers(text_chars);
// Heuristic: length difference determines insertions vs deletions
let len_diff = n as i32 - m as i32;
if len_diff >= 0 {
// Text is longer or equal: extra chars are insertions
let insertions = (len_diff as u8).min(distance);
let other_edits = distance.saturating_sub(insertions);
(insertions, 0, other_edits, 0)
} else {
// Text is shorter: missing chars are deletions
let deletions = ((-len_diff) as u8).min(distance);
let other_edits = distance.saturating_sub(deletions);
(0, deletions, other_edits, 0)
}
}
/// Find all matches in text using Bitap algorithm with k errors.
#[must_use]
pub fn find_all(&self, text: &str, threshold: f32) -> Vec<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
let text_chars: Vec<(usize, char)> = text.char_indices().collect();
if text_chars.is_empty() {
return vec![];
}
let mut matches: FxHashMap<(usize, usize), DamLevMatch> = FxHashMap::default();
// State vectors: R[d] tracks matching state with exactly d errors
// Bit i is 0 if we've matched pattern[0..=i] with d errors
// Use two buffers and swap to avoid allocation per character
let mut r: Vec<u64> = vec![!0u64; max_edits + 1];
let mut old_r: Vec<u64> = vec![!0u64; max_edits + 1];
// Initialize: we can delete up to k characters from the start of pattern
// R[d] starts with first d bits as 0 (matched d chars via deletion)
// Left shift advances pattern position (bit i → bit i+1)
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
for (char_idx, &(_, text_char)) in text_chars.iter().enumerate() {
let text_char = if self.case_insensitive {
text_char.to_lowercase().next().unwrap_or(text_char)
} else {
text_char
};
let char_mask = self.get_mask(text_char);
// Swap buffers: old_r gets previous r, r will be updated (no allocation!)
std::mem::swap(&mut r, &mut old_r);
// Update R[0] (exact matching) - use old_r since we swapped
r[0] = (old_r[0] << 1) | char_mask;
// Update R[d] for d > 0 (fuzzy matching)
for d in 1..=max_edits {
// Can insert from R[d-1]: consume text char without advancing pattern
let insert = old_r[d - 1];
// Can delete from R[d-1]: advance pattern without consuming text
// Uses r[d-1] (already updated) with << 1 to advance pattern position
let delete = r[d - 1] << 1;
// Can substitute from R[d-1]: consume both and treat as match
let substitute = old_r[d - 1] << 1;
// Regular match with d errors
let match_d = (old_r[d] << 1) | char_mask;
r[d] = match_d & insert & delete & substitute;
}
// Check for matches (bit pattern_len-1 is 0)
let end_byte = text_chars.get(char_idx + 1).map_or(text.len(), |(b, _)| *b);
for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
// Found a match with d edits
// Estimate start position (approximate)
let min_start_char = char_idx.saturating_sub(self.pattern_len + d);
let max_start_char =
char_idx.saturating_sub(self.pattern_len.saturating_sub(d + 1));
for start_char in min_start_char..=max_start_char.min(char_idx) {
let start_byte = text_chars.get(start_char).map_or(0, |(b, _)| *b);
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) = self
.compute_exact_edit_breakdown(&text.as_bytes()[start_byte..end_byte]);
// Use actual edit count from DP, verify it matches Bitap state
let total_edits = insertions + deletions + substitutions + swaps;
if total_edits as usize > d {
continue; // More edits than this state allows
}
let sim = self.calc_similarity(total_edits, insertions, deletions);
if sim >= threshold {
let key = (start_byte, end_byte);
let m = DamLevMatch {
start: start_byte,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
matches
.entry(key)
.and_modify(|existing| {
if m.similarity > existing.similarity {
*existing = m.clone();
}
})
.or_insert(m);
}
}
}
}
}
// Handle text shorter than pattern: positions reached during the last iteration
// need extra propagation (via deletion) to reach the accept position.
if text_chars.len() < self.pattern_len {
let chars_short = self.pattern_len - text_chars.len();
for _ in 0..chars_short.min(max_edits) {
std::mem::swap(&mut r, &mut old_r);
// Apply deletion propagation: advance pattern position without consuming text.
// From d-1 errors at position p, we can delete pattern[p] to reach d errors at p+1.
r[0] = old_r[0]; // Can't advance without consuming text or adding error
for d in 1..=max_edits {
// Deletion: skip pattern char without consuming text
let delete = old_r[d - 1] << 1;
// Keep existing state if already matched
r[d] = old_r[d] & delete;
}
// Check for matches after propagation
for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
let end_byte = text.len();
let min_start_char = text_chars
.len()
.saturating_sub(self.pattern_len.saturating_sub(d + 1));
for start_char in 0..=min_start_char.min(text_chars.len().saturating_sub(1))
{
let start_byte = text_chars.get(start_char).map_or(0, |(b, _)| *b);
let (insertions, deletions, substitutions, swaps) = self
.compute_exact_edit_breakdown(
&text.as_bytes()[start_byte..end_byte],
);
let total_edits = insertions + deletions + substitutions + swaps;
if total_edits as usize <= d {
let sim = self.calc_similarity(total_edits, insertions, deletions);
if sim >= threshold {
let key = (start_byte, end_byte);
let m = DamLevMatch {
start: start_byte,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
matches
.entry(key)
.and_modify(|existing| {
if m.similarity > existing.similarity {
*existing = m.clone();
}
})
.or_insert(m);
}
}
}
}
}
}
}
matches.into_values().collect()
}
/// Find all non-overlapping matches, preferring best (highest similarity) matches.
///
/// This method finds all overlapping candidates, sorts by similarity, then
/// greedily selects non-overlapping matches starting from highest similarity.
/// This ensures we prefer "Lorem" (sim=1.0) over "ore" (sim=0.6).
///
/// Matches must be at least `pattern_len - max_edits` characters long to be
/// considered valid. This prevents overly short fuzzy matches.
///
/// When `require_first_char` is true, matches must start with the same first
/// character as the pattern (case-insensitive). This filters out spurious
/// matches like "bore" when searching for "Lorem".
#[must_use]
pub fn find_best_non_overlapping(
&self,
text: &str,
threshold: f32,
require_first_char: bool,
) -> Vec<DamLevMatch> {
// Get all overlapping matches
let mut all_matches = self.find_all(text, threshold);
if all_matches.is_empty() {
return vec![];
}
// Filter: minimum match length = pattern_len - max_edits
let min_match_len = self
.pattern_len
.saturating_sub(self.limits.max_edits as usize);
all_matches.retain(|m| m.end - m.start >= min_match_len);
// Filter: require first character to match pattern's first char
// Respects case_insensitive setting - if case-sensitive, require exact first char match
if require_first_char && !self.pattern_chars.is_empty() {
let pattern_first = self.pattern_chars[0];
let text_bytes = text.as_bytes();
all_matches.retain(|m| {
if m.start >= text_bytes.len() {
return false;
}
// Decode the first character of the match
let (first_char, _) = decode_utf8_char_fast(text_bytes, m.start);
if self.case_insensitive {
first_char.eq_ignore_ascii_case(&pattern_first)
} else {
first_char == pattern_first
}
});
}
if all_matches.is_empty() {
return vec![];
}
// Sort by similarity descending, then by start position ascending
all_matches.sort_by(|a, b| match b.similarity.partial_cmp(&a.similarity) {
Some(std::cmp::Ordering::Equal) | None => a.start.cmp(&b.start),
Some(ord) => ord,
});
// Greedily select non-overlapping matches
let mut result = Vec::new();
let mut occupied = vec![false; text.len() + 1];
for m in all_matches {
// Check if this match overlaps with any already selected
let overlaps = (m.start..m.end).any(|i| occupied[i]);
if !overlaps {
// Mark this range as occupied
for i in m.start..m.end {
occupied[i] = true;
}
result.push(m);
}
}
// Sort result by start position for consistent ordering
result.sort_by_key(|m| m.start);
result
}
/// Fast find of non-overlapping matches optimized for iteration (greedy leftmost).
///
/// This is faster than `find_all()` followed by filtering because:
/// 1. It skips ahead after each match (no overlapping work)
/// 2. It only verifies the most likely start position per match
/// 3. For exact matches (d=0), it trusts Bitap without DP
///
/// When `require_first_char` is true, matches must start with the same first
/// character as the pattern (case-sensitive unless `case_insensitive` mode).
///
/// Note: This uses greedy-leftmost strategy. For best-match selection
/// (preferring higher similarity), use `find_best_non_overlapping` instead.
#[must_use]
pub fn find_all_non_overlapping(
&self,
text: &str,
threshold: f32,
require_first_char: bool,
) -> Vec<DamLevMatch> {
self.find_non_overlapping_impl(text, threshold, require_first_char, 0)
}
/// Find the first match using the same algorithm as `find_all_non_overlapping`.
/// Returns as soon as a match is found, avoiding scanning the rest of the text.
#[must_use]
pub fn find_first_non_overlapping(&self, text: &str, threshold: f32) -> Option<DamLevMatch> {
// Try ASCII fast path if both pattern and text are ASCII
if self.is_ascii && text.is_ascii() {
if let Some(m) = self.find_first_ascii_fast(text.as_bytes(), threshold) {
return Some(m);
}
// If fast path returns None due to max_edits > 4, fall through to generic path
if self.limits.max_edits <= 4 {
return None;
}
}
let matches = self.find_non_overlapping_impl(text, threshold, false, 1);
matches.into_iter().next()
}
/// Find up to `n` non-overlapping matches.
/// Stops searching after finding `n` matches for efficiency.
#[must_use]
pub fn find_n_non_overlapping(
&self,
text: &str,
threshold: f32,
require_first_char: bool,
n: usize,
) -> Vec<DamLevMatch> {
self.find_non_overlapping_impl(text, threshold, require_first_char, n)
}
/// Implementation of non-overlapping match search with optional limit.
/// `limit` of 0 means unlimited matches, otherwise stops after finding `limit` matches.
fn find_non_overlapping_impl(
&self,
text: &str,
threshold: f32,
require_first_char: bool,
limit: usize,
) -> Vec<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
let text_bytes = text.as_bytes();
let text_len = text_bytes.len();
// Handle empty text: matches if pattern can be fully deleted
if text_len == 0 {
if self.pattern_len <= max_edits {
let deletions = self.pattern_len as u8;
let sim = self.calc_similarity(deletions, 0, deletions);
if sim >= threshold {
return vec![DamLevMatch {
start: 0,
end: 0,
insertions: 0,
deletions,
substitutions: 0,
swaps: 0,
similarity: sim,
}];
}
}
return vec![];
}
// Precompute first-char check if needed
let first_char_check: Option<char> = if require_first_char && !self.pattern_chars.is_empty()
{
Some(self.pattern_chars[0])
} else {
None
};
let mut matches = Vec::new();
let mut last_end = 0usize;
// State vectors (3 buffers for transposition support)
let mut r: Vec<u64> = vec![!0u64; max_edits + 1];
let mut old_r: Vec<u64> = vec![!0u64; max_edits + 1];
let mut old_old_r: Vec<u64> = vec![!0u64; max_edits + 1];
// Initialize deletion states
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
// Track pending fuzzy match (wait for potential better exact match)
let mut pending_match: Option<(usize, DamLevMatch)> = None; // (edit_level, match)
let mut chars_since_pending = 0usize;
// Track previous character mask for transposition
let mut prev_mask: u64 = !0;
// Circular buffer to track byte positions of recent characters
// Used to correctly compute start position for matches with multi-byte UTF-8
let history_size = self.pattern_len + max_edits + 1;
let mut byte_history: Vec<usize> = vec![0; history_size];
let mut history_idx = 0usize;
let mut byte_pos = 0;
while byte_pos < text_len {
// Decode current character
let (text_char, char_len) = decode_utf8_char_fast(text_bytes, byte_pos);
let text_char = if self.case_insensitive {
text_char.to_lowercase().next().unwrap_or(text_char)
} else {
text_char
};
// Record byte position in circular buffer for correct UTF-8 start computation
byte_history[history_idx] = byte_pos;
history_idx = (history_idx + 1) % history_size;
let char_mask = self.get_mask(text_char);
// Rotate buffers: old_old_r <- old_r <- r
std::mem::swap(&mut old_old_r, &mut old_r);
std::mem::swap(&mut old_r, &mut r);
// Update R[0] (exact matching)
r[0] = (old_r[0] << 1) | char_mask;
// Update R[d] for d > 0 (fuzzy matching with transposition)
for d in 1..=max_edits {
let insert = old_r[d - 1];
let delete = r[d - 1] << 1;
let substitute = old_r[d - 1] << 1;
let match_d = (old_r[d] << 1) | char_mask;
let mut new_r = match_d & insert & delete & substitute;
// Transposition: check if we can swap adjacent chars
// trans_valid_mask: bit j is 0 if pattern[j]=curr AND pattern[j+1]=prev
let trans_valid_mask = char_mask | (prev_mask >> 1);
// From matched position k, we can reach k+2 via transposition at k+1
let trans = ((old_old_r[d - 1] << 1) | trans_valid_mask) << 1;
new_r &= trans;
r[d] = new_r;
}
// Update prev_mask for next iteration
prev_mask = char_mask;
let end_byte = byte_pos + char_len;
// Check for match at each error level (prefer lower error levels)
'error_levels: for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
// Found a potential match with d edits
// For fuzzy matches, the match length could vary:
// - With deletions: match is shorter than pattern
// - With insertions: match is longer than pattern
let min_match_len = self.pattern_len.saturating_sub(d);
let max_match_len = self.pattern_len + d;
// Track best candidate at this error level
let mut best_at_level: Option<DamLevMatch> = None;
// Try all possible match lengths to find the best one
// We check all lengths and pick: earliest start, then longest match
for try_len in min_match_len..=max_match_len {
// Compute start_byte by going back try_len characters (not bytes)
// Use the circular buffer to handle multi-byte UTF-8 correctly
let start_byte = if try_len <= history_size && try_len > 0 {
// Look up the byte position from the circular buffer
// history_idx points to the next slot, so most recent is (history_idx - 1)
// We need to go back (try_len - 1) more slots from there
let idx = (history_idx + history_size - try_len) % history_size;
byte_history[idx]
} else if try_len == 0 {
end_byte
} else {
// try_len > history_size: shouldn't happen normally, fall back to byte math
// This could be inaccurate for multi-byte chars
end_byte.saturating_sub(try_len)
};
if start_byte >= end_byte {
continue;
}
// Skip empty matches at end of text (can happen when try_len=0)
if start_byte >= text_len {
continue;
}
// Skip if this match overlaps with previous confirmed match
if start_byte < last_end {
continue;
}
// Check first-char filter if required
if let Some(pattern_first) = first_char_check {
let (match_first, _) = decode_utf8_char_fast(text_bytes, start_byte);
let matches_first = if self.case_insensitive {
match_first.eq_ignore_ascii_case(&pattern_first)
} else {
match_first == pattern_first
};
if !matches_first {
continue;
}
}
// For exact match (d=0), accept immediately
if d == 0 {
let sim = 1.0f32;
if sim >= threshold {
// Clear any pending fuzzy match (this exact match is better)
pending_match = None;
chars_since_pending = 0;
matches.push(DamLevMatch {
start: start_byte,
end: end_byte,
insertions: 0,
deletions: 0,
substitutions: 0,
swaps: 0,
similarity: sim,
});
// Early exit: return immediately if limit reached
if limit > 0 && matches.len() >= limit {
return matches;
}
last_end = end_byte;
// Reset state for next non-overlapping match
r.fill(!0u64);
old_r.fill(!0u64);
old_old_r.fill(!0u64);
for dd in 1..=max_edits {
r[dd] = r[dd - 1] << 1;
}
prev_mask = !0;
break 'error_levels; // Found exact match, move on
}
} else {
// For fuzzy match, verify with DP
let matched_text = &text_bytes[start_byte..end_byte];
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(matched_text);
let total_edits = insertions + deletions + substitutions + swaps;
if total_edits as usize <= max_edits {
let sim = self.calc_similarity(total_edits, insertions, deletions);
if sim >= threshold {
let candidate = DamLevMatch {
start: start_byte,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
// Check if this candidate is better than best at this level
// Prefer: earlier start, then longer match
let dominated = best_at_level.as_ref().is_some_and(|best| {
let best_len = best.end - best.start;
let cand_len = candidate.end - candidate.start;
best.start < candidate.start
|| (best.start == candidate.start
&& best_len >= cand_len)
});
if !dominated {
best_at_level = Some(candidate);
}
}
}
}
}
// If we found a valid match at this error level, update pending
if let Some(candidate) = best_at_level {
// Check if this is better than existing pending match
let dominated = pending_match.as_ref().is_some_and(|(pd, pm)| {
let pm_len = pm.end - pm.start;
let cand_len = candidate.end - candidate.start;
*pd < d
|| (*pd == d && pm.start < candidate.start)
|| (*pd == d && pm.start == candidate.start && pm_len >= cand_len)
});
if !dominated {
// Always reset counter when setting a new pending match
// This ensures the new match gets its full waiting period
chars_since_pending = 0;
pending_match = Some((d, candidate));
}
break 'error_levels; // Found valid fuzzy match at this level
}
}
}
// Check if we should commit the pending fuzzy match
if let Some((d, ref m)) = pending_match {
chars_since_pending += 1;
let match_len = m.end - m.start;
// Determine when to commit:
// - Exact matches (d=0): commit immediately
// - Fuzzy matches (d>0): wait at least 1 char to let potential exact matches appear
// This handles cases like "mhussei" (fuzzy at d=2) vs "hussein" (exact at d=0)
// where the exact match ends one character later
let commit_threshold = if d == 0 {
1 // Exact match: commit on first check
} else if match_len >= self.pattern_len {
2 // Full-length fuzzy match: wait 1 char for potential exact match
} else {
max_edits + 1 // Short match: wait longer
};
if chars_since_pending >= commit_threshold {
let (_, m) = pending_match.take().unwrap();
last_end = m.end;
matches.push(m);
// Early exit: return immediately if limit reached
if limit > 0 && matches.len() >= limit {
return matches;
}
// Reset state
r.fill(!0u64);
old_r.fill(!0u64);
old_old_r.fill(!0u64);
for dd in 1..=max_edits {
r[dd] = r[dd - 1] << 1;
}
prev_mask = !0;
chars_since_pending = 0;
}
}
byte_pos = end_byte;
}
// Commit any remaining pending match
if let Some((_, m)) = pending_match {
matches.push(m);
}
matches
}
/// Ultra-fast ASCII-only path for finding first match.
/// Only called when both pattern and text are pure ASCII.
/// Uses stack arrays instead of Vec, direct byte lookup instead of `HashMap`.
///
/// Returns Some((start, end, edits)) on match, None if no match found.
#[inline]
fn find_first_ascii_fast(&self, text: &[u8], threshold: f32) -> Option<DamLevMatch> {
debug_assert!(self.is_ascii);
let max_edits = self.limits.max_edits as usize;
let text_len = text.len();
// Handle empty text
if text_len == 0 {
if self.pattern_len <= max_edits {
let deletions = self.pattern_len as u8;
let sim = self.calc_similarity(deletions, 0, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: 0,
end: 0,
insertions: 0,
deletions,
substitutions: 0,
swaps: 0,
similarity: sim,
});
}
}
return None;
}
// Use fixed-size arrays for state vectors (up to 4 edits supported in fast path)
// For more edits, fall back to Vec-based implementation
if max_edits > 4 {
return None; // Signal caller to use generic path
}
// State vectors (3 buffers for transposition support) - stack allocated
let mut r: [u64; 5] = [!0u64; 5];
let mut old_r: [u64; 5] = [!0u64; 5];
let mut old_old_r: [u64; 5] = [!0u64; 5];
// Initialize deletion states
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
// Track pending fuzzy match
let mut pending_match: Option<(usize, DamLevMatch)> = None;
let mut chars_since_pending = 0usize;
// Track previous character mask for transposition
let mut prev_mask: u64 = !0;
// Circular buffer for start position tracking (pattern_len + max_edits + 1)
// Since ASCII: 1 byte = 1 char, we can use byte positions directly
let history_size = self.pattern_len + max_edits + 1;
// Use fixed array - max pattern is 64, max edits is 4, so max history is 69
let mut byte_history: [usize; 72] = [0; 72];
let mut history_idx = 0usize;
let mut byte_pos = 0;
// Pre-fetch for case insensitivity - use a static lookup table
let to_lower: fn(u8) -> u8 = if self.case_insensitive {
|b| b.to_ascii_lowercase()
} else {
|b| b
};
while byte_pos < text_len {
let byte = to_lower(text[byte_pos]);
// Record byte position
byte_history[history_idx % history_size] = byte_pos;
history_idx += 1;
// Direct byte mask lookup - no HashMap, no UTF-8 decode
let char_mask = if byte < 128 {
self.byte_masks[byte as usize]
} else {
!0u64 // Non-ASCII byte: no match (shouldn't happen in ASCII path)
};
// Rotate buffers
let tmp = old_old_r;
old_old_r = old_r;
old_r = r;
r = tmp;
// Update R[0] (exact matching)
r[0] = (old_r[0] << 1) | char_mask;
// Update R[d] for d > 0 (fuzzy matching with transposition)
for d in 1..=max_edits {
let insert = old_r[d - 1];
let delete = r[d - 1] << 1;
let substitute = old_r[d - 1] << 1;
let match_d = (old_r[d] << 1) | char_mask;
let mut new_r = match_d & insert & delete & substitute;
// Transposition
let trans_valid_mask = char_mask | (prev_mask >> 1);
let trans = ((old_old_r[d - 1] << 1) | trans_valid_mask) << 1;
new_r &= trans;
r[d] = new_r;
}
prev_mask = char_mask;
let end_byte = byte_pos + 1; // ASCII: 1 byte per char
// Check for match at each error level
'error_levels: for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
let min_match_len = self.pattern_len.saturating_sub(d);
let max_match_len = self.pattern_len + d;
let mut best_at_level: Option<DamLevMatch> = None;
for try_len in min_match_len..=max_match_len {
let start_byte =
if try_len <= history_size && try_len > 0 && history_idx >= try_len {
byte_history[(history_idx - try_len) % history_size]
} else if try_len == 0 {
end_byte
} else {
end_byte.saturating_sub(try_len)
};
if start_byte >= end_byte || start_byte >= text_len {
continue;
}
// For exact match (d=0), return immediately
if d == 0 {
let sim = 1.0f32;
if sim >= threshold {
return Some(DamLevMatch {
start: start_byte,
end: end_byte,
insertions: 0,
deletions: 0,
substitutions: 0,
swaps: 0,
similarity: sim,
});
}
} else {
// Fuzzy match - verify with DP
let matched_text = &text[start_byte..end_byte];
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(matched_text);
let total_edits = insertions + deletions + substitutions + swaps;
if total_edits as usize <= max_edits {
let sim = self.calc_similarity(total_edits, insertions, deletions);
if sim >= threshold {
let candidate = DamLevMatch {
start: start_byte,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
let dominated = best_at_level.as_ref().is_some_and(|best| {
let best_len = best.end - best.start;
let cand_len = candidate.end - candidate.start;
best.start < candidate.start
|| (best.start == candidate.start
&& best_len >= cand_len)
});
if !dominated {
best_at_level = Some(candidate);
}
}
}
}
}
if let Some(candidate) = best_at_level {
let dominated = pending_match.as_ref().is_some_and(|(pd, pm)| {
let pm_len = pm.end - pm.start;
let cand_len = candidate.end - candidate.start;
*pd < d
|| (*pd == d && pm.start < candidate.start)
|| (*pd == d && pm.start == candidate.start && pm_len >= cand_len)
});
if !dominated {
chars_since_pending = 0;
pending_match = Some((d, candidate));
}
break 'error_levels;
}
}
}
// Check if we should commit pending match
if let Some((d, ref m)) = pending_match {
chars_since_pending += 1;
let match_len = m.end - m.start;
let commit_threshold = if d == 0 {
1
} else if match_len >= self.pattern_len {
2
} else {
max_edits + 1
};
if chars_since_pending >= commit_threshold {
let (_, m) = pending_match.take().unwrap();
return Some(m);
}
}
byte_pos += 1;
}
// Return any pending match
pending_match.map(|(_, m)| m)
}
/// Compute exact Damerau-Levenshtein edit breakdown using dynamic programming.
/// Returns (insertions, deletions, substitutions, swaps).
///
/// Optimized version using:
/// - Myers' bit-vector algorithm for fast early positive confirmation
/// - 3-row rotation instead of full O(m×n) table (for transposition support)
/// - Stack allocation for small patterns (no heap allocation in common case)
fn compute_exact_edit_breakdown(&self, matched_text: &[u8]) -> (u8, u8, u8, u8) {
let pattern = &self.pattern_chars;
let m = pattern.len();
// Parse text as UTF-8
let Ok(text_str) = std::str::from_utf8(matched_text) else {
return (0, m as u8, 0, 0);
};
if m == 0 {
let n = text_str.chars().count();
return (n as u8, 0, 0, 0);
}
if text_str.is_empty() {
return (0, m as u8, 0, 0);
}
// For small text, use fully stack-allocated version (common case)
// Stack limit chosen to cover pattern_len <= 64 + typical edits
const STACK_LIMIT: usize = 72;
// For ASCII text, byte length == char count (fast path)
let is_ascii = text_str.is_ascii();
let n = if is_ascii {
text_str.len()
} else {
text_str.chars().count()
};
if n < STACK_LIMIT {
// Fast early rejection using Myers
// Since Myers doesn't support transpositions (counts as 2 subs instead of 1),
// we can only reject if Myers distance > max_edits + potential_transpositions
// Conservative: reject if Myers distance > max_edits + max_possible_transpositions
let max_possible_trans = (m.min(n) / 2) as u8;
// Build text chars for Myers check
let mut text_chars_buf: [char; STACK_LIMIT] = ['\0'; STACK_LIMIT];
for (idx, c) in text_str.chars().take(STACK_LIMIT).enumerate() {
text_chars_buf[idx] = if self.case_insensitive {
c.to_ascii_lowercase()
} else {
c
};
}
let text_chars = &text_chars_buf[..n];
let myers_dist = self.compute_edit_distance_myers(text_chars);
// If Myers distance is low enough that no transpositions could make it invalid,
// we still need full DP for exact breakdown
// If Myers distance is very high, reject early
// Use saturating_add to avoid overflow when max_edits is u8::MAX (unlimited)
if myers_dist > self.limits.max_edits.saturating_add(max_possible_trans) {
// Definitely too many edits - return high value for rejection
return (myers_dist, 0, 0, 0);
}
self.compute_edit_breakdown_small::<STACK_LIMIT>(pattern, text_str, m, n)
} else {
self.compute_edit_breakdown_large(pattern, text_str, m, n)
}
}
/// Optimized DP for small text (stack allocated, 3-row rotation).
#[inline]
fn compute_edit_breakdown_small<const N: usize>(
&self,
pattern: &[char],
text_str: &str,
m: usize,
n: usize,
) -> (u8, u8, u8, u8) {
debug_assert!(n < N);
// 3 rows for rotation: prev_prev (i-2), prev (i-1), curr (i)
// Each row has n+1 elements
type Cell = (u8, u8, u8, u8, u8); // (dist, ins, del, sub, swap)
let mut prev_prev: [Cell; N] = [(0, 0, 0, 0, 0); N];
let mut prev: [Cell; N] = [(0, 0, 0, 0, 0); N];
let mut curr: [Cell; N] = [(0, 0, 0, 0, 0); N];
// Stack-allocated text chars buffer (avoids heap allocation)
let mut text_chars_buf: [char; N] = ['\0'; N];
for (idx, c) in text_str.chars().take(N).enumerate() {
text_chars_buf[idx] = if self.case_insensitive {
c.to_ascii_lowercase()
} else {
c
};
}
let text_chars = &text_chars_buf[..n];
// Initialize row 0 (base case: insert j chars from text)
// This goes into prev since the loop starts at i=1 and uses prev for i-1
for j in 0..=n {
prev[j] = (j as u8, j as u8, 0, 0, 0);
}
let mut prev_pattern_char = '\0';
for i in 1..=m {
let pattern_char = if self.case_insensitive {
pattern[i - 1].to_ascii_lowercase()
} else {
pattern[i - 1]
};
// Base case for column 0: delete i chars from pattern
curr[0] = (i as u8, 0, i as u8, 0, 0);
for j in 1..=n {
let text_char = text_chars[j - 1];
if pattern_char == text_char {
// Match - no edit needed
curr[j] = prev[j - 1];
} else {
// Try substitution (from prev[j-1])
let (sub_d, sub_i, sub_del, sub_s, sub_sw) = prev[j - 1];
let mut best = (sub_d + 1, sub_i, sub_del, sub_s + 1, sub_sw);
// Try insertion (from curr[j-1])
let (ins_d, ins_i, ins_del, ins_s, ins_sw) = curr[j - 1];
if ins_d + 1 < best.0 {
best = (ins_d + 1, ins_i + 1, ins_del, ins_s, ins_sw);
}
// Try deletion (from prev[j])
let (del_d, del_i, del_del, del_s, del_sw) = prev[j];
if del_d + 1 < best.0 {
best = (del_d + 1, del_i, del_del + 1, del_s, del_sw);
}
// Try transposition (from prev_prev[j-2])
if i > 1 && j > 1 {
let prev_text_char = text_chars[j - 2];
if pattern_char == prev_text_char && prev_pattern_char == text_char {
let (tr_d, tr_i, tr_del, tr_s, tr_sw) = prev_prev[j - 2];
if tr_d + 1 < best.0 {
best = (tr_d + 1, tr_i, tr_del, tr_s, tr_sw + 1);
}
}
}
curr[j] = best;
}
}
// Rotate rows: prev_prev <- prev <- curr
std::mem::swap(&mut prev_prev, &mut prev);
std::mem::swap(&mut prev, &mut curr);
prev_pattern_char = pattern_char;
}
// Result is in prev[n] (after final rotation)
let (_, ins, del, sub, sw) = prev[n];
(ins, del, sub, sw)
}
/// Fallback DP for large text (heap allocated).
fn compute_edit_breakdown_large(
&self,
pattern: &[char],
text_str: &str,
m: usize,
n: usize,
) -> (u8, u8, u8, u8) {
type Cell = (u8, u8, u8, u8, u8);
// 3 rows for rotation
let mut prev_prev: Vec<Cell> = vec![(0, 0, 0, 0, 0); n + 1];
let mut prev: Vec<Cell> = vec![(0, 0, 0, 0, 0); n + 1];
let mut curr: Vec<Cell> = vec![(0, 0, 0, 0, 0); n + 1];
// Initialize row 0
for j in 0..=n {
prev_prev[j] = (j as u8, j as u8, 0, 0, 0);
}
let text_chars: Vec<char> = if self.case_insensitive {
text_str.chars().map(|c| c.to_ascii_lowercase()).collect()
} else {
text_str.chars().collect()
};
let mut prev_pattern_char = '\0';
for i in 1..=m {
let pattern_char = if self.case_insensitive {
pattern[i - 1].to_ascii_lowercase()
} else {
pattern[i - 1]
};
curr[0] = (i as u8, 0, i as u8, 0, 0);
for j in 1..=n {
let text_char = text_chars[j - 1];
if pattern_char == text_char {
curr[j] = prev[j - 1];
} else {
let (sub_d, sub_i, sub_del, sub_s, sub_sw) = prev[j - 1];
let mut best = (sub_d + 1, sub_i, sub_del, sub_s + 1, sub_sw);
let (ins_d, ins_i, ins_del, ins_s, ins_sw) = curr[j - 1];
if ins_d + 1 < best.0 {
best = (ins_d + 1, ins_i + 1, ins_del, ins_s, ins_sw);
}
let (del_d, del_i, del_del, del_s, del_sw) = prev[j];
if del_d + 1 < best.0 {
best = (del_d + 1, del_i, del_del + 1, del_s, del_sw);
}
if i > 1 && j > 1 {
let prev_text_char = text_chars[j - 2];
if pattern_char == prev_text_char && prev_pattern_char == text_char {
let (tr_d, tr_i, tr_del, tr_s, tr_sw) = prev_prev[j - 2];
if tr_d + 1 < best.0 {
best = (tr_d + 1, tr_i, tr_del, tr_s, tr_sw + 1);
}
}
}
curr[j] = best;
}
}
std::mem::swap(&mut prev_prev, &mut prev);
std::mem::swap(&mut prev, &mut curr);
prev_pattern_char = pattern_char;
}
let (_, ins, del, sub, sw) = prev[n];
(ins, del, sub, sw)
}
/// Find the first match in the text.
///
/// This delegates to `find_all_non_overlapping` and returns the first result.
/// While not optimal for all cases, this ensures correct behavior for edge cases
/// like transpositions and complex fuzzy matches.
#[must_use]
pub fn find_first(&self, text: &str, threshold: f32) -> Option<DamLevMatch> {
// Delegate to the well-tested find_all_non_overlapping
// require_first_char=false allows matches where first char is edited
let matches = self.find_all_non_overlapping(text, threshold, false);
matches.into_iter().min_by_key(|m| m.start)
}
/// Find first match starting from candidate positions only.
#[must_use]
pub fn find_first_with_candidates(
&self,
text: &str,
threshold: f32,
candidates: &super::hash::FxHashSet<usize>,
) -> Option<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
let text_chars: Vec<(usize, char)> = text.char_indices().collect();
if text_chars.is_empty() || candidates.is_empty() {
return None;
}
// For each candidate position, run a localized Bitap search
let mut sorted_candidates: Vec<usize> = candidates.iter().copied().collect();
sorted_candidates.sort_unstable();
// Pre-allocate state buffers outside the loop (reused across candidates)
let mut r: Vec<u64> = vec![!0u64; max_edits + 1];
let mut old_r: Vec<u64> = vec![!0u64; max_edits + 1];
for &start_byte in &sorted_candidates {
// Find the character index for this byte position using binary search (O(log N))
let start_char = text_chars
.binary_search_by_key(&start_byte, |(b, _)| *b)
.unwrap_or(0);
// Reset state for this candidate
r.fill(!0u64);
// Initialize deletion states - left shift advances pattern position
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
let max_window = self.pattern_len + max_edits;
// Track best match within this window
let mut best_match: Option<(usize, DamLevMatch)> = None;
for (rel_idx, &(_, text_char)) in text_chars[start_char..]
.iter()
.enumerate()
.take(max_window + 1)
{
let text_char = if self.case_insensitive {
text_char.to_lowercase().next().unwrap_or(text_char)
} else {
text_char
};
let char_mask = self.get_mask(text_char);
// Swap buffers: old_r gets previous r (no allocation!)
std::mem::swap(&mut r, &mut old_r);
r[0] = (old_r[0] << 1) | char_mask;
for d in 1..=max_edits {
let insert = old_r[d - 1];
let delete = r[d - 1] << 1; // left shift advances pattern position
let substitute = old_r[d - 1] << 1;
let match_d = (old_r[d] << 1) | char_mask;
r[d] = match_d & insert & delete & substitute;
}
// Check for match
let abs_idx = start_char + rel_idx;
let end_byte = text_chars.get(abs_idx + 1).map_or(text.len(), |(b, _)| *b);
for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) = self
.compute_exact_edit_breakdown(&text.as_bytes()[start_byte..end_byte]);
let sim = self.calc_similarity(d as u8, insertions, deletions);
if sim >= threshold {
let candidate = DamLevMatch {
start: start_byte,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
// Update best if this has fewer edits
let dominated =
best_match.as_ref().is_some_and(|(best_d, _)| *best_d <= d);
if !dominated {
best_match = Some((d, candidate));
}
// If exact match found, return immediately
if d == 0 {
return best_match.map(|(_, m)| m);
}
}
}
}
}
// Return best match from this candidate window if found
if let Some((_, m)) = best_match {
return Some(m);
}
}
None
}
/// Ultra-fast search starting from a specific byte position.
///
/// This method is optimized for the greedy-first hot path:
/// - No allocations (uses stack arrays for small k)
/// - Direct byte iteration
/// - Early termination on first match
/// - SIMD acceleration when available (`AVX2` on `x86_64`)
#[inline]
#[must_use]
pub fn find_at_byte_position(
&self,
text: &[u8],
start_pos: usize,
threshold: f32,
) -> Option<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
// Handle empty/exhausted text: pattern can still match via pure deletions
if start_pos >= text.len() {
// If pattern length <= max_edits, we can delete the entire pattern
if self.pattern_len <= max_edits {
let deletions = self.pattern_len as u8;
let sim = self.calc_similarity(deletions, 0, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: start_pos,
insertions: 0,
deletions,
substitutions: 0,
swaps: 0,
similarity: sim,
});
}
}
return None;
}
// SIMD fast path: NEON on aarch64 for ASCII patterns with k <= 1
#[cfg(all(feature = "simd", target_arch = "aarch64"))]
{
if self.is_ascii && max_edits <= 1 {
// SAFETY: NEON is mandatory on aarch64
return unsafe {
self.find_at_byte_position_neon(text, start_pos, threshold, max_edits)
};
}
}
// SIMD fast path: AVX2 on x86_64 for ASCII patterns with k <= 3
#[cfg(all(feature = "simd", target_arch = "x86_64"))]
{
if self.is_ascii && max_edits <= 3 && simd_avx2::is_available() {
// SAFETY: We've verified AVX2 is available via runtime detection
return unsafe {
self.find_at_byte_position_avx2(text, start_pos, threshold, max_edits)
};
}
}
// Use ASCII fast path when pattern is ASCII
// This avoids UTF-8 decoding and uses direct byte array lookup
if self.is_ascii && max_edits <= 4 {
return self.find_at_byte_position_ascii::<5>(text, start_pos, threshold);
}
// Use stack array for small k (common case), fall back to vec for large k
if max_edits <= 4 {
self.find_at_byte_position_small_k::<5>(text, start_pos, threshold)
} else {
self.find_at_byte_position_large_k(text, start_pos, threshold)
}
}
/// NEON-accelerated search for ASCII patterns with k <= 1.
///
/// # Safety
/// Safe on all aarch64 targets (NEON is mandatory).
#[cfg(all(feature = "simd", target_arch = "aarch64"))]
#[inline]
unsafe fn find_at_byte_position_neon(
&self,
text: &[u8],
start_pos: usize,
threshold: f32,
max_edits: usize,
) -> Option<DamLevMatch> {
debug_assert!(max_edits <= 1);
debug_assert!(self.is_ascii);
let max_window = self.pattern_len + max_edits;
let end_limit = (start_pos + max_window + 1).min(text.len());
let search_len = end_limit - start_pos;
if search_len == 0 {
return None;
}
// State arrays: r = current, old_r = previous, old_old_r = 2 iterations ago (for transposition)
let mut r = [!0u64; 4];
let mut old_r = [!0u64; 4];
// Initialize deletion states - left shift advances pattern position
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
// SAFETY: start_pos < text.len() verified by caller, search_len bounds checked above
let text_ptr = unsafe { text.as_ptr().add(start_pos) };
let byte_masks_ptr = self.byte_masks.as_ptr();
let accept_mask = self.accept_mask;
let mut prev_mask: u64 = !0u64;
// old_old_r is 2 iterations ago - on first iteration, it equals old_r's initial state
let mut old_old_r = old_r;
for i in 0..search_len {
// SAFETY: i < search_len which is bounded by text.len() - start_pos
let byte = unsafe { *text_ptr.add(i) };
let mask_idx = (byte & 0x7F) as usize;
// SAFETY: mask_idx is always < 128 due to & 0x7F, and byte_masks has 128 elements
let char_mask = unsafe { *byte_masks_ptr.add(mask_idx) };
// Rotate state history before update
std::mem::swap(&mut old_old_r, &mut old_r);
old_r = r;
// Use NEON state update
// SAFETY: NEON is mandatory on aarch64
unsafe {
simd_neon::update_states_with_trans_k1_neon(
&mut r, &old_r, &old_old_r, char_mask, prev_mask,
);
}
let char_count = i + 1;
for d in 0..=max_edits {
if (r[d] & accept_mask) == 0 {
let end_byte = start_pos + char_count;
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let sim = self.calc_similarity(d as u8, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
prev_mask = char_mask;
}
// Handle text shorter than pattern: positions reached during the last iteration
// need extra match propagation to reach the accept position.
let end_byte = start_pos + search_len;
let chars_short = self.pattern_len.saturating_sub(search_len);
if chars_short > 0 && prev_mask != !0u64 {
for _ in 0..chars_short.min(max_edits) {
old_r = r;
// Apply match propagation with last char's mask
for d in 1..=max_edits {
let match_d = (old_r[d] << 1) | prev_mask;
r[d] &= match_d;
}
// Check for accept
for d in 0..=max_edits {
if (r[d] & accept_mask) == 0 {
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
}
}
}
None
}
/// AVX2-accelerated search for ASCII patterns with k <= 3.
///
/// # Safety
/// Caller must ensure AVX2 is available (check with `simd_avx2::is_available()`).
#[cfg(all(feature = "simd", target_arch = "x86_64"))]
#[target_feature(enable = "avx2")]
#[inline]
unsafe fn find_at_byte_position_avx2(
&self,
text: &[u8],
start_pos: usize,
threshold: f32,
max_edits: usize,
) -> Option<DamLevMatch> {
debug_assert!(max_edits <= 3);
debug_assert!(self.is_ascii);
let max_window = self.pattern_len + max_edits;
let end_limit = (start_pos + max_window + 1).min(text.len());
let search_len = end_limit - start_pos;
if search_len == 0 {
return None;
}
// State arrays (4 elements for k <= 3)
let mut r = [!0u64; 4];
let mut old_r = [!0u64; 4];
#[allow(unused_assignments)]
let mut old_old_r = [!0u64; 4];
// Initialize deletion states - left shift advances pattern position
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
// SAFETY: start_pos < text.len() verified by caller, search_len bounds checked above
let text_ptr = unsafe { text.as_ptr().add(start_pos) };
let byte_masks_ptr = self.byte_masks.as_ptr();
let accept_mask = self.accept_mask;
let mut prev_mask: u64 = !0u64;
for i in 0..search_len {
// SAFETY: i < search_len which is bounded by text.len() - start_pos
let byte = unsafe { *text_ptr.add(i) };
// Direct array lookup for ASCII
let mask_idx = (byte & 0x7F) as usize;
// SAFETY: mask_idx is always < 128 due to & 0x7F, and byte_masks has 128 elements
let char_mask = unsafe { *byte_masks_ptr.add(mask_idx) };
// Save old states
old_old_r = old_r;
old_r = r;
// Use SIMD state update with transposition
// SAFETY: AVX2 availability verified by caller via simd_avx2::is_available()
unsafe {
simd_avx2::update_states_with_trans_avx2(
&mut r, &old_r, &old_old_r, char_mask, prev_mask, max_edits,
);
}
let char_count = i + 1;
// Check for match (prefer fewer edits)
for d in 0..=max_edits {
if (r[d] & accept_mask) == 0 {
let end_byte = start_pos + char_count;
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let sim = self.calc_similarity(d as u8, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
prev_mask = char_mask;
}
// Handle text shorter than pattern: positions reached during the last iteration
// need extra match propagation to reach the accept position.
let end_byte = start_pos + search_len;
let chars_short = self.pattern_len.saturating_sub(search_len);
if chars_short > 0 && prev_mask != !0u64 {
for _ in 0..chars_short.min(max_edits) {
old_r = r;
// Apply match propagation with last char's mask
for d in 1..=max_edits {
let match_d = (old_r[d] << 1) | prev_mask;
r[d] &= match_d;
}
// Check for accept
for d in 0..=max_edits {
if (r[d] & accept_mask) == 0 {
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
}
}
}
None
}
/// Search multiple positions in parallel using SIMD.
///
/// Processes up to 4 candidate positions simultaneously, returning the first match.
/// This avoids the cascade dependency issue by parallelizing across positions
/// rather than across error levels.
///
/// Returns `Some((position_index, match))` if a match is found.
#[cfg(all(feature = "simd", target_arch = "aarch64"))]
#[inline]
#[must_use]
pub fn find_at_positions_parallel(
&self,
text: &[u8],
positions: &[usize],
threshold: f32,
) -> Option<(usize, DamLevMatch)> {
if positions.is_empty() || !self.is_ascii {
return None;
}
let max_edits = self.limits.max_edits as usize;
// NEON processes 2 positions at a time for k=0
if max_edits == 0 {
// Process pairs of positions
let mut i = 0;
while i + 1 < positions.len() {
let pos_pair = [positions[i], positions[i + 1]];
if let Some((idx, m)) =
unsafe { self.find_at_2_positions_neon_k0(text, pos_pair, threshold) }
{
return Some((i + idx, m));
}
i += 2;
}
// Handle remaining position
if i < positions.len()
&& let Some(m) = self.find_at_byte_position(text, positions[i], threshold)
{
return Some((i, m));
}
return None;
}
// For k >= 1, fall back to sequential (NEON k=1 is already optimized)
for (i, &pos) in positions.iter().enumerate() {
if let Some(m) = self.find_at_byte_position(text, pos, threshold) {
return Some((i, m));
}
}
None
}
/// Search multiple positions in parallel using AVX2.
#[cfg(all(feature = "simd", target_arch = "x86_64"))]
#[inline]
#[must_use]
pub fn find_at_positions_parallel(
&self,
text: &[u8],
positions: &[usize],
threshold: f32,
) -> Option<(usize, DamLevMatch)> {
if positions.is_empty() || !self.is_ascii {
return None;
}
let max_edits = self.limits.max_edits as usize;
// AVX2 processes 4 positions at a time for k=0
if max_edits == 0 && simd_avx2::is_available() {
let mut i = 0;
while i + 3 < positions.len() {
let pos_quad = [
positions[i],
positions[i + 1],
positions[i + 2],
positions[i + 3],
];
if let Some((idx, m)) =
unsafe { self.find_at_4_positions_avx2_k0(text, pos_quad, threshold) }
{
return Some((i + idx, m));
}
i += 4;
}
// Handle remaining positions
while i < positions.len() {
if let Some(m) = self.find_at_byte_position(text, positions[i], threshold) {
return Some((i, m));
}
i += 1;
}
return None;
}
// Fall back to sequential for k >= 1 or no AVX2
for (i, &pos) in positions.iter().enumerate() {
if let Some(m) = self.find_at_byte_position(text, pos, threshold) {
return Some((i, m));
}
}
None
}
/// Fallback for non-SIMD builds
#[cfg(not(any(
all(feature = "simd", target_arch = "aarch64"),
all(feature = "simd", target_arch = "x86_64")
)))]
#[inline]
pub fn find_at_positions_parallel(
&self,
text: &[u8],
positions: &[usize],
threshold: f32,
) -> Option<(usize, DamLevMatch)> {
for (i, &pos) in positions.iter().enumerate() {
if let Some(m) = self.find_at_byte_position(text, pos, threshold) {
return Some((i, m));
}
}
None
}
/// NEON: Search 2 positions in parallel for k=0 (exact match).
///
/// Uses 128-bit NEON to process 2 independent exact-match searches.
#[cfg(all(feature = "simd", target_arch = "aarch64"))]
#[inline]
unsafe fn find_at_2_positions_neon_k0(
&self,
text: &[u8],
positions: [usize; 2],
threshold: f32,
) -> Option<(usize, DamLevMatch)> {
#[allow(clippy::wildcard_imports)]
use std::arch::aarch64::*;
let max_window = self.pattern_len;
let accept_mask = self.accept_mask;
let byte_masks = &self.byte_masks;
// Calculate search lengths for each position
let end0 = (positions[0] + max_window + 1).min(text.len());
let end1 = (positions[1] + max_window + 1).min(text.len());
let len0 = end0.saturating_sub(positions[0]);
let len1 = end1.saturating_sub(positions[1]);
let max_len = len0.max(len1);
if max_len == 0 {
return None;
}
// Initialize states: all 1s means no match yet
// r[0] = position 0 state, r[1] = position 1 state
let mut r = unsafe { vdupq_n_u64(!0u64) };
let accept_vec = unsafe { vdupq_n_u64(accept_mask) };
for i in 0..max_len {
// Get char masks for both positions (scalar loads, then combine)
let mask0 = if i < len0 {
let byte = text[positions[0] + i];
byte_masks[(byte & 0x7F) as usize]
} else {
!0u64 // No match possible
};
let mask1 = if i < len1 {
let byte = text[positions[1] + i];
byte_masks[(byte & 0x7F) as usize]
} else {
!0u64
};
// Combine masks into NEON vector
let char_masks = unsafe { vcombine_u64(vcreate_u64(mask0), vcreate_u64(mask1)) };
// State update: r = (r << 1) | char_mask
let shifted = unsafe { vshlq_n_u64(r, 1) };
r = unsafe { vorrq_u64(shifted, char_masks) };
// Check for matches: (r & accept_mask) == 0
let masked = unsafe { vandq_u64(r, accept_vec) };
// Extract and check each lane
let lane0 = unsafe { vgetq_lane_u64(masked, 0) };
let lane1 = unsafe { vgetq_lane_u64(masked, 1) };
if lane0 == 0 && i < len0 {
let end_byte = positions[0] + i + 1;
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[positions[0]..end_byte]);
let sim = self.calc_similarity(0, insertions, deletions);
if sim >= threshold {
return Some((
0,
DamLevMatch {
start: positions[0],
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
},
));
}
}
if lane1 == 0 && i < len1 {
let end_byte = positions[1] + i + 1;
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[positions[1]..end_byte]);
let sim = self.calc_similarity(0, insertions, deletions);
if sim >= threshold {
return Some((
1,
DamLevMatch {
start: positions[1],
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
},
));
}
}
}
None
}
/// AVX2: Search 4 positions in parallel for k=0 (exact match).
///
/// Uses 256-bit AVX2 to process 4 independent exact-match searches.
#[cfg(all(feature = "simd", target_arch = "x86_64"))]
#[target_feature(enable = "avx2")]
#[inline]
unsafe fn find_at_4_positions_avx2_k0(
&self,
text: &[u8],
positions: [usize; 4],
threshold: f32,
) -> Option<(usize, DamLevMatch)> {
#[allow(clippy::wildcard_imports)]
use std::arch::x86_64::*;
let max_window = self.pattern_len;
let accept_mask = self.accept_mask;
let byte_masks = &self.byte_masks;
// Calculate search lengths for each position
let ends: [usize; 4] = [
(positions[0] + max_window + 1).min(text.len()),
(positions[1] + max_window + 1).min(text.len()),
(positions[2] + max_window + 1).min(text.len()),
(positions[3] + max_window + 1).min(text.len()),
];
let lens: [usize; 4] = [
ends[0].saturating_sub(positions[0]),
ends[1].saturating_sub(positions[1]),
ends[2].saturating_sub(positions[2]),
ends[3].saturating_sub(positions[3]),
];
let max_len = lens[0].max(lens[1]).max(lens[2]).max(lens[3]);
if max_len == 0 {
return None;
}
// Initialize states: all 1s
let mut r = _mm256_set1_epi64x(!0i64);
let accept_vec = _mm256_set1_epi64x(accept_mask as i64);
for i in 0..max_len {
// Get char masks for all 4 positions
let masks: [u64; 4] = [
if i < lens[0] {
byte_masks[(text[positions[0] + i] & 0x7F) as usize]
} else {
!0u64
},
if i < lens[1] {
byte_masks[(text[positions[1] + i] & 0x7F) as usize]
} else {
!0u64
},
if i < lens[2] {
byte_masks[(text[positions[2] + i] & 0x7F) as usize]
} else {
!0u64
},
if i < lens[3] {
byte_masks[(text[positions[3] + i] & 0x7F) as usize]
} else {
!0u64
},
];
let char_masks = _mm256_set_epi64x(
masks[3] as i64,
masks[2] as i64,
masks[1] as i64,
masks[0] as i64,
);
// State update: r = (r << 1) | char_mask
let shifted = _mm256_slli_epi64(r, 1);
r = _mm256_or_si256(shifted, char_masks);
// Check for matches
let masked = _mm256_and_si256(r, accept_vec);
// Extract and check each lane (use movemask for efficiency)
let zero = _mm256_setzero_si256();
let cmp = _mm256_cmpeq_epi64(masked, zero);
let match_mask = _mm256_movemask_epi8(cmp);
// Check each position (lanes are in order: 0, 1, 2, 3)
// Each lane is 8 bytes, so bits 0-7 = lane 0, 8-15 = lane 1, etc.
if match_mask != 0 {
for (lane, &len) in lens.iter().enumerate() {
if i < len {
let lane_mask = 0xFF << (lane * 8);
if (match_mask & lane_mask) == lane_mask {
let end_byte = positions[lane] + i + 1;
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[positions[lane]..end_byte]);
let sim = self.calc_similarity(0, insertions, deletions);
if sim >= threshold {
return Some((
lane,
DamLevMatch {
start: positions[lane],
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
},
));
}
}
}
}
}
}
None
}
/// ASCII-optimized search - no UTF-8 decoding, direct byte mask lookup.
/// Uses unsafe to eliminate bounds checks in the hot loop.
#[inline(always)]
fn find_at_byte_position_ascii<const K: usize>(
&self,
text: &[u8],
start_pos: usize,
threshold: f32,
) -> Option<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
debug_assert!(max_edits < K);
let max_window = self.pattern_len + max_edits;
let end_limit = (start_pos + max_window + 1).min(text.len());
let search_len = end_limit - start_pos;
if search_len == 0 {
return None;
}
// SAFETY: We've bounds-checked above, and byte_masks has 128 elements
// which covers all ASCII bytes (0-127). Non-ASCII bytes are handled
// by returning !0u64 (no match).
unsafe {
self.find_at_byte_position_ascii_unchecked::<K>(
text, start_pos, search_len, threshold, max_edits,
)
}
}
/// Inner loop with no bounds checks - SAFETY: caller must ensure bounds are valid
#[inline(always)]
unsafe fn find_at_byte_position_ascii_unchecked<const K: usize>(
&self,
text: &[u8],
start_pos: usize,
search_len: usize,
threshold: f32,
max_edits: usize,
) -> Option<DamLevMatch> {
// SAFETY: caller guarantees all bounds are valid
unsafe {
// Stack-allocated state vectors
let mut r = [!0u64; K];
let mut old_r = [!0u64; K];
let mut old_old_r = [!0u64; K]; // State from 2 iterations ago for transposition
// Initialize deletion states - left shift advances pattern position
for d in 1..=max_edits {
*r.get_unchecked_mut(d) = *r.get_unchecked(d - 1) << 1;
}
let text_ptr = text.as_ptr().add(start_pos);
let byte_masks_ptr = self.byte_masks.as_ptr();
let accept_mask = self.accept_mask;
let _ = self.pattern_len;
let mut prev_byte: Option<u8> = None;
for i in 0..search_len {
let byte = *text_ptr.add(i);
// Direct array lookup - mask non-ASCII to 0 index (which has !0u64)
let mask_idx = (byte & 0x7F) as usize;
let char_mask = *byte_masks_ptr.add(mask_idx);
// Save states from 2 iterations ago
for d in 0..=max_edits {
*old_old_r.get_unchecked_mut(d) = *old_r.get_unchecked(d);
*old_r.get_unchecked_mut(d) = *r.get_unchecked(d);
}
// Update state 0 (exact match)
*r.get_unchecked_mut(0) = (*r.get_unchecked(0) << 1) | char_mask;
// Update fuzzy states
for d in 1..=max_edits {
let insert = *old_r.get_unchecked(d - 1);
let delete = *r.get_unchecked(d - 1) << 1; // left shift advances pattern position
let substitute = *old_r.get_unchecked(d - 1) << 1;
let match_d = (*old_r.get_unchecked(d) << 1) | char_mask;
let mut new_r = match_d & insert & delete & substitute;
// Transposition: if we have a previous character, check for swaps
// Transposition at position j means pattern[j]=curr AND pattern[j+1]=prev
if let Some(prev_b) = prev_byte {
let prev_mask_idx = (prev_b & 0x7F) as usize;
let prev_mask = *byte_masks_ptr.add(prev_mask_idx);
// trans_valid_mask: bit j is 0 if pattern[j]=curr AND pattern[j+1]=prev
let trans_valid_mask = char_mask | (prev_mask >> 1);
// From matched position k (bit k=0), we can reach k+2 via transposition at k+1
// Shift old_old_r left first to align: bit k becomes bit k+1
// This also makes bit 0 = 0, allowing transposition at position 0
let trans =
((*old_old_r.get_unchecked(d - 1) << 1) | trans_valid_mask) << 1;
new_r &= trans;
}
*r.get_unchecked_mut(d) = new_r;
}
let char_count = i + 1;
// Check for match (prefer fewer edits)
for d in 0..=max_edits {
if (*r.get_unchecked(d) & accept_mask) == 0 {
let end_byte = start_pos + char_count;
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let sim = self.calc_similarity(d as u8, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
prev_byte = Some(byte);
}
// Handle text shorter than pattern: positions reached during the last iteration
// need extra match propagation to reach the accept position.
// Re-process the last char_mask to allow match propagation.
let end_byte = start_pos + search_len;
if let Some(last_byte) = prev_byte {
let last_mask = *byte_masks_ptr.add((last_byte & 0x7F) as usize);
let chars_short = self.pattern_len.saturating_sub(search_len);
for _ in 0..chars_short.min(max_edits) {
for d in 0..=max_edits {
*old_r.get_unchecked_mut(d) = *r.get_unchecked(d);
}
// Apply match propagation: from position p with d errors,
// if pattern[p+1] matches last_char, reach position p+1 with d errors
for d in 1..=max_edits {
let match_d = (*old_r.get_unchecked(d) << 1) | last_mask;
*r.get_unchecked_mut(d) &= match_d;
}
// Check for accept after each propagation
for d in 0..=max_edits {
if (*r.get_unchecked(d) & accept_mask) == 0 {
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
}
}
}
None
}
}
#[inline]
fn find_at_byte_position_small_k<const K: usize>(
&self,
text: &[u8],
start_pos: usize,
threshold: f32,
) -> Option<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
debug_assert!(max_edits < K);
// Stack-allocated state vectors
let mut r = [!0u64; K];
let mut old_r = [!0u64; K];
let mut old_old_r = [!0u64; K]; // State from 2 iterations ago for transposition
// Initialize deletion states - left shift advances pattern position
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
// max_window is in characters, but we iterate bytes.
// For UTF-8, multiply by max char size (4) to ensure we process enough bytes.
let max_window_chars = self.pattern_len + max_edits;
let max_window_bytes = if self.is_ascii {
max_window_chars + 1
} else {
max_window_chars * 4 + 1
};
let end_limit = (start_pos + max_window_bytes).min(text.len());
// Cache previous mask to avoid redundant lookups in transposition check
let mut prev_mask: Option<u64> = None;
let case_insensitive = self.case_insensitive;
// Iterate bytes, handling UTF-8
let mut pos = start_pos;
let mut char_count = 0usize;
while pos < end_limit && char_count <= max_window_chars {
let byte = text[pos];
// Get character mask and length with fast paths
let (char_mask, char_len) = if byte < 128 {
// ASCII fast path
let lookup_byte = if case_insensitive {
byte.to_ascii_lowercase()
} else {
byte
};
(self.byte_masks[lookup_byte as usize], 1)
} else if byte < 224 && pos + 1 < text.len() {
// 2-byte UTF-8 fast path (Cyrillic, etc.)
let b1 = text[pos + 1];
if case_insensitive {
let codepoint = ((u32::from(byte) & 0x1F) << 6) | (u32::from(b1) & 0x3F);
let ch = unsafe { char::from_u32_unchecked(codepoint) };
let ch_lower = ch.to_lowercase().next().unwrap_or(ch);
(self.get_mask(ch_lower), 2)
} else {
(self.get_mask_2byte(byte, b1), 2)
}
} else {
// 3/4-byte UTF-8 or incomplete
let (ch, len) = decode_utf8_char_fast(text, pos);
let ch = if case_insensitive {
ch.to_lowercase().next().unwrap_or(ch)
} else {
ch
};
(self.get_mask(ch), len)
};
// Save old states
old_old_r[..=max_edits].copy_from_slice(&old_r[..=max_edits]);
old_r[..=max_edits].copy_from_slice(&r[..=max_edits]);
// Update states
r[0] = (r[0] << 1) | char_mask;
for d in 1..=max_edits {
let insert = old_r[d - 1];
let delete = r[d - 1] << 1; // left shift advances pattern position
let substitute = old_r[d - 1] << 1;
let match_d = (old_r[d] << 1) | char_mask;
let mut new_r = match_d & insert & delete & substitute;
// Transposition: if we have a previous mask, check for swaps
// (use cached prev_mask instead of recomputing)
if let Some(pm) = prev_mask {
// trans_valid_mask: bit j is 0 if pattern[j]=curr AND pattern[j+1]=prev
let trans_valid_mask = char_mask | (pm >> 1);
// From matched position k, we can reach k+2 via transposition at k+1
let trans = ((old_old_r[d - 1] << 1) | trans_valid_mask) << 1;
new_r &= trans;
}
r[d] = new_r;
}
let end_byte = pos + char_len;
// Check for match (prefer fewer edits)
for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let sim = self.calc_similarity(d as u8, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
prev_mask = Some(char_mask);
pos += char_len;
char_count += 1;
}
// Handle text shorter than pattern: positions reached during the last iteration
// need extra match propagation to reach the accept position.
// Re-process the last char_mask to allow match propagation.
let end_byte = pos;
if let Some(last_mask) = prev_mask {
let chars_short = self.pattern_len.saturating_sub(char_count);
for _ in 0..chars_short.min(max_edits) {
old_r = r;
// Note: old_old_r is intentionally not updated - transpositions don't apply
// when we're just propagating matches without processing new characters
// Apply match propagation: from position p with d errors,
// if pattern[p+1] matches last_char, reach position p+1 with d errors
// Note: transpositions don't apply here since we're not processing new characters
for d in 1..=max_edits {
let match_d = (old_r[d] << 1) | last_mask;
r[d] &= match_d;
}
// Check for accept after each propagation
for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
}
}
}
None
}
fn find_at_byte_position_large_k(
&self,
text: &[u8],
start_pos: usize,
threshold: f32,
) -> Option<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
let mut r = vec![!0u64; max_edits + 1];
let mut old_r = vec![!0u64; max_edits + 1];
let mut old_old_r = vec![!0u64; max_edits + 1]; // State from 2 iterations ago for transposition
// Initialize deletion states - left shift advances pattern position
for d in 1..=max_edits {
r[d] = r[d - 1] << 1;
}
// max_window is in characters, but we iterate bytes.
// For UTF-8, multiply by max char size (4) to ensure we process enough bytes.
let max_window_chars = self.pattern_len + max_edits;
let max_window_bytes = if self.is_ascii {
max_window_chars + 1
} else {
max_window_chars * 4 + 1
};
let end_limit = (start_pos + max_window_bytes).min(text.len());
let mut pos = start_pos;
let mut prev_mask: Option<u64> = None;
let case_insensitive = self.case_insensitive;
let mut char_count = 0usize;
while pos < end_limit && char_count <= max_window_chars {
let byte = text[pos];
// Get character mask and length with fast paths
let (char_mask, char_len) = if byte < 128 {
let lookup_byte = if case_insensitive {
byte.to_ascii_lowercase()
} else {
byte
};
(self.byte_masks[lookup_byte as usize], 1)
} else if byte < 224 && pos + 1 < text.len() {
// 2-byte UTF-8 fast path
let b1 = text[pos + 1];
if case_insensitive {
let codepoint = ((u32::from(byte) & 0x1F) << 6) | (u32::from(b1) & 0x3F);
let ch = unsafe { char::from_u32_unchecked(codepoint) };
let ch_lower = ch.to_lowercase().next().unwrap_or(ch);
(self.get_mask(ch_lower), 2)
} else {
(self.get_mask_2byte(byte, b1), 2)
}
} else {
let (ch, len) = decode_utf8_char_fast(text, pos);
let ch = if case_insensitive {
ch.to_lowercase().next().unwrap_or(ch)
} else {
ch
};
(self.get_mask(ch), len)
};
old_old_r.copy_from_slice(&old_r);
old_r.copy_from_slice(&r);
r[0] = (r[0] << 1) | char_mask;
for d in 1..=max_edits {
let insert = old_r[d - 1];
let delete = r[d - 1] << 1; // left shift advances pattern position
let substitute = old_r[d - 1] << 1;
let match_d = (old_r[d] << 1) | char_mask;
let mut new_r = match_d & insert & delete & substitute;
// Transposition: use cached prev_mask instead of recomputing
if let Some(pm) = prev_mask {
let trans_valid_mask = char_mask | (pm >> 1);
// From matched position k, we can reach k+2 via transposition at k+1
let trans = ((old_old_r[d - 1] << 1) | trans_valid_mask) << 1;
new_r &= trans;
}
r[d] = new_r;
}
let end_byte = pos + char_len;
for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let sim = self.calc_similarity(d as u8, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
prev_mask = Some(char_mask);
pos += char_len;
char_count += 1;
}
// Handle text shorter than pattern: positions reached during the last iteration
// need extra match propagation to reach the accept position.
let end_byte = pos;
if let Some(last_mask) = prev_mask {
let chars_short = self.pattern_len.saturating_sub(char_count);
for _ in 0..chars_short.min(max_edits) {
old_r.copy_from_slice(&r);
// Apply match propagation: from position p with d errors,
// if pattern[p+1] matches last_char, reach position p+1 with d errors
for d in 1..=max_edits {
let match_d = (old_r[d] << 1) | last_mask;
r[d] &= match_d;
}
// Check for accept after each propagation
for d in 0..=max_edits {
if (r[d] & self.accept_mask) == 0 {
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[start_pos..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: start_pos,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
}
}
}
}
}
None
}
/// Streaming search: scan entire text in one pass, return first match.
/// This is O(n * k) where n = text length, k = max edits.
/// Much faster for long texts than repeated `find_at_byte_position` calls.
#[inline]
#[must_use]
pub fn find_first_streaming(&self, text: &[u8], threshold: f32) -> Option<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
// Use const generics for common cases - already highly optimized
match max_edits {
0 => self.find_first_streaming_k::<1>(text, threshold, 0),
1 => self.find_first_streaming_k::<2>(text, threshold, 1),
2 => self.find_first_streaming_k::<3>(text, threshold, 2),
3 => self.find_first_streaming_k::<4>(text, threshold, 3),
4 => self.find_first_streaming_k::<5>(text, threshold, 4),
_ => self.find_first_streaming_large_k(text, threshold),
}
}
/// Streaming search with const-size state arrays for performance.
/// Uses three rotating buffers to support transposition detection.
/// Continues processing after finding fuzzy matches to prefer exact matches.
#[inline]
fn find_first_streaming_k<const K: usize>(
&self,
text: &[u8],
threshold: f32,
max_edits: usize,
) -> Option<DamLevMatch> {
debug_assert!(max_edits < K);
// Handle empty text: pattern can still match via pure deletions
if text.is_empty() && self.pattern_len <= max_edits {
let deletions = self.pattern_len as u8;
let sim = self.calc_similarity(deletions, 0, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: 0,
end: 0,
insertions: 0,
deletions,
substitutions: 0,
swaps: 0,
similarity: sim,
});
}
return None;
}
// Use three state arrays for rotation (need old_old for transposition)
let mut r0 = [!0u64; K];
let mut r1 = [!0u64; K];
let mut r2 = [!0u64; K];
// Initialize: can delete up to max_edits chars from pattern start
for d in 1..=max_edits {
r0[d] = r0[d - 1] << 1; // left shift advances pattern position
}
// Track byte positions where each error level's current match started
let mut start_bytes = [0usize; K];
let byte_masks = &self.byte_masks;
let accept_mask = self.accept_mask;
let case_insensitive = self.case_insensitive;
let mut pos = 0usize;
let mut rotation = 0usize; // 0, 1, 2 rotation for three buffers
let mut prev_mask: u64 = !0u64; // Previous character mask for transposition
// Track best match found so far (prefer fewer edits)
// After finding a fuzzy match, continue for max_edits more chars to find better matches
let mut best_match: Option<(usize, DamLevMatch)> = None; // (edit_level, match)
let mut chars_since_first_match = 0usize;
while pos < text.len() {
let byte = text[pos];
// Get character mask and length (ASCII fast path)
let (char_mask, char_len) = if byte < 128 {
let lookup_byte = if case_insensitive {
byte.to_ascii_lowercase()
} else {
byte
};
(byte_masks[lookup_byte as usize], 1)
} else if byte < 224 && pos + 1 < text.len() {
// 2-byte UTF-8 fast path (Cyrillic, Latin Extended, etc.)
let b1 = text[pos + 1];
if case_insensitive {
// Need full decode for case conversion
let codepoint = ((u32::from(byte) & 0x1F) << 6) | (u32::from(b1) & 0x3F);
let ch = unsafe { char::from_u32_unchecked(codepoint) };
let ch_lower = ch.to_lowercase().next().unwrap_or(ch);
(self.get_mask(ch_lower), 2)
} else {
(self.get_mask_2byte(byte, b1), 2)
}
} else {
// 3/4-byte UTF-8 or incomplete sequence
let (ch, len) = decode_utf8_char_fast(text, pos);
let ch = if case_insensitive {
ch.to_lowercase().next().unwrap_or(ch)
} else {
ch
};
(self.get_mask(ch), len)
};
// Three-way rotation: old_old -> old -> new
let (old_old_r, old_r, new_r) = match rotation {
0 => (&r2, &r0, &mut r1),
1 => (&r0, &r1, &mut r2),
_ => (&r1, &r2, &mut r0),
};
// Update R[0] (exact matching)
new_r[0] = (old_r[0] << 1) | char_mask;
// Update start position for d=0 if no partial match
if new_r[0] == !0u64 {
start_bytes[0] = pos + char_len;
}
// Update R[d] for d > 0 (fuzzy matching)
for d in 1..=max_edits {
let insert = old_r[d - 1]; // consume text char without advancing pattern
let delete = new_r[d - 1] << 1; // left shift advances pattern position
let substitute = old_r[d - 1] << 1; // replace pattern char
let match_d = (old_r[d] << 1) | char_mask;
let mut new_val = match_d & insert & delete & substitute;
// Transposition: check if we can swap adjacent chars
// trans_valid_mask: bit j is 0 if pattern[j]=curr AND pattern[j+1]=prev
let trans_valid_mask = char_mask | (prev_mask >> 1);
// From matched position k, we can reach k+2 via transposition at k+1
let trans = ((old_old_r[d - 1] << 1) | trans_valid_mask) << 1;
new_val &= trans;
new_r[d] = new_val;
// Update start position if no partial match
if new_r[d] == !0u64 {
start_bytes[d] = pos + char_len;
}
}
// Check for matches (prefer fewer edits)
let end_byte = pos + char_len;
for d in 0..=max_edits {
if (new_r[d] & accept_mask) == 0 {
// Streaming found a potential match ending here.
// Use tracked start position for this error level (fast path)
let tracked_start = start_bytes[d];
// Fast path: if tracked start gives exact pattern length match, use it directly
if end_byte >= tracked_start {
let match_len = end_byte - tracked_start;
// Ultra-fast path for exact matches (d=0, length matches exactly)
// Skip DP computation entirely - we know it's 0 edits
if d == 0 && match_len == self.pattern_len {
return Some(DamLevMatch {
start: tracked_start,
end: end_byte,
insertions: 0,
deletions: 0,
substitutions: 0,
swaps: 0,
similarity: 1.0,
});
}
// Check if this is likely the best match (close to pattern length)
if match_len >= self.pattern_len.saturating_sub(d)
&& match_len <= self.pattern_len + d
{
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[tracked_start..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
// For exact length matches with d=0, return immediately
if d == 0 {
return Some(DamLevMatch {
start: tracked_start,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
// For fuzzy matches, track as candidate and continue
let candidate = DamLevMatch {
start: tracked_start,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
// Prefer: fewer edits, then closer to pattern length
let len_diff =
(match_len as i32 - self.pattern_len as i32).abs();
if best_match.as_ref().is_none_or(|(best_d, b)| {
let b_len = b.end - b.start;
let b_len_diff =
(b_len as i32 - self.pattern_len as i32).abs();
d < *best_d
|| (d == *best_d && total < b.total_edits())
|| (d == *best_d
&& total == b.total_edits()
&& len_diff < b_len_diff)
}) {
if best_match.is_none() {
chars_since_first_match = 0;
}
best_match = Some((d, candidate));
}
}
}
}
}
// For fuzzy matches not caught by fast path, search all possible start positions
if d > 0 {
let search_start = end_byte.saturating_sub(self.pattern_len + d);
for try_start in search_start..end_byte {
// Skip if not at a valid UTF-8 char boundary
if try_start > 0 && text[try_start] >= 0x80 && text[try_start] < 0xC0 {
continue;
}
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[try_start..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
let candidate = DamLevMatch {
start: try_start,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
// Prefer: fewer edits, then closer to pattern length
let match_len = end_byte - try_start;
let len_diff =
(match_len as i32 - self.pattern_len as i32).abs();
if best_match.as_ref().is_none_or(|(best_d, b)| {
let b_len = b.end - b.start;
let b_len_diff =
(b_len as i32 - self.pattern_len as i32).abs();
d < *best_d
|| (d == *best_d && total < b.total_edits())
|| (d == *best_d
&& total == b.total_edits()
&& len_diff < b_len_diff)
}) {
if best_match.is_none() {
chars_since_first_match = 0;
}
best_match = Some((d, candidate));
}
}
}
}
}
}
}
// After finding a fuzzy match, check if we need to continue looking for better matches.
// Only continue if the match is "suspicious" (shorter than pattern, indicating possible
// early accept due to deletions). If match_length >= pattern_length, return immediately.
if let Some((_, ref m)) = best_match {
let match_len = m.end - m.start;
if match_len >= self.pattern_len {
// Match is at least pattern length - can't be early accept due to deletions
return best_match.map(|(_, m)| m);
}
// Short match - might be early accept, continue for a few more chars
chars_since_first_match += 1;
if chars_since_first_match > max_edits {
return best_match.map(|(_, m)| m);
}
}
prev_mask = char_mask;
pos += char_len;
rotation = (rotation + 1) % 3;
}
best_match.map(|(_, m)| m)
}
/// Streaming search for large k values (uses heap allocation with three-buffer rotation).
/// Supports transposition detection. Continues processing after fuzzy matches to prefer exact matches.
fn find_first_streaming_large_k(&self, text: &[u8], threshold: f32) -> Option<DamLevMatch> {
let max_edits = self.limits.max_edits as usize;
// Handle empty text: pattern can still match via pure deletions
if text.is_empty() && self.pattern_len <= max_edits {
let deletions = self.pattern_len as u8;
let sim = self.calc_similarity(deletions, 0, deletions);
if sim >= threshold {
return Some(DamLevMatch {
start: 0,
end: 0,
insertions: 0,
deletions,
substitutions: 0,
swaps: 0,
similarity: sim,
});
}
return None;
}
// Use three buffers for rotation (need old_old for transposition)
let mut r0 = vec![!0u64; max_edits + 1];
let mut r1 = vec![!0u64; max_edits + 1];
let mut r2 = vec![!0u64; max_edits + 1];
let mut start_bytes = vec![0usize; max_edits + 1];
// Initialize: can delete up to max_edits chars from pattern start
for d in 1..=max_edits {
r0[d] = r0[d - 1] << 1; // left shift advances pattern position
}
let byte_masks = &self.byte_masks;
let accept_mask = self.accept_mask;
let case_insensitive = self.case_insensitive;
let mut pos = 0usize;
let mut rotation = 0usize; // 0, 1, 2 rotation for three buffers
let mut prev_mask: u64 = !0u64; // Previous character mask for transposition
// Track best match found so far (prefer fewer edits)
// After finding a fuzzy match, continue for max_edits more chars to find better matches
let mut best_match: Option<(usize, DamLevMatch)> = None; // (edit_level, match)
let mut chars_since_first_match = 0usize;
while pos < text.len() {
let byte = text[pos];
let (char_mask, char_len) = if byte < 128 {
let lookup_byte = if case_insensitive {
byte.to_ascii_lowercase()
} else {
byte
};
(byte_masks[lookup_byte as usize], 1)
} else if byte < 224 && pos + 1 < text.len() {
// 2-byte UTF-8 fast path (Cyrillic, Latin Extended, etc.)
let b1 = text[pos + 1];
if case_insensitive {
let codepoint = ((u32::from(byte) & 0x1F) << 6) | (u32::from(b1) & 0x3F);
let ch = unsafe { char::from_u32_unchecked(codepoint) };
let ch_lower = ch.to_lowercase().next().unwrap_or(ch);
(self.get_mask(ch_lower), 2)
} else {
(self.get_mask_2byte(byte, b1), 2)
}
} else {
// 3/4-byte UTF-8 or incomplete sequence
let (ch, len) = decode_utf8_char_fast(text, pos);
let ch = if case_insensitive {
ch.to_lowercase().next().unwrap_or(ch)
} else {
ch
};
(self.get_mask(ch), len)
};
// Three-way rotation: old_old -> old -> new
let (old_old_r, old_r, new_r) = match rotation {
0 => (&r2, &r0, &mut r1),
1 => (&r0, &r1, &mut r2),
_ => (&r1, &r2, &mut r0),
};
// Update R[0] (exact matching)
new_r[0] = (old_r[0] << 1) | char_mask;
if new_r[0] == !0u64 {
start_bytes[0] = pos + char_len;
}
// Update R[d] for d > 0 (fuzzy matching)
for d in 1..=max_edits {
let insert = old_r[d - 1]; // consume text char without advancing pattern
let delete = new_r[d - 1] << 1; // left shift advances pattern position
let substitute = old_r[d - 1] << 1; // replace pattern char
let match_d = (old_r[d] << 1) | char_mask;
let mut new_val = match_d & insert & delete & substitute;
// Transposition: check if we can swap adjacent chars
// trans_valid_mask: bit j is 0 if pattern[j]=curr AND pattern[j+1]=prev
let trans_valid_mask = char_mask | (prev_mask >> 1);
// From matched position k, we can reach k+2 via transposition at k+1
let trans = ((old_old_r[d - 1] << 1) | trans_valid_mask) << 1;
new_val &= trans;
new_r[d] = new_val;
if new_r[d] == !0u64 {
start_bytes[d] = pos + char_len;
}
}
let end_byte = pos + char_len;
for d in 0..=max_edits {
if (new_r[d] & accept_mask) == 0 {
// Streaming found a potential match ending here.
// For exact match (d=0), return immediately
if d == 0 {
let tracked_start = start_bytes[0];
if end_byte >= tracked_start {
let match_len = end_byte - tracked_start;
if match_len == self.pattern_len {
return Some(DamLevMatch {
start: tracked_start,
end: end_byte,
insertions: 0,
deletions: 0,
substitutions: 0,
swaps: 0,
similarity: 1.0,
});
}
}
}
// Search all possible start positions
let search_start = end_byte.saturating_sub(self.pattern_len + d);
for try_start in search_start..end_byte {
// Skip if not at a valid UTF-8 char boundary
if try_start > 0 && text[try_start] >= 0x80 && text[try_start] < 0xC0 {
continue;
}
// Compute exact edit breakdown using DP
let (insertions, deletions, substitutions, swaps) =
self.compute_exact_edit_breakdown(&text[try_start..end_byte]);
let total = insertions + deletions + substitutions + swaps;
if total as usize <= d {
let sim = self.calc_similarity(total, insertions, deletions);
if sim >= threshold {
// For exact match (d=0, total=0), return immediately
if d == 0 && total == 0 {
return Some(DamLevMatch {
start: try_start,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
});
}
let candidate = DamLevMatch {
start: try_start,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
};
// Prefer: fewer edits, then closer to pattern length
let match_len = end_byte - try_start;
let len_diff = (match_len as i32 - self.pattern_len as i32).abs();
if best_match.as_ref().is_none_or(|(best_d, b)| {
let b_len = b.end - b.start;
let b_len_diff = (b_len as i32 - self.pattern_len as i32).abs();
d < *best_d
|| (d == *best_d && total < b.total_edits())
|| (d == *best_d
&& total == b.total_edits()
&& len_diff < b_len_diff)
}) {
if best_match.is_none() {
chars_since_first_match = 0;
}
best_match = Some((d, candidate));
}
}
}
}
}
}
// After finding a fuzzy match, check if we need to continue looking for better matches.
// Only continue if the match is "suspicious" (shorter than pattern, indicating possible
// early accept due to deletions). If match_length >= pattern_length, return immediately.
if let Some((_, ref m)) = best_match {
let match_len = m.end - m.start;
if match_len >= self.pattern_len {
// Match is at least pattern length - can't be early accept due to deletions
return best_match.map(|(_, m)| m);
}
// Short match - might be early accept, continue for a few more chars
chars_since_first_match += 1;
if chars_since_first_match > max_edits {
return best_match.map(|(_, m)| m);
}
}
prev_mask = char_mask;
pos += char_len;
rotation = (rotation + 1) % 3;
}
best_match.map(|(_, m)| m)
}
}
// SIMD-accelerated Bitap for ARM with NEON
#[cfg(all(feature = "simd", target_arch = "aarch64"))]
mod simd_neon {
#[allow(clippy::wildcard_imports)]
use std::arch::aarch64::*;
/// NEON state update with transposition for k <= 1.
#[inline]
pub unsafe fn update_states_with_trans_k1_neon(
r: &mut [u64; 4],
old_r: &[u64; 4],
old_old_r: &[u64; 4],
char_mask: u64,
prev_mask: u64,
) {
unsafe {
let old_vec = vld1q_u64(old_r.as_ptr());
let old_old_vec = vld1q_u64(old_old_r.as_ptr());
let mask = vdupq_n_u64(char_mask);
// match_d = (old_r[d] << 1) | char_mask
let match_d = vorrq_u64(vshlq_n_u64(old_vec, 1), mask);
// insert: [!0, old_r[0]]
let all_ones = vdupq_n_u64(!0u64);
let insert = vextq_u64(all_ones, old_vec, 1);
// substitute = insert << 1
let subst = vshlq_n_u64(insert, 1);
// Transposition
let trans_valid = char_mask | (prev_mask >> 1);
let trans_valid_vec = vdupq_n_u64(trans_valid);
let old_old_dm1 = vextq_u64(all_ones, old_old_vec, 1);
let trans_inner = vorrq_u64(vshlq_n_u64(old_old_dm1, 1), trans_valid_vec);
let trans = vshlq_n_u64(trans_inner, 1);
// partial = match_d & insert & substitute & trans
let partial = vandq_u64(vandq_u64(vandq_u64(match_d, insert), subst), trans);
vst1q_u64(r.as_mut_ptr(), partial);
r[1] &= r[0] << 1; // left shift advances pattern position
}
}
}
// SIMD-accelerated Bitap for x86_64 with AVX2
#[cfg(all(feature = "simd", target_arch = "x86_64"))]
mod simd_avx2 {
#[cfg(target_arch = "x86_64")]
#[allow(clippy::wildcard_imports)]
use std::arch::x86_64::*;
/// Check if AVX2 is available at runtime.
#[inline]
pub fn is_available() -> bool {
is_x86_feature_detected!("avx2")
}
/// SIMD-accelerated state update for Bitap with k <= 3.
///
/// Computes:
/// - `r[0]` = (`old_r[0]` << 1) | `char_mask`
/// - `r[d]` = ((`old_r[d]` << 1) | `char_mask`) & `old_r[d-1]` & (`r[d-1]` << 1) & (`old_r[d-1]` << 1)
///
/// The cascade dependency (r[d] depends on r[d-1]) is handled sequentially after
/// computing the independent terms in parallel.
///
/// # Safety
/// Requires AVX2 support. Caller must verify with `is_available()`.
#[target_feature(enable = "avx2")]
#[inline]
#[allow(dead_code)]
pub unsafe fn update_states_avx2(
r: &mut [u64; 4],
old_r: &[u64; 4],
char_mask: u64,
max_edits: usize,
) {
debug_assert!(max_edits <= 3);
unsafe {
// Load old states into 256-bit register
let old_vec = _mm256_loadu_si256(old_r.as_ptr().cast::<__m256i>());
let mask = _mm256_set1_epi64x(char_mask as i64);
// match_d = (old_r[d] << 1) | char_mask (parallel for all d)
let match_d = _mm256_or_si256(_mm256_slli_epi64(old_vec, 1), mask);
// insert = old_r[d-1]: shift lanes right, filling lane 0 with !0
// Use permute to shift: [old_r[0], old_r[1], old_r[2], old_r[3]] -> [!0, old_r[0], old_r[1], old_r[2]]
let all_ones = _mm256_set1_epi64x(!0i64);
// _mm256_permute4x64_epi64 with control 0b10_01_00_11 = [3,0,1,2] but we need [X,0,1,2]
// Instead, use blend: shift and insert !0 at position 0
let shifted = _mm256_permute4x64_epi64(old_vec, 0b10_01_00_00); // [0,0,1,2]
let insert = _mm256_blend_epi32(shifted, all_ones, 0b0000_0011); // lane 0 = !0
// substitute = old_r[d-1] << 1
let subst = _mm256_slli_epi64(insert, 1);
// Combine independent terms: match_d & insert & substitute
let partial = _mm256_and_si256(_mm256_and_si256(match_d, insert), subst);
// Store partial results
_mm256_storeu_si256(r.as_mut_ptr().cast::<__m256i>(), partial);
// Apply delete cascade: r[d] &= r[d-1] << 1
// Left shift advances pattern position, must be sequential due to dependency
if max_edits >= 1 {
r[1] &= r[0] << 1;
}
if max_edits >= 2 {
r[2] &= r[1] << 1;
}
if max_edits >= 3 {
r[3] &= r[2] << 1;
}
}
}
/// SIMD-accelerated state update with transposition support.
///
/// # Safety
/// Requires AVX2 support. Caller must verify with `is_available()`.
#[target_feature(enable = "avx2")]
#[inline]
pub unsafe fn update_states_with_trans_avx2(
r: &mut [u64; 4],
old_r: &[u64; 4],
old_old_r: &[u64; 4],
char_mask: u64,
prev_mask: u64,
max_edits: usize,
) {
debug_assert!(max_edits <= 3);
unsafe {
// Load old states
let old_vec = _mm256_loadu_si256(old_r.as_ptr().cast::<__m256i>());
let old_old_vec = _mm256_loadu_si256(old_old_r.as_ptr().cast::<__m256i>());
let mask = _mm256_set1_epi64x(char_mask as i64);
// match_d = (old_r[d] << 1) | char_mask
let match_d = _mm256_or_si256(_mm256_slli_epi64(old_vec, 1), mask);
// Shift for d-1 access
let all_ones = _mm256_set1_epi64x(!0i64);
let shifted_old = _mm256_permute4x64_epi64(old_vec, 0b10_01_00_00);
let insert = _mm256_blend_epi32(shifted_old, all_ones, 0b0000_0011);
// substitute = old_r[d-1] << 1
let subst = _mm256_slli_epi64(insert, 1);
// Transposition term
// trans_valid_mask: bit j is 0 if pattern[j]=curr AND pattern[j+1]=prev
let trans_valid = char_mask | (prev_mask >> 1);
let trans_valid_vec = _mm256_set1_epi64x(trans_valid as i64);
// Shift old_old for d-1 access
let shifted_old_old = _mm256_permute4x64_epi64(old_old_vec, 0b10_01_00_00);
let old_old_dm1 = _mm256_blend_epi32(shifted_old_old, all_ones, 0b0000_0011);
// trans = ((old_old_r[d-1] << 1) | trans_valid_mask) << 1
let trans_inner = _mm256_or_si256(_mm256_slli_epi64(old_old_dm1, 1), trans_valid_vec);
let trans = _mm256_slli_epi64(trans_inner, 1);
// Combine: match_d & insert & substitute & trans
let partial = _mm256_and_si256(
_mm256_and_si256(_mm256_and_si256(match_d, insert), subst),
trans,
);
// Store partial results
_mm256_storeu_si256(r.as_mut_ptr().cast::<__m256i>(), partial);
// Apply delete cascade - left shift advances pattern position
if max_edits >= 1 {
r[1] &= r[0] << 1;
}
if max_edits >= 2 {
r[2] &= r[1] << 1;
}
if max_edits >= 3 {
r[3] &= r[2] << 1;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_exact_match() {
let matcher = BitapMatcher::new("hello", EditLimits::new(0), false).unwrap();
let matches = matcher.find_all("hello world", 0.8);
assert!(!matches.is_empty());
assert!(matches.iter().any(|m| m.start == 0 && m.total_edits() == 0));
}
#[test]
fn test_one_substitution() {
let matcher = BitapMatcher::new("hello", EditLimits::new(1), false).unwrap();
let matches = matcher.find_all("hallo world", 0.5);
assert!(!matches.is_empty());
assert!(matches.iter().any(|m| m.start == 0));
}
#[test]
fn test_find_first() {
let matcher = BitapMatcher::new("quick", EditLimits::new(1), false).unwrap();
let result = matcher.find_first("The quick brown fox", 0.8);
assert!(result.is_some());
let m = result.unwrap();
assert_eq!(m.start, 4);
}
#[test]
fn test_case_insensitive() {
let matcher = BitapMatcher::new("hello", EditLimits::new(0), true).unwrap();
let matches = matcher.find_all("HELLO world", 0.8);
assert!(!matches.is_empty());
}
#[test]
fn test_pattern_too_long() {
let long_pattern = "a".repeat(65);
let result = BitapMatcher::new(&long_pattern, EditLimits::new(1), false);
assert!(result.is_none());
}
#[test]
fn test_transposition_match() {
// With transposition support, "ba" should match "ab" with 1 edit (swap)
// not 2 edits (2 substitutions)
let matcher = BitapMatcher::new("ab", EditLimits::new(1), false).unwrap();
let result = matcher.find_at_byte_position(b"ba", 0, 0.5);
assert!(result.is_some(), "Should find transposition match");
let m = result.unwrap();
assert_eq!(m.total_edits(), 1, "Transposition should count as 1 edit");
}
#[test]
fn test_transposition_in_word() {
// "teh" should match "the" with 1 transposition
let matcher = BitapMatcher::new("the", EditLimits::new(1), false).unwrap();
let result = matcher.find_at_byte_position(b"teh quick brown", 0, 0.5);
assert!(
result.is_some(),
"Should find transposition match for 'teh'"
);
let m = result.unwrap();
assert_eq!(m.total_edits(), 1, "Should be 1 edit for transposition");
}
#[test]
fn test_transposition_vs_two_substitutions() {
// Without transposition, matching "ab" against "ba" would need 2 substitutions
// With transposition, it's just 1 edit
// Test that with max_edits=1, we CAN find "ba" because transposition counts as 1
let matcher = BitapMatcher::new("ab", EditLimits::new(1), false).unwrap();
let result = matcher.find_at_byte_position(b"ba", 0, 0.0);
assert!(
result.is_some(),
"Transposition should allow match with 1 edit"
);
}
}
/// Match result with pattern index for multi-pattern search.
#[derive(Debug, Clone)]
pub struct MultiPatternMatch {
/// Index of the pattern that matched.
pub pattern_index: usize,
/// The match details.
pub match_result: DamLevMatch,
}
/// Multi-pattern Bitap matcher for searching multiple patterns in a single text pass.
///
/// This is more efficient than running N separate Bitap searches because:
/// 1. Text is scanned only once
/// 2. Character decoding is done once per character
/// 3. Better cache locality
#[derive(Debug)]
pub struct MultiBitapMatcher {
/// Individual matchers for each pattern.
matchers: Vec<BitapMatcher>,
/// Case insensitive matching.
case_insensitive: bool,
}
impl MultiBitapMatcher {
/// Create a new multi-pattern matcher.
///
/// Returns None if any pattern is too long or empty.
#[must_use]
pub fn new(patterns: &[&str], limits: &EditLimits, case_insensitive: bool) -> Option<Self> {
if patterns.is_empty() {
return None;
}
let matchers: Option<Vec<BitapMatcher>> = patterns
.iter()
.map(|p| BitapMatcher::new(p, limits.clone(), case_insensitive))
.collect();
Some(MultiBitapMatcher {
matchers: matchers?,
case_insensitive,
})
}
/// Find all matches for all patterns in a single text pass.
///
/// Returns matches with their pattern indices.
#[must_use]
pub fn find_all(&self, text: &str, threshold: f32) -> Vec<MultiPatternMatch> {
let text_chars: Vec<(usize, char)> = text.char_indices().collect();
if text_chars.is_empty() || self.matchers.is_empty() {
return vec![];
}
// Find max_edits across all patterns
let max_edits = self
.matchers
.iter()
.map(|m| m.limits.max_edits as usize)
.max()
.unwrap_or(0);
// State vectors for each pattern: r[pattern][edit_level]
let mut r: Vec<Vec<u64>> = self
.matchers
.iter()
.map(|_| vec![!0u64; max_edits + 1])
.collect();
let mut old_r: Vec<Vec<u64>> = self
.matchers
.iter()
.map(|_| vec![!0u64; max_edits + 1])
.collect();
// Initialize deletion states for each pattern
for (p_idx, matcher) in self.matchers.iter().enumerate() {
let p_max = matcher.limits.max_edits as usize;
for d in 1..=p_max {
r[p_idx][d] = r[p_idx][d - 1] << 1;
}
}
// Use FxHashMap for deduplication
let mut matches: FxHashMap<(usize, usize, usize), MultiPatternMatch> = FxHashMap::default();
// Process each character once
for (char_idx, &(_, text_char)) in text_chars.iter().enumerate() {
let text_char = if self.case_insensitive {
text_char.to_lowercase().next().unwrap_or(text_char)
} else {
text_char
};
// Update all pattern states
for (p_idx, matcher) in self.matchers.iter().enumerate() {
let p_max = matcher.limits.max_edits as usize;
let char_mask = matcher.get_mask(text_char);
// Swap buffers for this pattern
std::mem::swap(&mut r[p_idx], &mut old_r[p_idx]);
// Update R[0] (exact matching)
r[p_idx][0] = (old_r[p_idx][0] << 1) | char_mask;
// Update R[d] for d > 0 (fuzzy matching)
for d in 1..=p_max {
let insert = old_r[p_idx][d - 1];
let delete = r[p_idx][d - 1] << 1;
let substitute = old_r[p_idx][d - 1] << 1;
let match_d = (old_r[p_idx][d] << 1) | char_mask;
r[p_idx][d] = match_d & insert & delete & substitute;
}
// Check for matches
let end_byte = text_chars.get(char_idx + 1).map_or(text.len(), |(b, _)| *b);
for d in 0..=p_max {
if (r[p_idx][d] & matcher.accept_mask) == 0 {
// Found a match with d edits for pattern p_idx
let min_start_char = char_idx.saturating_sub(matcher.pattern_len + d);
let max_start_char =
char_idx.saturating_sub(matcher.pattern_len.saturating_sub(d + 1));
for start_char in min_start_char..=max_start_char.min(char_idx) {
let start_byte = text_chars.get(start_char).map_or(0, |(b, _)| *b);
let (insertions, deletions, substitutions, swaps) = matcher
.compute_exact_edit_breakdown(
&text.as_bytes()[start_byte..end_byte],
);
let total_edits = insertions + deletions + substitutions + swaps;
if total_edits as usize > d {
continue;
}
let sim = matcher.calc_similarity(total_edits, insertions, deletions);
if sim >= threshold {
let key = (start_byte, end_byte, p_idx);
let m = MultiPatternMatch {
pattern_index: p_idx,
match_result: DamLevMatch {
start: start_byte,
end: end_byte,
insertions,
deletions,
substitutions,
swaps,
similarity: sim,
},
};
matches
.entry(key)
.and_modify(|existing| {
if m.match_result.similarity
> existing.match_result.similarity
{
*existing = m.clone();
}
})
.or_insert(m);
}
}
}
}
}
}
matches.into_values().collect()
}
/// Get the number of patterns.
#[must_use]
pub fn pattern_count(&self) -> usize {
self.matchers.len()
}
/// Get a pattern by index.
#[must_use]
pub fn pattern(&self, index: usize) -> Option<&str> {
self.matchers.get(index).map(BitapMatcher::pattern)
}
}