exprim 0.4.1

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
Documentation
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
//! Analytic scanline coverage — exact-area anti-aliasing (performance advice
//! §3, §4). This is the AGG/font-rs family of algorithm: device-space edges
//! accumulate signed area, and a prefix-sum sweep turns that into per-pixel
//! coverage (exact in both x and y, no supersampling). The sweep hands the
//! executor a `u8` coverage row, from which it classifies contiguous spans and
//! dispatches a kernel once per span.
//!
//! Fast path (the realized font-rs kernel): each edge is walked **once**,
//! depositing signed area only into the pixels it actually crosses, into a
//! path-bbox-local 2D accumulation buffer; a per-row prefix-sum then converts
//! to coverage. This replaces the historical O(edges × rows) rescan (every edge
//! tested against every scanline of the band). The two structures produce
//! **byte-identical** coverage — the reorganization preserves, for every
//! accumulation cell, both the operands and their order (edge-index order), so
//! the float sums are bit-for-bit the same. `fill_scanline_ref` is the original
//! per-scanline implementation, retained (test-only) purely as the byte-identity
//! oracle; the production oversized/sparse-window fallback is
//! `fill_scanline_aet`.
//!
//! Vertical edges (A2) take a dedicated deposit that skips the x-walk. AVX2
//! (A3) accelerates only the per-element coverage *conversion* (abs/clamp/scale/
//! truncate/pack); the running prefix-sum stays scalar, so the AVX2 path is
//! bit-for-bit identical to the scalar path (verified by
//! `tests::avx2_convert_matches_scalar_bit_exact`). All scratch lives on the
//! kernel and is reused across fills; only touched cells are reset (advice §13).

#[cfg(feature = "profiling")]
pub(crate) use prof::{RasterClass, RasterProf};

/// Feature-gated per-fill attribution for the kernel: plain integer fields
/// updated in place, keyed by the caller's fill class, and drained into a
/// `ProfileReport` once per page (never a map update per fill).
#[cfg(feature = "profiling")]
mod prof {
    use crate::profiling::ProfileReport;
    use std::time::Duration;

    /// Who asked for the fill; set by the caller before filling.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    pub(crate) enum RasterClass {
        /// A page draw command (`paint_command`).
        #[default]
        Path,
        /// A clip-mask build.
        Clip,
        /// A glyph-cache miss bitmap.
        Glyph,
        /// Tiling fill masks and other callers.
        Other,
    }

    macro_rules! raster_class_prof {
        ($($field:ident),* $(,)?) => {
            /// Counters (`u64` events/work) and `ns_*` durations for one class.
            #[derive(Debug, Default, Clone, Copy)]
            pub(crate) struct RasterClassProf {
                $(pub(crate) $field: u64,)*
            }

            impl RasterClassProf {
                fn merge(&mut self, other: &Self) {
                    $(self.$field += other.$field;)*
                }

                fn drain_into(&self, class: RasterClass, out: &mut ProfileReport) {
                    $(
                        if self.$field != 0 {
                            let name: &'static str = match class {
                                RasterClass::Path => concat!("raster.path.", stringify!($field)),
                                RasterClass::Clip => concat!("raster.clip.", stringify!($field)),
                                RasterClass::Glyph => concat!("raster.glyph.", stringify!($field)),
                                RasterClass::Other => concat!("raster.other.", stringify!($field)),
                            };
                            if stringify!($field).starts_with("ns_") {
                                out.add_duration(name, Duration::from_nanos(self.$field));
                            } else {
                                out.increment(name, self.$field);
                            }
                        }
                    )*
                }
            }
        };
    }

    raster_class_prof!(
        // Volume.
        fills,
        fills_no_edges,
        fills_no_rows,
        subpaths,
        edges,
        edge_rows,
        // Routing.
        route_accum,
        route_aet_sparse,
        route_aet_oversize,
        accum_window_cells,
        aet_window_cells,
        // Rows and cells.
        rows_window,
        rows_emitted,
        covered_span_px,
        accum_cells_swept,
        aet_rows_dense_many,
        aet_rows_dense_short,
        aet_rows_sparse,
        aet_rows_repeated,
        aet_dense_cells_swept,
        aet_active_visits,
        // Fill-size buckets (window rows), to expose fixed per-fill cost.
        fills_rows_le4,
        fills_rows_le32,
        fills_rows_gt32,
        ns_rows_le4,
        ns_rows_le32,
        ns_rows_gt32,
        // Phases. `ns_total` includes the row callback (span dispatch and
        // compositing); `ns_callback` is only measured with `time_rows`.
        ns_total,
        ns_edge_build,
        ns_accum_deposit,
        ns_accum_sweep,
        ns_aet_setup,
        ns_aet_sweep,
        ns_callback,
        clock_reads,
    );

    #[derive(Debug, Default, Clone)]
    pub(crate) struct RasterProf {
        /// Class charged for the next fills.
        pub(crate) class: RasterClass,
        /// Time each fill's phases (about six clock reads per fill).
        pub(crate) time_fills: bool,
        /// Time every row callback (two clock reads per emitted row).
        pub(crate) time_rows: bool,
        /// Window rows of the fill in progress (0 until known).
        pub(crate) fill_rows: u64,
        by_class: [RasterClassProf; 4],
    }

    impl RasterProf {
        #[inline]
        pub(crate) fn cur(&mut self) -> &mut RasterClassProf {
            &mut self.by_class[self.class as usize]
        }

        pub(crate) fn merge(&mut self, other: &Self) {
            for (mine, theirs) in self.by_class.iter_mut().zip(&other.by_class) {
                mine.merge(theirs);
            }
        }

        /// Move the accumulated counters into `out` and reset them.
        pub(crate) fn drain_into(&mut self, out: &mut ProfileReport) {
            const CLASSES: [RasterClass; 4] = [
                RasterClass::Path,
                RasterClass::Clip,
                RasterClass::Glyph,
                RasterClass::Other,
            ];
            for (class, counters) in CLASSES.iter().zip(&mut self.by_class) {
                counters.drain_into(*class, out);
                *counters = RasterClassProf::default();
            }
        }
    }
}

/// Fill rule for coverage accumulation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FillRule {
    NonZero,
    EvenOdd,
}

/// A monotonic-in-y edge in device space.
#[derive(Debug, Clone, Copy)]
struct Edge {
    y_top: f32,
    y_bot: f32,
    x_at_top: f32,
    dxdy: f32,
    dir: f32,
}

/// Largest bbox-local accumulation window (in f32 cells) the fast path will
/// allocate. Beyond this, a fill defers to `fill_scanline_aet`, which needs only
/// an O(device-width) scanline buffer. 1 Mi cells = 4 MiB; glyphs and ordinary
/// vector fills sit far below it, so this only guards a pathologically large
/// single path against a device-area allocation.
const MAX_WINDOW_CELLS: usize = 1 << 20;

/// A large-but-sparse local window (`> CACHE_WINDOW_CELLS` cells with fewer than
/// `cells / 8` edges) is routed to the scanline path: there the fast path's
/// 2D accumulation buffer loses cache locality to the reference's single reused
/// O(device-width) row, and few edges mean little rescan waste to eliminate.
/// Both paths are byte-identical, so this only trades speed, never correctness,
/// and can never regress below the pre-rewrite baseline (measured: a spread-out
/// multi-glyph CJK run, few edges over a wide bbox, is faster on the reference).
/// Compact fills (glyph runs, ordinary vector paths) stay on the fast path.
const CACHE_WINDOW_CELLS: usize = 1 << 13; // 8 Ki cells (32 KiB f32) ≈ L1

/// Minimum covered-span width (pixels) before the AVX2 coverage conversion is
/// engaged. It is bit-for-bit identical to the scalar path (A3, verified by
/// `tests::avx2_convert_matches_scalar_bit_exact`) but **disabled by default**
/// (`usize::MAX`): measurement — both the page A/B and the kernel micro-bench —
/// showed it net-negative for glyph/vector fills. The kernel is deposit- and
/// (sequential) prefix-sum-bound, not convert-bound; SIMD-converting requires a
/// separate prefix-sum write-back pass whose cost exceeds the convert saving.
/// Retained, dispatched, and tested so a future convert-bound workload can lower
/// this constant; the sequential prefix-sum precludes a bit-exact SIMD sum.
const AVX2_MIN_SPAN: usize = usize::MAX;

/// Shortest run of untouched accumulation cells that the compact window hands
/// over as one constant run (run-aware mode) instead of as coverage bytes.
/// Below it a constant run costs the consumer more than the bytes it saves.
const COMPACT_RUN_MIN: usize = 16;

/// Rows narrower than this take the plain per-cell sweep: there is no room
/// for a gap worth finding, and small curved fills (the common case) should
/// not pay a zero test per cell.
const COMPACT_GAP_MIN_SPAN: usize = 32;

/// How many consecutive untouched cells start a gap. Fewer are converted like
/// any other cell (adding their zeros changes nothing), which keeps
/// edge-dense rows on the straight path.
const COMPACT_GAP_PROBE: usize = 4;

/// One run of an emitted coverage row, over device columns `[x0, x1)`, for
/// the run-aware fill entry [`RasterKernel::fill_runs_cancellable`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CovRun {
    pub x0: u32,
    pub x1: u32,
    /// `None`: the row buffer holds this run's coverage bytes. `Some(b)`: every
    /// column of the run has coverage `b`, and the row buffer was **not**
    /// written there (it still holds `0`) — a constant gap between edge
    /// crossings, such as the interior of a page-sized rectangle.
    pub fill: Option<u8>,
}

#[derive(Debug, Default)]
pub struct RasterKernel {
    edges: Vec<Edge>,
    /// Bbox-local 2D signed-area accumulation, row-major with per-fill `stride`.
    /// Kept zeroed between fills by resetting only touched cells.
    acc: Vec<f32>,
    /// Per-local-row touched column range (local column indices). `col_min > col_max`
    /// marks an untouched row.
    row_min: Vec<u32>,
    row_max: Vec<u32>,
    /// Per-scanline coverage bytes, indexed by absolute device column, length
    /// `width`. Only the emitted span is written and then re-zeroed.
    cov: Vec<u8>,
    /// Scanline accumulation buffer for the reference/fallback path, length
    /// `width + 1`.
    acc_row: Vec<f32>,
    // --- Active-edge-table (AET) scratch for `fill_scanline_aet`. All sized by
    // `edges.len()` / band height and reused across fills (advice §13). ---
    /// Contributing edge indices grouped by activation local-row via a CSR
    /// counting sort; scattered in edge-index order so each bucket is
    /// index-sorted.
    aet_order: Vec<u32>,
    /// CSR bucket offsets, length `bh + 1`: local row `lr`'s activating edges
    /// are `aet_order[aet_bucket_start[lr]..aet_bucket_start[lr + 1]]`.
    aet_bucket_start: Vec<u32>,
    /// Per-edge retirement row `er_end` (the `ceil(y_bot)`-derived exclusive
    /// end), only meaningful for edges that reach the active list.
    aet_erend: Vec<u32>,
    /// The active edge indices at the current row, kept index-sorted.
    aet_active: Vec<u32>,
    /// Double-buffer for the per-row merge of `aet_active` with a new bucket.
    aet_active_next: Vec<u32>,
    /// Per-row cell intervals `[start, end)` of `acc_row` written by this row's
    /// deposits, one per contributing edge (see `convert_row_sparse`).
    aet_touched: Vec<(u32, u32)>,
    /// The current row's runs in run-aware mode (see [`CovRun`]).
    row_runs: Vec<CovRun>,
    /// Set for the duration of a fill. Still set at the next fill's start,
    /// it means the previous fill unwound (a panic in a row callback or in
    /// the kernel) with deposits possibly left in the scratch, which is then
    /// cleared before use. A worker context that outlives a caught panic
    /// (the read seam keeps one per thread) cannot leak coverage into the
    /// next render.
    dirty: bool,
    pub last_edges: u64,
    pub last_rows: u64,
    pub last_covered: u64,
    /// Per-fill phase attribution (see [`prof`]).
    #[cfg(feature = "profiling")]
    pub(crate) prof: RasterProf,
}

impl RasterKernel {
    /// Rasterize `subpaths` (device-space polylines as index ranges into
    /// `points`) and invoke `row(y, x0, x1, cov)` once per covered row, where
    /// `cov[x0..=x1]` is `u8` coverage (255 = full) and all else is zero.
    pub fn fill(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        row: impl FnMut(usize, usize, usize, &mut [u8]),
    ) {
        let _ = self.fill_cancellable(points, subpaths, width, height, rule, None, row);
    }

    /// [`Self::fill`] with a cooperative cancellation probe. Returns `false`
    /// when cancellation interrupted the fill; scratch buffers are reset so
    /// the worker can be reused safely for a later request.
    #[allow(clippy::too_many_arguments)]
    pub fn fill_cancellable(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
        row: impl FnMut(usize, usize, usize, &mut [u8]),
    ) -> bool {
        self.fill_cancellable_in(
            points,
            subpaths,
            width,
            height,
            rule,
            0..usize::MAX,
            should_cancel,
            row,
        )
    }

    /// [`Self::fill_cancellable`] restricted to device rows `rows`: only rows
    /// inside the range are rasterized and handed to `row`.
    ///
    /// The emitted rows are byte-identical to the same rows of an unrestricted
    /// fill. A row's coverage is the prefix sum of the signed areas deposited
    /// into that row alone, by the edges crossing it, in edge order; no other
    /// row contributes. Skipping the rest therefore changes nothing in the
    /// rows that are kept, and a caller that would have discarded them (a clip
    /// mask's envelope, a draw's clipped bounds) saves their whole cost.
    #[allow(clippy::too_many_arguments)]
    pub fn fill_cancellable_in(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        rows: std::ops::Range<usize>,
        should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
        mut row: impl FnMut(usize, usize, usize, &mut [u8]),
    ) -> bool {
        self.fill_impl(
            points,
            subpaths,
            width,
            height,
            rule,
            rows,
            should_cancel,
            false,
            |y, x0, x1, cov, _| {
                row(y, x0, x1, cov);
                true
            },
        )
    }

    /// [`Self::fill_cancellable`] with the row handed over as runs: `row(y,
    /// first, last, cov, runs)` receives, besides the coverage buffer, the
    /// row's [`CovRun`]s in increasing column order. Columns in no run have
    /// zero coverage; a `fill: Some(b)` run was **not** written into `cov`, so
    /// a consumer that only needs spans (a solid Normal fill) can paint a
    /// page-wide interior without the buffer being filled, scanned and reset.
    /// A consumer that wants the plain buffer writes the constant runs into
    /// `cov` itself (within `first..=last`) and returns `true`, so the
    /// buffer is reset over the whole span; returning `false` promises `cov`
    /// was not written outside the `None` runs. The coverage is byte-identical
    /// to [`Self::fill_cancellable`]'s; only the hand-over differs.
    // Production draws always pass their row bounds through the `_in` form;
    // this unrestricted entry remains for the kernel's own tests.
    #[cfg_attr(not(test), allow(dead_code))]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn fill_runs_cancellable(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
        row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
    ) -> bool {
        self.fill_runs_cancellable_in(
            points,
            subpaths,
            width,
            height,
            rule,
            0..usize::MAX,
            should_cancel,
            row,
        )
    }

    /// [`Self::fill_runs_cancellable`] restricted to device rows `rows` (see
    /// [`Self::fill_cancellable_in`] for why the kept rows are unchanged).
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn fill_runs_cancellable_in(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        rows: std::ops::Range<usize>,
        should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
        row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
    ) -> bool {
        self.fill_impl(
            points,
            subpaths,
            width,
            height,
            rule,
            rows,
            should_cancel,
            true,
            row,
        )
    }

    /// The fill driver behind both entries; `runs_mode` selects the
    /// run-aware hand-over of the scanline (AET) path. Clears scratch a
    /// previous, unwound fill may have left dirty (see `dirty`).
    #[allow(clippy::too_many_arguments)]
    fn fill_impl(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        rows: std::ops::Range<usize>,
        should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
        runs_mode: bool,
        row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
    ) -> bool {
        if self.dirty {
            self.reset_cancelled_fill();
        }
        self.dirty = true;
        #[cfg(feature = "profiling")]
        let prof_start = self.prof.time_fills.then(std::time::Instant::now);
        #[cfg(feature = "profiling")]
        let time_rows = self.prof.time_rows;
        #[cfg(feature = "profiling")]
        let (mut callback_ns, mut callback_rows) = (0u64, 0u64);
        #[cfg(feature = "profiling")]
        let mut row = row;
        #[cfg(feature = "profiling")]
        let row = |y: usize, x0: usize, x1: usize, cov: &mut [u8], runs: &[CovRun]| -> bool {
            callback_rows += 1;
            if time_rows {
                let start = std::time::Instant::now();
                let dirty = row(y, x0, x1, cov, runs);
                callback_ns += start.elapsed().as_nanos() as u64;
                dirty
            } else {
                row(y, x0, x1, cov, runs)
            }
        };
        #[cfg(feature = "profiling")]
        {
            self.prof.fill_rows = 0;
        }
        let finished = self.fill_inner(
            points,
            subpaths,
            width,
            height,
            rule,
            rows,
            should_cancel,
            runs_mode,
            row,
        );
        #[cfg(feature = "profiling")]
        {
            let total = prof_start.map_or(0, |start| start.elapsed().as_nanos() as u64);
            let rows = self.prof.fill_rows;
            let covered = if rows > 0 { self.last_covered } else { 0 };
            let c = self.prof.cur();
            c.ns_total += total;
            c.ns_callback += callback_ns;
            c.rows_emitted += callback_rows;
            c.covered_span_px += covered;
            c.clock_reads += if prof_start.is_some() { 2 } else { 0 }
                + if time_rows { 2 * callback_rows } else { 0 };
            if rows > 32 {
                c.fills_rows_gt32 += 1;
                c.ns_rows_gt32 += total;
            } else if rows > 4 {
                c.fills_rows_le32 += 1;
                c.ns_rows_le32 += total;
            } else if rows > 0 {
                c.fills_rows_le4 += 1;
                c.ns_rows_le4 += total;
            }
        }
        self.dirty = false;
        finished
    }

    #[allow(clippy::too_many_arguments)]
    fn fill_inner(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        rows: std::ops::Range<usize>,
        should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
        runs_mode: bool,
        row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
    ) -> bool {
        if width == 0 || height == 0 {
            return true;
        }
        if should_cancel.is_some_and(|cancel| cancel()) {
            return false;
        }
        if self.cov.len() < width {
            self.cov.resize(width, 0);
        }
        #[cfg(feature = "profiling")]
        let mut lap = self.prof.time_fills.then(crate::profiling::Lap::start);
        #[cfg(feature = "profiling")]
        let prof_timed = u64::from(self.prof.time_fills);

        // Build monotonic-in-y edges and the path's device-space bounds.
        self.edges.clear();
        let mut y_min = f32::INFINITY;
        let mut y_max = f32::NEG_INFINITY;
        let mut x_min = f32::INFINITY;
        let mut x_max = f32::NEG_INFINITY;
        for (subpath_index, &(start, end)) in subpaths.iter().enumerate() {
            if subpath_index & 0x3f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                self.reset_cancelled_fill();
                return false;
            }
            let n = end - start;
            if n < 2 {
                continue;
            }
            for i in 0..n {
                let a = points[start + i];
                let b = points[start + (i + 1) % n];
                if a[1] == b[1] {
                    continue;
                }
                let (y_top, y_bot, x_at_top, dir) = if a[1] < b[1] {
                    (a[1], b[1], a[0], 1.0)
                } else {
                    (b[1], a[1], b[0], -1.0)
                };
                let dxdy = (b[0] - a[0]) / (b[1] - a[1]);
                self.edges.push(Edge {
                    y_top,
                    y_bot,
                    x_at_top,
                    dxdy,
                    dir,
                });
                y_min = y_min.min(y_top);
                y_max = y_max.max(y_bot);
                // x-extent of this edge's endpoints (device space).
                let x_at_bot = x_at_top + dxdy * (y_bot - y_top);
                x_min = x_min.min(x_at_top.min(x_at_bot));
                x_max = x_max.max(x_at_top.max(x_at_bot));
            }
        }
        #[cfg(feature = "profiling")]
        {
            let edge_build = crate::profiling::lap_opt(&mut lap);
            let edges = self.edges.len() as u64;
            let c = self.prof.cur();
            c.ns_edge_build += edge_build;
            c.clock_reads += 2 * prof_timed;
            c.fills += 1;
            c.subpaths += subpaths.len() as u64;
            c.edges += edges;
            if edges == 0 {
                c.fills_no_edges += 1;
            }
        }
        if self.edges.is_empty() {
            return true;
        }
        self.last_edges = self.edges.len() as u64;

        let row_start = y_min.floor().max(0.0) as usize;
        let row_end = (y_max.ceil().min(height as f32)) as usize;
        self.last_rows = row_end.saturating_sub(row_start) as u64;
        self.last_covered = 0;
        if row_end <= row_start {
            #[cfg(feature = "profiling")]
            {
                self.prof.cur().fills_no_rows += 1;
            }
            return true;
        }

        // The rows the caller accepts, within the path's own rows. Everything
        // below sizes and routes by the path's full window exactly as an
        // unrestricted fill does (so the same kernel runs); only the rows
        // deposited, converted and emitted are restricted.
        let emit_start = row_start.max(rows.start);
        let emit_end = row_end.min(rows.end);
        if emit_end <= emit_start {
            self.last_rows = 0;
            return true;
        }
        self.last_rows = (emit_end - emit_start) as u64;

        // Device-clamped x-window for the local accumulation buffer.
        let fwidth = width as f32;
        let bx = (x_min.floor().clamp(0.0, (width - 1) as f32)) as usize;
        let right = (x_max.ceil().clamp(0.0, fwidth)) as usize;
        let bw = right.saturating_sub(bx).max(1);
        let bh = row_end - row_start;
        let stride = bw + 2; // + carry cell (+1) + rounding slack (+1)
        let cells = stride.saturating_mul(bh);

        // Route to the scanline reference for a pathologically large single-path
        // window (device-area allocation guard) or a large-but-sparse window
        // (cache locality — see `CACHE_WINDOW_CELLS`). Both are byte-identical to
        // the fast path, so this only trades speed and never regresses output.
        let sparse = cells > CACHE_WINDOW_CELLS && self.edges.len().saturating_mul(8) < cells;
        #[cfg(feature = "profiling")]
        {
            self.prof.fill_rows = bh as u64;
            let c = self.prof.cur();
            c.rows_window += bh as u64;
            if cells > MAX_WINDOW_CELLS {
                c.route_aet_oversize += 1;
                c.aet_window_cells += cells as u64;
            } else if sparse {
                c.route_aet_sparse += 1;
                c.aet_window_cells += cells as u64;
            } else {
                c.route_accum += 1;
                c.accum_window_cells += cells as u64;
            }
        }
        if cells > MAX_WINDOW_CELLS || sparse {
            // The active-edge-table fallback: byte-identical to the naive
            // `fill_scanline_ref` (asserted by `aet_matches_reference_bit_exact`)
            // but O(edges + Σ active) instead of O(edges × rows), which is the
            // whole win on edge-dense sparse-window pages (map contours, etc.).
            let completed = self.fill_scanline_aet(
                width,
                height,
                rule,
                row_start,
                row_end,
                emit_start,
                emit_end,
                should_cancel,
                runs_mode,
                row,
            );
            if !completed {
                self.reset_cancelled_fill();
            }
            return completed;
        }

        if self.acc.len() < cells {
            self.acc.resize(cells, 0.0);
        }
        if self.row_min.len() < bh {
            self.row_min.resize(bh, 0);
            self.row_max.resize(bh, 0);
        }
        for lr in 0..bh {
            self.row_min[lr] = u32::MAX;
            self.row_max[lr] = 0;
        }

        // --- Pass 1: deposit each edge once, into only the rows it crosses. ---
        for edge_index in 0..self.edges.len() {
            if edge_index & 0x3f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                self.reset_cancelled_fill();
                return false;
            }
            let e = self.edges[edge_index];
            let er_start =
                ((e.y_top.floor() as isize).max(row_start as isize) as usize).max(emit_start);
            let er_end =
                ((e.y_bot.ceil() as isize).min(row_end as isize).max(0) as usize).min(emit_end);
            #[cfg(feature = "profiling")]
            {
                self.prof.cur().edge_rows += er_end.saturating_sub(er_start) as u64;
            }
            if e.dxdy == 0.0 {
                // A2: vertical fast path. x is constant; precompute column split.
                let xc = e.x_at_top.clamp(0.0, fwidth);
                let c = (xc.floor().clamp(0.0, fwidth - 1.0)) as usize;
                let lc = c.saturating_sub(bx).min(stride - 2);
                let frac = (c as f32 + 1.0) - xc; // == (c+1) - xmid, with xmid == xc
                for y in er_start..er_end {
                    if y & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                        self.reset_cancelled_fill();
                        return false;
                    }
                    let yf = y as f32;
                    let ya = e.y_top.max(yf);
                    let yb = e.y_bot.min(yf + 1.0);
                    if yb <= ya {
                        continue;
                    }
                    let cover = (yb - ya) * e.dir;
                    let this_px = cover * frac;
                    let lr = y - row_start;
                    let base = lr * stride;
                    self.acc[base + lc] += this_px;
                    self.acc[base + lc + 1] += cover - this_px;
                    if (lc as u32) < self.row_min[lr] {
                        self.row_min[lr] = lc as u32;
                    }
                    if (lc as u32) > self.row_max[lr] {
                        self.row_max[lr] = lc as u32;
                    }
                }
            } else {
                for y in er_start..er_end {
                    if y & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                        self.reset_cancelled_fill();
                        return false;
                    }
                    let yf = y as f32;
                    let ya = e.y_top.max(yf);
                    let yb = e.y_bot.min(yf + 1.0);
                    if yb <= ya {
                        continue;
                    }
                    let xa = e.x_at_top + (ya - e.y_top) * e.dxdy;
                    let xb = e.x_at_top + (yb - e.y_top) * e.dxdy;
                    let lr = y - row_start;
                    let base = lr * stride;
                    deposit_edge_row(
                        &mut self.acc,
                        base,
                        xa,
                        ya,
                        xb,
                        yb,
                        e.dir,
                        fwidth,
                        bx,
                        stride,
                        &mut self.row_min[lr],
                        &mut self.row_max[lr],
                    );
                }
            }
        }

        #[cfg(feature = "profiling")]
        {
            let deposit = crate::profiling::lap_opt(&mut lap);
            let c = self.prof.cur();
            c.ns_accum_deposit += deposit;
            c.clock_reads += 1 * prof_timed;
        }

        // --- Pass 2: per-row prefix-sum → coverage, emit spans, reset. ---
        // The scalar branch is a single fused pass (prefix-sum, convert, emit,
        // reset) — byte-identical to the reference inner loop and with no
        // per-row overhead. Wide rows take the AVX2 conversion, which requires a
        // separate prefix-sum write-back (the SIMD convert cannot fuse with the
        // sequential sum); it is bit-for-bit identical to the scalar branch.
        let use_avx2 = coverage_use_avx2();
        let mut row = row;
        for lr in (emit_start - row_start)..(emit_end - row_start) {
            if lr & 0x1f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                self.reset_cancelled_fill();
                return false;
            }
            let cmin = self.row_min[lr];
            let cmax = self.row_max[lr];
            if cmin > cmax {
                continue;
            }
            let (cmin, cmax) = (cmin as usize, cmax as usize);
            #[cfg(feature = "profiling")]
            {
                self.prof.cur().accum_cells_swept += (cmax - cmin + 1) as u64;
            }
            let base = lr * stride;
            let mut first = width;
            let mut last = 0usize;
            // Wide rows look for untouched gaps and, in run-aware mode, hand
            // the row over as runs; narrow rows (small curved fills, steep
            // hairlines) keep the plain per-cell sweep and a single run, with
            // no per-row bookkeeping.
            let find_gaps = cmax - cmin + 1 >= COMPACT_GAP_MIN_SPAN;
            let mut emit_runs = false;

            // `AVX2_MIN_SPAN == usize::MAX` is the documented "disabled"
            // sentinel (see its doc comment), making this deliberately
            // always-false until a workload lowers the constant.
            #[allow(clippy::absurd_extreme_comparisons)]
            if use_avx2 && cmax - cmin + 1 >= AVX2_MIN_SPAN {
                let acc = &mut self.acc[base..base + stride];
                let mut running = 0.0f32;
                for c in cmin..=cmax {
                    running += acc[c];
                    acc[c] = running;
                }
                convert_coverage(&acc[cmin..=cmax], &mut self.cov, bx + cmin, rule);
                for c in cmin..=cmax {
                    let x = bx + c;
                    if self.cov[x] != 0 {
                        first = first.min(x);
                        last = x;
                    }
                    acc[c] = 0.0;
                }
                acc[cmax + 1] = 0.0;
            } else if !find_gaps {
                let acc = &mut self.acc[base..base + stride];
                let mut running = 0.0f32;
                for c in cmin..=cmax {
                    running += acc[c];
                    acc[c] = 0.0;
                    let byte = coverage_byte(running, rule);
                    let x = bx + c;
                    self.cov[x] = byte;
                    if byte != 0 {
                        first = first.min(x);
                        last = x;
                    }
                }
                acc[cmax + 1] = 0.0;
            } else {
                // A cell no edge touched holds zero, and adding zero leaves the
                // running sum (up to the sign of a zero, which `coverage_byte`
                // does not see) and so the coverage byte unchanged. A stretch
                // of such cells is therefore one constant: its byte is
                // computed once and written with a `fill`, or, in run-aware
                // mode when long enough and fully covered, handed over as a
                // constant run without touching the buffer at all. The bytes, `first` and
                // `last` are exactly those of converting every cell; a
                // rectangle's row costs its two edge cells instead of its
                // width.
                let acc = &mut self.acc[base..base + stride];
                let mut running = 0.0f32;
                self.row_runs.clear();
                // Local column where the pending run of written cells starts.
                let mut cells_from = cmin;
                let mut c = cmin;
                emit_runs = runs_mode;
                while c <= cmax {
                    let v = acc[c];
                    if v == 0.0
                        && c + COMPACT_GAP_PROBE <= cmax + 1
                        && acc[c + 1..c + COMPACT_GAP_PROBE]
                            .iter()
                            .all(|&cell| cell == 0.0)
                    {
                        let gap = acc[c..=cmax]
                            .iter()
                            .position(|&cell| cell != 0.0)
                            .unwrap_or(cmax + 1 - c);
                        let end = c + gap;
                        let byte = coverage_byte(running, rule);
                        // Only empty and fully covered gaps become runs: a
                        // constant *partial* run would take the consumer's
                        // scalar constant blend, slower than the vectorized
                        // mask blend its bytes get.
                        if runs_mode && gap >= COMPACT_RUN_MIN && (byte == 0 || byte == 255) {
                            if cells_from < c {
                                self.row_runs.push(CovRun {
                                    x0: (bx + cells_from) as u32,
                                    x1: (bx + c) as u32,
                                    fill: None,
                                });
                            }
                            if byte != 0 {
                                self.row_runs.push(CovRun {
                                    x0: (bx + c) as u32,
                                    x1: (bx + end) as u32,
                                    fill: Some(byte),
                                });
                                first = first.min(bx + c);
                                last = bx + end - 1;
                            }
                            cells_from = end;
                        } else if byte != 0 {
                            self.cov[bx + c..bx + end].fill(byte);
                            first = first.min(bx + c);
                            last = bx + end - 1;
                        }
                        c = end;
                        continue;
                    }
                    running += v;
                    acc[c] = 0.0;
                    let byte = coverage_byte(running, rule);
                    let x = bx + c;
                    self.cov[x] = byte;
                    if byte != 0 {
                        first = first.min(x);
                        last = x;
                    }
                    c += 1;
                }
                acc[cmax + 1] = 0.0;
                if cells_from <= cmax {
                    self.row_runs.push(CovRun {
                        x0: (bx + cells_from) as u32,
                        x1: (bx + cmax + 1) as u32,
                        fill: None,
                    });
                }
            }

            if first <= last {
                self.last_covered += (last - first + 1) as u64;
                let y = row_start + lr;
                if emit_runs {
                    // Constant runs were not written into the buffer; a
                    // consumer that wrote them itself reports the row dirty.
                    if row(y, first, last, &mut self.cov, &self.row_runs) {
                        self.cov[first..=last].fill(0);
                    } else {
                        for run in &self.row_runs {
                            if run.fill.is_none() {
                                self.cov[run.x0 as usize..run.x1 as usize].fill(0);
                            }
                        }
                    }
                } else {
                    let whole = [CovRun {
                        x0: first as u32,
                        x1: last as u32 + 1,
                        fill: None,
                    }];
                    row(y, first, last, &mut self.cov, &whole);
                    self.cov[first..=last].fill(0);
                }
            }
        }
        #[cfg(feature = "profiling")]
        {
            let sweep = crate::profiling::lap_opt(&mut lap);
            let c = self.prof.cur();
            c.ns_accum_sweep += sweep;
            c.clock_reads += 1 * prof_timed;
        }
        true
    }

    /// Cancellation (or an unwound fill) may leave signed-area deposits in
    /// reusable scratch. Clear them on the exceptional path so the next
    /// render cannot inherit coverage.
    fn reset_cancelled_fill(&mut self) {
        self.acc.fill(0.0);
        self.acc_row.fill(0.0);
        self.cov.fill(0);
        self.aet_active.clear();
        self.aet_active_next.clear();
        self.aet_touched.clear();
        self.row_runs.clear();
    }

    /// Original per-scanline implementation: for each row, every edge is clipped
    /// to `[y, y+1)` and accumulated into an O(width) buffer, then prefix-summed.
    ///
    /// Test-only. Production routes oversized/sparse windows through
    /// [`Self::fill_scanline_aet`]; this naive version is kept solely as the
    /// byte-identity oracle that pins it (`aet_matches_reference_bit_exact`),
    /// so it is compiled out of shipping builds. Edges and bounds are already
    /// built by `fill`.
    #[cfg(test)]
    #[allow(clippy::too_many_arguments)]
    fn fill_scanline_ref(
        &mut self,
        width: usize,
        _height: usize,
        rule: FillRule,
        row_start: usize,
        row_end: usize,
        mut row: impl FnMut(usize, usize, usize, &mut [u8]),
    ) {
        if self.acc_row.len() < width + 1 {
            self.acc_row.resize(width + 1, 0.0);
        }
        let fwidth = width as f32;
        for y in row_start..row_end {
            let yf = y as f32;
            let mut col_min = width;
            let mut col_max = 0usize;
            for e in &self.edges {
                let ya = e.y_top.max(yf);
                let yb = e.y_bot.min(yf + 1.0);
                if yb <= ya {
                    continue;
                }
                let xa = e.x_at_top + (ya - e.y_top) * e.dxdy;
                let xb = e.x_at_top + (yb - e.y_top) * e.dxdy;
                accumulate(
                    &mut self.acc_row,
                    xa,
                    ya,
                    xb,
                    yb,
                    e.dir,
                    fwidth,
                    &mut col_min,
                    &mut col_max,
                );
            }
            if col_min > col_max {
                continue;
            }
            let mut running = 0.0f32;
            let mut first = width;
            let mut last = 0usize;
            for x in col_min..=col_max {
                running += self.acc_row[x];
                self.acc_row[x] = 0.0;
                let byte = coverage_byte(running, rule);
                self.cov[x] = byte;
                if byte != 0 {
                    first = first.min(x);
                    last = x;
                }
            }
            self.acc_row[col_max + 1] = 0.0;
            if first <= last {
                self.last_covered += (last - first + 1) as u64;
                row(y, first, last, &mut self.cov);
                for c in &mut self.cov[first..=last] {
                    *c = 0;
                }
            }
        }
    }

    /// Active-edge-table variant of [`Self::fill_scanline_ref`]: same O(width)
    /// scanline buffer, but instead of rescanning every edge per row it keeps
    /// only the edges overlapping the current row, so cost is O(edges + Σ active)
    /// rather than O(edges × rows). This is the production oversized/sparse-window
    /// fallback; `fill_scanline_ref` is retained naive as the byte-identity
    /// oracle. Bit-exactness holds because, per row, the *contributing* edges
    /// (those passing the `yb <= ya` clip) are accumulated in the identical
    /// original-edge-index order — only non-contributing float no-ops are skipped.
    #[allow(clippy::too_many_arguments)]
    fn fill_scanline_aet(
        &mut self,
        width: usize,
        _height: usize,
        rule: FillRule,
        row_start: usize,
        row_end: usize,
        emit_start: usize,
        emit_end: usize,
        should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
        runs_mode: bool,
        mut row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
    ) -> bool {
        if self.acc_row.len() < width + 1 {
            self.acc_row.resize(width + 1, 0.0);
        }
        let fwidth = width as f32;
        let bh = row_end - row_start;
        #[cfg(feature = "profiling")]
        let mut lap = self.prof.time_fills.then(crate::profiling::Lap::start);
        #[cfg(feature = "profiling")]
        let prof_timed = u64::from(self.prof.time_fills);

        // --- CSR counting sort: bucket contributing edges by activation row. ---
        // An edge's row span is exactly the fast path's (raster.rs deposit loop):
        // the saturating `as` casts also fix NaN (→0) and out-of-range coords, so
        // the AET must reproduce them verbatim rather than "improve" on them.
        //
        // With a row window (`emit_start..emit_end`), an edge that starts above
        // it is bucketed at the window's first row instead, and one that lies
        // wholly outside is dropped. Buckets are still filled in edge-index
        // order, so every row inside the window sees the same contributing
        // edges in the same order as the unrestricted sweep.
        self.aet_bucket_start.clear();
        self.aet_bucket_start.resize(bh + 1, 0);
        if self.aet_erend.len() < self.edges.len() {
            self.aet_erend.resize(self.edges.len(), 0);
        }
        let mut contributing = 0usize;
        #[cfg(feature = "profiling")]
        let mut prof_edge_rows = 0u64;
        for (edge_index, e) in self.edges.iter().enumerate() {
            if edge_index & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                return false;
            }
            let er_start = (e.y_top.floor() as isize)
                .max(row_start as isize)
                .max(emit_start as isize);
            let er_end = (e.y_bot.ceil() as isize)
                .min(row_end as isize)
                .max(0)
                .min(emit_end as isize);
            if er_start >= er_end {
                continue; // touches no row — a pure no-op in the reference too
            }
            let lr = er_start as usize - row_start;
            self.aet_bucket_start[lr + 1] += 1; // count into [lr+1] for the scan
            contributing += 1;
            #[cfg(feature = "profiling")]
            {
                prof_edge_rows += (er_end - er_start) as u64;
            }
        }
        for lr in 0..bh {
            self.aet_bucket_start[lr + 1] += self.aet_bucket_start[lr];
        }
        // Scatter edge indices in edge-index order → every bucket is index-sorted
        // for free. `aet_active_next` doubles as the per-row write cursor here.
        self.aet_order.clear();
        self.aet_order.resize(contributing, 0);
        self.aet_active_next.clear();
        self.aet_active_next
            .extend_from_slice(&self.aet_bucket_start[..bh]);
        for (i, e) in self.edges.iter().enumerate() {
            if i & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                return false;
            }
            let er_start = (e.y_top.floor() as isize)
                .max(row_start as isize)
                .max(emit_start as isize);
            let er_end = (e.y_bot.ceil() as isize)
                .min(row_end as isize)
                .max(0)
                .min(emit_end as isize);
            if er_start >= er_end {
                continue;
            }
            let lr = er_start as usize - row_start;
            let pos = self.aet_active_next[lr] as usize;
            self.aet_order[pos] = i as u32;
            self.aet_active_next[lr] += 1;
            self.aet_erend[i] = er_end as u32;
        }

        // --- Sweep rows, maintaining the index-sorted active list. ---
        //
        // Row repetition (run-aware mode only): when every active edge of a
        // row is vertical and spans the whole row, each deposit is
        // `accumulate(x, yf, x, yf + 1, dir)` — the same columns, the same
        // `cover = ((yf + 1) - yf) * dir = dir` (exact for `y < 2^24`) and the
        // same `x = x_at_top + (yf - y_top) * 0.0` (a zero of fixed sign, or
        // NaN in every row alike) — so the next row with the same active set,
        // still spanning it, accumulates bit-identical values in the same
        // order and converts to the same cells, runs and span. Its cells are
        // then kept in `cov` (`held`) and re-emitted instead of re-deposited
        // and re-converted: the interior rows of a page-sized rectangle or of
        // a stroked frame. Any change (an edge activating or retiring, an
        // edge ending inside the row, a consumer that wrote the buffer)
        // releases the held cells and computes the row normally.
        let mut held: Option<(usize, usize)> = None;
        self.aet_active.clear();
        #[cfg(feature = "profiling")]
        {
            let setup = crate::profiling::lap_opt(&mut lap);
            let c = self.prof.cur();
            c.ns_aet_setup += setup;
            c.edge_rows += prof_edge_rows;
            c.clock_reads += 2 * prof_timed;
        }
        for lr in (emit_start - row_start)..(emit_end - row_start) {
            if lr & 0x0f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                return false;
            }
            let y = row_start + lr;
            let yf = y as f32;
            let yu = y as u32;
            let prev_active = self.aet_active.len();

            // Merge row `lr`'s newly-activating edges into the active list,
            // dropping retired ones (er_end <= y), all order-preserving. Bucket
            // edges have er_start == y so they never retire this row; active and
            // bucket index-sets are disjoint, so no equal-key case arises.
            let b0 = self.aet_bucket_start[lr] as usize;
            let b1 = self.aet_bucket_start[lr + 1] as usize;
            self.aet_active_next.clear();
            let mut i = 0usize;
            let mut j = b0;
            while i < self.aet_active.len() && j < b1 {
                let a = self.aet_active[i];
                if self.aet_erend[a as usize] <= yu {
                    i += 1;
                    continue;
                }
                let bk = self.aet_order[j];
                if a < bk {
                    self.aet_active_next.push(a);
                    i += 1;
                } else {
                    self.aet_active_next.push(bk);
                    j += 1;
                }
            }
            while i < self.aet_active.len() {
                let a = self.aet_active[i];
                if self.aet_erend[a as usize] > yu {
                    self.aet_active_next.push(a);
                }
                i += 1;
            }
            while j < b1 {
                self.aet_active_next.push(self.aet_order[j]);
                j += 1;
            }
            std::mem::swap(&mut self.aet_active, &mut self.aet_active_next);

            if let Some((first, last)) = held {
                // No activation and no retirement leaves the (index-sorted)
                // active set unchanged; each edge must still span this row.
                let repeat = b0 == b1
                    && self.aet_active.len() == prev_active
                    && self
                        .aet_active
                        .iter()
                        .all(|&ei| self.edges[ei as usize].y_bot >= yf + 1.0);
                if repeat {
                    #[cfg(feature = "profiling")]
                    {
                        self.prof.cur().aet_rows_repeated += 1;
                    }
                    self.last_covered += (last - first + 1) as u64;
                    if row(y, first, last, &mut self.cov, &self.row_runs) {
                        for c in &mut self.cov[first..=last] {
                            *c = 0;
                        }
                        held = None;
                    }
                    continue;
                }
                for r in &self.row_runs {
                    if r.fill.is_none() {
                        self.cov[r.x0 as usize..r.x1 as usize].fill(0);
                    }
                }
                held = None;
            }

            // Accumulate active edges in edge-index order — identical operands
            // and order to the reference's `for e in &self.edges` filtered loop.
            let active = std::mem::take(&mut self.aet_active);
            let mut col_min = width;
            let mut col_max = 0usize;
            // Whether this row may be held for repetition (see above).
            let mut all_vertical_full = runs_mode && y < (1 << 24);
            self.aet_touched.clear();
            for (active_index, &ei) in active.iter().enumerate() {
                if active_index & 0xfff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
                    self.aet_active = active;
                    return false;
                }
                let e = self.edges[ei as usize];
                let ya = e.y_top.max(yf);
                let yb = e.y_bot.min(yf + 1.0);
                all_vertical_full &= e.dxdy == 0.0 && ya == yf && yb == yf + 1.0;
                if yb <= ya {
                    continue;
                }
                let xa = e.x_at_top + (ya - e.y_top) * e.dxdy;
                let xb = e.x_at_top + (yb - e.y_top) * e.dxdy;
                // Per-edge touched range: `deposit_partial` writes cells
                // `c` and `c + 1` for every column `c` it reports.
                let mut edge_min = width;
                let mut edge_max = 0usize;
                accumulate(
                    &mut self.acc_row,
                    xa,
                    ya,
                    xb,
                    yb,
                    e.dir,
                    fwidth,
                    &mut edge_min,
                    &mut edge_max,
                );
                if edge_min <= edge_max {
                    col_min = col_min.min(edge_min);
                    col_max = col_max.max(edge_max);
                    self.aet_touched
                        .push((edge_min as u32, edge_max as u32 + 2));
                }
            }
            self.aet_active = active;

            #[cfg(feature = "profiling")]
            {
                self.prof.cur().aet_active_visits += self.aet_active.len() as u64;
            }
            if col_min > col_max {
                continue;
            }
            #[cfg(feature = "profiling")]
            {
                let span = (col_max - col_min + 1) as u64;
                let intervals = self.aet_touched.len();
                let c = self.prof.cur();
                if intervals > SPARSE_MAX_INTERVALS {
                    c.aet_rows_dense_many += 1;
                    c.aet_dense_cells_swept += span;
                } else if (span as usize) < SPARSE_MIN_SPAN {
                    c.aet_rows_dense_short += 1;
                    c.aet_dense_cells_swept += span;
                } else {
                    c.aet_rows_sparse += 1;
                }
            }
            self.row_runs.clear();
            let (first, last) = convert_row_sparse(
                &mut self.acc_row,
                &mut self.cov,
                &mut self.aet_touched,
                col_min,
                col_max,
                rule,
                runs_mode.then_some(&mut self.row_runs),
            );
            if first <= last {
                self.last_covered += (last - first + 1) as u64;
                let dirty = row(y, first, last, &mut self.cov, &self.row_runs);
                if !runs_mode || dirty {
                    for c in &mut self.cov[first..=last] {
                        *c = 0;
                    }
                } else if all_vertical_full {
                    held = Some((first, last));
                } else {
                    // Only the cell runs were written (and may hold coverage).
                    for r in &self.row_runs {
                        if r.fill.is_none() {
                            self.cov[r.x0 as usize..r.x1 as usize].fill(0);
                        }
                    }
                }
            }
        }
        if held.is_some() {
            for r in &self.row_runs {
                if r.fill.is_none() {
                    self.cov[r.x0 as usize..r.x1 as usize].fill(0);
                }
            }
        }
        #[cfg(feature = "profiling")]
        {
            let sweep = crate::profiling::lap_opt(&mut lap);
            let c = self.prof.cur();
            c.ns_aet_sweep += sweep;
            c.clock_reads += 1 * prof_timed;
        }
        true
    }
}

/// Convert a run of prefix-summed signed-area values (`running[i]`) into coverage
/// bytes written at `cov[dst_start + i]`. Runtime-dispatched to AVX2 when
/// available; the scalar reference and the AVX2 path are bit-for-bit identical.
/// Above this many contributing edges on one row the touched intervals are
/// dense enough that sorting them costs more than the cells they would skip;
/// the row takes the plain dense sweep instead.
const SPARSE_MAX_INTERVALS: usize = 48;
/// Below this row span the dense sweep is already a handful of cells.
const SPARSE_MIN_SPAN: usize = 64;

/// Pass 2 for one scanline of the scanline (AET) path: prefix-sum the signed
/// areas in `acc[col_min..=col_max]` into coverage bytes in `cov`, reset the
/// touched cells, and return the first and last column with non-zero coverage
/// (`first > last` when none).
///
/// `touched` lists the `[start, end)` cell ranges the row's deposits wrote,
/// one per contributing edge. Cells outside every range still hold `0.0`, so
/// adding them leaves the running sum unchanged (up to the sign of zero, which
/// `coverage_byte` does not see): the running coverage is constant across each
/// gap and is written with one `fill` instead of a per-cell sum, convert, and
/// reset. This is what makes a page-sized rectangle, or the stroked border of
/// one, cost a few cells per row instead of a full-width float walk; the
/// output is byte-identical to the dense sweep (`aet_sparse_rows_match_dense`).
/// A row with many edges or a short span runs the dense sweep unchanged.
///
/// With `runs` (run-aware mode) the constant non-zero gaps are recorded as
/// `fill: Some(byte)` runs instead of being written into `cov`, and the
/// converted cells as `fill: None` runs; zero gaps are omitted. `first` /
/// `last` and every written cell are the same in both modes.
fn convert_row_sparse(
    acc: &mut [f32],
    cov: &mut [u8],
    touched: &mut [(u32, u32)],
    col_min: usize,
    col_max: usize,
    rule: FillRule,
    mut runs: Option<&mut Vec<CovRun>>,
) -> (usize, usize) {
    let width = cov.len();
    let mut running = 0.0f32;
    let mut first = width;
    let mut last = 0usize;

    // Append a written-cells run, merging with an adjacent one.
    fn push_cells(runs: &mut Option<&mut Vec<CovRun>>, x0: usize, x1: usize) {
        if let Some(runs) = runs.as_deref_mut()
            && x0 < x1
        {
            match runs.last_mut() {
                Some(prev) if prev.fill.is_none() && prev.x1 as usize == x0 => prev.x1 = x1 as u32,
                _ => runs.push(CovRun {
                    x0: x0 as u32,
                    x1: x1 as u32,
                    fill: None,
                }),
            }
        }
    }

    if touched.len() > SPARSE_MAX_INTERVALS || col_max - col_min + 1 < SPARSE_MIN_SPAN {
        push_cells(&mut runs, col_min, col_max + 1);
        for x in col_min..=col_max {
            running += acc[x];
            acc[x] = 0.0;
            let byte = coverage_byte(running, rule);
            cov[x] = byte;
            if byte != 0 {
                first = first.min(x);
                last = x;
            }
        }
        acc[col_max + 1] = 0.0;
        return (first, last);
    }

    touched.sort_unstable_by_key(|range| range.0);
    // Cells are converted through `col_max` (as the dense sweep does); the
    // carry cell `col_max + 1` is only reset.
    let convert_end = col_max + 1;
    let mut x = col_min;
    let mut i = 0;
    while i < touched.len() {
        let (start, mut end) = touched[i];
        i += 1;
        while i < touched.len() && touched[i].0 <= end {
            end = end.max(touched[i].1);
            i += 1;
        }
        let start = (start as usize).max(x);
        let end = end as usize;
        // Gap before this interval: untouched cells, constant coverage.
        if start > x {
            let byte = coverage_byte(running, rule);
            if byte != 0 {
                match runs.as_deref_mut() {
                    Some(runs) => runs.push(CovRun {
                        x0: x as u32,
                        x1: start as u32,
                        fill: Some(byte),
                    }),
                    None => cov[x..start].fill(byte),
                }
                first = first.min(x);
                last = start - 1;
            }
            x = start;
        }
        let stop = end.min(convert_end);
        push_cells(&mut runs, x, stop);
        while x < stop {
            running += acc[x];
            acc[x] = 0.0;
            let byte = coverage_byte(running, rule);
            cov[x] = byte;
            if byte != 0 {
                first = first.min(x);
                last = x;
            }
            x += 1;
        }
        for cell in &mut acc[stop..end] {
            *cell = 0.0;
        }
    }
    if x < convert_end {
        let byte = coverage_byte(running, rule);
        if byte != 0 {
            match runs {
                Some(runs) => runs.push(CovRun {
                    x0: x as u32,
                    x1: convert_end as u32,
                    fill: Some(byte),
                }),
                None => cov[x..convert_end].fill(byte),
            }
            first = first.min(x);
            last = col_max;
        }
    }
    acc[col_max + 1] = 0.0;
    (first, last)
}

/// Whether the AVX2 coverage-conversion path is available. The feature probe is
/// cached by the intrinsic, so this is a cheap load.
#[inline]
fn coverage_use_avx2() -> bool {
    #[cfg(target_arch = "x86_64")]
    {
        is_x86_feature_detected!("avx2")
    }
    #[cfg(not(target_arch = "x86_64"))]
    {
        false
    }
}

#[inline]
#[allow(
    unsafe_code,
    reason = "dispatches the AVX2 coverage kernel behind a runtime probe; see SAFETY comment"
)]
fn convert_coverage(running: &[f32], cov: &mut [u8], dst_start: usize, rule: FillRule) {
    // Slice the destination once, here, so the AVX2 kernel's length
    // precondition is a slice invariant rather than a caller promise: a wrong
    // `dst_start` panics on this index in *both* paths instead of becoming an
    // out-of-bounds write in the vector one.
    let dst = &mut cov[dst_start..dst_start + running.len()];
    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: AVX2 is present (runtime probe above) and
            // `dst.len() == running.len()` by construction of the slice.
            unsafe {
                convert_coverage_avx2(running, dst, rule);
            }
            return;
        }
    }
    convert_coverage_scalar(running, dst, rule);
}

/// Scalar reference for [`convert_coverage`]. `cov` is the already-offset
/// destination, so it and the AVX2 kernel take the same shape of argument.
#[inline]
fn convert_coverage_scalar(running: &[f32], cov: &mut [u8], rule: FillRule) {
    for (i, &r) in running.iter().enumerate() {
        cov[i] = coverage_byte(r, rule);
    }
}

/// The single source of truth for signed-area → coverage byte. Scalar; the AVX2
/// path replicates this op sequence per lane.
#[inline(always)]
fn coverage_byte(running: f32, rule: FillRule) -> u8 {
    let c = match rule {
        FillRule::NonZero => running.abs().min(1.0),
        FillRule::EvenOdd => {
            let m = running - 2.0 * (running * 0.5).floor();
            if m > 1.0 { 2.0 - m } else { m }
        }
    };
    (c * 255.0 + 0.5) as u8
}

/// AVX2 coverage conversion. Each lane runs the exact scalar `coverage_byte` op
/// sequence — abs via andnot, `min`/`floor`/compare via their intrinsics, the
/// `* 255.0` and `+ 0.5` as separate rounded ops (no FMA), and a truncating
/// f32→i32 cast (`cvtt`) matching `as u8` — so the result is bit-for-bit
/// identical to the scalar path. Verified by
/// `tests::avx2_convert_matches_scalar_bit_exact`.
///
/// # Safety
/// * The CPU must support AVX2 (the caller's runtime probe establishes this).
/// * `cov.len() >= running.len()` — the kernel writes `running.len()` bytes at
///   `cov[0..]` through unchecked stores. [`convert_coverage`] guarantees this
///   by slicing the destination to exactly `running.len()` before the call.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[allow(unsafe_code)]
unsafe fn convert_coverage_avx2(running: &[f32], cov: &mut [u8], rule: FillRule) {
    use core::arch::x86_64::*;

    let n = running.len();
    debug_assert!(
        cov.len() >= n,
        "convert_coverage_avx2: destination {} shorter than {n} coverage values",
        cov.len()
    );
    let sign = _mm256_set1_ps(-0.0);
    let one = _mm256_set1_ps(1.0);
    let two = _mm256_set1_ps(2.0);
    let half = _mm256_set1_ps(0.5);
    let s255 = _mm256_set1_ps(255.0);

    let mut i = 0usize;
    while i + 8 <= n {
        // SAFETY: `i + 8 <= n == running.len()`.
        let r = unsafe { _mm256_loadu_ps(running.as_ptr().add(i)) };
        let c = match rule {
            FillRule::NonZero => {
                // abs(r) then min(_, 1.0)
                let a = _mm256_andnot_ps(sign, r);
                _mm256_min_ps(a, one)
            }
            FillRule::EvenOdd => {
                // m = r - 2*floor(r*0.5); c = if m > 1 { 2 - m } else { m }
                let h = _mm256_mul_ps(r, half);
                let fh = _mm256_floor_ps(h);
                let m = _mm256_sub_ps(r, _mm256_mul_ps(two, fh));
                let gt = _mm256_cmp_ps::<_CMP_GT_OQ>(m, one);
                _mm256_blendv_ps(m, _mm256_sub_ps(two, m), gt)
            }
        };
        // (c * 255.0 + 0.5), separate mul/add to match scalar rounding.
        let scaled = _mm256_add_ps(_mm256_mul_ps(c, s255), half);
        // Truncating cast (matches `as u8`); values sit in [0.5, 255.5].
        let ints = _mm256_cvttps_epi32(scaled);
        // Pack 8×i32 → 8×u8: lane 0-3 and 4-7 packed to u16, then to u8.
        let lo = _mm256_castsi256_si128(ints);
        let hi = _mm256_extracti128_si256::<1>(ints);
        let p16 = _mm_packus_epi32(lo, hi); // 8×u16, in order 0..7
        let p8 = _mm_packus_epi16(p16, p16); // low 8 bytes = elems 0..7
        let bytes = _mm_cvtsi128_si64(p8) as u64;
        // SAFETY: `i + 8 <= n <= cov.len()` (the function's safety contract),
        // so the eight bytes written are inside `cov`.
        unsafe {
            let dst = cov.as_mut_ptr().add(i);
            core::ptr::copy_nonoverlapping(&bytes as *const u64 as *const u8, dst, 8);
        }
        i += 8;
    }
    // Scalar tail.
    while i < n {
        // SAFETY: `i < n <= cov.len()` (the function's safety contract).
        unsafe {
            *cov.get_unchecked_mut(i) = coverage_byte(*running.get_unchecked(i), rule);
        }
        i += 1;
    }
}

/// Deposit one edge segment (from `(xa, ya)` to `(xb, yb)`, `ya < yb`, both
/// within one scanline row) into a single local row of the 2D accumulation
/// buffer. `row_acc` is that row's slice (length `stride`); `bx` maps absolute
/// device columns to local indices. Byte-identical to `accumulate` — same area
/// math, only the storage index is local.
#[allow(clippy::too_many_arguments)]
#[inline]
fn deposit_edge_row(
    acc: &mut [f32],
    base: usize,
    xa: f32,
    ya: f32,
    xb: f32,
    yb: f32,
    dir: f32,
    width: f32,
    bx: usize,
    stride: usize,
    col_min: &mut u32,
    col_max: &mut u32,
) {
    let xa = xa.clamp(0.0, width);
    let xb = xb.clamp(0.0, width);
    let cover_total = (yb - ya) * dir;
    let (x0, x1) = if xa <= xb { (xa, xb) } else { (xb, xa) };
    let span = x1 - x0;

    if span < 1e-9 {
        deposit_local(
            acc,
            base,
            x0.floor(),
            cover_total,
            x0,
            width,
            bx,
            stride,
            col_min,
            col_max,
        );
        return;
    }

    let cover_per_x = cover_total / span;
    let mut c = x0.floor();
    while c < x1 - 1e-9 {
        let lo = c.max(x0);
        let hi = (c + 1.0).min(x1);
        if hi > lo {
            let cover_sub = cover_per_x * (hi - lo);
            let xmid = 0.5 * (lo + hi);
            deposit_local(
                acc, base, c, cover_sub, xmid, width, bx, stride, col_min, col_max,
            );
        }
        c += 1.0;
    }
}

/// Single-column deposit into local row `base` of `acc` (analog of
/// `deposit_partial`). `col` and `xmid` are absolute device coordinates (so the
/// area math matches the reference exactly); the write lands at `base + (col - bx)`.
#[allow(clippy::too_many_arguments)]
#[inline]
fn deposit_local(
    acc: &mut [f32],
    base: usize,
    col: f32,
    cover: f32,
    xmid: f32,
    width: f32,
    bx: usize,
    stride: usize,
    col_min: &mut u32,
    col_max: &mut u32,
) {
    let c = col.clamp(0.0, width - 1.0) as usize;
    let this_px = cover * ((c as f32 + 1.0) - xmid);
    let lc = c.saturating_sub(bx).min(stride - 2);
    acc[base + lc] += this_px;
    acc[base + lc + 1] += cover - this_px;
    if (lc as u32) < *col_min {
        *col_min = lc as u32;
    }
    if (lc as u32) > *col_max {
        *col_max = lc as u32;
    }
}

/// Reference per-scanline accumulate (unchanged original). Distributes the total
/// vertical crossing across the columns the segment spans.
#[allow(clippy::too_many_arguments)]
#[inline]
fn accumulate(
    acc: &mut [f32],
    xa: f32,
    ya: f32,
    xb: f32,
    yb: f32,
    dir: f32,
    width: f32,
    col_min: &mut usize,
    col_max: &mut usize,
) {
    let xa = xa.clamp(0.0, width);
    let xb = xb.clamp(0.0, width);
    let cover_total = (yb - ya) * dir;
    let (x0, x1) = if xa <= xb { (xa, xb) } else { (xb, xa) };
    let span = x1 - x0;

    if span < 1e-9 {
        deposit_partial(acc, x0.floor(), cover_total, x0, width, col_min, col_max);
        return;
    }

    let cover_per_x = cover_total / span;
    let mut c = x0.floor();
    while c < x1 - 1e-9 {
        let lo = c.max(x0);
        let hi = (c + 1.0).min(x1);
        if hi > lo {
            let cover_sub = cover_per_x * (hi - lo);
            let xmid = 0.5 * (lo + hi);
            deposit_partial(acc, c, cover_sub, xmid, width, col_min, col_max);
        }
        c += 1.0;
    }
}

#[inline]
fn deposit_partial(
    acc: &mut [f32],
    col: f32,
    cover: f32,
    xmid: f32,
    width: f32,
    col_min: &mut usize,
    col_max: &mut usize,
) {
    let c = col.clamp(0.0, width - 1.0) as usize;
    let this_px = cover * ((c as f32 + 1.0) - xmid);
    acc[c] += this_px;
    acc[c + 1] += cover - this_px;
    *col_min = (*col_min).min(c);
    *col_max = (*col_max).max(c);
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;

    fn coverage_grid(
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        w: usize,
        h: usize,
        rule: FillRule,
    ) -> Vec<u8> {
        let mut grid = vec![0u8; w * h];
        let mut k = RasterKernel::default();
        k.fill(points, subpaths, w, h, rule, |y, x0, x1, cov: &mut [u8]| {
            grid[y * w + x0..y * w + x1 + 1].copy_from_slice(&cov[x0..=x1]);
        });
        grid
    }

    /// Drive the reference per-scanline path directly (independent of the
    /// fast-path window cap) for byte-for-byte comparison.
    fn coverage_grid_ref(
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        w: usize,
        h: usize,
        rule: FillRule,
    ) -> Vec<u8> {
        let mut grid = vec![0u8; w * h];
        let mut k = RasterKernel::default();
        k.run_reference(points, subpaths, w, h, rule, |y, x0, x1, cov: &mut [u8]| {
            grid[y * w + x0..y * w + x1 + 1].copy_from_slice(&cov[x0..=x1]);
        });
        grid
    }

    /// Drive the production AET fallback directly (independent of the window
    /// cap) for byte-for-byte comparison against the naive reference.
    fn coverage_grid_aet(
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        w: usize,
        h: usize,
        rule: FillRule,
    ) -> Vec<u8> {
        let mut grid = vec![0u8; w * h];
        let mut k = RasterKernel::default();
        k.run_aet(points, subpaths, w, h, rule, |y, x0, x1, cov: &mut [u8]| {
            grid[y * w + x0..y * w + x1 + 1].copy_from_slice(&cov[x0..=x1]);
        });
        grid
    }

    /// Flattened device-space geometry: points plus `(start, end)` subpaths.
    type Geometry = (Vec<[f32; 2]>, Vec<(usize, usize)>);

    fn rect(x0: f32, y0: f32, x1: f32, y1: f32) -> Geometry {
        (vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]], vec![(0, 4)])
    }

    #[test]
    fn integer_rect_is_exact() {
        let (p, s) = rect(1.0, 1.0, 3.0, 3.0);
        let g = coverage_grid(&p, &s, 4, 4, FillRule::NonZero);
        for y in 0..4 {
            for x in 0..4 {
                let expected = if (1..3).contains(&x) && (1..3).contains(&y) {
                    255
                } else {
                    0
                };
                assert_eq!(g[y * 4 + x], expected, "pixel ({x},{y})");
            }
        }
    }

    #[test]
    fn cancellable_fill_stops_inside_one_path_and_resets_worker_scratch() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let (points, subpaths) = rect(0.0, 0.0, 128.0, 4096.0);
        let checks = AtomicUsize::new(0);
        let cancel = || checks.fetch_add(1, Ordering::Relaxed) >= 2;
        let mut rows = 0usize;
        let mut kernel = RasterKernel::default();
        let completed = kernel.fill_cancellable(
            &points,
            &subpaths,
            128,
            4096,
            FillRule::NonZero,
            Some(&cancel),
            |_, _, _, _| rows += 1,
        );
        assert!(!completed, "the single long fill must observe cancellation");
        assert!(rows < 4096, "cancellation must stop before page completion");

        // A cancelled deposit pass must not leak signed-area scratch into the
        // next request handled by this worker.
        let mut recovered = vec![0u8; 4];
        let (small_points, small_subpaths) = rect(0.0, 0.0, 2.0, 2.0);
        kernel.fill(
            &small_points,
            &small_subpaths,
            2,
            2,
            FillRule::NonZero,
            |y, x0, x1, cov| {
                recovered[y * 2 + x0..=y * 2 + x1].copy_from_slice(&cov[x0..=x1]);
            },
        );
        assert_eq!(recovered, vec![255; 4]);
    }

    /// A fill that unwinds out of its row callback leaves its deposits in the
    /// kernel's scratch. A worker that catches the panic and keeps the kernel
    /// must still fill the next path exactly as a fresh kernel does, on both
    /// the compact (2D accumulator) and the wide (AET) path.
    #[test]
    fn a_fill_after_an_unwound_fill_matches_a_fresh_kernel() {
        let grid = |kernel: &mut RasterKernel, g: &Geometry, w: usize, h: usize| {
            let mut out = vec![0u8; w * h];
            kernel.fill(&g.0, &g.1, w, h, FillRule::NonZero, |y, x0, x1, cov| {
                out[y * w + x0..=y * w + x1].copy_from_slice(&cov[x0..=x1]);
            });
            out
        };
        // (width, height, the fill that panics, the fill after it)
        let cases: [(usize, usize, Geometry, Geometry); 2] = [
            (
                48,
                48,
                (vec![[1.3, 0.7], [46.2, 3.1], [20.5, 47.4]], vec![(0, 3)]),
                rect(4.25, 4.75, 40.5, 41.0),
            ),
            (
                1193,
                24,
                (vec![[0.4, 0.2], [1192.7, 11.3], [3.1, 23.9]], vec![(0, 3)]),
                rect(2.0, 5.5, 1150.0, 6.0),
            ),
        ];
        for (w, h, first, second) in cases {
            let want = grid(&mut RasterKernel::default(), &second, w, h);
            let mut kernel = RasterKernel::default();
            let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let mut rows = 0;
                kernel.fill(&first.0, &first.1, w, h, FillRule::NonZero, |_, _, _, _| {
                    rows += 1;
                    if rows == 3 {
                        panic!("synthetic panic inside a fill");
                    }
                });
            }));
            assert!(unwound.is_err());
            let got = grid(&mut kernel, &second, w, h);
            assert!(
                got == want,
                "{w}x{h}: the fill after an unwound fill differs from a fresh kernel's"
            );
        }
    }

    #[test]
    fn half_pixel_horizontal_is_exact() {
        let (p, s) = rect(0.0, 0.0, 0.5, 2.0);
        let g = coverage_grid(&p, &s, 2, 2, FillRule::NonZero);
        for y in 0..2 {
            assert!(
                (g[y * 2] as i32 - 128).abs() <= 1,
                "left col row {y} = {}",
                g[y * 2]
            );
            assert_eq!(g[y * 2 + 1], 0);
        }
    }

    #[test]
    fn half_pixel_vertical_is_exact() {
        let (p, s) = rect(0.0, 0.0, 2.0, 0.5);
        let g = coverage_grid(&p, &s, 2, 2, FillRule::NonZero);
        assert!((g[0] as i32 - 128).abs() <= 1, "row0 = {}", g[0]);
        assert_eq!(g[2], 0, "row1 uncovered");
    }

    #[test]
    fn even_odd_hole() {
        let mut p = vec![[0.0, 0.0], [6.0, 0.0], [6.0, 6.0], [0.0, 6.0]];
        p.extend_from_slice(&[[2.0, 2.0], [4.0, 2.0], [4.0, 4.0], [2.0, 4.0]]);
        let s = vec![(0, 4), (4, 8)];
        let g = coverage_grid(&p, &s, 6, 6, FillRule::EvenOdd);
        assert_eq!(g[3 * 6 + 3], 0, "hole center");
        assert_eq!(g[3 * 6 + 1], 255, "ring pixel");
    }

    #[test]
    fn nonzero_overlap_saturates() {
        let mut p = vec![[0.0, 0.0], [3.0, 0.0], [3.0, 3.0], [0.0, 3.0]];
        p.extend_from_slice(&[[1.0, 0.0], [4.0, 0.0], [4.0, 3.0], [1.0, 3.0]]);
        let s = vec![(0, 4), (4, 8)];
        let g = coverage_grid(&p, &s, 4, 3, FillRule::NonZero);
        assert_eq!(g[2], 255, "overlap column stays 255");
    }

    #[test]
    fn triangle_area_matches() {
        let p = vec![[0.0, 0.0], [4.0, 0.0], [0.0, 4.0]];
        let s = vec![(0, 3)];
        let g = coverage_grid(&p, &s, 4, 4, FillRule::NonZero);
        let total: f32 = g.iter().map(|&b| b as f32 / 255.0).sum();
        assert!((total - 8.0).abs() < 0.1, "area ~= {total}");
    }

    // Deterministic PRNG for fuzzing edge geometry.
    struct Lcg(u64);
    impl Lcg {
        fn next_u32(&mut self) -> u32 {
            self.0 = self
                .0
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (self.0 >> 33) as u32
        }
        fn f(&mut self, lo: f32, hi: f32) -> f32 {
            lo + (self.next_u32() as f32 / u32::MAX as f32) * (hi - lo)
        }
    }

    fn random_path(rng: &mut Lcg, w: f32, h: f32) -> (Vec<[f32; 2]>, Vec<(usize, usize)>) {
        let mut pts = Vec::new();
        let mut subs = Vec::new();
        let nsub = 1 + (rng.next_u32() % 3) as usize;
        for _ in 0..nsub {
            let start = pts.len();
            let nv = 3 + (rng.next_u32() % 6) as usize;
            for _ in 0..nv {
                pts.push([rng.f(-2.0, w + 2.0), rng.f(-2.0, h + 2.0)]);
            }
            subs.push((start, pts.len()));
        }
        (pts, subs)
    }

    /// The fast path must be byte-for-byte identical to the reference
    /// per-scanline path across a large corpus of random geometry, for both
    /// fill rules. This is the determinism gate: if it holds, page hashes are
    /// unchanged from the pre-rewrite kernel.
    #[test]
    fn fast_path_matches_reference_bit_exact() {
        let mut rng = Lcg(0xC0FFEE_1234_5678);
        for w in [1usize, 3, 8, 17, 40, 128] {
            for h in [1usize, 3, 8, 17, 40, 96] {
                for rule in [FillRule::NonZero, FillRule::EvenOdd] {
                    for _ in 0..40 {
                        let (p, s) = random_path(&mut rng, w as f32, h as f32);
                        let fast = coverage_grid(&p, &s, w, h, rule);
                        let refr = coverage_grid_ref(&p, &s, w, h, rule);
                        assert_eq!(
                            fast, refr,
                            "fast vs reference mismatch at {w}x{h} rule {rule:?}"
                        );
                    }
                }
            }
        }
    }

    /// The AET fallback must be byte-for-byte identical to the naive reference
    /// per-scanline path — the same determinism gate, applied to the path
    /// production actually routes edge-dense/sparse-window fills through.
    #[test]
    fn aet_matches_reference_bit_exact() {
        let mut rng = Lcg(0x5EED_A57_9911_2244);
        for w in [1usize, 3, 8, 17, 40, 128] {
            for h in [1usize, 3, 8, 17, 40, 96] {
                for rule in [FillRule::NonZero, FillRule::EvenOdd] {
                    for _ in 0..40 {
                        let (p, s) = random_path(&mut rng, w as f32, h as f32);
                        let aet = coverage_grid_aet(&p, &s, w, h, rule);
                        let refr = coverage_grid_ref(&p, &s, w, h, rule);
                        assert_eq!(
                            aet, refr,
                            "aet vs reference mismatch at {w}x{h} rule {rule:?}"
                        );
                    }
                }
            }
        }
    }

    /// The sparse row conversion (gaps between touched cells written as a
    /// constant run) must be byte-identical to the dense sweep on the wide
    /// rows it exists for: page-sized rectangles, a stroked border ring,
    /// diagonals, and random geometry over a wide device.
    #[test]
    fn aet_sparse_rows_match_dense() {
        let w = 1193usize;
        let h = 24usize;
        let mut cases: Vec<Geometry> = vec![
            rect(0.0, 0.0, w as f32, h as f32),
            rect(0.37, 0.61, 1190.91, 23.4),
            rect(-5.0, -3.0, 1300.0, 40.0),
            rect(3.0, 2.0, 1100.0, 20.0),
            rect(3.5, 2.0, 4.2, 20.0), // sub-pixel wide
            // Stroked-border ring: outer rect plus reversed inner rect.
            (
                vec![
                    [1.3, 1.2],
                    [1191.7, 1.2],
                    [1191.7, 22.8],
                    [1.3, 22.8],
                    [3.3, 3.2],
                    [3.3, 20.8],
                    [1189.7, 20.8],
                    [1189.7, 3.2],
                ],
                vec![(0, 4), (4, 8)],
            ),
            // Two separate rects on one row, then a long diagonal.
            (
                vec![
                    [10.0, 2.5],
                    [300.5, 2.5],
                    [300.5, 21.5],
                    [10.0, 21.5],
                    [700.25, 4.0],
                    [1180.0, 4.0],
                    [1180.0, 19.0],
                    [700.25, 19.0],
                ],
                vec![(0, 4), (4, 8)],
            ),
            (vec![[0.0, 0.0], [1193.0, 24.0], [0.0, 24.0]], vec![(0, 3)]),
        ];
        let mut rng = Lcg(0x5A5A_1234_8765_4321);
        for _ in 0..60 {
            cases.push(random_path(&mut rng, w as f32, h as f32));
        }
        for (p, s) in &cases {
            for rule in [FillRule::NonZero, FillRule::EvenOdd] {
                let aet = coverage_grid_aet(p, s, w, h, rule);
                let refr = coverage_grid_ref(p, s, w, h, rule);
                assert_eq!(aet, refr, "sparse AET vs reference mismatch, rule {rule:?}");
                // The production entry point routes these wide sparse windows
                // through the AET too.
                let prod = coverage_grid(p, s, w, h, rule);
                assert_eq!(prod, refr, "fill vs reference mismatch, rule {rule:?}");
            }
        }
    }

    /// The run-aware hand-over (`fill_runs_cancellable`) must describe exactly
    /// the coverage `fill` produces: cell runs read from the buffer plus
    /// constant runs, every other column zero, runs ordered and disjoint, and
    /// constant runs never written into the buffer. Both consumer contracts
    /// are exercised (`false`: buffer untouched outside cell runs; `true`:
    /// constant runs materialized into the buffer), each over a sequence of
    /// fills on one kernel so a missed reset shows up in the next fill.
    #[test]
    fn fill_runs_match_fill() {
        let w = 1193usize;
        let h = 24usize;
        let mut cases: Vec<Geometry> = vec![
            rect(0.0, 0.0, w as f32, h as f32),
            rect(0.37, 0.61, 1190.91, 23.4),
            rect(-5.0, -3.0, 1300.0, 40.0),
            rect(3.5, 2.0, 4.2, 20.0),
            (
                vec![
                    [1.3, 1.2],
                    [1191.7, 1.2],
                    [1191.7, 22.8],
                    [1.3, 22.8],
                    [3.3, 3.2],
                    [3.3, 20.8],
                    [1189.7, 20.8],
                    [1189.7, 3.2],
                ],
                vec![(0, 4), (4, 8)],
            ),
            // Overlapping rects: a constant run of partial (non-0/255) coverage
            // under even-odd, and of 255 under nonzero.
            (
                vec![
                    [10.0, 2.5],
                    [900.5, 2.5],
                    [900.5, 21.5],
                    [10.0, 21.5],
                    [300.25, 4.0],
                    [1180.0, 4.0],
                    [1180.0, 19.0],
                    [300.25, 19.0],
                ],
                vec![(0, 4), (4, 8)],
            ),
            // A half-covered wide band: constant 128-ish coverage across a row.
            rect(2.0, 5.5, 1150.0, 6.0),
            (vec![[0.0, 0.0], [1193.0, 24.0], [0.0, 24.0]], vec![(0, 3)]),
            // Compact window (fast path): one cell run per row.
            rect(3.25, 2.5, 40.75, 9.5),
            // Row repetition: nested rects activating and retiring inside the
            // band (integral and fractional), and a diagonal that interrupts
            // the vertical-only rows for a while.
            (
                vec![
                    [0.5, 0.0],
                    [1192.5, 0.0],
                    [1192.5, 24.0],
                    [0.5, 24.0],
                    [100.0, 5.0],
                    [600.0, 5.0],
                    [600.0, 12.3],
                    [100.0, 12.3],
                    [700.7, 9.0],
                    [701.2, 9.0],
                    [701.2, 17.0],
                    [700.7, 17.0],
                ],
                vec![(0, 4), (4, 8), (8, 12)],
            ),
            (
                vec![
                    [2.0, 1.0],
                    [1100.0, 1.0],
                    [1100.0, 23.0],
                    [2.0, 23.0],
                    [300.0, 6.0],
                    [340.0, 14.0],
                    [320.0, 14.0],
                ],
                vec![(0, 4), (4, 7)],
            ),
        ];
        let mut rng = Lcg(0x0BAD_C0DE_1357_9BDF);
        for _ in 0..40 {
            cases.push(random_path(&mut rng, w as f32, h as f32));
        }
        for materialize in [false, true] {
            let mut k = RasterKernel::default();
            for (p, s) in &cases {
                for rule in [FillRule::NonZero, FillRule::EvenOdd] {
                    let expect = coverage_grid(p, s, w, h, rule);
                    let mut grid = vec![0u8; w * h];
                    let mut spans = Vec::new();
                    k.fill_runs_cancellable(p, s, w, h, rule, None, |y, x0, x1, cov, runs| {
                        spans.push((y, x0, x1));
                        let mut prev_end = 0u32;
                        for r in runs {
                            assert!(r.x0 < r.x1 && r.x0 >= prev_end, "runs ordered: {runs:?}");
                            prev_end = r.x1;
                            let row = &mut grid[y * w..(y + 1) * w];
                            match r.fill {
                                None => row[r.x0 as usize..r.x1 as usize]
                                    .copy_from_slice(&cov[r.x0 as usize..r.x1 as usize]),
                                Some(c) => {
                                    assert!(
                                        cov[r.x0 as usize..r.x1 as usize].iter().all(|&b| b == 0),
                                        "constant run written into the buffer"
                                    );
                                    row[r.x0 as usize..r.x1 as usize].fill(c);
                                }
                            }
                        }
                        if materialize {
                            for r in runs {
                                if let Some(c) = r.fill {
                                    cov[r.x0 as usize..r.x1 as usize].fill(c);
                                }
                            }
                        }
                        materialize
                    });
                    assert_eq!(
                        grid, expect,
                        "runs vs fill, rule {rule:?} materialize {materialize}"
                    );
                    // The row bounds handed over match `fill`'s.
                    let mut plain = Vec::new();
                    RasterKernel::default()
                        .fill(p, s, w, h, rule, |y, x0, x1, _| plain.push((y, x0, x1)));
                    assert_eq!(spans, plain, "row spans, rule {rule:?}");
                }
            }
        }
    }

    /// AET bit-exactness on the boundary geometry the activation/retirement
    /// bookkeeping is most likely to get wrong.
    #[test]
    fn aet_matches_reference_on_edge_cases() {
        let cases: Vec<Geometry> = vec![
            rect(1.0, 2.0, 5.0, 6.0),   // integral y_top/y_bot
            rect(0.5, 2.3, 4.5, 5.7),   // fractional band
            rect(-3.0, -2.0, 4.0, 5.0), // negative y, row_start clamp
            rect(2.0, 0.0, 3.0, 8.0),   // spans the whole band
            (vec![[1.0, 1.5], [7.0, 1.5], [4.0, 6.5]], vec![(0, 3)]), // triangle, shared birth row
        ];
        // Plus many thin edges all activating on the same row (stress the merge).
        let mut many = Vec::new();
        let mut subs = Vec::new();
        for k in 0..500u32 {
            let x = 0.1 + (k as f32) * 0.01;
            let base = many.len();
            many.extend_from_slice(&[[x, 0.2], [x + 0.005, 0.2], [x + 0.005, 7.8], [x, 7.8]]);
            subs.push((base, base + 4));
        }
        let mut all = cases;
        all.push((many, subs));
        for (p, s) in &all {
            for rule in [FillRule::NonZero, FillRule::EvenOdd] {
                let aet = coverage_grid_aet(p, s, 8, 8, rule);
                let refr = coverage_grid_ref(p, s, 8, 8, rule);
                assert_eq!(
                    aet, refr,
                    "aet vs reference edge-case mismatch, rule {rule:?}"
                );
            }
        }
    }

    /// AVX2 coverage conversion must be bit-for-bit identical to the scalar
    /// reference over a wide range of signed-area values and both rules.
    #[test]
    #[allow(
        unsafe_code,
        reason = "bit-compares the AVX2 kernel against the scalar reference; see SAFETY comment"
    )]
    fn avx2_convert_matches_scalar_bit_exact() {
        let mut rng = Lcg(0xA5A5_0F0F_1111_2222);
        let n = 8 * 200 + 5; // exercise the SIMD body and the scalar tail
        let mut running = Vec::with_capacity(n);
        for _ in 0..n {
            // Include out-of-[0,1] and negative values (nonzero winding, even-odd
            // multi-wrap) so clamping/triangle-wave/truncation are all exercised.
            running.push(rng.f(-8.0, 8.0));
        }
        for rule in [FillRule::NonZero, FillRule::EvenOdd] {
            let mut a = vec![0u8; n];
            let mut b = vec![0u8; n];
            convert_coverage_scalar(&running, &mut a, rule);
            #[cfg(target_arch = "x86_64")]
            {
                if is_x86_feature_detected!("avx2") {
                    // SAFETY: AVX2 is present (runtime probe above) and
                    // `b.len() == running.len()` by construction.
                    unsafe { convert_coverage_avx2(&running, &mut b, rule) };
                } else {
                    convert_coverage_scalar(&running, &mut b, rule);
                }
            }
            #[cfg(not(target_arch = "x86_64"))]
            convert_coverage_scalar(&running, &mut b, rule);
            assert_eq!(a, b, "avx2 vs scalar coverage mismatch, rule {rule:?}");
        }
    }
}

#[cfg(test)]
impl RasterKernel {
    /// Test-only: build edges/bounds (as `fill` does) then rasterize via a
    /// scanline fallback — the naive reference (`aet == false`) or the AET
    /// (`aet == true`) — so tests can drive either independent of the window cap.
    #[allow(clippy::too_many_arguments)]
    fn run_fallback(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        row: impl FnMut(usize, usize, usize, &mut [u8]),
        aet: bool,
    ) {
        if width == 0 || height == 0 {
            return;
        }
        if self.cov.len() < width {
            self.cov.resize(width, 0);
        }
        self.edges.clear();
        let mut y_min = f32::INFINITY;
        let mut y_max = f32::NEG_INFINITY;
        for &(start, end) in subpaths {
            let n = end - start;
            if n < 2 {
                continue;
            }
            for i in 0..n {
                let a = points[start + i];
                let b = points[start + (i + 1) % n];
                if a[1] == b[1] {
                    continue;
                }
                let (y_top, y_bot, x_at_top, dir) = if a[1] < b[1] {
                    (a[1], b[1], a[0], 1.0)
                } else {
                    (b[1], a[1], b[0], -1.0)
                };
                let dxdy = (b[0] - a[0]) / (b[1] - a[1]);
                self.edges.push(Edge {
                    y_top,
                    y_bot,
                    x_at_top,
                    dxdy,
                    dir,
                });
                y_min = y_min.min(y_top);
                y_max = y_max.max(y_bot);
            }
        }
        if self.edges.is_empty() {
            return;
        }
        self.last_edges = self.edges.len() as u64;
        let row_start = y_min.floor().max(0.0) as usize;
        let row_end = (y_max.ceil().min(height as f32)) as usize;
        self.last_rows = row_end.saturating_sub(row_start) as u64;
        self.last_covered = 0;
        if row_end <= row_start {
            return;
        }
        if aet {
            let mut row = row;
            let _ = self.fill_scanline_aet(
                width,
                height,
                rule,
                row_start,
                row_end,
                row_start,
                row_end,
                None,
                false,
                |y, x0, x1, cov, _| {
                    row(y, x0, x1, cov);
                    true
                },
            );
        } else {
            self.fill_scanline_ref(width, height, rule, row_start, row_end, row);
        }
    }

    fn run_reference(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        row: impl FnMut(usize, usize, usize, &mut [u8]),
    ) {
        self.run_fallback(points, subpaths, width, height, rule, row, false);
    }

    fn run_aet(
        &mut self,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        row: impl FnMut(usize, usize, usize, &mut [u8]),
    ) {
        self.run_fallback(points, subpaths, width, height, rule, row, true);
    }
}

#[cfg(test)]
mod row_window_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    //! A row-restricted fill must emit exactly the rows an unrestricted fill
    //! emits inside the window, byte for byte, on every kernel route and in
    //! both hand-over modes.

    use super::{CovRun, FillRule, RasterKernel};

    struct Rng(u64);

    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        fn range(&mut self, lo: f32, hi: f32) -> f32 {
            lo + (hi - lo) * ((self.next() >> 40) as f32 / (1u64 << 24) as f32)
        }
        fn pick(&mut self, n: u64) -> u64 {
            self.next() % n
        }
    }

    /// One emitted row with every run materialized to bytes.
    type Row = (usize, usize, usize, Vec<u8>);

    fn materialize(first: usize, last: usize, cov: &[u8], runs: &[CovRun]) -> Vec<u8> {
        let mut bytes = vec![0u8; last - first + 1];
        for run in runs {
            // A cell run may extend past the covered span (trailing zeros).
            let (x0, x1) = (
                (run.x0 as usize).max(first),
                (run.x1 as usize).min(last + 1),
            );
            if x0 >= x1 {
                continue;
            }
            match run.fill {
                Some(value) => bytes[x0 - first..x1 - first].fill(value),
                None => bytes[x0 - first..x1 - first].copy_from_slice(&cov[x0..x1]),
            }
        }
        bytes
    }

    #[allow(clippy::too_many_arguments)]
    fn collect(
        kernel: &mut RasterKernel,
        points: &[[f32; 2]],
        subpaths: &[(usize, usize)],
        width: usize,
        height: usize,
        rule: FillRule,
        rows: std::ops::Range<usize>,
        runs_mode: bool,
    ) -> Vec<Row> {
        let mut out: Vec<Row> = Vec::new();
        if runs_mode {
            assert!(kernel.fill_runs_cancellable_in(
                points,
                subpaths,
                width,
                height,
                rule,
                rows,
                None,
                |y, first, last, cov, runs| {
                    out.push((y, first, last, materialize(first, last, cov, runs)));
                    false
                },
            ));
        } else {
            assert!(kernel.fill_cancellable_in(
                points,
                subpaths,
                width,
                height,
                rule,
                rows,
                None,
                |y, first, last, cov| out.push((y, first, last, cov[first..=last].to_vec())),
            ));
        }
        out
    }

    /// Random geometry aimed at each route: `0` a small compact polygon, `1`
    /// a few edges over a huge window (sparse AET), `2` many small polygons
    /// spread over the surface (dense AET rows, like a stroke outline), `3`
    /// axis-aligned frames (vertical-only rows, row repetition), `4` thin
    /// rules and small boxes that stay in the compact window with long
    /// untouched interiors (constant runs), some overlapping.
    fn geometry(rng: &mut Rng, kind: u64, w: f32, h: f32) -> (Vec<[f32; 2]>, Vec<(usize, usize)>) {
        let mut points = Vec::new();
        let mut subpaths = Vec::new();
        let mut polygon = |points: &mut Vec<[f32; 2]>, vertices: &[[f32; 2]]| {
            let start = points.len();
            points.extend_from_slice(vertices);
            subpaths.push((start, points.len()));
        };
        match kind {
            0 => {
                let (cx, cy) = (rng.range(0.0, w), rng.range(0.0, h));
                let n = 3 + rng.pick(6) as usize;
                let vertices: Vec<[f32; 2]> = (0..n)
                    .map(|_| [cx + rng.range(-25.0, 25.0), cy + rng.range(-25.0, 25.0)])
                    .collect();
                polygon(&mut points, &vertices);
            }
            1 => {
                let n = 3 + rng.pick(3) as usize;
                let vertices: Vec<[f32; 2]> = (0..n)
                    .map(|_| [rng.range(-40.0, w + 40.0), rng.range(-40.0, h + 40.0)])
                    .collect();
                polygon(&mut points, &vertices);
            }
            2 => {
                for _ in 0..(60 + rng.pick(200)) {
                    let (cx, cy) = (rng.range(-5.0, w + 5.0), rng.range(-5.0, h + 5.0));
                    let r = rng.range(0.3, 6.0);
                    let vertices: Vec<[f32; 2]> = (0..8)
                        .map(|i| {
                            let t = i as f32 / 8.0 * std::f32::consts::TAU;
                            [cx + r * t.cos(), cy + r * t.sin()]
                        })
                        .collect();
                    polygon(&mut points, &vertices);
                }
            }
            4 => {
                for _ in 0..(1 + rng.pick(3)) {
                    let wide = rng.pick(2) == 0;
                    let (rw, rh) = if wide {
                        (rng.range(20.0, w * 0.95), rng.range(0.2, 9.0))
                    } else {
                        (rng.range(0.2, 9.0), rng.range(20.0, h * 0.95))
                    };
                    let (x0, y0) = (rng.range(-5.0, w - rw), rng.range(-5.0, h - rh));
                    let snap = |v: f32, on: bool| if on { v.round() } else { v };
                    let on = rng.pick(3) == 0;
                    let (x0, y0, x1, y1) = (
                        snap(x0, on),
                        snap(y0, on),
                        snap(x0 + rw, on),
                        snap(y0 + rh, on),
                    );
                    polygon(&mut points, &[[x0, y0], [x1, y0], [x1, y1], [x0, y1]]);
                    if rng.pick(4) == 0 {
                        // A slanted sliver across the rule: partial coverage
                        // inside an otherwise constant row.
                        polygon(
                            &mut points,
                            &[
                                [x0 + 3.3, y0 - 1.0],
                                [x0 + 9.1, y0 - 1.0],
                                [x0 + 30.7, y1 + 1.0],
                            ],
                        );
                    }
                }
            }
            _ => {
                for _ in 0..(1 + rng.pick(4)) {
                    let (x0, y0) = (rng.range(-10.0, w * 0.6), rng.range(-10.0, h * 0.6));
                    let (x1, y1) = (x0 + rng.range(1.0, w * 0.6), y0 + rng.range(1.0, h * 0.6));
                    // Half the frames are integer-aligned.
                    let snap = |v: f32, on: bool| if on { v.round() } else { v };
                    let on = rng.pick(2) == 0;
                    let (x0, y0, x1, y1) = (snap(x0, on), snap(y0, on), snap(x1, on), snap(y1, on));
                    polygon(&mut points, &[[x0, y0], [x1, y0], [x1, y1], [x0, y1]]);
                }
            }
        }
        (points, subpaths)
    }

    #[test]
    fn windowed_fill_equals_the_same_rows_of_a_full_fill() {
        let mut rng = Rng(0x2545_f491_4f6c_dd1d);
        let (width, height) = (700usize, 420usize);
        let mut kernel = RasterKernel::default();
        let mut reference_kernel = RasterKernel::default();
        let mut nonempty = 0;
        for case in 0..500 {
            let kind = case % 5;
            let (points, subpaths) = geometry(&mut rng, kind, width as f32, height as f32);
            let rule = if rng.pick(2) == 0 {
                FillRule::NonZero
            } else {
                FillRule::EvenOdd
            };
            let runs_mode = rng.pick(2) == 0;
            let full = collect(
                &mut reference_kernel,
                &points,
                &subpaths,
                width,
                height,
                rule,
                0..usize::MAX,
                runs_mode,
            );
            // The two hand-over modes describe the same rows.
            let other_mode = collect(
                &mut reference_kernel,
                &points,
                &subpaths,
                width,
                height,
                rule,
                0..usize::MAX,
                !runs_mode,
            );
            assert!(
                full == other_mode,
                "case {case} kind {kind}: runs and bytes disagree"
            );
            // Windows inside, straddling, covering and outside the path's rows.
            let a = rng.pick(height as u64 + 40) as usize;
            let b = a + rng.pick(height as u64 / 2 + 2) as usize;
            for rows in [a..b, 0..a, a..usize::MAX, b..b, 0..usize::MAX] {
                let expected: Vec<Row> = full
                    .iter()
                    .filter(|row| rows.contains(&row.0))
                    .cloned()
                    .collect();
                let got = collect(
                    &mut kernel,
                    &points,
                    &subpaths,
                    width,
                    height,
                    rule,
                    rows.clone(),
                    runs_mode,
                );
                assert!(
                    got == expected,
                    "case {case} kind {kind} rows {rows:?} runs_mode {runs_mode}: {} rows vs {}",
                    got.len(),
                    expected.len()
                );
                if !got.is_empty() && got.len() < full.len() {
                    nonempty += 1;
                }
            }
        }
        assert!(
            nonempty > 400,
            "only {nonempty} windows actually restricted a fill"
        );
    }
}