html-to-markdown-rs 3.16.0

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Xberg ecosystem.
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
//! HTML preprocessing and normalization.
//!
//! Functions for preprocessing HTML before conversion, including script/style stripping,
//! tag repair, and malformed HTML handling.

use std::borrow::Cow;
use std::str;

/// If `idx` starts an `<svg`/`</svg` tag, adjust `svg_depth` accordingly and return the index
/// just past the tag. Returns `None` when `idx` does not start an svg tag (or the tag is
/// unterminated), in which case the caller's scan is unaffected.
///
/// Extracted from `strip_script_and_style_tags` — identical `<svg`/`</svg` detection and depth
/// bookkeeping, unchanged.
fn track_svg_tag(bytes: &[u8], idx: usize, svg_depth: &mut usize) -> Option<usize> {
    if matches_tag_start(bytes, idx + 1, b"svg") {
        if let Some(open_end) = find_tag_end(bytes, idx + 1 + b"svg".len()) {
            *svg_depth += 1;
            return Some(open_end);
        }
    } else if matches_end_tag_start(bytes, idx + 1, b"svg") {
        if let Some(close_end) = find_tag_end(bytes, idx + 2 + b"svg".len()) {
            if *svg_depth > 0 {
                *svg_depth = svg_depth.saturating_sub(1);
            }
            return Some(close_end);
        }
    }
    None
}

/// Strip a `<script>…</script>` or `<style>…</style>` element starting at `idx` (which must
/// point at the `<`), appending everything before it to `*output` (lazily allocated) and
/// inserting a single space if collapsing the removed span would otherwise fuse two
/// non-whitespace characters together.
///
/// `open_tag_pattern` is the lowercase opening-tag prefix including `<` (e.g. `b"<script"`);
/// `close_tag_name` is the bare lowercase tag name for the closing-tag scan (e.g. `b"script"`).
/// `json_ld_exempt` additionally requires the opening tag not be a `type="application/ld+json"`
/// script — only meaningful for the script element, so callers stripping `<style>` pass `false`.
///
/// Returns `Some(new_pos)` when the element was stripped — the caller should set both `last`
/// and `idx` to it and `continue` the scan — or `None` when `idx` does not start a strippable
/// element of this kind, in which case the caller falls through unchanged.
///
/// Extracted from `strip_script_and_style_tags` — identical prefix/whitespace-boundary/
/// closing-tag-scan logic, unchanged.
fn strip_raw_text_element(
    input: &str,
    bytes: &[u8],
    idx: usize,
    len: usize,
    last: usize,
    output: &mut Option<String>,
    open_tag_pattern: &[u8],
    close_tag_name: &[u8],
    json_ld_exempt: bool,
) -> Option<usize> {
    let prefix_len = open_tag_pattern.len();
    if idx + prefix_len >= len || !eq_ascii_insensitive(&bytes[idx..idx + prefix_len], open_tag_pattern) {
        return None;
    }
    let after_tag = bytes[idx + prefix_len];
    if !(after_tag == b'>' || after_tag == b' ' || after_tag == b'\t' || after_tag == b'\n' || after_tag == b'\r') {
        return None;
    }

    let mut tag_end = idx + prefix_len;
    while tag_end < len && bytes[tag_end] != b'>' {
        tag_end += 1;
    }
    if tag_end >= len {
        return None;
    }
    tag_end += 1;

    if json_ld_exempt {
        let tag_content = &input[idx..tag_end];
        if is_json_ld_script_open_tag(tag_content) {
            return None;
        }
    }

    let close_idx = find_closing_tag_bytes(bytes, tag_end, close_tag_name)?;

    let out = output.get_or_insert_with(|| String::with_capacity(len));
    out.push_str(&input[last..idx]);
    if idx > 0 && close_idx < len && !bytes[idx - 1].is_ascii_whitespace() && !bytes[close_idx].is_ascii_whitespace() {
        out.push(' ');
    }
    Some(close_idx)
}

/// Strip script and style tags and their content from HTML.
pub fn strip_script_and_style_tags(input: &str) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();

    if len == 0 {
        return Cow::Borrowed(input);
    }

    let mut idx = 0;
    let mut last = 0;
    let mut output: Option<String> = None;
    let mut svg_depth = 0usize;

    if !bytes.contains(&b'<') {
        return Cow::Borrowed(input);
    }

    while idx < len {
        if bytes[idx] == b'<' && idx + 1 < len {
            if let Some(new_idx) = track_svg_tag(bytes, idx, &mut svg_depth) {
                idx = new_idx;
                continue;
            }

            if svg_depth > 0 {
                idx += 1;
                continue;
            }

            // ~keep Check for </script or </style (closing tags first for safety)
            if bytes[idx + 1] == b'/' && idx + 2 < len {
                if idx + 9 <= len && eq_ascii_insensitive(&bytes[idx..idx + 9], b"</script>") {
                    idx += 9;
                    continue;
                }

                if idx + 8 <= len && eq_ascii_insensitive(&bytes[idx..idx + 8], b"</style>") {
                    idx += 8;
                    continue;
                }
            }

            if let Some(new_pos) =
                strip_raw_text_element(input, bytes, idx, len, last, &mut output, b"<script", b"script", true)
            {
                last = new_pos;
                idx = new_pos;
                continue;
            }

            if let Some(new_pos) =
                strip_raw_text_element(input, bytes, idx, len, last, &mut output, b"<style", b"style", false)
            {
                last = new_pos;
                idx = new_pos;
                continue;
            }
        }

        idx += 1;
    }

    if let Some(mut out) = output {
        if last < len {
            out.push_str(&input[last..]);
        }
        Cow::Owned(out)
    } else {
        Cow::Borrowed(input)
    }
}

/// Upper bound on how far a closing-tag scan may travel from its start offset.
///
/// ~keep DoS guard: hostile input can contain an unterminated element followed
/// ~keep by hundreds of megabytes of text; the scan gives up rather than walking
/// ~keep the whole document for every such tag.
const MAX_CLOSING_TAG_SCAN: usize = 100_000_000;

/// If `idx` starts a `</tag>` (or `</tag ...>`) closing tag matching `tag` (case-insensitively),
/// return the index just past its `>`. Returns `None` when `idx` does not start such a tag.
///
/// Extracted from `find_closing_tag_bytes`'s inner match — identical boundary checks and
/// closing-`>` scan, unchanged.
fn match_closing_tag_at(bytes: &[u8], idx: usize, len: usize, tag: &[u8]) -> Option<usize> {
    let tag_len = tag.len();
    if idx + 2 >= len || bytes[idx + 1] != b'/' {
        return None;
    }
    if idx + 2 + tag_len > len || !eq_ascii_insensitive(&bytes[idx + 2..idx + 2 + tag_len], tag) {
        return None;
    }
    let after_tag = idx + 2 + tag_len;
    if after_tag >= len || !(bytes[after_tag] == b'>' || bytes[after_tag].is_ascii_whitespace()) {
        return None;
    }

    let mut close_idx = after_tag;
    while close_idx < len && bytes[close_idx] != b'>' {
        close_idx += 1;
    }
    if close_idx < len { Some(close_idx + 1) } else { None }
}

/// Find the position of the FIRST closing tag in bytes, ignoring nesting.
/// Returns the position AFTER the closing tag (including the '>').
/// This is highly optimized for performance and uses a fast-path scan.
///
/// ~keep First-match (not depth-aware) is correct ONLY for the HTML raw-text
/// ~keep elements `<script>` and `<style>`: inside their bodies `<script` is
/// ~keep text, not a tag, so the first `</script>` is the spec terminator.
/// ~keep Counting depth here would treat `var s = "<script>"` as an opening tag
/// ~keep and run past the real close, swallowing the rest of the document.
/// ~keep Elements that can nest must use `find_closing_tag_bytes_nested`; do not
/// ~keep unify the two functions.
#[inline]
pub fn find_closing_tag_bytes(bytes: &[u8], start: usize, tag: &[u8]) -> Option<usize> {
    let len = bytes.len();
    let mut idx = start;

    while idx < len && (idx - start) < MAX_CLOSING_TAG_SCAN {
        if bytes[idx] != b'<' {
            if let Some(pos) = memchr::memchr(b'<', &bytes[idx..]) {
                idx += pos;
            } else {
                break;
            }
        }

        if let Some(close_pos) = match_closing_tag_at(bytes, idx, len, tag) {
            return Some(close_pos);
        }

        idx += 1;
    }

    None
}

/// Void elements that never carry a closing tag, so an occurrence of one inside
/// a subtree must not raise the nesting depth of a closing-tag scan.
const VOID_ELEMENT_NAMES: [&[u8]; 4] = [b"br", b"hr", b"img", b"input"];

/// Whether an opening tag closes itself: XHTML-style `<tag/>` or a void element.
///
/// ~keep Shared by `strip_hidden_elements` and `find_closing_tag_bytes_nested`
/// ~keep so the element the stripper treats as self-closing and the element the
/// ~keep depth counter refuses to count can never disagree.
#[inline]
fn is_self_closing_tag(tag_slice: &[u8], tag_name: &[u8]) -> bool {
    tag_slice.ends_with(b"/>")
        || VOID_ELEMENT_NAMES
            .iter()
            .any(|void_name| tag_name.eq_ignore_ascii_case(void_name))
}

/// Byte sequences delimiting the regions of an HTML document whose bytes are
/// character data rather than markup.
const COMMENT_OPEN: &[u8] = b"<!--";
const COMMENT_CLOSE: &[u8] = b"-->";
const CDATA_OPEN: &[u8] = b"<![CDATA[";
const CDATA_CLOSE: &[u8] = b"]]>";

/// Elements whose body is raw text: `<` inside them never starts a tag.
const RAW_TEXT_ELEMENT_NAMES: [&[u8]; 2] = [b"script", b"style"];

/// Index just past the first occurrence of `terminator` at or after `from`,
/// or the input length when the region is never terminated.
///
/// ~keep An unterminated comment/CDATA region runs to EOF per HTML5, so
/// ~keep returning `len` (rather than `None`) keeps the caller from resuming a
/// ~keep tag scan inside text that will never be markup.
#[inline]
fn find_sequence_end(bytes: &[u8], from: usize, terminator: &[u8]) -> usize {
    let len = bytes.len();
    if from >= len {
        return len;
    }
    match bytes[from..].windows(terminator.len()).position(|w| w == terminator) {
        Some(offset) => from + offset + terminator.len(),
        None => len,
    }
}

/// If a `<` at `idx` opens a region that is NOT markup — an HTML comment, a
/// CDATA section, or the body of a raw-text element — return the index just
/// past that region. Returns `None` when `idx` does not open such a region.
///
/// ~keep A depth-counting close-tag scan MUST consult this before interpreting
/// ~keep a `<`: `<!-- </div> -->` and `<script>{"a":"</div>"}</script>` contain
/// ~keep byte sequences that look like tags but are text. Counting them ends the
/// ~keep scan early (leaking the hidden element's tail into the output) or
/// ~keep inflates the depth (swallowing the following visible sibling).
#[inline]
pub fn skip_opaque_region(bytes: &[u8], idx: usize) -> Option<usize> {
    let len = bytes.len();
    if idx >= len || bytes[idx] != b'<' {
        return None;
    }

    if bytes[idx..].starts_with(COMMENT_OPEN) {
        return Some(find_sequence_end(bytes, idx + COMMENT_OPEN.len(), COMMENT_CLOSE));
    }

    if bytes[idx..].starts_with(CDATA_OPEN) {
        return Some(find_sequence_end(bytes, idx + CDATA_OPEN.len(), CDATA_CLOSE));
    }

    for raw_text_name in RAW_TEXT_ELEMENT_NAMES {
        if matches_tag_start(bytes, idx + 1, raw_text_name) {
            let open_end = find_tag_end(bytes, idx + 1 + raw_text_name.len())?;
            // ~keep First-match close is the spec terminator for raw text — see
            // ~keep the doc comment on `find_closing_tag_bytes`.
            return Some(find_closing_tag_bytes(bytes, open_end, raw_text_name).unwrap_or(len));
        }
    }

    None
}

/// Whether the `<` at `idx` starts a tag rather than a stray `<` in text.
///
/// ~keep Mirrors the `is_valid_tag` test in `preprocess_html`: without it a
/// ~keep literal `<` in text (`a < b`) would make a scan jump to the next `>`,
/// ~keep stepping over the real closing tag in between.
#[inline]
fn opens_a_tag(bytes: &[u8], idx: usize) -> bool {
    match bytes.get(idx + 1) {
        Some(b'/' | b'!') => bytes.get(idx + 2).is_some_and(u8::is_ascii_alphabetic),
        Some(byte) => byte.is_ascii_alphabetic(),
        None => false,
    }
}

/// Find the closing tag that matches an opening `<tag>`, counting nested
/// elements of the same name. Returns the position AFTER the closing tag
/// (including the '>'), or `None` if the element is never closed.
///
/// ~keep Required for elements that can nest (`div`, `span`, ...): the
/// ~keep first-match `find_closing_tag_bytes` stops at the INNER `</tag>`, which
/// ~keep leaves the hidden element's tail in the document. Kept separate from
/// ~keep that function because raw-text elements must NOT count depth — see its
/// ~keep doc comment.
///
/// ~keep Only real markup may move the depth counter, so every `<` is first
/// ~keep offered to `skip_opaque_region`, and a tag that is not the target is
/// ~keep jumped via the quote-aware `find_tag_end` rather than byte-by-byte:
/// ~keep otherwise `</tag>` written inside a comment, a quoted attribute value,
/// ~keep or a raw-text body is mistaken for the element's terminator.
#[inline]
pub fn find_closing_tag_bytes_nested(bytes: &[u8], start: usize, tag: &[u8]) -> Option<usize> {
    let len = bytes.len();
    if tag.is_empty() {
        return None;
    }

    let mut idx = start;
    let mut depth = 1usize;

    while idx < len && (idx - start) < MAX_CLOSING_TAG_SCAN {
        if bytes[idx] != b'<' {
            match memchr::memchr(b'<', &bytes[idx..]) {
                Some(pos) => idx += pos,
                None => break,
            }
        }

        if let Some(region_end) = skip_opaque_region(bytes, idx) {
            idx = region_end;
            continue;
        }

        if matches_end_tag_start(bytes, idx + 1, tag) {
            if let Some(close_end) = find_tag_end(bytes, idx + 2 + tag.len()) {
                depth -= 1;
                if depth == 0 {
                    return Some(close_end);
                }
                idx = close_end;
                continue;
            }
        } else if matches_tag_start(bytes, idx + 1, tag) {
            if let Some(open_end) = find_tag_end(bytes, idx + 1 + tag.len()) {
                if !is_self_closing_tag(&bytes[idx..open_end], tag) {
                    depth += 1;
                }
                idx = open_end;
                continue;
            }
        } else if opens_a_tag(bytes, idx) {
            if let Some(unrelated_tag_end) = find_tag_end(bytes, idx + 1) {
                idx = unrelated_tag_end;
                continue;
            }
        }

        idx += 1;
    }

    None
}

/// Compare bytes ignoring ASCII case.
#[inline]
pub fn eq_ascii_insensitive(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.iter().zip(b.iter()).all(|(x, y)| x.eq_ignore_ascii_case(y))
}

/// Normalize HTML comment endings that would confuse the `tl` parser.
///
/// The `astral-tl` parser mishandles HTML comments whose closing sequence
/// contains more than two dashes before the `>` (e.g. `<!-- foo --->` or
/// `<!-- foo ---->`).  When it encounters such a comment it creates an empty
/// comment node and silently discards every byte that follows, so all document
/// content after the comment is lost. It also mishandles the opposite,
/// too-few-dashes shape: `<!-->` and `<!--->`, HTML5's "abrupt-closing-of-
/// empty-comment" quirk, where the closing `-->` shares its dashes with the
/// opening `<!--`. With no unshared `-->` left in the remaining input, `tl`
/// treats the comment as unterminated and drops everything after it, exactly
/// like the excess-dash case.
///
/// This function rewrites both bogus shapes: every `--[-]+>` sequence that
/// terminates an HTML comment is normalised to `-->`, and every abrupt
/// `<!-->`/`<!--->` open+close is normalised to the well-formed empty comment
/// `<!---->`.  Regular `-->` closings are left unchanged.
///
/// # Algorithm
///
/// Scans the input byte-by-byte looking for `<!--`.  For each comment found it
/// scans forward for `-->` using the HTML5 comment-end state machine:
///
/// - `--[` zero or more `-` `]>` ends the comment.
/// - Any other character after `--` resets back into the comment body.
///
/// If the actual number of leading dashes before `>` is more than two the
/// closing sequence is replaced with `-->`. If `>` (or `->`) appears
/// immediately after the opening `<!--`, with no other content consumed, the
/// whole `<!-->`/`<!--->` run is replaced with `<!---->`.
pub fn normalize_bogus_comment_endings(input: &str) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();

    if len < 5 || !bytes.windows(4).any(|w| w == b"<!--") {
        return Cow::Borrowed(input);
    }

    let mut idx = 0;
    let mut last = 0;
    let mut output: Option<String> = None;

    while idx + 3 < len {
        if !(bytes[idx] == b'<' && bytes[idx + 1] == b'!' && bytes[idx + 2] == b'-' && bytes[idx + 3] == b'-') {
            idx += 1;
            continue;
        }

        idx += 4;

        // ~keep `<!-->` (zero shared dashes) and `<!--->` (one shared dash) never
        // ~keep accumulate `consecutive_dashes >= 2` below, so the general scan can
        // ~keep never see them as closed -- it would run to EOF looking for an
        // ~keep unshared `-->` and swallow the rest of the document. Caught here,
        // ~keep before that scan starts.
        if bytes.get(idx) == Some(&b'>') {
            let out = output.get_or_insert_with(|| String::with_capacity(len));
            out.push_str(&input[last..idx - 4]);
            out.push_str("<!---->");
            idx += 1;
            last = idx;
            continue;
        }
        if bytes.get(idx) == Some(&b'-') && bytes.get(idx + 1) == Some(&b'>') {
            let out = output.get_or_insert_with(|| String::with_capacity(len));
            out.push_str(&input[last..idx - 4]);
            out.push_str("<!---->");
            idx += 2;
            last = idx;
            continue;
        }

        let mut consecutive_dashes: usize = 0;

        while idx < len {
            let b = bytes[idx];
            if b == b'-' {
                consecutive_dashes += 1;
                idx += 1;
            } else if b == b'>' && consecutive_dashes >= 2 {
                if consecutive_dashes > 2 {
                    let out = output.get_or_insert_with(|| String::with_capacity(len));
                    let close_start = idx - consecutive_dashes;
                    out.push_str(&input[last..close_start]);
                    out.push_str("-->");
                    idx += 1;
                    last = idx;
                } else {
                    idx += 1;
                }
                break;
            } else {
                consecutive_dashes = 0;
                idx += 1;
            }
        }
    }

    match output {
        Some(mut out) => {
            if last < len {
                out.push_str(&input[last..]);
            }
            Cow::Owned(out)
        }
        None => Cow::Borrowed(input),
    }
}

/// Normalize closing tags whose `>` appears on a subsequent line.
///
/// Some HTML formatters (JSX-style) write closing tags as:
///
/// ```html
/// </a
/// >
/// ```
///
/// The `tl` parser does not handle end-tags with a newline before the closing
/// `>`, leaving the element unclosed so all subsequent siblings become children
/// of the open element.  This pass collapses such patterns to a single-line
/// closing tag (`</a>`) before the document reaches `tl`.
///
/// Only the whitespace between the tag name and the closing `>` is normalised;
/// the rest of the document is untouched.
pub fn normalize_split_closing_tags(input: &str) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();

    if len < 4 || !bytes.contains(&b'\n') {
        return Cow::Borrowed(input);
    }

    let mut idx = 0;
    let mut last = 0;
    let mut output: Option<String> = None;

    while idx + 2 < len {
        let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) else {
            break;
        };
        idx += offset;
        if bytes.get(idx + 1) != Some(&b'/') {
            idx += 1;
            continue;
        }

        // ~keep Scan tag name: ASCII letters, digits, hyphens (HTML5 allows hyphens in custom elements)
        let name_start = idx + 2;
        let mut name_end = name_start;
        while name_end < len && (bytes[name_end].is_ascii_alphanumeric() || bytes[name_end] == b'-') {
            name_end += 1;
        }

        if name_end == name_start {
            idx += 1;
            continue;
        }

        let ws_start = name_end;
        let mut ws_end = ws_start;
        let mut has_newline = false;
        while ws_end < len && bytes[ws_end].is_ascii_whitespace() {
            if bytes[ws_end] == b'\n' || bytes[ws_end] == b'\r' {
                has_newline = true;
            }
            ws_end += 1;
        }

        if !has_newline || ws_end >= len || bytes[ws_end] != b'>' {
            idx += 1;
            continue;
        }

        let tag_name = &input[name_start..name_end];
        let out = output.get_or_insert_with(|| String::with_capacity(len));
        out.push_str(&input[last..idx]);
        out.push_str("</");
        out.push_str(tag_name);
        out.push('>');

        idx = ws_end + 1;
        last = idx;
    }

    match output {
        Some(mut out) => {
            if last < len {
                out.push_str(&input[last..]);
            }
            Cow::Owned(out)
        }
        None => Cow::Borrowed(input),
    }
}

/// Collapse an empty HTML comment `<!---->` at `idx` to `<!-- -->` (a single interior space).
/// Returns `Some(new_pos)` when found, `None` otherwise.
///
/// Extracted from `preprocess_html`'s main scan loop — identical prefix match and rewrite,
/// unchanged.
fn collapse_empty_comment(
    input: &str,
    bytes: &[u8],
    idx: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    const EMPTY_COMMENT: &[u8] = b"<!---->";
    if !bytes[idx..].starts_with(EMPTY_COMMENT) {
        return None;
    }
    let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
    out.push_str(&input[last..idx]);
    out.push_str("<!-- -->");
    Some(idx + EMPTY_COMMENT.len())
}

/// Normalize an XML-style self-closing void element (`<br/>`, `<hr/>`, `<img/>`) at `idx` to its
/// HTML5 form (`<br>`, `<hr>`, `<img>`). Returns `Some(new_pos)` when matched, `None` otherwise.
///
/// Extracted from `preprocess_html`'s main scan loop — identical pattern table and rewrite,
/// unchanged.
fn normalize_self_closing_void(
    input: &str,
    bytes: &[u8],
    idx: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    const SELF_CLOSING: [(&[u8], &str); 3] = [(b"<br/>", "<br>"), (b"<hr/>", "<hr>"), (b"<img/>", "<img>")];
    for (pattern, replacement) in &SELF_CLOSING {
        if bytes[idx..].starts_with(pattern) {
            let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
            out.push_str(&input[last..idx]);
            out.push_str(replacement);
            return Some(idx + pattern.len());
        }
    }
    None
}

/// Lowercase the tag name of an HTML5 void element written in upper or mixed case.
///
/// The bundled astral-tl parser compares a tag's raw source bytes against an all-lowercase
/// void-element table, so `<META>` misses it and is pushed onto the open-element stack as a
/// *container*. The parent's close tag then cannot pop it and every following sibling is
/// absorbed as its child: for `<head><META ...></head><body>` that leaves `<body>` a
/// grandchild of `<head>`, out of reach of `converter::metadata`'s direct-child rescue, and
/// the whole document converts to an empty string (issue #467). Tier-1 lowercases tag names
/// before lookup and was never affected, so this also closes a tier divergence.
///
/// Only the name is rewritten -- attribute names and values are left byte for byte alone.
/// Non-void elements need no rewrite: the parser compares open and close tags against each
/// other, so `<DIV>...</DIV>` already matches.
///
/// Returns `Some(new_pos)` when a name was rewritten, `None` otherwise.
fn normalize_void_tag_case(
    input: &str,
    bytes: &[u8],
    idx: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    let name_start = idx + 1;
    if !bytes.get(name_start)?.is_ascii_alphabetic() {
        return None;
    }
    let name_end = crate::converter::main_helpers::scan_tag_name_end(bytes, name_start);
    let name = &bytes[name_start..name_end];
    // ~keep Uppercase check first: it is a byte scan, while the void-element test allocates.
    if !name.iter().any(u8::is_ascii_uppercase) || !crate::converter::main_helpers::is_html5_void_element(name) {
        return None;
    }
    let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
    out.push_str(&input[last..idx]);
    out.push('<');
    out.push_str(&input[name_start..name_end].to_ascii_lowercase());
    Some(name_end)
}

/// Strip a raw-text `<script>` or `<style>` element in `preprocess_html`'s pass, replacing its
/// content with an empty element (`<tag ...></tag>`) rather than removing it outright. A
/// `<script type="application/ld+json">` open tag is left alone (its JSON-LD body must survive
/// for metadata extraction), matching neither `TAGS` entry in that case — mirrored by the
/// `continue` below, which moves on to the next `TAGS` entry instead of stopping the scan.
///
/// Returns `Some(new_pos)` when a tag was stripped, `None` when `idx` does not start such a tag.
///
/// Extracted from `preprocess_html`'s main scan loop — identical tag matching and JSON-LD
/// exemption, unchanged.
fn strip_raw_text_tag_reopen(
    input: &str,
    bytes: &[u8],
    idx: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    const TAGS: [&[u8]; 2] = [b"script", b"style"];

    for tag in TAGS {
        if matches_tag_start(bytes, idx + 1, tag) {
            if let Some(open_end) = find_tag_end(bytes, idx + 1 + tag.len()) {
                if tag == b"script" && is_json_ld_script_open_tag(&input[idx..open_end]) {
                    continue;
                }
                let remove_end = find_closing_tag(bytes, open_end, tag).unwrap_or(open_end);
                let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
                out.push_str(&input[last..idx]);
                out.push_str(&input[idx..open_end]);
                out.push_str("</");
                if let Ok(tag_str) = str::from_utf8(tag) {
                    out.push_str(tag_str);
                }
                out.push('>');

                return Some(remove_end);
            }
        }
    }

    None
}

/// Strip a `<!doctype ...>` declaration at `idx`. Returns `Some(new_pos)` when found and
/// terminated, `None` otherwise.
///
/// Extracted from `preprocess_html`'s main scan loop — identical whitespace-skip and
/// case-insensitive `doctype` match, unchanged.
fn strip_doctype(
    input: &str,
    bytes: &[u8],
    idx: usize,
    len: usize,
    last: usize,
    output: &mut Option<String>,
) -> Option<usize> {
    const DOCTYPE: &[u8] = b"doctype";

    if idx + 2 >= len || bytes[idx + 1] != b'!' {
        return None;
    }
    let mut cursor = idx + 2;
    while cursor < len && bytes[cursor].is_ascii_whitespace() {
        cursor += 1;
    }

    if cursor + DOCTYPE.len() > len || !bytes[cursor..cursor + DOCTYPE.len()].eq_ignore_ascii_case(DOCTYPE) {
        return None;
    }

    let end = find_tag_end(bytes, cursor + DOCTYPE.len())?;
    let out = output.get_or_insert_with(|| String::with_capacity(input.len()));
    out.push_str(&input[last..idx]);
    Some(end)
}

/// Whether `<` at `idx` opens something that looks like real markup (a tag, a `<!...>`
/// declaration/comment, or a `<?...?>` processing instruction) rather than a bare `<` that must
/// be entity-escaped so a later HTML parse does not swallow following content as a bogus tag.
///
/// Extracted from `preprocess_html`'s main scan loop — identical byte-class checks, unchanged.
fn looks_like_tag_start(bytes: &[u8], idx: usize, len: usize) -> bool {
    if idx + 1 >= len {
        return false;
    }
    match bytes[idx + 1] {
        b'!' => {
            idx + 2 < len
                && (bytes[idx + 2] == b'-'
                    || bytes[idx + 2].is_ascii_alphabetic()
                    || bytes[idx + 2].is_ascii_uppercase())
        }
        b'/' => idx + 2 < len && (bytes[idx + 2].is_ascii_alphabetic() || bytes[idx + 2].is_ascii_uppercase()),
        b'?' => true,
        c if c.is_ascii_alphabetic() || c.is_ascii_uppercase() => true,
        _ => false,
    }
}

/// Preprocess HTML to normalize tags and fix common issues.
pub fn preprocess_html(input: &str) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();
    if len == 0 {
        return Cow::Borrowed(input);
    }

    let mut idx = 0;
    let mut last = 0;
    let mut output: Option<String> = None;
    let mut svg_depth = 0usize;

    while idx < len {
        if bytes[idx] == b'<' {
            if let Some(new_pos) = collapse_empty_comment(input, bytes, idx, last, &mut output) {
                last = new_pos;
                idx = new_pos;
                continue;
            }

            if let Some(new_pos) = normalize_self_closing_void(input, bytes, idx, last, &mut output) {
                last = new_pos;
                idx = new_pos;
                continue;
            }

            if let Some(new_idx) = track_svg_tag(bytes, idx, &mut svg_depth) {
                idx = new_idx;
                continue;
            }

            if svg_depth == 0 {
                if let Some(new_pos) = normalize_void_tag_case(input, bytes, idx, last, &mut output) {
                    last = new_pos;
                    idx = new_pos;
                    continue;
                }

                if let Some(new_pos) = strip_raw_text_tag_reopen(input, bytes, idx, last, &mut output) {
                    last = new_pos;
                    idx = new_pos;
                    continue;
                }

                if let Some(new_pos) = strip_doctype(input, bytes, idx, len, last, &mut output) {
                    last = new_pos;
                    idx = new_pos;
                    continue;
                }
            }

            if !looks_like_tag_start(bytes, idx, len) {
                let out = output.get_or_insert_with(|| String::with_capacity(input.len() + 4));
                out.push_str(&input[last..idx]);
                out.push_str("&lt;");
                idx += 1;
                last = idx;
                continue;
            }
        }

        idx += 1;
    }

    if let Some(mut out) = output {
        if last < len {
            out.push_str(&input[last..]);
        }
        Cow::Owned(out)
    } else {
        Cow::Borrowed(input)
    }
}

/// Find the end of an unquoted attribute value starting at `start`: the first ASCII whitespace
/// or `>` byte, or `bytes.len()` if neither occurs before the end of `bytes`.
///
/// Extracted from `is_json_ld_script_open_tag`'s unquoted-value branch — identical scan,
/// unchanged.
fn scan_unquoted_attr_value_end(bytes: &[u8], start: usize) -> usize {
    let mut end = start;
    while end < bytes.len() && !bytes[end].is_ascii_whitespace() && bytes[end] != b'>' {
        end += 1;
    }
    end
}

/// Check if a script tag is a JSON-LD script.
pub fn is_json_ld_script_open_tag(tag: &str) -> bool {
    let bytes = tag.as_bytes();
    let mut idx = 0;
    while idx + 4 <= bytes.len() {
        if eq_ascii_case_insensitive(&bytes[idx..], b"type") {
            let before_ok = idx == 0
                || bytes
                    .get(idx.saturating_sub(1))
                    .is_some_and(|b| b.is_ascii_whitespace() || *b == b'<' || *b == b'/');
            let after_ok = bytes
                .get(idx + 4)
                .is_some_and(|b| b.is_ascii_whitespace() || *b == b'=');
            if !before_ok || !after_ok {
                idx += 4;
                continue;
            }

            let mut i = idx + 4;
            while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
                i += 1;
            }
            if bytes.get(i) != Some(&b'=') {
                idx += 4;
                continue;
            }
            i += 1;
            while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
                i += 1;
            }
            if i >= bytes.len() {
                return false;
            }

            let (value_start, value_end) = match bytes[i] {
                b'"' | b'\'' => {
                    let quote = bytes[i];
                    let start = i + 1;
                    let mut end = start;
                    while end < bytes.len() && bytes[end] != quote {
                        end += 1;
                    }
                    (start, end)
                }
                _ => {
                    let start = i;
                    (start, scan_unquoted_attr_value_end(bytes, start))
                }
            };

            let value = &tag[value_start..value_end];
            let media_type = value.split(';').next().unwrap_or(value).trim();
            return eq_ascii_case_insensitive(media_type.as_bytes(), b"application/ld+json");
        }
        idx += 1;
    }
    false
}

/// Case-insensitive byte comparison for ASCII.
#[inline]
pub fn eq_ascii_case_insensitive(haystack: &[u8], needle: &[u8]) -> bool {
    if haystack.len() < needle.len() {
        return false;
    }
    haystack
        .iter()
        .zip(needle.iter())
        .all(|(a, b)| a.eq_ignore_ascii_case(b))
}

/// Check if bytes match a tag start pattern.
pub fn matches_tag_start(bytes: &[u8], mut start: usize, tag: &[u8]) -> bool {
    if start >= bytes.len() {
        return false;
    }

    if start + tag.len() > bytes.len() {
        return false;
    }

    if !bytes[start..start + tag.len()].eq_ignore_ascii_case(tag) {
        return false;
    }

    start += tag.len();

    match bytes.get(start) {
        Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r') => true,
        Some(_) => false,
        None => true,
    }
}

/// Find the end of an HTML tag (the position of '>').
pub fn find_tag_end(bytes: &[u8], mut idx: usize) -> Option<usize> {
    loop {
        idx += memchr::memchr3(b'"', b'\'', b'>', bytes.get(idx..)?)?;
        let delimiter = bytes[idx];
        idx += 1;
        if delimiter == b'>' {
            return Some(idx);
        }
        idx += memchr::memchr(delimiter, &bytes[idx..])? + 1;
    }
}

/// Find the closing tag for a given tag name.
pub fn find_closing_tag(bytes: &[u8], mut idx: usize, tag: &[u8]) -> Option<usize> {
    let len = bytes.len();
    let mut depth = 1usize;

    while idx < len {
        if bytes[idx] == b'<' {
            if matches_tag_start(bytes, idx + 1, tag) {
                if let Some(next) = find_tag_end(bytes, idx + 1 + tag.len()) {
                    depth += 1;
                    idx = next;
                    continue;
                }
            } else if matches_end_tag_start(bytes, idx + 1, tag) {
                if let Some(close) = find_tag_end(bytes, idx + 2 + tag.len()) {
                    depth -= 1;
                    if depth == 0 {
                        return Some(close);
                    }
                    idx = close;
                    continue;
                }
            }
        }

        idx += 1;
    }

    None
}

/// Check if bytes match an end tag pattern.
pub fn matches_end_tag_start(bytes: &[u8], start: usize, tag: &[u8]) -> bool {
    if start >= bytes.len() || bytes[start] != b'/' {
        return false;
    }
    matches_tag_start(bytes, start + 1, tag)
}

/// Outcome of scanning one `<...>` tag starting at `tag_start` (the index of `<`), for
/// `normalize_unclosed_list_items`.
enum ListTagScan {
    /// A named tag was fully parsed. `name_start..name_end` bounds the tag name (captured
    /// before any attributes); `idx` is the position just past its `>`, or `bytes.len()` if the
    /// tag is unterminated after the name.
    Tag {
        is_close: bool,
        name_start: usize,
        name_end: usize,
        idx: usize,
    },
    /// The tag had no name (e.g. `<>` or `</>`); `idx` is where scanning should resume.
    Empty { idx: usize },
    /// The input ended before the tag could be parsed; scanning must stop entirely.
    Truncated,
}

/// Advance `*idx`/`*in_comment` past a `<!--`/`-->` boundary, or past the current byte if
/// already inside a comment. Returns `true` when the caller's scan loop should `continue`
/// immediately (the position was consumed as comment text or a comment boundary), `false` when
/// `bytes[*idx]` is unrelated to comment tracking and `*idx` is unchanged.
///
/// Extracted from `normalize_unclosed_list_items`'s main scan loop — identical comment
/// state-machine, unchanged.
fn advance_past_comment(bytes: &[u8], idx: &mut usize, len: usize, in_comment: &mut bool) -> bool {
    let b = bytes[*idx];

    if *in_comment {
        if b == b'-' && *idx + 2 < len && bytes[*idx + 1] == b'-' && bytes[*idx + 2] == b'>' {
            *in_comment = false;
            *idx += 3;
        } else {
            *idx += 1;
        }
        return true;
    }

    if b == b'<' && *idx + 3 < len && bytes[*idx + 1] == b'!' && bytes[*idx + 2] == b'-' && bytes[*idx + 3] == b'-' {
        *in_comment = true;
        *idx += 4;
        return true;
    }

    false
}

/// Scan one tag for `normalize_unclosed_list_items`, starting at `tag_start` (the index of `<`).
///
/// Extracted from `normalize_unclosed_list_items`'s main scan loop — identical open/close-slash,
/// whitespace-skip, name-scan, and quote-aware attribute scan, unchanged.
fn scan_list_tag(bytes: &[u8], tag_start: usize, len: usize) -> ListTagScan {
    let mut idx = tag_start + 1;
    if idx >= len {
        return ListTagScan::Truncated;
    }

    let is_close = bytes[idx] == b'/';
    if is_close {
        idx += 1;
        if idx >= len {
            return ListTagScan::Truncated;
        }
    }

    while idx < len && bytes[idx].is_ascii_whitespace() {
        idx += 1;
    }

    let name_start = idx;
    while idx < len {
        let ch = bytes[idx];
        if ch == b'>' || ch == b'/' || ch.is_ascii_whitespace() {
            break;
        }
        idx += 1;
    }
    let name_end = idx;
    if name_end == name_start {
        return ListTagScan::Empty { idx };
    }

    let mut in_single_quote = false;
    let mut in_double_quote = false;
    while idx < len {
        match bytes[idx] {
            b'\'' if !in_double_quote => {
                in_single_quote = !in_single_quote;
                idx += 1;
            }
            b'"' if !in_single_quote => {
                in_double_quote = !in_double_quote;
                idx += 1;
            }
            b'>' if !in_single_quote && !in_double_quote => {
                idx += 1;
                break;
            }
            _ => {
                idx += 1;
            }
        }
    }

    ListTagScan::Tag {
        is_close,
        name_start,
        name_end,
        idx,
    }
}

/// Whether `name_bytes` names an HTML element whose body is raw/verbatim text — `<pre>`,
/// `<code>`, `<script>`, or `<style>` — inside which list-item auto-closing must not run.
///
/// Extracted from `normalize_unclosed_list_items`'s main scan loop — identical tag-name checks,
/// unchanged.
fn is_verbatim_tag_name(name_bytes: &[u8]) -> bool {
    name_bytes.eq_ignore_ascii_case(b"pre")
        || name_bytes.eq_ignore_ascii_case(b"code")
        || name_bytes.eq_ignore_ascii_case(b"script")
        || name_bytes.eq_ignore_ascii_case(b"style")
}

/// The closing tag text for an auto-closed list-item element name (`"li"`, `"dt"`, or `"dd"`).
///
/// Extracted from `normalize_unclosed_list_items` — identical lookup, unchanged.
fn list_item_close_tag(item: &'static str) -> &'static str {
    match item {
        "li" => "</li>",
        "dt" => "</dt>",
        "dd" => "</dd>",
        _ => unreachable!(),
    }
}

/// Append `&input[*last_flush..pos]` followed by `close_tag` to the lazily-allocated `*output`,
/// then advance `*last_flush` to `pos`.
///
/// Extracted from `normalize_unclosed_list_items`'s local `emit_close_before!` macro as a plain
/// function — identical operations and order, unchanged.
fn emit_close_before(
    input: &str,
    len: usize,
    last_flush: &mut usize,
    output: &mut Option<String>,
    pos: usize,
    close_tag: &str,
) {
    let out = output.get_or_insert_with(|| String::with_capacity(len + 64));
    out.push_str(&input[*last_flush..pos]);
    out.push_str(close_tag);
    *last_flush = pos;
}

/// Update the open-list-item state machine for one non-verbatim tag and emit an auto-close for
/// a still-open `<li>`/`<dt>`/`<dd>` where HTML allows omitting the end tag.
///
/// Extracted from `normalize_unclosed_list_items`'s main scan loop — identical container/
/// list-item bookkeeping and close-tag emission, unchanged.
#[allow(clippy::too_many_arguments)]
fn apply_list_item_tag(
    input: &str,
    len: usize,
    tag_start: usize,
    is_close: bool,
    name_bytes: &[u8],
    open_item: &mut Option<&'static str>,
    list_stack: &mut Vec<Option<&'static str>>,
    last_flush: &mut usize,
    output: &mut Option<String>,
) {
    let is_list_container = name_bytes.eq_ignore_ascii_case(b"ul")
        || name_bytes.eq_ignore_ascii_case(b"ol")
        || name_bytes.eq_ignore_ascii_case(b"dl");

    let is_li = name_bytes.eq_ignore_ascii_case(b"li");
    let is_def_term = name_bytes.eq_ignore_ascii_case(b"dt");
    let is_def_desc = name_bytes.eq_ignore_ascii_case(b"dd");
    let is_list_item = is_li || is_def_term || is_def_desc;

    if is_close {
        if is_list_container {
            if let Some(item) = open_item.take() {
                emit_close_before(input, len, last_flush, output, tag_start, list_item_close_tag(item));
            }
            *open_item = list_stack.pop().unwrap_or(None);
        } else if is_list_item {
            *open_item = None;
        }
        return;
    }

    if is_list_container {
        list_stack.push(open_item.take());
    } else if is_list_item {
        let item_name: &'static str = if is_li {
            "li"
        } else if is_def_term {
            "dt"
        } else {
            "dd"
        };

        if let Some(prev_item) = open_item.replace(item_name) {
            emit_close_before(
                input,
                len,
                last_flush,
                output,
                tag_start,
                list_item_close_tag(prev_item),
            );
        }
    }
}

/// Close implicitly-terminated list-item elements that `tl` would otherwise
/// absorb as deep children, causing stack overflows on large documents.
///
/// The HTML5 parsing spec (§13.2.6.4.7 "in body" insertion mode) states that
/// an open `<li>`, `<dt>`, or `<dd>` tag is *implicitly closed* when:
///
/// - Another `<li>` / `<dt>` / `<dd>` open tag is encountered, or
/// - The closing `</ul>`, `</ol>`, or `</dl>` tag is reached.
///
/// The `tl` parser is not a full HTML5 parser; it does not apply implicit
/// closure rules.  When it encounters `<li>content<li>more` it treats the
/// second `<li>` as a child of the first, producing a linear chain of depth
/// equal to the number of items.  A list with 400 unclosed `<li>` items
/// causes `walk_node` to recurse 400 levels deep; with 467 such lists in a
/// single document (curl.se/changes.html) the cumulative stack depth triggers
/// an OS-level stack overflow.
///
/// This function rewrites the source HTML in one linear pass before `tl` sees
/// it, inserting the missing `</li>`, `</dt>`, and `</dd>` close tags exactly
/// where the HTML5 spec says they belong.
///
/// # Scope
///
/// Only the three list-item element types are handled here; `<p>` and other
/// auto-closing block elements are intentionally left to the existing
/// `has_inline_block_misnest` → `repair_with_html5ever` path.
/// Whether `bytes` holds any tag that could open or close a list item, which is the only
/// reason to run the rewrite scan at all.
///
/// Extracted from `normalize_unclosed_list_items`' early-exit guard — identical window scan,
/// unchanged.
fn contains_list_item_tag(bytes: &[u8], len: usize) -> bool {
    len >= 4
        && bytes
            .windows(3)
            .any(|w| w.eq_ignore_ascii_case(b"<li") || w.eq_ignore_ascii_case(b"<dt") || w.eq_ignore_ascii_case(b"<dd"))
}

/// Track `<pre>`/`<code>` nesting depth, whose contents are verbatim and must never be rewritten.
///
/// Extracted from `normalize_unclosed_list_items`' scan loop — identical saturating arithmetic,
/// unchanged.
const fn update_verbatim_depth(depth: &mut usize, is_close: bool) {
    *depth = if is_close { depth.saturating_sub(1) } else { *depth + 1 };
}

pub fn normalize_unclosed_list_items(input: &str) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();
    if !contains_list_item_tag(bytes, len) {
        return Cow::Borrowed(input);
    }

    let mut open_item: Option<&'static str> = None;
    let mut list_stack: Vec<Option<&'static str>> = Vec::new();
    let mut in_pre_or_code: usize = 0;
    let mut in_comment = false;
    let mut idx = 0usize;
    let mut last_flush = 0usize;
    let mut output: Option<String> = None;

    while idx < len {
        if advance_past_comment(bytes, &mut idx, len, &mut in_comment) {
            continue;
        }

        if bytes[idx] != b'<' {
            idx += 1;
            continue;
        }

        let tag_start = idx;
        let (is_close, name_start, name_end) = match scan_list_tag(bytes, tag_start, len) {
            ListTagScan::Truncated => break,
            ListTagScan::Empty { idx: new_idx } => {
                idx = new_idx;
                continue;
            }
            ListTagScan::Tag {
                is_close,
                name_start,
                name_end,
                idx: new_idx,
            } => {
                idx = new_idx;
                (is_close, name_start, name_end)
            }
        };
        let name_bytes = &bytes[name_start..name_end];

        if is_verbatim_tag_name(name_bytes) {
            update_verbatim_depth(&mut in_pre_or_code, is_close);
            continue;
        }
        if in_pre_or_code > 0 {
            continue;
        }

        apply_list_item_tag(
            input,
            len,
            tag_start,
            is_close,
            name_bytes,
            &mut open_item,
            &mut list_stack,
            &mut last_flush,
            &mut output,
        );
    }

    if let Some(item) = open_item.take() {
        emit_close_before(input, len, &mut last_flush, &mut output, len, list_item_close_tag(item));
    }

    match output {
        Some(mut out) => {
            if last_flush < len {
                out.push_str(&input[last_flush..]);
            }
            Cow::Owned(out)
        }
        None => Cow::Borrowed(input),
    }
}

/// Sanitize malformed markdown-like URLs in HTML attributes.
///
/// Handles cases like: `//[domain.com/path](http://domain.com/path)`
/// Extracts the actual URL from parentheses.
///
/// This is an internal function used during preprocessing to extract valid URLs
/// from malformed HTML that contains markdown-like syntax.
///
/// # Arguments
/// * `url` - The URL string to sanitize
///
/// # Returns
/// * `Cow<str>` - Either the borrowed original URL or an owned sanitized version
pub fn sanitize_markdown_url(url: &str) -> Cow<'_, str> {
    let Some(mid) = url.find("](") else {
        return Cow::Borrowed(url);
    };

    if !url[..mid].contains('[') {
        return Cow::Borrowed(url);
    }

    let paren_start = mid + 2;
    let Some(rel_end) = url[paren_start..].find(')') else {
        return Cow::Borrowed(url);
    };
    let paren_end = paren_start + rel_end;
    if paren_start >= paren_end {
        return Cow::Borrowed(url);
    }

    Cow::Owned(url[paren_start..paren_end].to_string())
}

/// Strip elements that are never rendered from HTML: those carrying the `hidden`
/// attribute, and those hidden via an inline `style="display:none"`,
/// `style="visibility:hidden"` or `style="font-size:0"` declaration.
///
/// `font-size: 0` is the one conditional case — it is also a spacing hack whose children
/// restore a readable size — so its subtree is kept when a descendant re-declares a non-zero
/// `font-size` or contains an image, whose intrinsic size is independent of font size (issues #468, #476).
///
/// Scans for opening tags matching either condition, finds their matching
/// closing tag, and removes the entire element (tag + content, so nested
/// content never leaks out). Self-closing tags are also removed.
/// Find `needle` in `haystack` at or after `from`, returning its start offset.
fn find_subslice(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
    if from >= haystack.len() {
        return None;
    }
    memchr::memmem::find(&haystack[from..], needle).map(|off| from + off)
}

/// If `<` at `idx` (with `next`/`rest` already read) opens a real HTML comment (`<!--`) or a
/// CDATA section (`<![CDATA[`), return the index just past its terminator (or `len` if
/// unterminated). Returns `None` for anything else, in which case `idx` is unaffected.
///
/// Extracted from `strip_bogus_comments`'s main scan loop — identical terminator lookups,
/// unchanged.
fn skip_real_comment_or_cdata(bytes: &[u8], idx: usize, len: usize, next: u8, rest: &[u8]) -> Option<usize> {
    // ~keep Step over a real comment as one unit. Its interior is not markup, and a
    // ~keep downlevel conditional comment (`<!--[if gte mso 9]> … <![endif]-->`, which
    // ~keep Microsoft Word emits by the dozen) contains a `<![endif]` that looks exactly
    // ~keep like a bogus comment. Stripping that would delete the `-->` closing the real
    // ~keep comment, leaving it unterminated and swallowing the rest of the document.
    if next == b'!' && rest.starts_with(b"--") {
        return Some(find_subslice(bytes, idx + 4, b"-->").map_or(len, |end| end + 3));
    }
    // ~keep Likewise CDATA: its interior is character data, not markup.
    if next == b'!' && rest.starts_with(b"[CDATA[") {
        return Some(find_subslice(bytes, idx + 9, b"]]>").map_or(len, |end| end + 3));
    }
    None
}

/// Whether `<` at `idx` (real comments/CDATA already ruled out by `skip_real_comment_or_cdata`)
/// starts a "bogus comment" per the HTML5 tokenizer.
///
/// Extracted from `strip_bogus_comments`'s main scan loop — identical classification, unchanged.
fn is_bogus_comment_marker(bytes: &[u8], idx: usize, len: usize, next: u8, rest: &[u8]) -> bool {
    if next == b'?' {
        return true;
    }
    if next == b'!' {
        // ~keep Real comments and CDATA already returned above. `<!DOCTYPE` is a doctype,
        // ~keep handled elsewhere; anything else after `<!` is a bogus comment.
        return !(rest.len() >= 7 && rest[..7].eq_ignore_ascii_case(b"DOCTYPE"));
    }
    if next == b'/' {
        // ~keep `</` followed by a letter is a real end tag; anything else -- including
        // ~keep end-of-input -- is a bogus comment.
        return idx + 2 >= len || !bytes[idx + 2].is_ascii_alphabetic();
    }
    false
}

fn has_bogus_comment_candidate(bytes: &[u8]) -> bool {
    // ~keep Markers inside quotes, comments, or CDATA may produce false positives here;
    // ~keep the full scanner resolves those. Reject only inputs containing no removal marker.
    memchr::memchr3_iter(b'?', b'!', b'/', bytes).any(|idx| {
        if idx == 0 || bytes[idx - 1] != b'<' {
            return false;
        }
        let next = bytes[idx];
        let rest = &bytes[idx + 1..];
        if next == b'!' && (rest.starts_with(b"--") || rest.starts_with(b"[CDATA[")) {
            return false;
        }
        is_bogus_comment_marker(bytes, idx - 1, bytes.len(), next, rest)
    })
}

/// Remove HTML5 *bogus comments* so they do not leak into the output as text.
///
/// The tokenizer enters the bogus-comment state from three places, and in all of them the
/// run through the next `>` becomes a comment token, which renders as nothing:
///
/// - `<?` — a "processing instruction" is not a thing in HTML; `<?php … ?>` is a comment.
/// - `<!` not beginning `--`, `DOCTYPE`, or `[CDATA[`.
/// - `</` followed by anything that is not an ASCII letter, e.g. `</3>` or `</ >`.
///
/// Real comments already convert to nothing, so leaving these as text was inconsistent as
/// well as wrong: `<?php echo 1; ?>` emitted `?php echo 1; ?>`, and `<!bogus>` emitted a
/// stray `>`.
///
/// `<![CDATA[` is deliberately NOT treated as a bogus comment here. It only is one outside
/// foreign content; inside `<svg>` or `<math>` it is real CDATA, and this pass has no
/// element context to tell them apart. Getting that wrong would corrupt SVG, so the narrower
/// behaviour is kept (see `tools/benchmark-harness/fixtures/synthetic/cdata_in_svg.html`).
///
/// Real tags are skipped with the quote-aware [`find_tag_end`] rather than scanned through,
/// so a `<?` or `<!` inside an attribute value cannot be mistaken for a bogus comment.
pub fn strip_bogus_comments(input: &str) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();
    // ~keep The shortest bogus comment is two bytes (`<?`, `</`, `<!` at end of input), so
    // ~keep the cheap bail must not be wider than that.
    if len < 2 || !has_bogus_comment_candidate(bytes) {
        return Cow::Borrowed(input);
    }

    let mut idx = 0;
    let mut last = 0;
    let mut output: Option<String> = None;

    while let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) {
        idx += offset;
        if idx + 1 >= len {
            break;
        }

        let next = bytes[idx + 1];
        let rest = if idx + 2 <= len {
            &bytes[idx + 2..]
        } else {
            &bytes[len..]
        };

        if let Some(new_idx) = skip_real_comment_or_cdata(bytes, idx, len, next, rest) {
            idx = new_idx;
            continue;
        }

        if !is_bogus_comment_marker(bytes, idx, len, next, rest) {
            // ~keep Skip a real tag wholesale so a `<?`/`<!` sitting inside a quoted
            // ~keep attribute value is never seen as a bogus comment of its own.
            if next.is_ascii_alphabetic() {
                if let Some(tag_end) = find_tag_end(bytes, idx + 1) {
                    idx = tag_end;
                    continue;
                }
            }
            idx += 1;
            continue;
        }

        // ~keep The bogus-comment state ends at the first `>` regardless of quoting, or at
        // ~keep end-of-input if there is none -- unlike a tag, it has no attribute grammar.
        let end = memchr::memchr(b'>', &bytes[idx + 1..]).map_or(len, |off| idx + 1 + off + 1);
        let out = output.get_or_insert_with(|| String::with_capacity(len));
        out.push_str(&input[last..idx]);
        last = end;
        idx = end;
    }

    match output {
        Some(mut out) => {
            out.push_str(&input[last..]);
            Cow::Owned(out)
        }
        None => Cow::Borrowed(input),
    }
}

/// Compute the end index of the hidden element starting at `idx` whose opening tag spans
/// `idx..tag_end` — either just past the opening tag itself (self-closing) or past its matching
/// closing tag.
///
/// Extracted from `strip_hidden_elements`'s main scan loop — identical tag-name scan and
/// self-closing/closing-tag dispatch, unchanged.
fn hidden_element_remove_end(bytes: &[u8], idx: usize, tag_end: usize, len: usize) -> usize {
    let name_start = idx + 1;
    let mut name_end = name_start;
    while name_end < len && !bytes[name_end].is_ascii_whitespace() && bytes[name_end] != b'>' && bytes[name_end] != b'/'
    {
        name_end += 1;
    }
    let tag_name = &bytes[name_start..name_end];

    if is_self_closing_tag(&bytes[idx..tag_end], tag_name) {
        tag_end
    } else {
        find_closing_tag_bytes_nested(bytes, tag_end, tag_name).unwrap_or(tag_end)
    }
}

/// Where the removal of the element whose open tag spans `idx..tag_end` ends, or `None` when
/// the element must be kept.
///
/// The `hidden` attribute and a definitive `display`/`visibility` declaration remove the
/// subtree outright. `font-size: 0` must preserve images and descendants that restore a readable size.
fn hidden_element_removal_end(input: &str, bytes: &[u8], idx: usize, tag_end: usize, len: usize) -> Option<usize> {
    let tag_slice = &input[idx..tag_end];
    if tag_has_hidden_attribute(tag_slice) {
        return Some(hidden_element_remove_end(bytes, idx, tag_end, len));
    }
    match hidden_style_reason(tag_slice)? {
        HiddenStyleReason::Definitive => Some(hidden_element_remove_end(bytes, idx, tag_end, len)),
        HiddenStyleReason::FontSizeZero => {
            if matches_tag_start(bytes, idx + 1, b"img") {
                return None;
            }
            let remove_end = hidden_element_remove_end(bytes, idx, tag_end, len);
            // ~keep Scan past the element's own open tag so its `font-size: 0` is not re-read.
            let subtree = input.get(tag_end..remove_end).unwrap_or("");
            (!region_restores_visible_content(subtree)).then_some(remove_end)
        }
    }
}

pub fn strip_hidden_elements(input: &str) -> Cow<'_, str> {
    let bytes = input.as_bytes();
    let len = bytes.len();

    if len == 0 || !bytes.contains(&b'<') {
        return Cow::Borrowed(input);
    }

    // ~keep Every removal requires a `hidden` or `style` attribute; without either
    // ~keep initial ASCII letter, even malformed or quoted tag-like text cannot match.
    if memchr::memchr2(b'h', b'H', bytes).is_none() && memchr::memchr2(b's', b'S', bytes).is_none() {
        return Cow::Borrowed(input);
    }

    // ~keep DoS guard: a run of unterminated `<` (no `>` anywhere in the rest of the
    // ~keep document) makes `find_tag_end` scan to EOF on every single one, turning this
    // ~keep loop quadratic. Once no `>` remains past `idx`, `find_tag_end` is guaranteed
    // ~keep to fail regardless of quoting, so `last_gt` lets every remaining iteration
    // ~keep skip the call in O(1) instead of re-scanning to the end each time.
    let last_gt = bytes.iter().rposition(|&b| b == b'>');

    let mut idx = 0;
    let mut last = 0;
    let mut output: Option<String> = None;

    while idx < len {
        let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) else {
            break;
        };
        idx += offset;
        // ~keep A `<` not immediately followed by an ASCII letter can never start a real
        // ~keep HTML tag name (HTML5 tokenizer "tag open state"), so it is never worth a
        // ~keep `find_tag_end` scan. Without this, a run like `<<<<<` treats every `<` as a
        // ~keep candidate tag start, and each failing scan re-walks the same suffix.
        let starts_tag_name = idx + 1 < len && bytes[idx + 1].is_ascii_alphabetic();
        if starts_tag_name && last_gt.is_some_and(|gt| gt > idx) {
            if let Some(tag_end) = find_tag_end(bytes, idx + 1) {
                if let Some(remove_end) = hidden_element_removal_end(input, bytes, idx, tag_end, len) {
                    let out = output.get_or_insert_with(|| String::with_capacity(len));
                    out.push_str(&input[last..idx]);
                    last = remove_end;
                    idx = remove_end;
                    continue;
                }
            }
        }
        idx += 1;
    }

    if let Some(mut out) = output {
        if last < len {
            out.push_str(&input[last..]);
        }
        Cow::Owned(out)
    } else {
        Cow::Borrowed(input)
    }
}

/// Consume an optional `=value` following an attribute name, starting at `i` (already past the
/// name and any whitespace). Returns the index just past the value (quoted or bare), or `i`
/// unchanged if there is no `=`.
///
/// Extracted from `tag_has_hidden_attribute` — identical quote-aware value scan, unchanged.
fn skip_attribute_value(bytes: &[u8], mut i: usize, len: usize) -> usize {
    if i >= len || bytes[i] != b'=' {
        return i;
    }
    i += 1;
    while i < len && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    if i < len && (bytes[i] == b'"' || bytes[i] == b'\'') {
        let quote = bytes[i];
        i += 1;
        while i < len && bytes[i] != quote {
            i += 1;
        }
        i += 1;
    } else {
        while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
            i += 1;
        }
    }
    i
}

/// Check if an opening tag string contains the `hidden` attribute.
///
/// Handles: `hidden`, `hidden=""`, `hidden="hidden"`, `hidden="true"`.
/// Does NOT match attributes like `data-hidden` or `aria-hidden`.
///
/// ~keep `pub(crate)`: also called from `tier1::scanner` so the Tier-1 byte
/// ~keep scanner bails on the same hidden-attribute condition this pass strips,
/// ~keep rather than re-implementing the scan a second time.
pub fn tag_has_hidden_attribute(tag: &str) -> bool {
    let bytes = tag.as_bytes();
    let len = bytes.len();

    let mut i = 0;
    while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
        i += 1;
    }

    // ~keep Walk name=value pairs rather than scanning the raw tag text for the word
    // ~keep `hidden`: a plain substring scan also matches inside quoted VALUES, so
    // ~keep `<div title="... hidden from search engines">` read as hidden and the whole
    // ~keep visible element was stripped.
    while i < len {
        while i < len && (bytes[i].is_ascii_whitespace() || bytes[i] == b'/') {
            i += 1;
        }
        if i >= len || bytes[i] == b'>' {
            return false;
        }

        let name_start = i;
        while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'=' && bytes[i] != b'>' && bytes[i] != b'/' {
            i += 1;
        }
        let name = &bytes[name_start..i];

        while i < len && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        i = skip_attribute_value(bytes, i, len);

        if name.eq_ignore_ascii_case(b"hidden") {
            return true;
        }
    }
    false
}

/// Remove `/* ... */` comments from a CSS declaration.
///
/// ~keep A comment before the property name shifts the first `:` so that
/// ~keep `split_once(':')` yields `"/* note */ display"` as the property, which never
/// ~keep matches — silently defeating the hidden-element check and leaking the content.
fn strip_css_comments(declaration: &str) -> Cow<'_, str> {
    if !declaration.contains("/*") {
        return Cow::Borrowed(declaration);
    }
    let mut out = String::with_capacity(declaration.len());
    let mut rest = declaration;
    while let Some(start) = rest.find("/*") {
        out.push_str(&rest[..start]);
        let Some(end) = rest[start + 2..].find("*/") else {
            rest = "";
            break;
        };
        rest = &rest[start + 2 + end + 2..];
    }
    out.push_str(rest);
    Cow::Owned(out)
}

/// Why an element's inline `style` marks it as never rendered.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HiddenStyleReason {
    /// `display: none` or `visibility: hidden` — neither the element nor its subtree renders,
    /// whatever a descendant declares.
    Definitive,
    /// `font-size: 0` — the element's own text is invisible, but the same declaration is also
    /// the classic inline-block/email spacing hack, where a descendant sets its own non-zero
    /// `font-size` and *does* render. Callers must check the subtree before removing it.
    FontSizeZero,
}

/// Last-declaration-wins scan of an inline `style` value for the three properties that decide
/// whether an element renders.
///
/// Returns `(display_hides, visibility_hides, font_size_zero)`, where the third element is
/// `None` when `font-size` is not declared at all, and `Some(is_zero)` when it is.
fn scan_visibility_declarations(style_value: &str) -> (bool, bool, Option<bool>) {
    // ~keep CSS cascade: within one declaration block the LAST declaration for a property
    // ~keep wins, so `display:none; display:block` is VISIBLE. Matching with `.any()`
    // ~keep stripped it.
    let mut display_hides = false;
    let mut visibility_hides = false;
    let mut font_size_zero = None;
    for declaration in style_value.split(';') {
        let cleaned = strip_css_comments(declaration);
        let Some((property, value)) = cleaned.split_once(':') else {
            continue;
        };
        let property = property.trim();
        // ~keep `!important` (any casing, with or without a preceding space) is a CSS
        // ~keep priority flag, not part of the value — drop everything from `!` onward.
        let value = value.split('!').next().unwrap_or("").trim();
        if property.eq_ignore_ascii_case("display") {
            display_hides = value.eq_ignore_ascii_case("none");
        } else if property.eq_ignore_ascii_case("visibility") {
            visibility_hides = value.eq_ignore_ascii_case("hidden");
        } else if property.eq_ignore_ascii_case("font-size") {
            font_size_zero = Some(css_length_is_zero(value));
        }
    }
    (display_hides, visibility_hides, font_size_zero)
}

/// Whether a CSS length value is an exact zero: `0`, `0px`, `0.0em`, `.0%` and friends, in any
/// casing. A unit is optional (CSS permits a bare `0`) but must be a real length or percentage
/// unit when present, so a function call or keyword never reads as zero.
fn css_length_is_zero(value: &str) -> bool {
    const ZERO_UNITS: [&str; 16] = [
        "px", "pt", "pc", "em", "rem", "ex", "ch", "vw", "vh", "vmin", "vmax", "cm", "mm", "in", "q", "%",
    ];
    let digits_end = value
        .find(|c: char| !c.is_ascii_digit() && c != '.')
        .unwrap_or(value.len());
    let (number, unit) = value.split_at(digits_end);
    if number.is_empty() || number == "." || number.matches('.').count() > 1 {
        return false;
    }
    if number.bytes().any(|b| b != b'0' && b != b'.') {
        return false;
    }
    let unit = unit.trim();
    unit.is_empty() || ZERO_UNITS.iter().any(|candidate| unit.eq_ignore_ascii_case(candidate))
}

/// Classify how an opening tag's inline `style` attribute hides the element, if at all.
///
/// This is a targeted declaration scan, not a full CSS parser: it extracts the raw `style`
/// attribute value, splits it on `;`, and inspects each `property: value` pair. Untrusted
/// input is handled defensively — extra whitespace around `:` and `;`, mixed casing, and a
/// trailing `!important` (with or without a preceding space) are all tolerated.
pub fn hidden_style_reason(tag: &str) -> Option<HiddenStyleReason> {
    let style_value = extract_attribute_value(tag, "style")?;
    let (display_hides, visibility_hides, font_size_zero) = scan_visibility_declarations(style_value);
    if display_hides || visibility_hides {
        return Some(HiddenStyleReason::Definitive);
    }
    if font_size_zero == Some(true) {
        return Some(HiddenStyleReason::FontSizeZero);
    }
    None
}

/// Whether an opening tag's inline `style` declares a non-zero `font-size`, which makes the
/// element render even inside a `font-size: 0` ancestor.
fn tag_sets_non_zero_font_size(tag: &str) -> bool {
    let Some(style_value) = extract_attribute_value(tag, "style") else {
        return false;
    };
    scan_visibility_declarations(style_value).2 == Some(false)
}

/// Whether `region` contains an image or re-declares a non-zero `font-size`.
///
/// `font-size: 0` on a wrapper is a well-known inline-block/email spacing hack: the wrapper
/// kills the whitespace between children while each child restores a readable size. Removing
/// such a subtree would delete genuinely visible text, so the removal is skipped when a
/// descendant opts back in. This is a one-level-of-inheritance heuristic, not a cascade — a
/// size restored from a stylesheet is out of reach of a byte-level pass.
fn region_restores_visible_content(region: &str) -> bool {
    let bytes = region.as_bytes();
    let len = bytes.len();
    let mut idx = 0;
    while idx < len {
        if let Some(end) = skip_opaque_region(bytes, idx) {
            idx = end;
            continue;
        }
        if bytes[idx] == b'<' && idx + 1 < len && bytes[idx + 1].is_ascii_alphabetic() {
            if let Some(tag_end) = find_tag_end(bytes, idx + 1) {
                let tag = &region[idx..tag_end];
                if tag_has_hidden_attribute(tag) || hidden_style_reason(tag) == Some(HiddenStyleReason::Definitive) {
                    idx = hidden_element_remove_end(bytes, idx, tag_end, len);
                    continue;
                }
                if tag_sets_non_zero_font_size(tag) || matches_tag_start(bytes, idx + 1, b"img") {
                    return true;
                }
                idx = tag_end;
                continue;
            }
        }
        idx += 1;
    }
    false
}

/// Check if an opening tag's inline `style` attribute hides the element.
///
/// ~keep `pub`: also called from `tier1::scanner` (see `tag_has_hidden_attribute` above).
/// ~keep Tier-1 bails on any hit, including the `font-size: 0` case whose subtree Tier-2 may
/// ~keep still keep — a conservative bail that falls through to Tier-2 rather than diverging.
pub fn tag_has_hidden_style(tag: &str) -> bool {
    hidden_style_reason(tag).is_some()
}

/// If `i` (already past an attribute name and whitespace) points at `=`, scan its value with
/// `scan_attribute_value` and return `(Some(value), next_i)`; otherwise return `(None, i)`
/// unchanged.
///
/// Extracted from `extract_attribute_value` — identical `=value` handling, unchanged.
fn scan_optional_attribute_value<'a>(bytes: &[u8], tag: &'a str, mut i: usize, len: usize) -> (Option<&'a str>, usize) {
    if i >= len || bytes[i] != b'=' {
        return (None, i);
    }
    i += 1;
    while i < len && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    let (val, next) = scan_attribute_value(bytes, tag, i);
    (Some(val), next)
}

/// Extract the value of a named attribute from a raw opening-tag string.
///
/// Walks name=value pairs left to right (skipping the leading tag name) and
/// returns the first case-insensitive match. Handles double- and single-quoted
/// values and bare (unquoted) values. Returns `None` when the attribute is
/// absent or is a boolean attribute with no `=value`.
fn extract_attribute_value<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> {
    let bytes = tag.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' {
        i += 1;
    }

    while i < len {
        while i < len && (bytes[i].is_ascii_whitespace() || bytes[i] == b'/') {
            i += 1;
        }
        if i >= len || bytes[i] == b'>' {
            break;
        }

        let name_start = i;
        while i < len && bytes[i] != b'=' && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' && bytes[i] != b'/' {
            i += 1;
        }
        let name = &tag[name_start..i];

        while i < len && bytes[i].is_ascii_whitespace() {
            i += 1;
        }

        let (value, next_i) = scan_optional_attribute_value(bytes, tag, i, len);
        i = next_i;

        if name.eq_ignore_ascii_case(attr_name) {
            return value;
        }
    }
    None
}

/// Scan a single attribute value starting at `start`, handling quoted and bare forms.
///
/// Returns the extracted value slice and the byte index immediately following it.
fn scan_attribute_value<'a>(bytes: &[u8], tag: &'a str, start: usize) -> (&'a str, usize) {
    let len = bytes.len();
    if start < len && (bytes[start] == b'"' || bytes[start] == b'\'') {
        let quote = bytes[start];
        let val_start = start + 1;
        let mut end = val_start;
        while end < len && bytes[end] != quote {
            end += 1;
        }
        let value = &tag[val_start..end];
        let next = if end < len { end + 1 } else { end };
        return (value, next);
    }

    let val_start = start;
    let mut end = start;
    while end < len && !bytes[end].is_ascii_whitespace() && bytes[end] != b'>' {
        end += 1;
    }
    (&tag[val_start..end], end)
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use super::{
        find_closing_tag_bytes, find_closing_tag_bytes_nested, find_tag_end, normalize_bogus_comment_endings,
        normalize_split_closing_tags, normalize_unclosed_list_items, sanitize_markdown_url, strip_bogus_comments,
        strip_hidden_elements,
    };

    #[test]
    fn should_find_tag_end_outside_quotes_from_the_requested_byte() {
        let cases: &[(&[u8], usize, Option<usize>)] = &[
            (b"", 0, None),
            (b">", 0, Some(1)),
            (b">", 1, None),
            (b">", usize::MAX, None),
            (b"a>b", 0, Some(2)),
            (b"'>' >", 0, Some(5)),
            (b"\"'>'\">", 0, Some(6)),
            (b"'\" >' >", 0, Some(7)),
            (b"\"unterminated >", 0, None),
            (b"\"abc\">", 1, None),
            (b"\\\">", 0, None),
            (b"\xff'>\0'\xfe>", 0, Some(7)),
        ];
        for &(input, start, expected) in cases {
            assert_eq!(find_tag_end(input, start), expected, "input: {input:?}, start: {start}");
        }
    }

    #[test]
    fn should_borrow_html_without_bogus_comments() {
        for input in [
            "",
            "<",
            "é日 text<",
            "<p title='a<?b>c'>é日</p><",
            "<!--[if gte mso 9]><?ignored?><![endif]--><p>kept</p>",
            "<![CDATA[<?not markup>]]><p>kept</p>",
            "<!DOCTYPE html><p>kept</p>",
            "<!-- unterminated <?ignored>",
            "<![CDATA[unterminated <?ignored>",
        ] {
            let actual = strip_bogus_comments(input);
            assert_eq!(actual.as_ref(), input, "input: {input}");
            assert!(matches!(actual, Cow::Borrowed(_)), "input: {input}");
        }
    }

    #[test]
    fn should_remove_bogus_comments_at_utf8_and_markup_boundaries() {
        for (input, expected) in [
            ("é<?a><!b></3>日<", "é日<"),
            ("<p title='a<?b>c'>é</p><?drop>日", "<p title='a<?b>c'>é</p>日"),
            ("<!-- <?kept> --><?drop>æ—¥", "<!-- <?kept> -->æ—¥"),
            ("<![CDATA[<?kept>]]><?drop>æ—¥", "<![CDATA[<?kept>]]>æ—¥"),
            ("é<?'quoted>日", "é日"),
            ("é<?", "é"),
            ("é<!", "é"),
            ("é</", "é"),
        ] {
            let actual = strip_bogus_comments(input);
            assert_eq!(actual.as_ref(), expected, "input: {input}");
            assert!(matches!(actual, Cow::Owned(_)), "input: {input}");
        }
    }

    #[test]
    fn should_distinguish_bogus_markers_from_recognized_prefixes() {
        for (input, expected) in [
            ("é /!? 日", "é /!? 日"),
            ("<!DOC>é", "é"),
            ("<!DOCTYPE", "<!DOCTYPE"),
            ("<!dOcTyPe html><p>é</p>", "<!dOcTyPe html><p>é</p>"),
            ("<![cdata[x]]>é", "é"),
            ("<![CDATA[<?x>]]>é", "<![CDATA[<?x>]]>é"),
            ("<!--<?x>-->é", "<!--<?x>-->é"),
            ("</é>日", "日"),
            ("</a>", "</a>"),
            ("</A>", "</A>"),
            ("<p title='<!bad><?bad></3>'>é</p>", "<p title='<!bad><?bad></3>'>é</p>"),
        ] {
            let actual = strip_bogus_comments(input);
            assert_eq!(actual.as_ref(), expected, "input: {input}");
            assert_eq!(matches!(actual, Cow::Borrowed(_)), input == expected, "input: {input}");
        }
    }

    #[test]
    fn normalize_bogus_comment_endings_leaves_well_formed_comment_unchanged() {
        let input = "<p>A</p><!-- foo --><p>B</p>";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), input);
    }

    #[test]
    fn normalize_bogus_comment_endings_rewrites_triple_dash_close() {
        let input = "<!-- foo --->";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), "<!-- foo -->");
    }

    #[test]
    fn normalize_bogus_comment_endings_rewrites_four_dash_close() {
        let input = "<!-- foo ---->";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), "<!-- foo -->");
    }

    #[test]
    fn normalize_bogus_comment_endings_preserves_content_after_comment() {
        let input = "<h1>One</h1><!-- /// ---><p>Two</p>";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), "<h1>One</h1><!-- /// --><p>Two</p>");
    }

    #[test]
    fn normalize_bogus_comment_endings_handles_multiple_bogus_comments() {
        let input = "<p>A</p><!-- x ---><p>B</p><!-- y ----><p>C</p>";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), "<p>A</p><!-- x --><p>B</p><!-- y --><p>C</p>");
    }

    #[test]
    fn normalize_bogus_comment_endings_rewrites_abrupt_closing_of_empty_comment() {
        // ~keep `<!-->` and `<!--->` are HTML5's "abrupt-closing-of-empty-comment"
        // ~keep quirk: legal, empty comments whose open and close share dashes.
        let input = "<p>Before</p><!--><p>After</p>";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), "<p>Before</p><!----><p>After</p>");

        let input = "<p>Before</p><!---><p>After</p>";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), "<p>Before</p><!----><p>After</p>");
    }

    #[test]
    fn normalize_bogus_comment_endings_handles_no_comments() {
        let input = "<p>Just a paragraph</p>";
        let result = normalize_bogus_comment_endings(input);
        assert_eq!(result.as_ref(), input);
    }

    #[test]
    fn normalize_bogus_comment_endings_empty_input() {
        let result = normalize_bogus_comment_endings("");
        assert_eq!(result.as_ref(), "");
    }

    #[test]
    fn should_preserve_hidden_style_markers_without_false_negative_skips() {
        let cases = [
            ("<ul><li>a<li>b<li>c</ul>\n", "<ul><li>a<li>b<li>c</ul>\n", false),
            ("é<div>visible</div>", "é<div>visible</div>", false),
            ("<b HIDDEN>x</b>", "", true),
            ("<b STYLE='DISPLAY:NONE'>x</b>", "", true),
            ("<b style='display:none'>x</b>", "", true),
            ("<b title='HIDDEN STYLE'>x</b>", "<b title='HIDDEN STYLE'>x</b>", false),
        ];
        for (input, expected, owned) in cases {
            let actual = strip_hidden_elements(input);
            assert_eq!(actual, expected, "input: {input:?}");
            assert_eq!(matches!(actual, Cow::Owned(_)), owned, "input: {input:?}");
        }
    }

    #[test]
    fn should_preserve_hidden_element_scan_boundaries_and_borrowing() {
        let cases = [
            ("é text<", "é text<", false),
            ("<span hidden", "<span hidden", false),
            ("<<span hidden>x</span>終", "<終", true),
            ("< span hidden>x</ span>", "< span hidden>x</ span>", false),
            (
                "<div title='<span hidden>x</span>'>ok</div>",
                "<div title=''>ok</div>",
                true,
            ),
            ("<i hidden>x</i><b hidden>y</b>z", "z", true),
            (
                "<div data-hidden='true'>x</div>",
                "<div data-hidden='true'>x</div>",
                false,
            ),
            (
                "<div style='font-size:0'><b style='font-size:12px'>x</b></div>",
                "<div style='font-size:0'><b style='font-size:12px'>x</b></div>",
                false,
            ),
        ];
        for (input, expected, owned) in cases {
            let actual = strip_hidden_elements(input);
            assert_eq!(actual, expected, "input: {input:?}");
            assert_eq!(matches!(actual, Cow::Owned(_)), owned, "input: {input:?}");
        }
    }

    #[test]
    fn should_preserve_split_closing_tag_boundaries_and_borrowing() {
        let cases = [
            ("é\ntext</", "é\ntext</", false),
            ("é\ntext<", "é\ntext<", false),
            ("\n<", "\n<", false),
            ("\n</</a\n>", "\n</</a>", true),
            ("\n</a!></b\r\n >", "\n</a!></b>", true),
            ("é</custom-42\n>終</B\n>", "é</custom-42>終</B>", true),
            ("\n</a ", "\n</a ", false),
            ("</a\r>", "</a\r>", false),
            ("\n</a\r>", "\n</a>", true),
            ("\n</ a\n>", "\n</ a\n>", false),
            ("<!-- </a\n> -->", "<!-- </a> -->", true),
            ("<x a='</b\n>'>", "<x a='</b>'>", true),
        ];
        for (input, expected, owned) in cases {
            let actual = normalize_split_closing_tags(input);
            assert_eq!(actual, expected, "input: {input:?}");
            assert_eq!(matches!(actual, Cow::Owned(_)), owned, "input: {input:?}");
        }
    }

    #[test]
    fn normalize_split_closing_tags_collapses_newline_before_close_bracket() {
        let input = "<a href=\"#x\">text</a\n>";
        let result = normalize_split_closing_tags(input);
        assert_eq!(result.as_ref(), "<a href=\"#x\">text</a>");
    }

    #[test]
    fn normalize_split_closing_tags_collapses_indented_newline_before_close_bracket() {
        let input = "<a href=\"#x\">text</a\n  >";
        let result = normalize_split_closing_tags(input);
        assert_eq!(result.as_ref(), "<a href=\"#x\">text</a>");
    }

    #[test]
    fn normalize_split_closing_tags_leaves_well_formed_closing_tags_unchanged() {
        let input = "<a href=\"#x\">text</a>";
        let result = normalize_split_closing_tags(input);
        assert_eq!(result.as_ref(), input);
    }

    #[test]
    fn normalize_split_closing_tags_handles_multiple_split_closing_tags() {
        let input = "<li><a href=\"#a\">A</a\n  >\n<a href=\"#b\">B</a\n>";
        let result = normalize_split_closing_tags(input);
        assert_eq!(result.as_ref(), "<li><a href=\"#a\">A</a>\n<a href=\"#b\">B</a>");
    }

    #[test]
    fn normalize_split_closing_tags_does_not_collapse_inline_whitespace() {
        let input = "<a href=\"#x\">text</a >";
        let result = normalize_split_closing_tags(input);
        // ~keep A space before > is actually valid HTML and tl handles it fine.
        // ~keep We must not touch it to avoid over-normalising.
        assert_eq!(result.as_ref(), input);
    }

    #[test]
    fn normalize_split_closing_tags_empty_input() {
        let result = normalize_split_closing_tags("");
        assert_eq!(result.as_ref(), "");
    }

    #[test]
    fn sanitize_markdown_url_extracts_scheme_relative_markdown_like_url() {
        let input = "//[p1.zemanta.com/v2/p/ns/45625/PAGE\\_VIEW/](http://p1.zemanta.com/v2/p/ns/45625/PAGE_VIEW/)";
        let sanitized = sanitize_markdown_url(input);
        assert_eq!(sanitized, "http://p1.zemanta.com/v2/p/ns/45625/PAGE_VIEW/");
    }

    #[test]
    fn sanitize_markdown_url_extracts_standard_markdown_like_url() {
        let input = "[label](https://example.com/path?q=1)";
        let sanitized = sanitize_markdown_url(input);
        assert_eq!(sanitized, "https://example.com/path?q=1");
    }

    #[test]
    fn sanitize_markdown_url_leaves_normal_urls_unchanged() {
        let input = "https://example.com/normal";
        let sanitized = sanitize_markdown_url(input);
        assert_eq!(sanitized, input);
    }

    #[test]
    fn normalize_unclosed_list_items_leaves_well_formed_list_unchanged() {
        let input = "<ul><li>A</li><li>B</li></ul>";
        let result = normalize_unclosed_list_items(input);
        assert_eq!(result.as_ref(), input);
    }

    #[test]
    fn normalize_unclosed_list_items_closes_unclosed_li_before_next_li() {
        let input = "<ul><li>A<li>B</ul>";
        let result = normalize_unclosed_list_items(input);
        assert_eq!(result.as_ref(), "<ul><li>A</li><li>B</li></ul>");
    }

    #[test]
    fn normalize_unclosed_list_items_closes_chain_of_unclosed_li() {
        let input = "<ul><li>A<li>B<li>C</ul>";
        let result = normalize_unclosed_list_items(input);
        assert_eq!(result.as_ref(), "<ul><li>A</li><li>B</li><li>C</li></ul>");
    }

    #[test]
    fn normalize_unclosed_list_items_does_not_modify_input_without_list_items() {
        let input = "<p>Hello</p><div>World</div>";
        let result = normalize_unclosed_list_items(input);
        assert!(matches!(result, std::borrow::Cow::Borrowed(_)));
    }

    #[test]
    fn normalize_unclosed_list_items_handles_nested_list_correctly() {
        let input = "<ul><li>Outer<ul><li>Inner A<li>Inner B</ul><li>Outer B</ul>";
        let result = normalize_unclosed_list_items(input);
        assert_eq!(
            result.as_ref(),
            "<ul><li>Outer<ul><li>Inner A</li><li>Inner B</li></ul></li><li>Outer B</li></ul>"
        );
    }

    #[test]
    fn normalize_unclosed_list_items_handles_dt_and_dd() {
        let input = "<dl><dt>Term A<dd>Def A<dt>Term B<dd>Def B</dl>";
        let result = normalize_unclosed_list_items(input);
        assert_eq!(
            result.as_ref(),
            "<dl><dt>Term A</dt><dd>Def A</dd><dt>Term B</dt><dd>Def B</dd></dl>"
        );
    }

    #[test]
    fn normalize_unclosed_list_items_does_not_touch_content_in_pre() {
        let input = "<ul><li>A<pre><li>not-a-list-item</pre><li>B</ul>";
        let result = normalize_unclosed_list_items(input);
        assert_eq!(
            result.as_ref(),
            "<ul><li>A<pre><li>not-a-list-item</pre></li><li>B</li></ul>"
        );
    }

    #[test]
    fn normalize_unclosed_list_items_skips_html_comments() {
        let input = "<ul><li>A<!-- <li>comment --><li>B</ul>";
        let result = normalize_unclosed_list_items(input);
        assert_eq!(result.as_ref(), "<ul><li>A<!-- <li>comment --></li><li>B</li></ul>");
    }

    #[test]
    fn normalize_unclosed_list_items_empty_input() {
        let result = normalize_unclosed_list_items("");
        assert_eq!(result.as_ref(), "");
    }

    #[test]
    fn strip_hidden_elements_removes_display_none_element() {
        let input = r#"<p>visible</p><div style="display:none">secret</div><p>also visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p><p>also visible</p>");
    }

    #[test]
    fn strip_hidden_elements_removes_visibility_hidden_element() {
        let input = r#"<p>visible</p><span style="visibility:hidden">secret</span><p>also visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p><p>also visible</p>");
    }

    #[test]
    fn strip_hidden_elements_tolerates_whitespace_around_declaration() {
        let input = r#"<div style="display : none">secret</div><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_tolerates_mixed_case_declaration() {
        let input = r#"<div style="Display:NONE">secret</div><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_tolerates_important_flag() {
        let input = r#"<div style="display:none !important">secret</div><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_matches_declaration_among_others() {
        let input = r#"<div style="color:red; display:none; margin:0">secret</div><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_leaves_visible_style_untouched() {
        let input = r#"<div style="color:red; display:block">visible</div>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), input);
    }

    #[test]
    fn strip_hidden_elements_removes_nested_content_inside_hidden_parent() {
        let input = r#"<div style="display:none"><p>secret</p><span>also secret</span></div><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_removes_parent_that_nests_the_same_tag_name() {
        let input = r#"<p>A<div style="display:none">S1<div>S2</div>LEAKED</div>B</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>AB</p>");
    }

    #[test]
    fn strip_hidden_elements_removes_deeply_nested_same_tag_subtree() {
        let input = r#"<div style="display:none">L0<div>L1<div>L2</div>T2</div>T1</div><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_matches_closing_tag_case_insensitively() {
        let input = r#"<DIV style="display:none">x<div>y</div>z</DIV><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_does_not_match_a_tag_with_a_longer_name() {
        let input = r#"<div style="display:none">a<divider>b</divider>c</div><p>visible</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>");
    }

    #[test]
    fn strip_hidden_elements_drops_only_the_open_tag_when_never_closed() {
        let input = r#"<p>visible</p><div style="display:none">dangling"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>visible</p>dangling");
    }

    #[test]
    fn find_closing_tag_bytes_nested_skips_inner_same_name_element() {
        let html = b"<div>a<div>b</div>c</div>tail";
        let start = "<div>".len();
        let end = find_closing_tag_bytes_nested(html, start, b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn find_closing_tag_bytes_nested_ignores_self_closing_inner_tag() {
        let html = b"<div>a<div/>b</div>tail";
        let start = "<div>".len();
        let end = find_closing_tag_bytes_nested(html, start, b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn find_closing_tag_bytes_nested_returns_none_for_unbalanced_input() {
        let html = b"<div>a<div>b</div>";
        assert_eq!(find_closing_tag_bytes_nested(html, "<div>".len(), b"div"), None);
    }

    #[test]
    fn find_closing_tag_bytes_nested_ignores_close_tag_inside_a_comment() {
        let html = b"<div>a<!-- </div> -->b</div>tail";
        let end = find_closing_tag_bytes_nested(html, "<div>".len(), b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn find_closing_tag_bytes_nested_ignores_open_tag_inside_a_comment() {
        let html = b"<div>a<!-- <div> -->b</div>tail";
        let end = find_closing_tag_bytes_nested(html, "<div>".len(), b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn find_closing_tag_bytes_nested_ignores_close_tag_inside_a_quoted_attribute() {
        let html = br#"<div>a<span title="</div>">x</span>b</div>tail"#;
        let end = find_closing_tag_bytes_nested(html, "<div>".len(), b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn find_closing_tag_bytes_nested_ignores_close_tag_inside_a_raw_text_body() {
        let html = br#"<div>a<script>var s = "</div>";</script>b</div>tail"#;
        let end = find_closing_tag_bytes_nested(html, "<div>".len(), b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn find_closing_tag_bytes_nested_ignores_close_tag_inside_a_cdata_section() {
        let html = b"<div>a<![CDATA[ </div> ]]>b</div>tail";
        let end = find_closing_tag_bytes_nested(html, "<div>".len(), b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn find_closing_tag_bytes_nested_does_not_skip_over_a_literal_less_than_in_text() {
        let html = b"<div>a < b</div>tail";
        let end = find_closing_tag_bytes_nested(html, "<div>".len(), b"div").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }

    #[test]
    fn strip_hidden_elements_ignores_a_close_tag_written_inside_a_comment() {
        let input = r#"<p>A</p><div style="display:none">SECRET<!-- </div> -->MORE</div><p>B</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), "<p>A</p><p>B</p>");
    }

    #[test]
    fn strip_hidden_elements_keeps_sibling_when_a_comment_holds_an_unbalanced_open_tag() {
        let input = r#"<div id="wrap"><div style="display:none">S<!-- <div> --></div><p>VISIBLE</p></div><p>after</p>"#;
        let result = strip_hidden_elements(input);
        assert_eq!(result.as_ref(), r#"<div id="wrap"><p>VISIBLE</p></div><p>after</p>"#);
    }

    #[test]
    fn find_closing_tag_bytes_stays_first_match_for_raw_text_elements() {
        let html = br#"<script>var s = "<script>";</script>tail"#;
        let start = "<script>".len();
        let end = find_closing_tag_bytes(html, start, b"script").expect("closing tag not found");
        assert_eq!(&html[end..], b"tail");
    }
}