libxml-rs 0.1.0-alpha.42

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated ABI-FUNCTION-SIGNATURE plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions); Phase-12 real downstream substitution (binary/static/docker substitution, export-surface disposition, ELF version graphs); Phase-13 hostile audit courts (ABI/ownership/allocator/callbacks/failure/threads/oracle-contamination) byte-identical vs the system oracle incl. the upstream thread-local globals model; Phase-14 downstream custodian validation courts (lxml/Nokogiri/PHP/Debian). Test counts live in atlas/TEST_COUNTS.json, residuals in atlas/RESIDUAL_LEDGER.json (generated evidence).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
//! exports_parser — C ABI exports for the XML parser family (§11.1-I).
//!
//! Implements the parser/parserInternals/xmlIO/encoding/tree export surface:
//! parser-context creation and lifecycle, the `xmlCtxtRead*` family, parser
//! input buffers and streams, encoding switches, the deprecated node-info
//! sequence, global I/O callback registration, external-entity loaders, the
//! `xmlFile*` I/O callbacks, low-level character scanning helpers and the
//! SAX/DTD parse front-ends.
//!
//! Where an internal engine entry point exists (e.g. `crate::xml::parser::helpers`),
//! the export wraps it; otherwise the function is ported from upstream
//! `parser.c` / `parserInternals.c` / `xmlIO.c` / `error.c` / `encoding.c`
//! (see `archaeology/libxml2-git`).
//!
//! # Upstream contract
//!
//! Parity target is upstream `parser.c`, `parserInternals.c`, `xmlIO.c`,
//! `error.c` and `encoding.c` (libxml2 2.15.3) with the `parser.h`/
//! `parserInternals.h`/`xmlIO.h` signatures. Residuals R-000164 (parser/tree
//! structural parity), R-000165 (parser-context accessors and input
//! constructors) and R-000169 (input filename ownership) all land here.
//!
//! # Conceptual behavior
//!
//! This module implements the parser export surface: parser-context
//! creation/lifecycle, the `xmlCtxtRead*`/`xmlRead*` families, parser input
//! buffers and streams, encoding switches, the deprecated node-info sequence,
//! global I/O callback registration, external-entity loaders, the `xmlFile*`
//! I/O callbacks and the SAX/DTD parse front-ends. Internal engine entry
//! points are wrapped; the rest are ported from the upstream sources.
//!
//! # Ownership & safety invariants
//!
//! Parser contexts are caller-owned (freed with `xmlFreeParserCtxt`); docs
//! returned by `xmlRead*` are caller-owned (freed with `xmlFreeDoc`); inputs
//! created by `xmlNewInputFrom*` are owned by the context once pushed.
//! Filenames stored in `_xmlParserInput.filename` and `doc->URL` are owned
//! copies — R-000169 fixed xml_strndup on non-NUL-terminated Rust Strings
//! (heap-buffer-overflow) and borrowed filename pointers.
//!
//! # Historical quirks & epochs
//!
//! QUIRK-0001/LORE-0001: since 2.9.0 (commit `52d8ade7`, 2012-07-30) default
//! parser limits apply unless `XML_PARSE_HUGE` is set. E-002: parse-error
//! diagnostics changed across 2.9.10 (non-recursive parser refactor) and
//! 2.12.x (error-handling rework); E-005: exit codes reworked in 2.13.0.
//! R-000164 (11.1-N) aligned the parse-time DOM construction with upstream
//! (TREE-001 byte-identical).
//!
//! # Deliberate oddities
//!
//! The deprecated `xmlParse*` no-ops and the `xmlFileMatch`/
//! `xmlParserInputRead` trivial bodies are deliberate (R-000138 set:
//! upstreams own bodies are empty/trivial). `xmlReadMemory` accepts size-0
//! input (R-000163) and applies options/URL on both success and recovery
//! paths (R-000164).
//!
//! # Proving courts
//!
//! The PARSER court family, the ERROR-001 probe (error-family-probe.c, 48/48
//! byte-identical), the TREE-001 structural probe and the DSO-LOADER/
//! HEADER-COMPILE courts cover this module; the parser unit suite runs under
//! cargo test.
//!
//! # Tempting simplifications that would break parity
//!
//! A tempting simplification is to store the input filename as a borrowed
//! pointer into a Rust String — R-000169 proved that produces dangling
//! `filename`/`doc->URL` pointers and heap-reuse garbage on the second parse;
//! every construction path must own its filename copy. Another shortcut,
//! skipping the `XML_PARSE_HUGE`/limits logic, would diverge from the 2.9.0+
//! oracle on large documents (PARSER-LIMIT courts).

#![allow(missing_docs)]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]

// SAFETY-SCOPE: EXPORT-PARSER-MECHANICAL-001
// (11.1-Z.3 proof scope, classified-generated) — this module is the
// mechanical extern-"C" export surface: every `unsafe` block in it is
// the documented indirection/registry-access pattern whose validity
// rests on the upstream C contract, and the exported signatures are
// machine-measured by the ABI-FUNCTION-SIGNATURE and DSO-LOADER
// courts and the C-API differential probes. The safety contract of
// each export is stated in its own doc comment; this scope covers the
// mechanical wrappers' unsafe blocks.

use core::ffi::CStr;
use core::ptr;
use std::os::raw::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void};

use parking_lot::Mutex;

use crate::abi::allocator::{
    xmlFreeImpl, xmlMallocImpl, xmlMallocZero, xmlMemStrdupImpl, xmlReallocImpl,
};
use crate::abi::callbacks::{
    xmlGenericErrorFunc, xmlInputCloseCallback, xmlInputReadCallback, xmlOutputCloseCallback,
    xmlOutputWriteCallback, xmlStructuredErrorFunc,
};
use crate::abi::structs::*;
use crate::abi::types::*;
use crate::xml::parser::helpers;
use crate::xml::parser::input::InputBuffer;
use crate::xml::{dtd, encoding, entities, errors, globals, io, string, tree};

// ═══════════════════════════════════════════════════════════════════════════════
// Local ABI types (upstream xmlIO.h / parser.h, not present in callbacks.rs)
// ═══════════════════════════════════════════════════════════════════════════════

/// `xmlInputMatchCallback` — decide whether a filename is handled by the
/// registered input callback pair.
type xmlInputMatchCallback = unsafe extern "C" fn(filename: *const c_char) -> c_int;

/// `xmlInputOpenCallback` — open a resource and return an I/O context.
type xmlInputOpenCallback = unsafe extern "C" fn(filename: *const c_char) -> *mut c_void;

/// `xmlOutputMatchCallback` — decide whether a filename is handled by the
/// registered output callback pair.
type xmlOutputMatchCallback = unsafe extern "C" fn(filename: *const c_char) -> c_int;

/// `xmlOutputOpenCallback` — open a resource for writing and return a context.
type xmlOutputOpenCallback = unsafe extern "C" fn(filename: *const c_char) -> *mut c_void;

/// `xmlExternalEntityLoader` — resolve an external entity to a parser input.
type xmlExternalEntityLoader = unsafe extern "C" fn(
    URL: *const c_char,
    ID: *const c_char,
    ctxt: *mut _xmlParserCtxt,
) -> *mut _xmlParserInput;

#[derive(Clone, Copy)]
struct InputCallbackEntry {
    matchcb: Option<xmlInputMatchCallback>,
    opencb: Option<xmlInputOpenCallback>,
    readcb: Option<xmlInputReadCallback>,
    closecb: Option<xmlInputCloseCallback>,
}

#[allow(dead_code)]
#[derive(Clone, Copy)]
struct OutputCallbackEntry {
    matchcb: Option<xmlOutputMatchCallback>,
    opencb: Option<xmlOutputOpenCallback>,
    writecb: Option<xmlOutputWriteCallback>,
    closecb: Option<xmlOutputCloseCallback>,
}

static INPUT_CALLBACKS: Mutex<Vec<InputCallbackEntry>> = Mutex::new(Vec::new());
static OUTPUT_CALLBACKS: Mutex<Vec<OutputCallbackEntry>> = Mutex::new(Vec::new());

static EXTERNAL_ENTITY_LOADER: Mutex<Option<xmlExternalEntityLoader>> =
    Mutex::new(Some(default_external_entity_loader));

// Deprecated legacy function codes not present in types.rs (upstream xmlerror.h).
const XML_ERR_USER_STOP: c_int = 111;
#[allow(dead_code)]
const XML_ERR_RESOURCE_LIMIT: c_int = 114;

// XML_SCAN_* flags (upstream include/private/parser.h).
const XML_SCAN_NC: c_int = 1;
const XML_SCAN_NMTOKEN: c_int = 2;
const XML_SCAN_OLD10: c_int = 4;

// xmlParserLoadSubset bits (upstream parser.h).
#[allow(dead_code)]
const XML_DETECT_IDS: c_int = 1 << 0;
const XML_COMPLETE_ATTRS: c_int = 1 << 1;

/// Keep enough input around to show errors in context (parserInternals.c).
const LINE_LEN: usize = 80;

/// Minimal amount of data the parser expects in the buffer (parserInternals.c).
#[allow(dead_code)]
const INPUT_CHUNK: usize = 100;

const XML_INVALID_CHAR: c_int = -1;

// ═══════════════════════════════════════════════════════════════════════════════
// Internal helpers
// ═══════════════════════════════════════════════════════════════════════════════

/// Shared context initialisation: zeroes `ctxt`, installs the SAX handler and
/// sets the initial parser state (upstream `xmlInitSAXParserCtxt`).
///
/// # Safety
///
/// `ctxt` must be a valid, writable, freshly allocated parser context.
unsafe fn init_sax_parser_ctxt(
    ctxt: *mut _xmlParserCtxt,
    sax: *const _xmlSAXHandler,
    userData: *mut c_void,
) -> c_int {
    unsafe {
        ptr::write_bytes(ctxt as *mut u8, 0, core::mem::size_of::<_xmlParserCtxt>());

        let c = &mut *ctxt;

        // SAX handler.
        if c.sax.is_null() {
            let new_sax =
                xmlMallocZero(core::mem::size_of::<_xmlSAXHandler>()) as *mut _xmlSAXHandler;
            if new_sax.is_null() {
                return -1;
            }
            c.sax = new_sax;
        }
        if sax.is_null() {
            crate::xml::sax::xmlSAX2InitDefaultSAXHandler(c.sax);
            c.userData = ctxt as *mut c_void;
        } else if (*sax).initialized == XML_SAX2_MAGIC as c_uint {
            // Full SAX2 handler copy.
            ptr::copy_nonoverlapping(sax, c.sax, 1);
            c.userData = if userData.is_null() {
                ctxt as *mut c_void
            } else {
                userData
            };
        } else {
            // SAX1 handler: only the V1 prefix is meaningful.
            ptr::write_bytes(c.sax as *mut u8, 0, core::mem::size_of::<_xmlSAXHandler>());
            ptr::copy_nonoverlapping(
                sax as *const u8,
                c.sax as *mut u8,
                core::mem::size_of::<_xmlSAXHandlerV1>(),
            );
            c.userData = if userData.is_null() {
                ctxt as *mut c_void
            } else {
                userData
            };
        }

        c.wellFormed = 1;
        c.standalone = -1;
        c.errNo = XML_ERR_OK;
        c.valid = 1;
        c.nsWellFormed = 1;
        c.instate = xmlParserInputState::XML_PARSER_START as c_int;
        c.keepBlanks = globals::get_keep_blanks_default();
        c.replaceEntities = globals::get_substitute_entities_default();
        c.linenumbers = 1;
        c.charset = xmlCharEncoding::XML_CHAR_ENCODING_UTF8 as c_int;
        c.pedantic = globals::get_pedantic_parser_default();
        c.loadsubset = globals::get_load_ext_dtd_default();
        c.docdict = 1;
        c.options = 0;

        c.vctxt.userData = ctxt as *mut c_void;
        c.vctxt.valid = 1;
    }
    0
}

/// Mirror `options` into the parser context's historical struct members
/// (upstream `xmlCtxtSetOptionsInternal`).
///
/// `keepBlanks` is special: the executed 2.15.3 oracle seeds it from the
/// deprecated `xmlKeepBlanksDefaultValue` at context creation and only ever
/// LOWERS it (XML_PARSE_NOBLANKS) — option application never re-raises it.
/// Empirical: a context created while `xmlKeepBlanksDefault(0)` drops
/// whitespace-only text for ALL its reads, even reused ones, and
/// `xmlCtxtUseOptions`/read options without NOBLANKS do not restore it.
///
/// # Safety
///
/// `ctxt` must be a valid, writable parser context.
pub(crate) unsafe fn apply_options(ctxt: *mut _xmlParserCtxt, options: c_int) {
    unsafe {
        let c = &mut *ctxt;
        c.options = options;
        c.recovery = (options & XML_PARSE_RECOVER != 0) as c_int;
        c.replaceEntities = (options & XML_PARSE_NOENT != 0) as c_int;
        c.loadsubset = ((options & XML_PARSE_DTDLOAD != 0) as c_int)
            | if options & XML_PARSE_DTDATTR != 0 {
                XML_COMPLETE_ATTRS
            } else {
                0
            };
        c.validate = (options & XML_PARSE_DTDVALID != 0) as c_int;
        c.pedantic = (options & XML_PARSE_PEDANTIC != 0) as c_int;
        if options & XML_PARSE_NOBLANKS != 0 {
            c.keepBlanks = 0;
        }
        c.dictNames = if options & XML_PARSE_NODICT != 0 {
            0
        } else {
            1
        };
    }
}

/// Find the registered encoding handler for an `xmlCharEncoding` value, or NULL.
unsafe fn encoding_handler_for(enc: c_int) -> *mut _xmlCharEncodingHandler {
    let e: xmlCharEncoding = unsafe { core::mem::transmute(enc) };
    match encoding::encoding_name(e) {
        Some(name) => {
            let mut nul = name.to_vec();
            nul.push(0);
            encoding::find_encoding_handler(nul.as_ptr() as *const xmlChar)
        }
        None => ptr::null_mut(),
    }
}

/// Build a `_xmlParserInput` that references the data owned by `buf` (an input
/// buffer previously created by the xmlIO layer). The buffer keeps the data
/// alive; the returned input must be freed with `helpers::free_parser_input`.
///
/// # Safety
///
/// `buf` must be a valid input buffer or NULL, and must outlive the returned
/// input.
unsafe fn parser_input_from_buf(buf: *mut _xmlParserInputBuffer) -> *mut _xmlParserInput {
    let input =
        unsafe { xmlMallocZero(core::mem::size_of::<_xmlParserInput>()) } as *mut _xmlParserInput;
    if input.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        (*input).buf = buf;
        (*input).line = 1;
        (*input).col = 1;
        if !buf.is_null() {
            let b = &*buf;
            if !b.buffer.is_null() {
                let xbuf = &*(b.buffer as *mut _xmlBuffer);
                if !xbuf.content.is_null() {
                    (*input).base = xbuf.content;
                    (*input).cur = xbuf.content;
                    (*input).end = xbuf.content.add(xbuf.use_ as usize);
                    (*input).length = xbuf.use_ as c_int;
                }
            }
        }
    }
    input
}

/// `pub(crate)` wrapper of [`parser_input_from_buf`] for the sibling
/// xmlNewInputFrom* family (11.1-X R-000165 closure).
pub(crate) unsafe fn parser_input_from_buf_pub(
    buf: *mut _xmlParserInputBuffer,
) -> *mut _xmlParserInput {
    unsafe { parser_input_from_buf(buf) }
}

/// Materialise an `InputBuffer` (owned copy) from a raw `_xmlParserInput`,
/// so the data survives the caller's input lifetime.
///
/// # Safety
///
/// `input` must be a valid pointer to a `_xmlParserInput`.
unsafe fn input_buffer_from_parser_input(input: *mut _xmlParserInput) -> InputBuffer {
    unsafe {
        let pi = &*input;
        if !pi.buf.is_null() {
            let b = &*pi.buf;
            if let Some(read) = b.readcallback {
                return helpers::input_from_io(Some(read), b.closecallback, b.context);
            }
        }
        if !pi.base.is_null() && !pi.end.is_null() && pi.end >= pi.base {
            let len = (pi.end as usize).saturating_sub(pi.base as usize);
            let slice = core::slice::from_raw_parts(pi.base, len);
            return InputBuffer::from_memory(slice, None);
        }
        InputBuffer::from_memory(&[], None)
    }
}

/// Core of `xmlCtxtRead*`: reset the context, wire an input buffer, parse,
/// and return the resulting document (freed on hard error unless recovery).
///
/// # Safety
///
/// `ctxt` must be a valid parser context; `input` is consumed.
unsafe fn ctxt_read_doc(
    ctxt: *mut _xmlParserCtxt,
    input: InputBuffer,
    url: *const c_char,
    options: c_int,
) -> *mut _xmlDoc {
    unsafe {
        xmlCtxtReset(ctxt);
        apply_options(ctxt, options);
        helpers::setup_parser_input(ctxt, input);
        if helpers::parse_document(ctxt) != 0 {
            let doc = (*ctxt).myDoc;
            (*ctxt).myDoc = ptr::null_mut();
            if options & XML_PARSE_RECOVER != 0 {
                return doc;
            }
            if !doc.is_null() {
                tree::free_doc(doc);
            }
            return ptr::null_mut();
        }
        let doc = (*ctxt).myDoc;
        if !doc.is_null() && !url.is_null() {
            (*doc).URL = string::xml_strdup(url as *const xmlChar);
        }
        doc
    }
}

/// Parse DTD declaration text using the internal engine by wrapping it in a
/// synthetic document (`<!DOCTYPE none [ ... ]><none/>`) when the text is a
/// bare DTD subset, or parsing it directly when it is already a document.
///
/// Returns a detached DTD (never owned by a document), or NULL.
///
/// # Safety
///
/// `ctxt` must be a valid parser context; `data` must be readable for `len`
/// bytes.
unsafe fn parse_dtd_text(
    ctxt: *mut _xmlParserCtxt,
    data: &[u8],
    public_id: *const xmlChar,
    system_id: *const xmlChar,
) -> *mut _xmlDtd {
    unsafe {
        // If the content is already a full document (contains a DOCTYPE),
        // parse it directly; otherwise wrap the declarations.
        let has_doctype = data
            .windows(9)
            .any(|w| w.eq_ignore_ascii_case(b"<!DOCTYPE"));
        let mut wrapped: Vec<u8>;
        let parse_data: &[u8] = if has_doctype {
            data
        } else {
            wrapped = Vec::with_capacity(data.len() + 32);
            wrapped.extend_from_slice(b"<!DOCTYPE none [");
            wrapped.extend_from_slice(data);
            wrapped.extend_from_slice(b"]><none/>");
            &wrapped
        };

        let input = InputBuffer::from_memory(parse_data, None);
        helpers::setup_parser_input(ctxt, input);
        let rc = helpers::parse_document(ctxt);
        let doc = (*ctxt).myDoc;
        (*ctxt).myDoc = ptr::null_mut();

        if rc == 0 && !doc.is_null() && !(*doc).intSubset.is_null() {
            let dtd = (*doc).intSubset;
            (*doc).intSubset = ptr::null_mut();
            (*dtd).parent = ptr::null_mut();
            (*dtd).doc = ptr::null_mut();
            if !public_id.is_null() {
                (*dtd).ExternalID = string::xml_strdup(public_id);
            }
            if !system_id.is_null() {
                (*dtd).SystemID = string::xml_strdup(system_id);
            }
            tree::free_doc(doc);
            return dtd;
        }

        if !doc.is_null() {
            tree::free_doc(doc);
        }
        // Fallback: an empty DTD carrying the identifiers.

        dtd::new_dtd(
            ptr::null_mut(),
            c"none".as_ptr() as *const xmlChar,
            public_id,
            system_id,
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Context creation / lifecycle
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a new parser context with a default SAX2 handler.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserCtxtPtr xmlNewParserCtxt(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlNewParserCtxt() -> *mut _xmlParserCtxt {
    unsafe {
        globals::init_parser();
        let ctxt = xmlMallocZero(core::mem::size_of::<_xmlParserCtxt>()) as *mut _xmlParserCtxt;
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        if init_sax_parser_ctxt(ctxt, ptr::null(), ptr::null_mut()) < 0 {
            helpers::free_parser_ctxt(ctxt);
            return ptr::null_mut();
        }
        ctxt
    }
}

/// Create a new parser context using the given SAX handler (or the default
/// SAX2 handler when `sax` is NULL).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserCtxtPtr xmlNewSAXParserCtxt(const xmlSAXHandler *sax, void *userData);
/// ```
///
/// # SAFETY
///
/// - `sax`, `userData` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlNewSAXParserCtxt(
    sax: *const _xmlSAXHandler,
    userData: *mut c_void,
) -> *mut _xmlParserCtxt {
    unsafe {
        globals::init_parser();
        let ctxt = xmlMallocZero(core::mem::size_of::<_xmlParserCtxt>()) as *mut _xmlParserCtxt;
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        if init_sax_parser_ctxt(ctxt, sax, userData) < 0 {
            helpers::free_parser_ctxt(ctxt);
            return ptr::null_mut();
        }
        ctxt
    }
}

/// Initialise a parser context (legacy API): zeroes the context, installs a
/// default SAX2 handler and sets the initial parser state.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlInitParserCtxt(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlInitParserCtxt(ctxt: *mut _xmlParserCtxt) -> c_int {
    unsafe { init_sax_parser_ctxt(ctxt, ptr::null(), ptr::null_mut()) }
}

/// Clear (reset) a parser context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlClearParserCtxt(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlClearParserCtxt(ctxt: *mut _xmlParserCtxt) {
    unsafe { xmlCtxtReset(ctxt) }
}

/// Reset a parser context: drop the input stack, node/name stacks, strings,
/// document and error state so the context can be reused.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCtxtReset(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtReset(ctxt: *mut _xmlParserCtxt) {
    if ctxt.is_null() {
        return;
    }
    unsafe {
        let c = &mut *ctxt;

        // Free all inputs on the stack.
        let input_nr = c.inputNr;
        let input_tab = c.inputTab;
        if !input_tab.is_null() {
            for i in 0..input_nr {
                let input = *input_tab.add(i as usize);
                if !input.is_null() {
                    helpers::free_parser_input(input);
                }
            }
            xmlFreeImpl(input_tab as *mut c_void);
        }
        c.inputTab = ptr::null_mut();
        c.inputMax = 0;
        c.inputNr = 0;
        c.input = ptr::null_mut();

        // Free the stored InputBuffer (stashed by setup_parser_input; the
        // side table keeps ctxt._private application data — 11.1-X).
        helpers::free_stashed_input_buffer(ctxt);
        // Drop any incremental-push state (SP-14.3.1-3).
        helpers::free_push_state(ctxt);

        // Node stack (array only; nodes are owned by the doc).
        if !c.nodeTab.is_null() {
            xmlFreeImpl(c.nodeTab as *mut c_void);
        }
        c.nodeTab = ptr::null_mut();
        c.nodeMax = 0;
        c.nodeNr = 0;
        c.node = ptr::null_mut();

        // Name stack.
        if !c.nameTab.is_null() {
            xmlFreeImpl(c.nameTab as *mut c_void);
        }
        c.nameTab = ptr::null_mut();
        c.nameMax = 0;
        c.nameNr = 0;
        c.name = ptr::null();

        // Space stack: keep the allocation, reset the counter.
        c.spaceNr = 0;
        c.space = ptr::null_mut();

        // Namespaces.
        c.nsNr = 0;

        // Strings owned by the context.
        if !c.version.is_null() {
            xmlFreeImpl(c.version as *mut c_void);
            c.version = ptr::null_mut();
        }
        if !c.encoding.is_null() {
            xmlFreeImpl(c.encoding as *mut c_void);
            c.encoding = ptr::null_mut();
        }
        if !c.extSubURI.is_null() {
            xmlFreeImpl(c.extSubURI as *mut c_void);
            c.extSubURI = ptr::null_mut();
        }
        if !c.extSubSystem.is_null() {
            xmlFreeImpl(c.extSubSystem as *mut c_void);
            c.extSubSystem = ptr::null_mut();
        }
        if !c.directory.is_null() {
            xmlFreeImpl(c.directory as *mut c_void);
            c.directory = ptr::null_mut();
        }

        // Document: the context owns it until reset/free.
        if !c.myDoc.is_null() {
            tree::free_doc(c.myDoc);
        }
        c.myDoc = ptr::null_mut();

        // Parser state.
        c.standalone = -1;
        c.hasExternalSubset = 0;
        c.hasPErefs = 0;
        c.instate = xmlParserInputState::XML_PARSER_START as c_int;
        c.wellFormed = 1;
        c.nsWellFormed = 1;
        c.disableSAX = 0;
        c.valid = 1;
        c.record_info = 0;
        c.checkIndex = 0;
        c.inSubset = 0;
        c.errNo = XML_ERR_OK;
        c.depth = 0;
        c.nbentities = 0;
        c.sizeentities = 0;
        c.nbErrors = 0;
        c.nbWarnings = 0;

        xmlInitNodeInfoSeq(&mut c.node_seq);

        if c.lastError.code != XML_ERR_OK {
            errors::reset_error(&mut c.lastError);
        }
    }
}

/// Reset a push-parser context and set up a fresh input chunk.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlCtxtResetPush(xmlParserCtxtPtr ctxt, const char *chunk, int size,
///                      const char *filename, const char *encoding);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `chunk`, `filename`, `encoding` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtResetPush(
    ctxt: *mut _xmlParserCtxt,
    chunk: *const c_char,
    size: c_int,
    filename: *const c_char,
    encoding: *const c_char,
) -> c_int {
    if ctxt.is_null() {
        return 1;
    }
    unsafe {
        xmlCtxtReset(ctxt);

        let slice = if size > 0 && !chunk.is_null() {
            core::slice::from_raw_parts(chunk as *const u8, size as usize)
        } else {
            &[]
        };
        let uri = if filename.is_null() {
            None
        } else {
            CStr::from_ptr(filename).to_str().ok()
        };
        let input = InputBuffer::from_memory(slice, uri);
        helpers::setup_parser_input(ctxt, input);

        if !encoding.is_null() {
            let handler = encoding::find_encoding_handler(encoding as *const xmlChar);
            if !handler.is_null() {
                xmlSwitchToEncoding(ctxt, handler);
            }
        }
    }
    0
}

/// Apply a full set of parser options, clearing options not present.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlCtxtSetOptions(xmlParserCtxtPtr ctxt, int options);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtSetOptions(ctxt: *mut _xmlParserCtxt, options: c_int) -> c_int {
    if ctxt.is_null() {
        return -1;
    }
    const ALL_MASK: c_int = XML_PARSE_RECOVER
        | XML_PARSE_NOENT
        | XML_PARSE_DTDLOAD
        | XML_PARSE_DTDATTR
        | XML_PARSE_DTDVALID
        | XML_PARSE_NOERROR
        | XML_PARSE_NOWARNING
        | XML_PARSE_PEDANTIC
        | XML_PARSE_NOBLANKS
        | XML_PARSE_SAX1
        | XML_PARSE_NONET
        | XML_PARSE_NODICT
        | XML_PARSE_NSCLEAN
        | XML_PARSE_NOCDATA
        | XML_PARSE_COMPACT
        | XML_PARSE_OLD10
        | XML_PARSE_HUGE
        | XML_PARSE_OLDSAX
        | XML_PARSE_IGNORE_ENC
        | XML_PARSE_BIG_LINES;

    unsafe {
        apply_options(ctxt, options & ALL_MASK);
    }
    options & !ALL_MASK
}

/// Install a per-context structured error handler.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCtxtSetErrorHandler(xmlParserCtxtPtr ctxt,
///                             xmlStructuredErrorFunc handler, void *data);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `data` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `handler` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtSetErrorHandler(
    ctxt: *mut _xmlParserCtxt,
    handler: Option<xmlStructuredErrorFunc>,
    data: *mut c_void,
) {
    if ctxt.is_null() {
        return;
    }
    unsafe {
        (*ctxt).errorHandler = handler;
        (*ctxt).errorCtxt = data;
    }
}

/// Set the maximum entity expansion amplification factor.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCtxtSetMaxAmplification(xmlParserCtxtPtr ctxt, unsigned maxAmpl);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtSetMaxAmplification(ctxt: *mut _xmlParserCtxt, maxAmpl: c_uint) {
    if ctxt.is_null() || maxAmpl == 0 {
        return;
    }
    unsafe {
        (*ctxt).maxAmpl = maxAmpl;
    }
}

/// Get the last error raised on the context, or NULL.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// const xmlError *xmlCtxtGetLastError(void *ctx);
/// ```
///
/// # SAFETY
///
/// - `ctx` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtGetLastError(ctx: *mut c_void) -> *const _xmlError {
    if ctx.is_null() {
        return ptr::null();
    }
    let ctxt = ctx as *mut _xmlParserCtxt;
    unsafe {
        if (*ctxt).lastError.code == XML_ERR_OK {
            return ptr::null();
        }
        &(*ctxt).lastError
    }
}

/// Reset the context's last-error state.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCtxtResetLastError(void *ctx);
/// ```
///
/// # SAFETY
///
/// - `ctx` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtResetLastError(ctx: *mut c_void) {
    if ctx.is_null() {
        return;
    }
    let ctxt = ctx as *mut _xmlParserCtxt;
    unsafe {
        (*ctxt).errNo = XML_ERR_OK;
        if (*ctxt).lastError.code != XML_ERR_OK {
            // Upstream xmlResetError frees the owned strings.
            crate::xml::globals::free_error_strings(&(*ctxt).lastError);
            errors::reset_error(&mut (*ctxt).lastError);
        }
    }
}

/// Handle an out-of-memory error on a parser context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCtxtErrMemory(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtErrMemory(ctxt: *mut _xmlParserCtxt) {
    if ctxt.is_null() {
        return;
    }
    unsafe {
        let c = &mut *ctxt;
        c.errNo = XML_ERR_NO_MEMORY;
        c.instate = xmlParserInputState::XML_PARSER_EOF as c_int;
        c.wellFormed = 0;
        c.disableSAX = 2;

        c.lastError.domain = XML_FROM_PARSER;
        c.lastError.code = XML_ERR_NO_MEMORY;
        c.lastError.level = xmlErrorLevel::XML_ERR_FATAL as c_int;
        // Owned copy (upstream xmlRaiseMemoryError): the per-context last
        // error strings are freed on reset/free, so static literals would be
        // a double-free/UB hazard.
        c.lastError.message =
            crate::abi::allocator::xmlMemStrdupImpl(c"out of memory\n".as_ptr()) as *mut c_char;

        if let Some(handler) = c.errorHandler {
            handler(c.errorCtxt, &c.lastError);
        } else if !c.sax.is_null() {
            if let Some(serror) = (*c.sax).serror {
                serror(c.userData, &c.lastError);
            }
        }
    }
}

/// Stop the parser: no further processing will happen.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlStopParser(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlStopParser(ctxt: *mut _xmlParserCtxt) {
    if ctxt.is_null() {
        return;
    }
    unsafe {
        (*ctxt).disableSAX = 2;
        if (*ctxt).errNo == XML_ERR_OK {
            (*ctxt).errNo = XML_ERR_USER_STOP;
            (*ctxt).lastError.code = XML_ERR_USER_STOP;
            (*ctxt).wellFormed = 0;
        }
    }
}

/// Return the byte offset of the current parse position within the current
/// entity, or -1 when it cannot be computed.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// long xmlByteConsumed(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlByteConsumed(ctxt: *mut _xmlParserCtxt) -> c_long {
    if ctxt.is_null() {
        return -1;
    }
    unsafe {
        let input = (*ctxt).input;
        if input.is_null() {
            return -1;
        }
        if !(*input).buf.is_null() && !(*(*input).buf).encoder.is_null() {
            // With an encoder we cannot cheaply compute the original byte
            // position; report the raw consumed count.
            return (*(*input).buf).rawconsumed as c_long;
        }
        let consumed = (*input).consumed;
        if (*input).base.is_null() {
            return consumed as c_long;
        }
        (consumed + ((*input).cur as usize).saturating_sub((*input).base as usize) as c_ulong)
            as c_long
    }
}

/// Extract the directory part of a filename (newly allocated).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// char *xmlParserGetDirectory(const char *filename);
/// ```
///
/// # SAFETY
///
///
/// - `filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserGetDirectory(filename: *const c_char) -> *mut c_char {
    if filename.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let len = libc::strlen(filename);
        let mut last_sep: Option<usize> = None;
        for i in 0..len {
            if *filename.add(i) == b'/' as c_char {
                last_sep = Some(i);
            }
        }
        match last_sep {
            Some(0) => xmlMemStrdupImpl(c"/".as_ptr() as *const c_char) as *mut c_char,
            Some(pos) => {
                let slice = core::slice::from_raw_parts(filename as *const u8, pos);
                let mut v = slice.to_vec();
                v.push(0);
                xmlMemStrdupImpl(v.as_ptr() as *const c_char) as *mut c_char
            }
            None => xmlMemStrdupImpl(c".".as_ptr() as *const c_char) as *mut c_char,
        }
    }
}

/// Check whether a file exists: 0 if stat fails, 2 if it is a directory,
/// 1 otherwise.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlCheckFilename(const char *path);
/// ```
///
/// # SAFETY
///
///
/// - `path` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCheckFilename(path: *const c_char) -> c_int {
    if path.is_null() {
        return 0;
    }
    unsafe {
        let mut st: libc::stat = core::mem::zeroed();
        if libc::stat(path, &mut st) != 0 {
            return 0;
        }
        if st.st_mode & libc::S_IFMT == libc::S_IFDIR {
            2
        } else {
            1
        }
    }
}

/// Test whether a public/system ID pair is one of the XHTML DTDs.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlIsXHTML(const xmlChar *systemID, const xmlChar *publicID);
/// ```
///
/// # SAFETY
///
///
/// - `systemID`, `publicID` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlIsXHTML(systemID: *const xmlChar, publicID: *const xmlChar) -> c_int {
    const XHTML_STRICT_PUBLIC_ID: &[u8] = b"-//W3C//DTD XHTML 1.0 Strict//EN\0";
    const XHTML_STRICT_SYSTEM_ID: &[u8] = b"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\0";
    const XHTML_FRAME_PUBLIC_ID: &[u8] = b"-//W3C//DTD XHTML 1.0 Frameset//EN\0";
    const XHTML_FRAME_SYSTEM_ID: &[u8] = b"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\0";
    const XHTML_TRANS_PUBLIC_ID: &[u8] = b"-//W3C//DTD XHTML 1.0 Transitional//EN\0";
    const XHTML_TRANS_SYSTEM_ID: &[u8] =
        b"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\0";

    if systemID.is_null() && publicID.is_null() {
        return -1;
    }
    unsafe {
        if !publicID.is_null()
            && (string::xml_strcmp(publicID, XHTML_STRICT_PUBLIC_ID.as_ptr() as *const xmlChar)
                == 0
                || string::xml_strcmp(publicID, XHTML_FRAME_PUBLIC_ID.as_ptr() as *const xmlChar)
                    == 0
                || string::xml_strcmp(publicID, XHTML_TRANS_PUBLIC_ID.as_ptr() as *const xmlChar)
                    == 0)
        {
            return 1;
        }
        if !systemID.is_null()
            && (string::xml_strcmp(systemID, XHTML_STRICT_SYSTEM_ID.as_ptr() as *const xmlChar)
                == 0
                || string::xml_strcmp(systemID, XHTML_FRAME_SYSTEM_ID.as_ptr() as *const xmlChar)
                    == 0
                || string::xml_strcmp(systemID, XHTML_TRANS_SYSTEM_ID.as_ptr() as *const xmlChar)
                    == 0)
        {
            return 1;
        }
    }
    0
}

// ═══════════════════════════════════════════════════════════════════════════════
// Context creation from sources
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a parser context for an in-memory document.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserCtxtPtr xmlCreateMemoryParserCtxt(const char *buffer, int size);
/// ```
///
/// # SAFETY
///
///
/// - `buffer` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCreateMemoryParserCtxt(
    buffer: *const c_char,
    size: c_int,
) -> *mut _xmlParserCtxt {
    if buffer.is_null() || size < 0 {
        return ptr::null_mut();
    }
    unsafe {
        let ctxt = xmlNewParserCtxt();
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        let input = helpers::input_from_memory(buffer, size);
        helpers::setup_parser_input(ctxt, input);
        ctxt
    }
}

/// Create a parser context for push parsing.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserCtxtPtr xmlCreatePushParserCtxt(xmlSAXHandler *sax, void *user_data,
///                                          const char *chunk, int size,
///                                          const char *filename);
/// ```
///
/// # SAFETY
///
/// - `sax`, `user_data` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `chunk`, `filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCreatePushParserCtxt(
    sax: *mut _xmlSAXHandler,
    user_data: *mut c_void,
    chunk: *const c_char,
    size: c_int,
    filename: *const c_char,
) -> *mut _xmlParserCtxt {
    unsafe {
        let ctxt = xmlNewSAXParserCtxt(sax, user_data);
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        // UPSTREAM-PARITY (parser.c xmlCreatePushParserCtxt): the push
        // context forces dictNames on (and clears XML_PARSE_NODICT), so
        // element/attribute names are interned in the document dictionary
        // and pointer-identical to xmlDictLookup results — lxml's
        // _MultiTagMatcher (iterparse tag=...) compares name pointers.
        (*ctxt).options &= !crate::abi::types::XML_PARSE_NODICT;
        (*ctxt).dictNames = 1;
        let slice = if size > 0 && !chunk.is_null() {
            core::slice::from_raw_parts(chunk as *const u8, size as usize)
        } else {
            &[]
        };
        let uri = if filename.is_null() {
            None
        } else {
            CStr::from_ptr(filename).to_str().ok()
        };
        let input = InputBuffer::from_memory(slice, uri);
        helpers::setup_parser_input(ctxt, input);
        ctxt
    }
}

/// Create a parser context for an I/O stream.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserCtxtPtr xmlCreateIOParserCtxt(xmlSAXHandler *sax, void *user_data,
///                                        xmlInputReadCallback ioread,
///                                        xmlInputCloseCallback ioclose,
///                                        void *ioctx, xmlCharEncoding enc);
/// ```
///
/// # SAFETY
///
/// - `sax`, `user_data`, `ioctx` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `ioread`, `ioclose` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCreateIOParserCtxt(
    sax: *mut _xmlSAXHandler,
    user_data: *mut c_void,
    ioread: Option<xmlInputReadCallback>,
    ioclose: Option<xmlInputCloseCallback>,
    ioctx: *mut c_void,
    enc: c_int,
) -> *mut _xmlParserCtxt {
    unsafe {
        let ctxt = xmlNewSAXParserCtxt(sax, user_data);
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        let input = helpers::input_from_io(ioread, ioclose, ioctx);
        helpers::setup_parser_input(ctxt, input);
        if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int {
            xmlSwitchEncoding(ctxt, enc);
        }
        ctxt
    }
}

/// Create a parser context for a file or URL.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserCtxtPtr xmlCreateURLParserCtxt(const char *filename, int options);
/// ```
///
/// # SAFETY
///
///
/// - `filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCreateURLParserCtxt(
    filename: *const c_char,
    options: c_int,
) -> *mut _xmlParserCtxt {
    if filename.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let ctxt = xmlNewParserCtxt();
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        apply_options(ctxt, options);
        let input = match open_filename_routed(filename, ctxt) {
            RoutedFileOpen::Loaded(i) => i,
            RoutedFileOpen::Failed => {
                // UPSTREAM-PARITY (parserInternals.c xmlNewInputFromFile via
                // the registered loader): NULL loader result is XML_IO_ENOENT
                // — raise xmlCtxtErrIO, no built-in fallback.
                emit_io_warning(ctxt, io_load_failure_message(filename));
                helpers::free_parser_ctxt(ctxt);
                return ptr::null_mut();
            }
            RoutedFileOpen::EntityLoaderFailed => {
                // UPSTREAM-PARITY (parser.c xmlCreateURLParserCtxt ->
                // xmlLoadResource): a custom entity loader returning NULL
                // fails the open SILENTLY.
                helpers::free_parser_ctxt(ctxt);
                return ptr::null_mut();
            }
            RoutedFileOpen::Builtin => match helpers::input_from_file(filename) {
                Ok(i) => i,
                Err(_) => {
                    helpers::free_parser_ctxt(ctxt);
                    return ptr::null_mut();
                }
            },
        };
        helpers::setup_parser_input(ctxt, input);
        ctxt
    }
}

/// Create a parser context for an external entity.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserCtxtPtr xmlCreateEntityParserCtxt(const xmlChar *URL,
///                                            const xmlChar *ID,
///                                            const xmlChar *base);
/// ```
///
/// # SAFETY
///
///
/// - `URL`, `ID`, `base` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCreateEntityParserCtxt(
    URL: *const xmlChar,
    ID: *const xmlChar,
    base: *const xmlChar,
) -> *mut _xmlParserCtxt {
    let _ = base; // base URI resolution is a no-op here
    unsafe {
        let ctxt = xmlNewParserCtxt();
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        let input = xmlLoadExternalEntity(URL as *const c_char, ID as *const c_char, ctxt);
        if input.is_null() {
            helpers::free_parser_ctxt(ctxt);
            return ptr::null_mut();
        }
        if xmlPushInput(ctxt, input) < 0 {
            helpers::free_parser_input(input);
            helpers::free_parser_ctxt(ctxt);
            return ptr::null_mut();
        }
        ctxt
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CtxtRead family
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse an XML in-memory document with a given context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlCtxtReadDoc(xmlParserCtxtPtr ctxt, const xmlChar *cur,
///                          const char *URL, const char *encoding, int options);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `cur`, `URL`, `_encoding` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtReadDoc(
    ctxt: *mut _xmlParserCtxt,
    cur: *const xmlChar,
    URL: *const c_char,
    encoding: *const c_char,
    options: c_int,
) -> *mut _xmlDoc {
    if ctxt.is_null() || cur.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let len = string::xml_strlen(cur);
        let mut input = helpers::input_from_memory(cur as *const c_char, len as c_int);
        if !encoding.is_null() {
            let name = core::ffi::CStr::from_ptr(encoding).to_bytes();
            input.apply_explicit_input_encoding(name);
        }
        ctxt_read_doc(ctxt, input, URL, options)
    }
}

/// Parse an XML file with a given context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlCtxtReadFile(xmlParserCtxtPtr ctxt, const char *filename,
///                           const char *encoding, int options);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `filename`, `_encoding` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtReadFile(
    ctxt: *mut _xmlParserCtxt,
    filename: *const c_char,
    _encoding: *const c_char,
    options: c_int,
) -> *mut _xmlDoc {
    if ctxt.is_null() || filename.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        // UPSTREAM-PARITY (parser.c xmlCtxtReadFile -> xmlCtxtNewInputFromUrl
        // -> xmlLoadResource): a registered external entity loader governs the
        // open; below it the xmlParserInputBufferCreateFilenameDefault (php
        // streams loader) is consulted; a NULL loader result raises
        // xmlCtxtErrIO(XML_IO_ENOENT, filename) — "I/O warning : failed to
        // load \"%s\": %s\n" — and parsing fails.
        match open_filename_routed(filename, ctxt) {
            RoutedFileOpen::Loaded(input) => ctxt_read_doc(ctxt, input, filename, options),
            RoutedFileOpen::Failed => {
                emit_io_warning(ctxt, io_load_failure_message(filename));
                ptr::null_mut()
            }
            RoutedFileOpen::EntityLoaderFailed => {
                // UPSTREAM-PARITY (parser.c xmlCtxtReadFile): a custom entity
                // loader returning NULL fails the read SILENTLY.
                ptr::null_mut()
            }
            RoutedFileOpen::Builtin => match helpers::input_from_file(filename) {
                Ok(input) => ctxt_read_doc(ctxt, input, filename, options),
                Err(_) => ptr::null_mut(),
            },
        }
    }
}

/// Parse an XML in-memory block with a given context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlCtxtReadMemory(xmlParserCtxtPtr ctxt, const char *buffer,
///                             int size, const char *URL, const char *encoding,
///                             int options);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `buffer`, `URL`, `_encoding` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtReadMemory(
    ctxt: *mut _xmlParserCtxt,
    buffer: *const c_char,
    size: c_int,
    URL: *const c_char,
    encoding: *const c_char,
    options: c_int,
) -> *mut _xmlDoc {
    if ctxt.is_null() || buffer.is_null() || size < 0 {
        return ptr::null_mut();
    }
    unsafe {
        let mut input = helpers::input_from_memory(buffer, size);
        // UPSTREAM-PARITY (xmlCtxtNewInputFromMemory): an explicit `encoding`
        // argument switches the input to that encoding BEFORE the parse, so
        // the parser never sees raw UCS-2/UCS-4/Latin-1 bytes (lxml feeds
        // PEP-393 python strings this way). Best-effort: when the name is
        // unknown or the buffer was already converted the raw bytes stay and
        // BOM/declaration detection decides as usual.
        if !encoding.is_null() {
            let name = core::ffi::CStr::from_ptr(encoding).to_bytes();
            input.apply_explicit_input_encoding(name);
        }
        ctxt_read_doc(ctxt, input, URL, options)
    }
}

/// Parse an XML document from a file descriptor with a given context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlCtxtReadFd(xmlParserCtxtPtr ctxt, int fd, const char *URL,
///                         const char *encoding, int options);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `URL`, `_encoding` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtReadFd(
    ctxt: *mut _xmlParserCtxt,
    fd: c_int,
    URL: *const c_char,
    _encoding: *const c_char,
    options: c_int,
) -> *mut _xmlDoc {
    if ctxt.is_null() || fd < 0 {
        return ptr::null_mut();
    }
    unsafe {
        let mut buf = Vec::new();
        let mut tmp = [0u8; 4096];
        loop {
            let n = libc::read(fd, tmp.as_mut_ptr() as *mut c_void, tmp.len());
            if n <= 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n as usize]);
        }
        let input = helpers::input_from_memory(buf.as_ptr() as *const c_char, buf.len() as c_int);
        ctxt_read_doc(ctxt, input, URL, options)
    }
}

/// Parse an XML document from I/O callbacks with a given context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlCtxtReadIO(xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread,
///                         xmlInputCloseCallback ioclose, void *ioctx,
///                         const char *URL, const char *encoding, int options);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `ioctx` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `URL`, `_encoding` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// - `ioread`, `ioclose` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtReadIO(
    ctxt: *mut _xmlParserCtxt,
    ioread: Option<xmlInputReadCallback>,
    ioclose: Option<xmlInputCloseCallback>,
    ioctx: *mut c_void,
    URL: *const c_char,
    _encoding: *const c_char,
    options: c_int,
) -> *mut _xmlDoc {
    if ctxt.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let input = helpers::input_from_io(ioread, ioclose, ioctx);
        // UPSTREAM-PARITY (parser.c xmlCtxtNewInputFromIO): the URL becomes
        // the input's filename, which feeds the `file:line:` error prefix.
        let input = if !URL.is_null() {
            match std::ffi::CStr::from_ptr(URL).to_str() {
                Ok(s) => input.with_filename(s),
                Err(_) => input,
            }
        } else {
            input
        };
        ctxt_read_doc(ctxt, input, URL, options)
    }
}

/// Parse a document from a raw parser input, taking ownership of `input`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlCtxtParseDocument(xmlParserCtxtPtr ctxt, xmlParserInputPtr input);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `input` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCtxtParseDocument(
    ctxt: *mut _xmlParserCtxt,
    input: *mut _xmlParserInput,
) -> *mut _xmlDoc {
    if ctxt.is_null() || input.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        // Determine whether the caller's input is already owned by the
        // context's input stack (pushed via xmlPushInput).
        let mut owned = false;
        let nr = (*ctxt).inputNr;
        let tab = (*ctxt).inputTab;
        if !tab.is_null() {
            for i in 0..nr {
                if *tab.add(i as usize) == input {
                    owned = true;
                    break;
                }
            }
        }
        if (*ctxt).input == input {
            owned = true;
        }

        // Copy the data first so the context reset cannot invalidate it.
        let ib = input_buffer_from_parser_input(input);

        xmlCtxtReset(ctxt);
        helpers::setup_parser_input(ctxt, ib);
        helpers::parse_document(ctxt);

        if !owned {
            helpers::free_parser_input(input);
        }

        (*ctxt).myDoc
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Parser input buffers / streams
// ═══════════════════════════════════════════════════════════════════════════════

/// Allocate a parser input buffer for the given encoding.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserInputBufferPtr xmlAllocParserInputBuffer(xmlCharEncoding enc);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlAllocParserInputBuffer(enc: c_int) -> *mut _xmlParserInputBuffer {
    unsafe {
        let buf = xmlMallocZero(core::mem::size_of::<_xmlParserInputBuffer>())
            as *mut _xmlParserInputBuffer;
        if buf.is_null() {
            return ptr::null_mut();
        }
        let b = &mut *buf;
        b.buffer = io::buf_create(crate::abi::data_globals::xmlDefaultBufferSize) as *mut c_void;
        b.raw = io::buf_create(crate::abi::data_globals::xmlDefaultBufferSize) as *mut c_void;
        if b.buffer.is_null() || b.raw.is_null() {
            io::buf_free(b.buffer as *mut _xmlBuffer);
            io::buf_free(b.raw as *mut _xmlBuffer);
            xmlFreeImpl(buf as *mut c_void);
            return ptr::null_mut();
        }
        b.compressed = -1;

        if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int
            && enc != xmlCharEncoding::XML_CHAR_ENCODING_ERROR as c_int
        {
            let handler = encoding_handler_for(enc);
            if !handler.is_null() {
                b.encoder = handler as *mut c_void;
            }
        }
        buf
    }
}

/// Grow an input buffer by reading up to `len` bytes from its source.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlParserInputBufferGrow(xmlParserInputBufferPtr in, int len);
/// ```
///
/// # SAFETY
///
/// - `in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserInputBufferGrow(
    in_: *mut _xmlParserInputBuffer,
    len: c_int,
) -> c_int {
    if in_.is_null() || len <= 0 {
        return 0;
    }
    unsafe {
        let b = &mut *in_;
        if b.error != 0 {
            return -1;
        }
        let Some(read_cb) = b.readcallback else {
            // Memory-based buffer: nothing to grow.
            return 0;
        };
        let mut tmp = vec![0u8; len as usize];
        let n = read_cb(b.context, tmp.as_mut_ptr() as *mut c_char, len);
        if n < 0 {
            b.error = 1;
            return -1;
        }
        if n == 0 {
            return 0;
        }
        io::input_buffer_push(in_, tmp.as_ptr() as *const c_char, n);
        n
    }
}

/// Push `len` bytes into an input buffer (push parser).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlParserInputBufferPush(xmlParserInputBufferPtr in, int len, const char *buf);
/// ```
///
/// # SAFETY
///
/// - `in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `buf` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserInputBufferPush(
    in_: *mut _xmlParserInputBuffer,
    len: c_int,
    buf: *const c_char,
) -> c_int {
    if in_.is_null() {
        return -1;
    }
    if len < 0 || (len > 0 && buf.is_null()) {
        return -1;
    }
    if len == 0 {
        return 0;
    }
    io::input_buffer_push(in_, buf, len)
}

/// Read up to `len` bytes from an input buffer's source.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlParserInputBufferRead(xmlParserInputBufferPtr in, int len);
/// ```
///
/// # SAFETY
///
/// - `in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserInputBufferRead(
    in_: *mut _xmlParserInputBuffer,
    len: c_int,
) -> c_int {
    xmlParserInputBufferGrow(in_, len)
}

/// Deprecated: reading directly from an input stream is an error.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlParserInputRead(xmlParserInputPtr in, int len);
/// ```
///
/// # SAFETY
///
/// - `_in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub const unsafe extern "C" fn xmlParserInputRead(
    _in_: *mut _xmlParserInput,
    _len: c_int,
) -> c_int {
    -1
}

/// Grow a parser input's buffer by reading more data from its source.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlParserInputGrow(xmlParserInputPtr in, int len);
/// ```
///
/// # SAFETY
///
/// - `in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserInputGrow(in_: *mut _xmlParserInput, len: c_int) -> c_int {
    if in_.is_null() || len < 0 {
        return -1;
    }
    unsafe {
        let pi = &*in_;
        if pi.base.is_null() || pi.cur.is_null() {
            return -1;
        }
        if pi.buf.is_null() {
            // Pure memory input: nothing to grow.
            return 0;
        }
        let b = &*pi.buf;
        // Memory buffers are not growable.
        if b.readcallback.is_none() && b.encoder.is_null() {
            return 0;
        }
        xmlParserInputBufferGrow(pi.buf, len)
    }
}

/// Shrink a parser input, releasing already-consumed data from the buffer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlParserInputShrink(xmlParserInputPtr in);
/// ```
///
/// # SAFETY
///
/// - `in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserInputShrink(in_: *mut _xmlParserInput) {
    if in_.is_null() {
        return;
    }
    unsafe {
        let pi = &mut *in_;
        if pi.buf.is_null() || pi.base.is_null() || pi.cur.is_null() {
            return;
        }
        let used = (pi.cur as usize).saturating_sub(pi.base as usize);
        if used > LINE_LEN {
            // The candidate's inputs are backed by stable memory buffers, so
            // the base pointer cannot move; account for the consumed bytes.
            pi.consumed = pi.consumed.saturating_add((used - LINE_LEN) as c_ulong);
        }
    }
}

/// Create a new (empty) parser input stream.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserInputPtr xmlNewInputStream(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlNewInputStream(ctxt: *mut _xmlParserCtxt) -> *mut _xmlParserInput {
    unsafe {
        let input = xmlMallocZero(core::mem::size_of::<_xmlParserInput>()) as *mut _xmlParserInput;
        if input.is_null() {
            if !ctxt.is_null() {
                xmlCtxtErrMemory(ctxt);
            }
            return ptr::null_mut();
        }
        (*input).line = 1;
        (*input).col = 1;
        input
    }
}

/// Wrap an input buffer in a parser input stream.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserInputPtr xmlNewIOInputStream(xmlParserCtxtPtr ctxt,
///                                       xmlParserInputBufferPtr input,
///                                       xmlCharEncoding enc);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `input` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlNewIOInputStream(
    ctxt: *mut _xmlParserCtxt,
    input: *mut _xmlParserInputBuffer,
    enc: c_int,
) -> *mut _xmlParserInput {
    if ctxt.is_null() || input.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let pi = xmlNewInputStream(ctxt);
        if pi.is_null() {
            return ptr::null_mut();
        }
        (*pi).buf = input;
        if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int
            && enc != xmlCharEncoding::XML_CHAR_ENCODING_ERROR as c_int
        {
            let handler = encoding_handler_for(enc);
            if !handler.is_null() {
                io::input_buffer_set_encoder(input, handler);
            }
        }
        pi
    }
}

/// Create a parser input stream from a zero-terminated string. The string
/// must remain valid for the lifetime of the input (static mode).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserInputPtr xmlNewStringInputStream(xmlParserCtxtPtr ctxt,
///                                           const xmlChar *buffer);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `buffer` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlNewStringInputStream(
    ctxt: *mut _xmlParserCtxt,
    buffer: *const xmlChar,
) -> *mut _xmlParserInput {
    if ctxt.is_null() || buffer.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let input = xmlNewInputStream(ctxt);
        if input.is_null() {
            return ptr::null_mut();
        }
        let len = string::xml_strlen(buffer);
        (*input).base = buffer;
        (*input).cur = buffer;
        (*input).end = buffer.add(len);
        (*input).length = len as c_int;
        input
    }
}

/// Setup the parser context to parse a new buffer (legacy API).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSetupParserForBuffer(xmlParserCtxtPtr ctxt, const xmlChar* buffer,
///                              const char *filename);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `buffer`, `filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSetupParserForBuffer(
    ctxt: *mut _xmlParserCtxt,
    buffer: *const xmlChar,
    filename: *const c_char,
) {
    if ctxt.is_null() || buffer.is_null() {
        return;
    }
    unsafe {
        xmlCtxtReset(ctxt);
        let len = string::xml_strlen(buffer);
        let uri = if filename.is_null() {
            None
        } else {
            CStr::from_ptr(filename).to_str().ok()
        };
        let input = InputBuffer::from_memory(core::slice::from_raw_parts(buffer, len), uri);
        helpers::setup_parser_input(ctxt, input);
    }
}

/// Push an input stream onto the context's input stack.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `input` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPushInput(
    ctxt: *mut _xmlParserCtxt,
    input: *mut _xmlParserInput,
) -> c_int {
    if ctxt.is_null() || input.is_null() {
        return -1;
    }
    unsafe {
        let c = &mut *ctxt;
        if c.inputNr >= c.inputMax {
            let new_max = if c.inputMax == 0 { 5 } else { c.inputMax * 2 };
            let new_tab = xmlReallocImpl(
                c.inputTab as *mut c_void,
                (new_max as usize) * core::mem::size_of::<*mut _xmlParserInput>(),
            ) as *mut *mut _xmlParserInput;
            if new_tab.is_null() {
                return -1;
            }
            c.inputTab = new_tab;
            c.inputMax = new_max;
        }
        *c.inputTab.add(c.inputNr as usize) = input;
        c.input = input;
        (*input).id = c.input_id;
        c.input_id += 1;
        let idx = c.inputNr;
        c.inputNr += 1;
        idx
    }
}

/// Pop the top input from the context's input stack and free it; returns the
/// current character after the pop (0 at end of input).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlChar xmlPopInput(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPopInput(ctxt: *mut _xmlParserCtxt) -> xmlChar {
    if ctxt.is_null() || (*ctxt).inputNr <= 1 {
        return 0;
    }
    unsafe {
        let c = &mut *ctxt;
        c.inputNr -= 1;
        let popped = *c.inputTab.add(c.inputNr as usize);
        *c.inputTab.add(c.inputNr as usize) = ptr::null_mut();
        if c.inputNr > 0 {
            c.input = *c.inputTab.add((c.inputNr - 1) as usize);
        } else {
            c.input = ptr::null_mut();
        }
        if !popped.is_null() {
            helpers::free_parser_input(popped);
        }
        if c.input.is_null() {
            return 0;
        }
        let cur = (*c.input).cur;
        let end = (*c.input).end;
        if cur.is_null() || cur >= end {
            0
        } else {
            *cur
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Encoding switching
// ═══════════════════════════════════════════════════════════════════════════════

/// Switch the input encoding of the current input.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlSwitchEncoding(xmlParserCtxtPtr ctxt, xmlCharEncoding enc);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSwitchEncoding(ctxt: *mut _xmlParserCtxt, enc: c_int) -> c_int {
    if ctxt.is_null() || (*ctxt).input.is_null() {
        return -1;
    }
    if enc == xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int {
        return 0;
    }
    unsafe {
        let handler = encoding_handler_for(enc);
        if handler.is_null() {
            return -1;
        }
        xmlSwitchToEncoding(ctxt, handler)
    }
}

/// Switch the input encoding by name.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlSwitchEncodingName(xmlParserCtxtPtr ctxt, const char *encoding);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `encoding` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSwitchEncodingName(
    ctxt: *mut _xmlParserCtxt,
    encoding: *const c_char,
) -> c_int {
    if ctxt.is_null() || encoding.is_null() {
        return -1;
    }
    unsafe {
        let handler = encoding::find_encoding_handler(encoding as *const xmlChar);
        if handler.is_null() {
            return -1;
        }
        xmlSwitchToEncoding(ctxt, handler)
    }
}

/// Switch the encoding of a specific parser input using an encoding handler.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlSwitchInputEncoding(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
///                            xmlCharEncodingHandlerPtr handler);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `input`, `handler` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSwitchInputEncoding(
    ctxt: *mut _xmlParserCtxt,
    input: *mut _xmlParserInput,
    handler: *mut _xmlCharEncodingHandler,
) -> c_int {
    let _ = ctxt;
    if input.is_null() {
        return -1;
    }
    unsafe {
        if (*input).buf.is_null() {
            return -1;
        }
        io::input_buffer_set_encoder((*input).buf, handler);
    }
    0
}

/// Switch the encoding of the current input using an encoding handler.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlSwitchToEncoding(xmlParserCtxtPtr ctxt,
///                         xmlCharEncodingHandlerPtr handler);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `handler` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSwitchToEncoding(
    ctxt: *mut _xmlParserCtxt,
    handler: *mut _xmlCharEncodingHandler,
) -> c_int {
    if ctxt.is_null() {
        return -1;
    }
    unsafe {
        let input = (*ctxt).input;
        if input.is_null() {
            return -1;
        }
        // Memory-parser inputs (xmlCreateMemoryParserCtxt) carry buf == NULL;
        // their bytes live in the Rust-side InputBuffer (helpers.rs side
        // table), which already transcoded any BOM/declared encoding. A
        // caller-driven switch (PHP dom overrideEncoding) must therefore
        // transcode the whole buffered stream there (upstream applies the
        // input-buffer encoder before any read).
        if (*input).buf.is_null() && !(*handler).name.is_null() {
            return helpers::apply_memory_encoding_override(ctxt, (*handler).name);
        }
        io::input_buffer_set_encoder((*input).buf, handler);
    }
    0
}

// ═══════════════════════════════════════════════════════════════════════════════
// Node info sequence (deprecated, parser.h)
// ═══════════════════════════════════════════════════════════════════════════════

/// Initialise a node info sequence.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlInitNodeInfoSeq(xmlParserNodeInfoSeqPtr seq);
/// ```
///
/// # SAFETY
///
/// - `seq` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlInitNodeInfoSeq(seq: *mut _xmlParserNodeInfoSeq) {
    if seq.is_null() {
        return;
    }
    unsafe {
        (*seq).length = 0;
        (*seq).maximum = 0;
        (*seq).buffer = ptr::null_mut();
    }
}

/// Clear (release and reinitialise) a node info sequence.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlClearNodeInfoSeq(xmlParserNodeInfoSeqPtr seq);
/// ```
///
/// # SAFETY
///
/// - `seq` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlClearNodeInfoSeq(seq: *mut _xmlParserNodeInfoSeq) {
    if seq.is_null() {
        return;
    }
    unsafe {
        if !(*seq).buffer.is_null() {
            xmlFreeImpl((*seq).buffer as *mut c_void);
        }
        xmlInitNodeInfoSeq(seq);
    }
}

/// Find the index where the info record for `node` is (or should be) in the
/// sorted sequence; binary search by node pointer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// unsigned long xmlParserFindNodeInfoIndex(xmlParserNodeInfoSeqPtr seq,
///                                          xmlNodePtr node);
/// ```
///
/// # SAFETY
///
/// - `seq`, `node` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserFindNodeInfoIndex(
    seq: *mut _xmlParserNodeInfoSeq,
    node: *mut _xmlNode,
) -> c_ulong {
    if seq.is_null() || node.is_null() {
        return c_ulong::MAX;
    }
    unsafe {
        let s = &*seq;
        if s.buffer.is_null() || s.length == 0 {
            return 0;
        }
        let mut lower: usize = 0;
        let mut upper: usize = s.length as usize;
        while lower < upper {
            let middle = lower + (upper - lower) / 2;
            let cur_node = (*s.buffer.add(middle)).node;
            if cur_node == node {
                return middle as c_ulong;
            }
            if (cur_node as usize) < (node as usize) {
                lower = middle + 1;
            } else {
                upper = middle;
            }
        }
        lower as c_ulong
    }
}

/// Find the node info record for a given node, or NULL.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// const xmlParserNodeInfo *xmlParserFindNodeInfo(xmlParserCtxtPtr ctxt,
///                                                xmlNodePtr node);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserFindNodeInfo(
    ctxt: *mut _xmlParserCtxt,
    node: *mut _xmlNode,
) -> *const _xmlParserNodeInfo {
    if ctxt.is_null() || node.is_null() {
        return ptr::null();
    }
    unsafe {
        let seq = &(*ctxt).node_seq;
        let seq_mut = seq as *const _ as *mut _xmlParserNodeInfoSeq;
        let pos = xmlParserFindNodeInfoIndex(seq_mut, node);
        if !seq.buffer.is_null() && (pos as usize) < (seq.length as usize) {
            let info = &*seq.buffer.add(pos as usize);
            if info.node == node {
                return info;
            }
        }
        ptr::null()
    }
}

/// Insert a node info record into the context's sorted sequence.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlParserAddNodeInfo(xmlParserCtxtPtr ctxt, xmlParserNodeInfoPtr info);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `info` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserAddNodeInfo(
    ctxt: *mut _xmlParserCtxt,
    info: *mut _xmlParserNodeInfo,
) {
    if ctxt.is_null() || info.is_null() {
        return;
    }
    unsafe {
        let seq = &mut (*ctxt).node_seq;
        let node = (*info).node;
        let pos = xmlParserFindNodeInfoIndex(seq, node as *mut _xmlNode) as usize;

        if pos < seq.length as usize && !seq.buffer.is_null() && (*seq.buffer.add(pos)).node == node
        {
            // Node already recorded: update the record in place.
            ptr::copy_nonoverlapping(info, seq.buffer.add(pos), 1);
            return;
        }

        // Grow the buffer (upstream xmlGrowCapacity: 50% growth from a
        // minimum of 4, capped at XML_MAX_ITEMS = 1 billion).
        if seq.length + 1 > seq.maximum {
            let new_max = xml_grow_capacity(seq.maximum);
            if new_max < 0 {
                xmlCtxtErrMemory(ctxt);
                return;
            }
            let new_buf = xmlReallocImpl(
                seq.buffer as *mut c_void,
                (new_max as usize) * core::mem::size_of::<_xmlParserNodeInfo>(),
            ) as *mut _xmlParserNodeInfo;
            if new_buf.is_null() {
                xmlCtxtErrMemory(ctxt);
                return;
            }
            seq.buffer = new_buf;
            seq.maximum = new_max as c_ulong;
        }

        // Shift elements right to make room at `pos`.
        let length = seq.length as usize;
        for i in (pos + 1..=length).rev() {
            ptr::copy_nonoverlapping(seq.buffer.add(i - 1), seq.buffer.add(i), 1);
        }
        ptr::copy_nonoverlapping(info, seq.buffer.add(pos), 1);
        seq.length += 1;
    }
}

/// Upstream `xmlGrowCapacity` (private/memory.h) for a zero-based capacity:
/// 50% growth, minimum initial allocation 4, capped at XML_MAX_ITEMS.
/// Returns the new capacity or -1 on overflow/cap exhaustion.
// The `as u64` casts are width-correcting for 32-bit platforms where
// `c_ulong` is 32 bits; on x86-64 they are identity casts.
#[allow(clippy::unnecessary_cast)]
const unsafe fn xml_grow_capacity(capacity: c_ulong) -> c_int {
    const XML_MAX_ITEMS: u64 = 1_000_000_000;
    const ELEM_SIZE: usize = core::mem::size_of::<_xmlParserNodeInfo>();
    if capacity == 0 {
        return 4;
    }
    if capacity as u64 >= XML_MAX_ITEMS || (capacity as usize) > usize::MAX / 2 / ELEM_SIZE {
        return -1;
    }
    let extra = capacity.div_ceil(2);
    if capacity as u64 > XML_MAX_ITEMS - extra as u64 {
        return XML_MAX_ITEMS as c_int;
    }
    (capacity + extra) as c_int
}

// ═══════════════════════════════════════════════════════════════════════════════
// I/O callback registration (xmlIO.h)
// ═══════════════════════════════════════════════════════════════════════════════

/// Register a new set of input I/O callbacks.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlRegisterInputCallbacks(xmlInputMatchCallback matchFunc,
///                               xmlInputOpenCallback openFunc,
///                               xmlInputReadCallback readFunc,
///                               xmlInputCloseCallback closeFunc);
/// ```
///
/// # SAFETY
///
///
/// - `matchFunc`, `openFunc`, `readFunc`, `closeFunc` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlRegisterInputCallbacks(
    matchFunc: Option<xmlInputMatchCallback>,
    openFunc: Option<xmlInputOpenCallback>,
    readFunc: Option<xmlInputReadCallback>,
    closeFunc: Option<xmlInputCloseCallback>,
) -> c_int {
    unsafe {
        globals::init_parser();
    }
    let mut table = INPUT_CALLBACKS.lock();
    if table.len() >= 10 {
        return -1;
    }
    table.push(InputCallbackEntry {
        matchcb: matchFunc,
        opencb: openFunc,
        readcb: readFunc,
        closecb: closeFunc,
    });
    (table.len() - 1) as c_int
}

/// Register the default compiled-in input callbacks (the `xmlFile*` pair).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlRegisterDefaultInputCallbacks(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlRegisterDefaultInputCallbacks() {
    unsafe {
        xmlRegisterInputCallbacks(
            Some(xmlFileMatch),
            Some(xmlFileOpen),
            Some(xmlFileRead),
            Some(xmlFileClose),
        );
    }
}

/// Remove the top input callback from the stack.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlPopInputCallbacks(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlPopInputCallbacks() -> c_int {
    unsafe {
        globals::init_parser();
    }
    let mut table = INPUT_CALLBACKS.lock();
    if table.is_empty() {
        return -1;
    }
    table.pop();
    table.len() as c_int
}

/// Clear the entire input callback table.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCleanupInputCallbacks(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlCleanupInputCallbacks() {
    unsafe {
        globals::init_parser();
    }
    INPUT_CALLBACKS.lock().clear();
}

/// Read a URI through the registered input callbacks (upstream
/// `xmlParserInputBufferCreateFilename`): the first registered pair whose
/// match callback accepts the URI is opened, read to EOF, and closed.
/// Returns `None` when no registered pair matches — callers fall back to
/// the regular file path. NULL callbacks inside a matching pair are treated
/// like upstream (an entry whose match callback is NULL is skipped).
///
/// Used by the XInclude loader so custom I/O schemes registered through
/// `xmlRegisterInputCallbacks` are honored (upstream xmlXIncludeLoadDoc →
/// xmlNewInputFromFile; Phase-12 EXTERNAL-CONSUMERS court: io1.c registers
/// an sql: scheme and XInclude hrefs route through it).
///
/// # SAFETY
///
/// - `uri` must be a valid NUL-terminated C string live for the call.
pub(crate) unsafe fn read_uri_via_input_callbacks(uri: *const c_char) -> Option<Vec<u8>> {
    let table = INPUT_CALLBACKS.lock();
    for e in table.iter() {
        let Some(matchcb) = e.matchcb else {
            continue;
        };
        // SAFETY: callbacks were registered by the caller and must uphold
        // the xmlInput*Callback contracts.
        if unsafe { matchcb(uri) } == 0 {
            continue;
        }
        let (Some(opencb), Some(readcb)) = (e.opencb, e.readcb) else {
            return None;
        };
        // SAFETY: the open callback returns a context for read/close.
        let ctx = unsafe { opencb(uri) };
        if ctx.is_null() {
            return None;
        }
        let mut data = Vec::new();
        let mut buf = [0u8; 4096];
        loop {
            // SAFETY: readcb fills `buf` per the xmlInputReadCallback contract.
            let n = unsafe { readcb(ctx, buf.as_mut_ptr() as *mut c_char, buf.len() as c_int) };
            if n < 0 {
                if let Some(closecb) = e.closecb {
                    unsafe { closecb(ctx) };
                }
                return None;
            }
            if n == 0 {
                break;
            }
            data.extend_from_slice(&buf[..n as usize]);
        }
        if let Some(closecb) = e.closecb {
            unsafe { closecb(ctx) };
        }
        return Some(data);
    }
    None
}

/// Register a new set of output I/O callbacks.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlRegisterOutputCallbacks(xmlOutputMatchCallback matchFunc,
///                                xmlOutputOpenCallback openFunc,
///                                xmlOutputWriteCallback writeFunc,
///                                xmlOutputCloseCallback closeFunc);
/// ```
///
/// # SAFETY
///
///
/// - `matchFunc`, `openFunc`, `writeFunc`, `closeFunc` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlRegisterOutputCallbacks(
    matchFunc: Option<xmlOutputMatchCallback>,
    openFunc: Option<xmlOutputOpenCallback>,
    writeFunc: Option<xmlOutputWriteCallback>,
    closeFunc: Option<xmlOutputCloseCallback>,
) -> c_int {
    unsafe {
        globals::init_parser();
    }
    let mut table = OUTPUT_CALLBACKS.lock();
    if table.len() >= 10 {
        return -1;
    }
    table.push(OutputCallbackEntry {
        matchcb: matchFunc,
        opencb: openFunc,
        writecb: writeFunc,
        closecb: closeFunc,
    });
    (table.len() - 1) as c_int
}

/// Register the default compiled-in output callbacks.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlRegisterDefaultOutputCallbacks(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlRegisterDefaultOutputCallbacks() {
    unsafe {
        xmlRegisterOutputCallbacks(Some(xmlFileMatch), None, None, None);
    }
}

/// Register the HTTP POST output callbacks (upstream: default output callbacks).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlRegisterHTTPPostCallbacks(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlRegisterHTTPPostCallbacks() {
    unsafe { xmlRegisterDefaultOutputCallbacks() }
}

/// Remove the top output callback from the stack.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlPopOutputCallbacks(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlPopOutputCallbacks() -> c_int {
    unsafe {
        globals::init_parser();
    }
    let mut table = OUTPUT_CALLBACKS.lock();
    if table.is_empty() {
        return -1;
    }
    table.pop();
    table.len() as c_int
}

/// Clear the entire output callback table.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCleanupOutputCallbacks(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlCleanupOutputCallbacks() {
    unsafe {
        globals::init_parser();
    }
    OUTPUT_CALLBACKS.lock().clear();
}

// ═══════════════════════════════════════════════════════════════════════════════
// External entity loaders (parser.h)
// ═══════════════════════════════════════════════════════════════════════════════

/// Default external entity loader: resolve `url` against the filesystem,
/// honouring XML_PARSE_NONET.
///
/// # Safety
///
/// `url`/`publicId` must be valid C strings or NULL; `ctxt` may be NULL.
unsafe extern "C" fn default_external_entity_loader(
    url: *const c_char,
    public_id: *const c_char,
    ctxt: *mut _xmlParserCtxt,
) -> *mut _xmlParserInput {
    let _ = public_id;
    if url.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        // Refuse network access when NONET is set.
        if !ctxt.is_null() && (*ctxt).options & XML_PARSE_NONET != 0 {
            let len = libc::strlen(url);
            if len >= 7 && libc::strncasecmp(url, c"http://".as_ptr() as *const c_char, 7) == 0 {
                return ptr::null_mut();
            }
        }
        // UPSTREAM-PARITY (parserInternals.c xmlDefaultExternalEntityLoader
        // -> xmlNewInputFromFile -> xmlNewInputFromUrl): the registered
        // xmlParserInputBufferCreateFilenameDefault (php streams loader) is
        // consulted BEFORE the input-callback table and the built-in open. A
        // NULL loader result is XML_IO_ENOENT — xmlCtxtErrIO is raised and
        // there is no fallback.
        if globals::get_parser_input_buffer_create_filename_value_cross_dso().is_some() {
            // SAFETY: url is a valid NUL-terminated C string for the call.
            return match call_loader_materialize(url) {
                Err(()) => {
                    emit_io_warning(ctxt, io_load_failure_message(url));
                    ptr::null_mut()
                }
                Ok(data) => {
                    // Build a MEMORY-backed C input: the entity machinery
                    // consumes the loader result through base/end (upstream
                    // buffers the external entity content the same way). A
                    // zero-length result (php://memory, 0-byte file) is a
                    // VALID empty input — the parse reports "Document is
                    // empty" (php DOM createFromFile).
                    let mem = if data.is_empty() {
                        crate::xml::io::input_buffer_create_empty()
                    } else {
                        io::input_buffer_create_mem(
                            data.as_ptr() as *const c_char,
                            data.len() as c_int,
                            xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int,
                        )
                    };
                    if mem.is_null() {
                        return ptr::null_mut();
                    }
                    parser_input_from_buf(mem)
                }
            };
        }
        // Try the registered input callbacks first.
        let table = INPUT_CALLBACKS.lock();
        for entry in table.iter() {
            if let (Some(match_cb), Some(open_cb)) = (entry.matchcb, entry.opencb) {
                if match_cb(url) != 0 {
                    let ctx = open_cb(url);
                    if !ctx.is_null() {
                        let buf = helpers::alloc_parser_input_buffer();
                        if buf.is_null() {
                            if let Some(close_cb) = entry.closecb {
                                close_cb(ctx);
                            }
                            return ptr::null_mut();
                        }
                        (*buf).context = ctx;
                        (*buf).readcallback = entry.readcb;
                        (*buf).closecallback = entry.closecb;
                        return parser_input_from_buf(buf);
                    }
                }
            }
        }

        // Fall back to a plain file open.
        let buf =
            io::input_buffer_create_file(url, xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int);
        if buf.is_null() {
            // UPSTREAM-PARITY (parserInternals.c xmlNewInputFromFile): a
            // failed load raises xmlCtxtErrIO(ctxt, XML_IO_ENOENT, url) —
            // "I/O warning : failed to load \"%s\": %s\n" with the
            // strerror text (HOSTILE-FAILURE F7).
            let errno = *libc::__errno_location();
            let errstr = if errno == 0 {
                String::new()
            } else {
                std::ffi::CStr::from_ptr(libc::strerror(errno))
                    .to_string_lossy()
                    .into_owned()
            };
            let url_str = std::ffi::CStr::from_ptr(url).to_string_lossy();
            emit_io_warning(ctxt, format!("failed to load \"{url_str}\": {errstr}\n"));
            return ptr::null_mut();
        }
        parser_input_from_buf(buf)
    }
}

/// UPSTREAM-PARITY (parserInternals.c xmlCtxtErrIO): raise an I/O warning
/// (XML_FROM_IO, XML_IO_ENOENT, XML_ERR_WARNING) through the parser's
/// channel — "I/O warning : <message>".
pub(crate) unsafe fn emit_io_warning(ctxt: *mut _xmlParserCtxt, message: String) {
    let msg_c = std::ffi::CString::new(message).unwrap_or_default();
    let delivery = if ctxt.is_null() {
        crate::xml::errors::GenericDelivery::Stream
    } else {
        unsafe { crate::xml::errors::parser_delivery(ctxt) }
    };
    unsafe {
        crate::xml::errors::raise_error_streamed(
            ctxt as *mut c_void,
            crate::abi::types::XML_FROM_IO,
            crate::abi::types::XML_IO_ENOENT,
            crate::abi::types::xmlErrorLevel::XML_ERR_WARNING as c_int,
            ptr::null(),
            0,
            0,
            ptr::null(),
            ptr::null(),
            ptr::null(),
            0,
            msg_c.as_ptr(),
            None,
            None,
            delivery,
            None,
        );
    }
}

/// Result of routing a filename open through the registered loaders
/// (upstream 2.14+ `xmlLoadResource` layering).
#[allow(dead_code)]
pub(crate) enum RoutedFileOpen {
    /// No custom loader is registered — the caller falls back to the built-in
    /// file open (`helpers::input_from_file`).
    Builtin,
    /// A registered loader returned NULL: upstream reports `XML_IO_ENOENT`
    /// with NO built-in fallback (php streams loader: missing file, percent-
    /// encoded-NUL guard, disabled entity loader).
    Failed,
    /// A registered EXTERNAL ENTITY loader (`xmlSetExternalEntityLoader`)
    /// returned NULL for a file/URL open. Upstream `xmlCtxtNewInputFromUrl`
    /// propagates that NULL silently (no `xmlCtxtErrIO` — the custom loader
    /// owns its own error reporting), so callers fail without a warning.
    EntityLoaderFailed,
    /// The loader produced an input buffer whose bytes were materialized
    /// (filename = the original URI).
    Loaded(InputBuffer),
}

/// UPSTREAM-PARITY (parserInternals.c `xmlNewInputFromUrl`): when a custom
/// `xmlParserInputBufferCreateFilenameDefault` is registered (PHP installs
/// its streams loader at request init), filename opens consult it FIRST —
/// php streams unescape `file://` URIs, enforce the percent-encoded-NUL
/// guard, honor stream contexts and emit their own failure warnings. A NULL
/// loader result is `XML_IO_ENOENT`; upstream does NOT fall back to the
/// built-in open in that case. Without a registered loader the caller keeps
/// the built-in path.
///
/// Invoke the registered loader and materialize the produced buffer's bytes
/// through its read callback, releasing the C buffer/stream exactly once
/// (the close callback runs when the buffer is freed). Returns `Err(())` on
/// a NULL loader result or a read-callback error.
///
/// # Safety
///
/// - `uri` must be a valid NUL-terminated C string live for the call; the
///   registered loader callback (if any) must uphold the
///   `xmlParserInputBufferCreateFilenameFunc` contract.
pub(crate) unsafe fn call_loader_materialize(uri: *const c_char) -> Result<Vec<u8>, ()> {
    // SAFETY: reads the per-thread loader slot — through the R-000177
    // cross-DSO bridge so the whole-archive facade copies observe the
    // loader a consumer registered via the core DSO's exported setter
    // (upstream: single core DSO, registration visible everywhere).
    let Some(func) = globals::get_parser_input_buffer_create_filename_value_cross_dso() else {
        return Err(());
    };
    // SAFETY: `func` is the consumer-registered C loader and must uphold the
    // xmlParserInputBufferCreateFilenameFunc contract (uri + enc in, buffer
    // out, or NULL on failure).
    let buf = unsafe { func(uri, xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int) };
    if buf.is_null() {
        return Err(());
    }
    let (read, ctx) = unsafe {
        let b = &*buf;
        (b.readcallback, b.context)
    };
    let mut data: Vec<u8> = Vec::new();
    let mut result = Err(());
    if let Some(read) = read {
        let mut tmp = [0u8; 4096];
        loop {
            // SAFETY: the loader's buffer carries the consumer's read
            // callback + context (xmlParserInputBufferCreateIO contract).
            let n = unsafe { read(ctx, tmp.as_mut_ptr() as *mut c_char, tmp.len() as c_int) };
            if n < 0 {
                break;
            }
            if n == 0 {
                result = Ok(());
                break;
            }
            data.extend_from_slice(&tmp[..n as usize]);
        }
    } else {
        // A memory-backed loader buffer (no read callback): copy its content.
        unsafe {
            let b = &*buf;
            if !b.buffer.is_null() {
                let xbuf = &*(b.buffer as *mut _xmlBuffer);
                if !xbuf.content.is_null() && xbuf.use_ > 0 {
                    data.extend_from_slice(std::slice::from_raw_parts(
                        xbuf.content as *const u8,
                        xbuf.use_ as usize,
                    ));
                }
            }
        }
        result = Ok(());
    }
    // Release the loader's C buffer: the close callback (php streams IO
    // close) runs exactly once now that the bytes are owned here.
    io::input_buffer_free(buf);
    result.map(|()| data)
}

/// Route a filename open through the registered loaders, materializing the
/// result into an owned [`InputBuffer`] (filename = the original URI).
///
/// UPSTREAM LAYERING (2.14+ `xmlLoadResource`, R-000177): a REGISTERED
/// external entity loader (`xmlSetExternalEntityLoader`) is consulted first
/// for file/URL opens — main documents go through the same resource loader
/// as entities (`xmlCtxtNewInputFromUrl` -> `xmlLoadResource` ->
/// `xmlCurrentExternalEntityLoader`). A NULL custom-loader result is
/// `EntityLoaderFailed` (silent upstream — no `xmlCtxtErrIO`, the custom
/// loader reports its own errors). With NO custom entity loader the default
/// loader's tail is the `xmlParserInputBufferCreateFilenameDefault` (php
/// streams) loader, which is what the rest of this function implements
/// (upstream `xmlNewInputFromUrl`).
///
/// The registration is read through the R-000177 cross-DSO bridge (facade
/// copies must see a loader registered via the core DSO's exported setter).
///
/// # Safety
///
/// - `uri` must be a valid NUL-terminated C string live for the call.
/// - `ctxt` must be NULL or a valid parser context live for the call (passed
///   to the entity loader exactly as upstream `xmlLoadResource` does).
pub(crate) unsafe fn open_filename_routed(
    uri: *const c_char,
    ctxt: *mut _xmlParserCtxt,
) -> RoutedFileOpen {
    // A custom external entity loader governs file/URL opens too.
    if external_entity_loader_active() {
        // SAFETY: uri is a valid C string; ctxt is NULL or valid.
        let input = xmlLoadExternalEntity(uri, ptr::null(), ctxt);
        if input.is_null() {
            return RoutedFileOpen::EntityLoaderFailed;
        }
        // Materialize the loader's bytes into an owned InputBuffer (the
        // loader result is freed here; the parse consumes the copy).
        let loaded = input_bytes_owned(input);
        let named = if uri.is_null() {
            None
        } else {
            // SAFETY: uri is a valid NUL-terminated C string.
            Some(
                unsafe { CStr::from_ptr(uri) }
                    .to_string_lossy()
                    .into_owned(),
            )
        };
        return RoutedFileOpen::Loaded(InputBuffer::from_memory(
            loaded.as_deref().unwrap_or(&[]),
            named.as_deref(),
        ));
    }
    // No registered loader: the caller keeps the built-in open. The slot is
    // read through the R-000177 cross-DSO bridge (facade copies must see a
    // loader registered via the core DSO's exported setter).
    if globals::get_parser_input_buffer_create_filename_value_cross_dso().is_none() {
        return RoutedFileOpen::Builtin;
    }
    // SAFETY: uri is a valid NUL-terminated C string for the call.
    let loaded = unsafe { call_loader_materialize(uri) };
    match loaded {
        Err(()) => RoutedFileOpen::Failed,
        Ok(bytes) => {
            let named = if uri.is_null() {
                None
            } else {
                // SAFETY: uri is a valid NUL-terminated C string.
                Some(
                    unsafe { CStr::from_ptr(uri) }
                        .to_string_lossy()
                        .into_owned(),
                )
            };
            RoutedFileOpen::Loaded(InputBuffer::from_memory(&bytes, named.as_deref()))
        }
    }
}

/// True when a custom external entity loader is registered process-wide
/// (the core DSO's `xmlSetExternalEntityLoader` registration, or this DSO's
/// own when the accessor does not resolve in a single-DSO link). The
/// process-visible registration is authoritative (R-000177).
fn external_entity_loader_active() -> bool {
    match foreign_external_entity_loader() {
        Some(_) => true,
        None => EXTERNAL_ENTITY_LOADER.lock().is_some(),
    }
}

/// Route a filename open through the `xmlParserInputBufferCreateFilenameDefault`
/// (php streams) loader ONLY — no external-entity-loader consult.
///
/// The xmlTextReader family reads through `xmlNewInputFromFile` upstream,
/// which does NOT go through the external entity loader (verified against
/// the executed 2.15.3 oracle), so the reader must not pick up an
/// `xmlSetExternalEntityLoader` registration.
///
/// # Safety
///
/// - `uri` must be a valid NUL-terminated C string live for the call.
pub(crate) unsafe fn open_filename_routed_input_only(uri: *const c_char) -> RoutedFileOpen {
    // No registered loader: the caller keeps the built-in open. The slot is
    // read through the R-000177 cross-DSO bridge (facade copies must see a
    // loader registered via the core DSO's exported setter).
    if globals::get_parser_input_buffer_create_filename_value_cross_dso().is_none() {
        return RoutedFileOpen::Builtin;
    }
    // SAFETY: uri is a valid NUL-terminated C string for the call.
    let loaded = unsafe { call_loader_materialize(uri) };
    match loaded {
        Err(()) => RoutedFileOpen::Failed,
        Ok(bytes) => {
            let named = if uri.is_null() {
                None
            } else {
                // SAFETY: uri is a valid NUL-terminated C string.
                Some(
                    unsafe { CStr::from_ptr(uri) }
                        .to_string_lossy()
                        .into_owned(),
                )
            };
            RoutedFileOpen::Loaded(InputBuffer::from_memory(&bytes, named.as_deref()))
        }
    }
}

/// Copy the bytes of a loader-produced `_xmlParserInput` into an owned
/// `Vec` and release the input (upstream `xmlCtxtParseDocument` consumes the
/// input; the candidate's parse paths own an [`InputBuffer`]). The input's
/// underlying buffer is freed with the input (xmlFreeInputStream).
///
/// # Safety
///
/// - `input` must be a valid `_xmlParserInput` produced by a registered
///   loader / `xmlLoadExternalEntity`, not yet freed.
unsafe fn input_bytes_owned(input: *mut _xmlParserInput) -> Option<Vec<u8>> {
    unsafe {
        let base = (*input).base;
        let end = (*input).end;
        let len = if base.is_null() {
            0
        } else {
            end.offset_from(base).max(0) as usize
        };
        let bytes = if base.is_null() || len == 0 {
            None
        } else {
            Some(core::slice::from_raw_parts(base, len).to_vec())
        };
        crate::abi::exports_xml2::xmlFreeInputStream(input);
        bytes
    }
}

/// Compose the upstream `xmlCtxtErrIO(XML_IO_ENOENT, uri)` message text:
/// `failed to load "<uri>": <errno text>\n`. When errno is stale (the
/// registered php streams loader returned NULL without touching errno, e.g.
/// the percent-NUL guard) the `XML_IO_ENOENT` table text is used.
///
/// # Safety
///
/// - `uri` must be NULL or a valid NUL-terminated C string live for the call.
pub(crate) fn io_load_failure_message(uri: *const c_char) -> String {
    // SAFETY: reads errno only.
    let errno = unsafe { *libc::__errno_location() };
    let errstr = if errno == 0 {
        // xmlErrString(XML_IO_ENOENT) table text (error.c 2.15).
        "No such file or directory".to_string()
    } else {
        // SAFETY: strerror(errno) returns a static message for the value.
        unsafe { std::ffi::CStr::from_ptr(libc::strerror(errno)) }
            .to_string_lossy()
            .into_owned()
    };
    let url_str = if uri.is_null() {
        String::new()
    } else {
        // SAFETY: uri is a valid NUL-terminated C string.
        unsafe { std::ffi::CStr::from_ptr(uri) }
            .to_string_lossy()
            .into_owned()
    };
    format!("failed to load \"{url_str}\": {errstr}\n")
}

/// Set the application-wide external entity loader.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSetExternalEntityLoader(xmlExternalEntityLoader f);
/// ```
///
/// # SAFETY
///
///
/// - `f` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSetExternalEntityLoader(f: Option<xmlExternalEntityLoader>) {
    *EXTERNAL_ENTITY_LOADER.lock() = f;
}

/// Get the current external entity loader.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlExternalEntityLoader xmlGetExternalEntityLoader(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlGetExternalEntityLoader() -> Option<xmlExternalEntityLoader> {
    *EXTERNAL_ENTITY_LOADER.lock()
}

/// External entity loader that disables network access.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserInputPtr xmlNoNetExternalEntityLoader(const char *URL,
///                                                const char *ID,
///                                                xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `URL`, `ID` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlNoNetExternalEntityLoader(
    URL: *const c_char,
    ID: *const c_char,
    ctxt: *mut _xmlParserCtxt,
) -> *mut _xmlParserInput {
    unsafe {
        let old_options = if ctxt.is_null() { 0 } else { (*ctxt).options };
        if !ctxt.is_null() {
            (*ctxt).options |= XML_PARSE_NONET;
        }
        let input = default_external_entity_loader(URL, ID, ctxt);
        if !ctxt.is_null() {
            (*ctxt).options = old_options;
        }
        input
    }
}

/// Load an external entity using the registered loader.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserInputPtr xmlLoadExternalEntity(const char *URL, const char *ID,
///                                         xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `URL`, `ID` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlLoadExternalEntity(
    URL: *const c_char,
    ID: *const c_char,
    ctxt: *mut _xmlParserCtxt,
) -> *mut _xmlParserInput {
    // R-000177: the loader xmlSetExternalEntityLoader registers binds to the
    // CORE DSO, so a load performed by a whole-archive facade's private copy
    // must consult the process-visible registration first (upstream: one
    // core instance, one loader). Single-DSO links resolve their own export.
    let loader = match foreign_external_entity_loader() {
        Some(f) => Some(f),
        None => *EXTERNAL_ENTITY_LOADER.lock(),
    };
    match loader {
        Some(f) => unsafe { f(URL, ID, ctxt) },
        None => unsafe { default_external_entity_loader(URL, ID, ctxt) },
    }
}

/// Resolve the process-visible `xmlGetExternalEntityLoader` (the CORE DSO's
/// registration) via the dynamic symbol scope.
#[cfg(target_os = "linux")]
fn foreign_external_entity_loader() -> Option<xmlExternalEntityLoader> {
    use std::sync::OnceLock;
    type Getter = unsafe extern "C" fn() -> Option<xmlExternalEntityLoader>;
    static GETTER: OnceLock<Option<Getter>> = OnceLock::new();
    let getter = *GETTER.get_or_init(|| {
        // SAFETY: dlsym(RTLD_DEFAULT) returns the exported accessor address
        // or NULL; the transmute (pointer-sized) is sound.
        unsafe {
            let sym = libc::dlsym(libc::RTLD_DEFAULT, c"xmlGetExternalEntityLoader".as_ptr());
            if sym.is_null() {
                None
            } else {
                Some(std::mem::transmute::<*mut c_void, Getter>(sym))
            }
        }
    });
    getter.and_then(|g| unsafe { g() })
}

#[cfg(not(target_os = "linux"))]
fn foreign_external_entity_loader() -> Option<xmlExternalEntityLoader> {
    None
}

/// Check an input for HTTP access; with XML_PARSE_NONET set, HTTP inputs are
/// refused and freed.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlParserInputPtr xmlCheckHTTPInput(xmlParserCtxtPtr ctxt,
///                                     xmlParserInputPtr ret);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `ret` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCheckHTTPInput(
    ctxt: *mut _xmlParserCtxt,
    ret: *mut _xmlParserInput,
) -> *mut _xmlParserInput {
    if ret.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        if !ctxt.is_null() && (*ctxt).options & XML_PARSE_NONET != 0 {
            let filename = (*ret).filename;
            if !filename.is_null() {
                let len = libc::strlen(filename);
                if len >= 7
                    && libc::strncasecmp(filename, c"http://".as_ptr() as *const c_char, 7) == 0
                {
                    // free_parser_input now frees the owned buffer (upstream
                    // xmlFreeInputStream semantics); no separate buf free.
                    helpers::free_parser_input(ret);
                    return ptr::null_mut();
                }
            }
        }
        ret
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// xmlFile* I/O callbacks (xmlIO.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Match callback: the file I/O handlers accept every filename.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlFileMatch(const char *filename);
/// ```
///
/// # SAFETY
///
///
/// - `_filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub const unsafe extern "C" fn xmlFileMatch(_filename: *const c_char) -> c_int {
    1
}

/// Open a file and return a `FILE *` I/O context (cast to `void *`).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlFileOpen(const char *filename);
/// ```
///
/// # SAFETY
///
///
/// - `filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlFileOpen(filename: *const c_char) -> *mut c_void {
    if filename.is_null() {
        return ptr::null_mut();
    }
    unsafe { libc::fopen(filename, c"rb".as_ptr() as *const c_char) as *mut c_void }
}

/// Read up to `len` bytes from a `FILE *` I/O context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlFileRead(void *context, char *buffer, int len);
/// ```
///
/// # SAFETY
///
/// - `context`, `buffer` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlFileRead(
    context: *mut c_void,
    buffer: *mut c_char,
    len: c_int,
) -> c_int {
    if context.is_null() || buffer.is_null() || len <= 0 {
        return -1;
    }
    unsafe {
        let n = libc::fread(
            buffer as *mut c_void,
            1,
            len as usize,
            context as *mut libc::FILE,
        );
        if n < len as usize && libc::ferror(context as *mut libc::FILE) != 0 {
            return -1;
        }
        n as c_int
    }
}

/// Close a `FILE *` I/O context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlFileClose(void *context);
/// ```
///
/// # SAFETY
///
/// - `context` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlFileClose(context: *mut c_void) -> c_int {
    if context.is_null() {
        return -1;
    }
    unsafe {
        let file = context as *mut libc::FILE;
        let fd = libc::fileno(file);
        if fd == 0 {
            // stdin must not be closed.
            return 0;
        }
        if fd == 1 || fd == 2 {
            // stdout/stderr are only flushed.
            return if libc::fflush(file) == 0 { 0 } else { -1 };
        }
        libc::fclose(file)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Low-level character scanning (parserInternals.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Return the current character (UTF-8 decoded, EOL normalised) and its byte
/// length in `*len`. Does not advance the input pointer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `len` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCurrentChar(ctxt: *mut _xmlParserCtxt, len: *mut c_int) -> c_int {
    if ctxt.is_null() || len.is_null() || (*ctxt).input.is_null() {
        return 0;
    }
    unsafe {
        let pi = &*((*ctxt).input);
        let cur = pi.cur;
        if cur.is_null() {
            *len = 0;
            return 0;
        }
        let avail = (pi.end as usize).saturating_sub(cur as usize);
        let c = *cur;

        if c < 0x80 {
            if c == b'\r' {
                // EOL normalisation: CR (optionally CRLF) becomes LF.
                if avail >= 2 && *cur.add(1) == b'\n' {
                    (*(*ctxt).input).cur = cur.add(1);
                }
                *len = 1;
                return b'\n' as c_int;
            }
            if c == 0 {
                if avail == 0 {
                    *len = 0;
                } else {
                    *len = 1;
                }
                return 0;
            }
            *len = 1;
            return c as c_int;
        }

        // Multi-byte UTF-8.
        if avail < 2 || (*cur.add(1) & 0xc0) != 0x80 {
            *len = 1;
            return XML_INVALID_CHAR;
        }
        if c < 0xe0 {
            if c < 0xc2 {
                *len = 1;
                return XML_INVALID_CHAR;
            }
            let val = (((c & 0x1f) as c_int) << 6) | ((*cur.add(1) & 0x3f) as c_int);
            *len = 2;
            return val;
        }
        if avail < 3 || (*cur.add(2) & 0xc0) != 0x80 {
            *len = 1;
            return XML_INVALID_CHAR;
        }
        if c < 0xf0 {
            let val = (((c & 0x0f) as c_int) << 12)
                | (((*cur.add(1) & 0x3f) as c_int) << 6)
                | ((*cur.add(2) & 0x3f) as c_int);
            if val < 0x800 || (0xd800..0xe000).contains(&val) {
                *len = 1;
                return XML_INVALID_CHAR;
            }
            *len = 3;
            return val;
        }
        if avail < 4 || (*cur.add(3) & 0xc0) != 0x80 {
            *len = 1;
            return XML_INVALID_CHAR;
        }
        let val = (((c & 0x07) as c_int) << 18)
            | (((*cur.add(1) & 0x3f) as c_int) << 12)
            | (((*cur.add(2) & 0x3f) as c_int) << 6)
            | ((*cur.add(3) & 0x3f) as c_int);
        if !(0x10000..0x110000).contains(&val) {
            *len = 1;
            return XML_INVALID_CHAR;
        }
        *len = 4;
        val
    }
}

/// Advance to the next character, updating line/column accounting.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlNextChar(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlNextChar(ctxt: *mut _xmlParserCtxt) {
    if ctxt.is_null() || (*ctxt).input.is_null() {
        return;
    }
    unsafe {
        let pi = &mut *((*ctxt).input);
        let cur = pi.cur;
        if cur.is_null() {
            return;
        }
        let avail = (pi.end as usize).saturating_sub(cur as usize);
        if avail == 0 {
            return;
        }
        let c = *cur;

        if c < 0x80 {
            if c == b'\n' {
                pi.cur = cur.add(1);
                pi.line += 1;
                pi.col = 1;
            } else if c == b'\r' {
                // CRLF is a single line break.
                pi.cur = cur.add(if avail >= 2 && *cur.add(1) == b'\n' {
                    2
                } else {
                    1
                });
                pi.line += 1;
                pi.col = 1;
            } else {
                pi.cur = cur.add(1);
                pi.col += 1;
            }
            return;
        }

        pi.col += 1;

        if avail < 2 || (*cur.add(1) & 0xc0) != 0x80 {
            pi.cur = cur.add(1);
            return;
        }
        if c < 0xe0 {
            if c < 0xc2 {
                pi.cur = cur.add(1);
                return;
            }
            pi.cur = cur.add(2);
            return;
        }
        if avail < 3 || (*cur.add(2) & 0xc0) != 0x80 {
            pi.cur = cur.add(1);
            return;
        }
        if c < 0xf0 {
            let val = (((c as c_int) << 8) as u32) | (*cur.add(1) as u32);
            if (val < 0xe0a0) || (0xeda0..0xee00).contains(&val) {
                pi.cur = cur.add(1);
                return;
            }
            pi.cur = cur.add(3);
            return;
        }
        if avail < 4 || (*cur.add(3) & 0xc0) != 0x80 {
            pi.cur = cur.add(1);
            return;
        }
        let val = (((c as c_int) << 8) as u32) | (*cur.add(1) as u32);
        if !(0xf090..0xf490).contains(&val) {
            pi.cur = cur.add(1);
            return;
        }
        pi.cur = cur.add(4);
    }
}

/// Skip blank characters (space, tab, LF, CR), updating line/column.
/// Returns the number of blanks skipped.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlSkipBlankChars(xmlParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSkipBlankChars(ctxt: *mut _xmlParserCtxt) -> c_int {
    if ctxt.is_null() || (*ctxt).input.is_null() {
        return 0;
    }
    unsafe {
        let pi = &mut *((*ctxt).input);
        let mut cur = pi.cur;
        if cur.is_null() {
            return 0;
        }
        let end = pi.end;
        let mut res = 0;
        while cur < end && (*cur == 0x20 || *cur == 0x09 || *cur == 0x0a || *cur == 0x0d) {
            if *cur == b'\n' {
                pi.line += 1;
                pi.col = 1;
            } else {
                pi.col += 1;
            }
            cur = cur.add(1);
            res += 1;
        }
        pi.cur = cur;
        res
    }
}

/// XML 1.0 5th-edition NameStartChar predicate (upstream `xmlIsNameStartCharNew`).
const fn is_name_start_char_new(c: c_int) -> bool {
    if c == b' ' as c_int || c == b'>' as c_int || c == b'/' as c_int {
        return false;
    }
    (c >= b'a' as c_int && c <= b'z' as c_int)
        || (c >= b'A' as c_int && c <= b'Z' as c_int)
        || c == b'_' as c_int
        || c == b':' as c_int
        || (c >= 0xC0 && c <= 0xD6)
        || (c >= 0xD8 && c <= 0xF6)
        || (c >= 0xF8 && c <= 0x2FF)
        || (c >= 0x370 && c <= 0x37D)
        || (c >= 0x37F && c <= 0x1FFF)
        || (c >= 0x200C && c <= 0x200D)
        || (c >= 0x2070 && c <= 0x218F)
        || (c >= 0x2C00 && c <= 0x2FEF)
        || (c >= 0x3001 && c <= 0xD7FF)
        || (c >= 0xF900 && c <= 0xFDCF)
        || (c >= 0xFDF0 && c <= 0xFFFD)
        || (c >= 0x10000 && c <= 0xEFFFF)
}

/// XML 1.0 5th-edition NameChar predicate (upstream `xmlIsNameCharNew`).
const fn is_name_char_new(c: c_int) -> bool {
    if c == b' ' as c_int || c == b'>' as c_int || c == b'/' as c_int {
        return false;
    }
    (c >= b'a' as c_int && c <= b'z' as c_int)
        || (c >= b'A' as c_int && c <= b'Z' as c_int)
        || (c >= b'0' as c_int && c <= b'9' as c_int)
        || c == b'_' as c_int
        || c == b':' as c_int
        || c == b'-' as c_int
        || c == b'.' as c_int
        || c == 0xB7
        || (c >= 0xC0 && c <= 0xD6)
        || (c >= 0xD8 && c <= 0xF6)
        || (c >= 0xF8 && c <= 0x2FF)
        || (c >= 0x300 && c <= 0x36F)
        || (c >= 0x370 && c <= 0x37D)
        || (c >= 0x37F && c <= 0x1FFF)
        || (c >= 0x200C && c <= 0x200D)
        || (c >= 0x203F && c <= 0x2040)
        || (c >= 0x2070 && c <= 0x218F)
        || (c >= 0x2C00 && c <= 0x2FEF)
        || (c >= 0x3001 && c <= 0xD7FF)
        || (c >= 0xF900 && c <= 0xFDCF)
        || (c >= 0xFDF0 && c <= 0xFFFD)
        || (c >= 0x10000 && c <= 0xEFFFF)
}

/// Scan an XML Name (or NCName/Nmtoken) at `ctxt->input->cur`, advancing the
/// input pointer. Returns a pointer to the end of the name, or NULL when the
/// name exceeds `max` bytes.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// const xmlChar *xmlScanName(xmlParserCtxtPtr ctxt, int max, int flags);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlScanName(
    ctxt: *mut _xmlParserCtxt,
    max: c_int,
    flags: c_int,
) -> *const xmlChar {
    if ctxt.is_null() || (*ctxt).input.is_null() || max <= 0 {
        return ptr::null();
    }
    unsafe {
        let pi = &mut *((*ctxt).input);
        let mut ptr = pi.cur;
        if ptr.is_null() {
            return ptr::null();
        }
        let end = pi.end;
        let mut remaining = max as usize;
        let stop: u8 = if flags & XML_SCAN_NC != 0 { b':' } else { 0 };
        let old10 = flags & XML_SCAN_OLD10 != 0;
        let mut f = flags;

        loop {
            if ptr >= end {
                break;
            }
            let c = *ptr;
            let (cp, len) = if c < 0x80 {
                if stop != 0 && c == stop {
                    break;
                }
                (c as c_int, 1usize)
            } else {
                // Decode a multi-byte UTF-8 character.
                let avail = (end as usize).saturating_sub(ptr as usize);
                let mut l = 4usize;
                let cp = decode_utf8_char(ptr, avail, &mut l);
                if cp < 0 {
                    break;
                }
                (cp, l)
            };

            let ok = if f & XML_SCAN_NMTOKEN != 0 {
                if old10 {
                    is_name_char_old10(cp)
                } else {
                    is_name_char_new(cp)
                }
            } else if old10 {
                is_name_start_char_old10(cp)
            } else {
                is_name_start_char_new(cp)
            };
            if !ok {
                break;
            }
            if len > remaining {
                return ptr::null();
            }
            ptr = ptr.add(len);
            remaining -= len;
            f |= XML_SCAN_NMTOKEN;
        }

        pi.cur = ptr;
        ptr
    }
}

/// Decode a UTF-8 character at `ptr` with `avail` bytes available; returns the
/// codepoint (or -1 on invalid/truncated input) and sets `*len` to its length.
const unsafe fn decode_utf8_char(ptr: *const u8, avail: usize, len: &mut usize) -> c_int {
    unsafe {
        let c = *ptr;
        if avail < 2 || (*ptr.add(1) & 0xc0) != 0x80 {
            return -1;
        }
        if c < 0xe0 {
            if c < 0xc2 {
                return -1;
            }
            *len = 2;
            return (((c & 0x1f) as c_int) << 6) | ((*ptr.add(1) & 0x3f) as c_int);
        }
        if avail < 3 || (*ptr.add(2) & 0xc0) != 0x80 {
            return -1;
        }
        if c < 0xf0 {
            let val = (((c & 0x0f) as c_int) << 12)
                | (((*ptr.add(1) & 0x3f) as c_int) << 6)
                | ((*ptr.add(2) & 0x3f) as c_int);
            if val < 0x800 || (val >= 0xd800 && val < 0xe000) {
                return -1;
            }
            *len = 3;
            return val;
        }
        if avail < 4 || (*ptr.add(3) & 0xc0) != 0x80 {
            return -1;
        }
        let val = (((c & 0x07) as c_int) << 18)
            | (((*ptr.add(1) & 0x3f) as c_int) << 12)
            | (((*ptr.add(2) & 0x3f) as c_int) << 6)
            | ((*ptr.add(3) & 0x3f) as c_int);
        if val < 0x10000 || val >= 0x110000 {
            return -1;
        }
        *len = 4;
        val
    }
}

/// XML 1.0 (pre-revision-5) NameStartChar predicate: Letter, '_' or ':'.
const fn is_name_start_char_old10(c: c_int) -> bool {
    (c >= b'a' as c_int && c <= b'z' as c_int)
        || (c >= b'A' as c_int && c <= b'Z' as c_int)
        || c == b'_' as c_int
        || c == b':' as c_int
        || (c >= 0xC0 && c <= 0xD6)
        || (c >= 0xD8 && c <= 0xF6)
        || (c >= 0xF8 && c <= 0x2FF)
        || (c >= 0x370 && c <= 0x37D)
        || (c >= 0x37F && c <= 0x1FFF)
        || (c >= 0x200C && c <= 0x200D)
        || (c >= 0x2070 && c <= 0x218F)
        || (c >= 0x2C00 && c <= 0x2FEF)
        || (c >= 0x3001 && c <= 0xD7FF)
        || (c >= 0xF900 && c <= 0xFDCF)
        || (c >= 0xFDF0 && c <= 0xFFFD)
        || (c >= 0x10000 && c <= 0xEFFFF)
}

/// XML 1.0 (pre-revision-5) NameChar predicate: NameStartChar, digits, '.',
/// '-', combining chars and extenders.
const fn is_name_char_old10(c: c_int) -> bool {
    is_name_start_char_old10(c)
        || (c >= b'0' as c_int && c <= b'9' as c_int)
        || c == b'.' as c_int
        || c == b'-' as c_int
        || c == 0xB7
        || (c >= 0x300 && c <= 0x36F)
        || c == 0x02D0
        || c == 0x02D1
        || c == 0x0387
        || c == 0x0640
        || c == 0x0E46
        || c == 0x0EC6
        || c == 0x3005
        || (c >= 0x3031 && c <= 0x3035)
        || (c >= 0x309D && c <= 0x309E)
        || (c >= 0x30FC && c <= 0x30FE)
}

/// Decode entities from the current input position: char references and
/// (predefined and DTD-declared) entity references are substituted. Stops at
/// the first of `end`/`end2`/`end3`, or after `len` bytes (`len < 0` = rest).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlChar *xmlDecodeEntities(xmlParserCtxtPtr ctxt, int len, xmlChar end,
///                            xmlChar end2, xmlChar end3);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlDecodeEntities(
    ctxt: *mut _xmlParserCtxt,
    len: c_int,
    end: xmlChar,
    end2: xmlChar,
    end3: xmlChar,
) -> *mut xmlChar {
    if ctxt.is_null() || (*ctxt).input.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let pi = &*((*ctxt).input);
        let cur = pi.cur;
        if cur.is_null() {
            return ptr::null_mut();
        }
        let avail = (pi.end as usize).saturating_sub(cur as usize);
        let n = if len < 0 {
            avail
        } else {
            (len as usize).min(avail)
        };

        let mut out: Vec<u8> = Vec::new();
        let mut i = 0usize;

        while i < n {
            let c = *cur.add(i);
            if c == end || c == end2 || c == end3 {
                break;
            }
            if c != b'&' {
                out.push(c);
                i += 1;
                continue;
            }

            // Character reference: &#...; or &#x...;
            if i + 1 < n && *cur.add(i + 1) == b'#' {
                let (value, consumed) = parse_char_ref(cur.add(i), n - i);
                if consumed == 0 {
                    out.push(b'&');
                    i += 1;
                    continue;
                }
                let mut buf = [0u8; 4];
                let blen = copy_char_utf8(&mut buf, value);
                out.extend_from_slice(&buf[..blen]);
                i += consumed;
                continue;
            }

            // Entity reference: &name;
            let mut j = i + 1;
            while j < n
                && ((*cur.add(j)).is_ascii_alphanumeric()
                    || *cur.add(j) == b'_'
                    || *cur.add(j) == b'-'
                    || *cur.add(j) == b'.'
                    || *cur.add(j) == b':')
            {
                j += 1;
            }
            if j < n && *cur.add(j) == b';' {
                let name = core::slice::from_raw_parts(cur.add(i + 1), j - i - 1);
                let mut replaced = false;
                // Predefined entities.
                let content: Option<&[u8]> = match name {
                    b"amp" => Some(b"&"),
                    b"lt" => Some(b"<"),
                    b"gt" => Some(b">"),
                    b"quot" => Some(b"\""),
                    b"apos" => Some(b"'"),
                    _ => None,
                };
                if let Some(c) = content {
                    out.extend_from_slice(c);
                    replaced = true;
                } else {
                    // DTD-declared entity.
                    let mut name_nul = name.to_vec();
                    name_nul.push(0);
                    let ent = entities::get_entity((*ctxt).myDoc, name_nul.as_ptr());
                    if !ent.is_null() && !(*ent).content.is_null() {
                        let clen = string::xml_strlen((*ent).content);
                        out.extend_from_slice(core::slice::from_raw_parts((*ent).content, clen));
                        replaced = true;
                    }
                }
                if replaced {
                    i = j + 1;
                    continue;
                }
            }
            out.push(b'&');
            i += 1;
        }

        out.push(0);
        let result = xmlMallocImpl(out.len()) as *mut xmlChar;
        if result.is_null() {
            return ptr::null_mut();
        }
        ptr::copy_nonoverlapping(out.as_ptr(), result, out.len());
        result
    }
}

/// Parse a numeric character reference at `ptr` (starting at '&#'); returns
/// the value and total bytes consumed, or (0, 0) when malformed.
const unsafe fn parse_char_ref(ptr: *const u8, avail: usize) -> (c_int, usize) {
    unsafe {
        if avail < 3 || *ptr != b'&' || *ptr.add(1) != b'#' {
            return (0, 0);
        }
        let mut i = 2usize;
        let hex = i < avail && (*ptr.add(i) == b'x' || *ptr.add(i) == b'X');
        if hex {
            i += 1;
        }
        let start = i;
        let mut value: u32 = 0;
        while i < avail && *ptr.add(i) != b';' {
            let d = (*ptr.add(i) as char).to_digit(if hex { 16 } else { 10 });
            match d {
                Some(d) => {
                    value = value
                        .saturating_mul(if hex { 16 } else { 10 })
                        .saturating_add(d);
                    i += 1;
                }
                None => return (0, 0),
            }
        }
        if i == start || i >= avail || *ptr.add(i) != b';' {
            return (0, 0);
        }
        (value as c_int, i + 1)
    }
}

/// Encode a codepoint into a UTF-8 byte sequence; returns the byte count.
const fn copy_char_utf8(out: &mut [u8; 4], val: c_int) -> usize {
    if val < 0x80 {
        out[0] = val as u8;
        1
    } else if val < 0x800 {
        out[0] = 0xC0 | ((val >> 6) as u8);
        out[1] = 0x80 | ((val & 0x3F) as u8);
        2
    } else if val < 0x10000 {
        out[0] = 0xE0 | ((val >> 12) as u8);
        out[1] = 0x80 | (((val >> 6) & 0x3F) as u8);
        out[2] = 0x80 | ((val & 0x3F) as u8);
        3
    } else if val < 0x110000 {
        out[0] = 0xF0 | ((val >> 18) as u8);
        out[1] = 0x80 | (((val >> 12) & 0x3F) as u8);
        out[2] = 0x80 | (((val >> 6) & 0x3F) as u8);
        out[3] = 0x80 | ((val & 0x3F) as u8);
        4
    } else {
        out[0] = 0;
        1
    }
}

/// Detect the character encoding of a buffer from its initial bytes.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlCharEncoding xmlDetectCharEncoding(const unsigned char *in, int len);
/// ```
///
/// # SAFETY
///
/// - `in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub const unsafe extern "C" fn xmlDetectCharEncoding(in_: *const c_uchar, len: c_int) -> c_int {
    if in_.is_null() {
        return xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int;
    }
    unsafe {
        if len >= 4 {
            if *in_ == 0x00 && *in_.add(1) == 0x00 && *in_.add(2) == 0x00 && *in_.add(3) == 0x3C {
                return xmlCharEncoding::XML_CHAR_ENCODING_UCS4BE as c_int;
            }
            if *in_ == 0x3C && *in_.add(1) == 0x00 && *in_.add(2) == 0x00 && *in_.add(3) == 0x00 {
                return xmlCharEncoding::XML_CHAR_ENCODING_UCS4LE as c_int;
            }
            if *in_ == 0x4C && *in_.add(1) == 0x6F && *in_.add(2) == 0xA7 && *in_.add(3) == 0x94 {
                return xmlCharEncoding::XML_CHAR_ENCODING_EBCDIC as c_int;
            }
            if *in_ == 0x3C && *in_.add(1) == 0x3F && *in_.add(2) == 0x78 && *in_.add(3) == 0x6D {
                return xmlCharEncoding::XML_CHAR_ENCODING_UTF8 as c_int;
            }
            if *in_ == 0x3C && *in_.add(1) == 0x00 && *in_.add(2) == 0x3F && *in_.add(3) == 0x00 {
                return xmlCharEncoding::XML_CHAR_ENCODING_UTF16LE as c_int;
            }
            if *in_ == 0x00 && *in_.add(1) == 0x3C && *in_.add(2) == 0x00 && *in_.add(3) == 0x3F {
                return xmlCharEncoding::XML_CHAR_ENCODING_UTF16BE as c_int;
            }
        }
        if len >= 3 && *in_ == 0xEF && *in_.add(1) == 0xBB && *in_.add(2) == 0xBF {
            return xmlCharEncoding::XML_CHAR_ENCODING_UTF8 as c_int;
        }
        if len >= 2 {
            if *in_ == 0xFE && *in_.add(1) == 0xFF {
                return xmlCharEncoding::XML_CHAR_ENCODING_UTF16BE as c_int;
            }
            if *in_ == 0xFF && *in_.add(1) == 0xFE {
                return xmlCharEncoding::XML_CHAR_ENCODING_UTF16LE as c_int;
            }
        }
    }
    xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int
}

/// Convert the first line of `in` using the encoding handler, appending the
/// result to `out`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlCharEncFirstLine(xmlCharEncodingHandlerPtr handler,
///                         struct _xmlBuffer *out, struct _xmlBuffer *in);
/// ```
///
/// # SAFETY
///
/// - `handler`, `out`, `in_` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlCharEncFirstLine(
    handler: *mut _xmlCharEncodingHandler,
    out: *mut _xmlBuffer,
    in_: *mut _xmlBuffer,
) -> c_int {
    encoding::xmlCharEncInFunc(handler, out, in_)
}

/// Check whether the current thread is the main thread.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlIsMainThread(void);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub const unsafe extern "C" fn xmlIsMainThread() -> c_int {
    1
}

// ═══════════════════════════════════════════════════════════════════════════════
// Error reporting helpers (xmlerror.h)
// ═══════════════════════════════════════════════════════════════════════════════

/// Print file and line information for a parser input to the generic error
/// channel.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlParserPrintFileInfo(struct _xmlParserInput *input);
/// ```
///
/// # SAFETY
///
/// - `input` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserPrintFileInfo(input: *mut _xmlParserInput) {
    if input.is_null() {
        return;
    }
    unsafe {
        let channel: Option<xmlGenericErrorFunc> = globals::get_generic_error_func();
        let data = globals::get_generic_error_ctx();
        let Some(ch) = channel else { return };

        let msg = if !(*input).filename.is_null() {
            let file = CStr::from_ptr((*input).filename);
            let s = format!("{}:{}: ", file.to_string_lossy(), (*input).line);
            std::ffi::CString::new(s).unwrap_or_default()
        } else {
            let s = format!("Entity: line {}: ", (*input).line);
            std::ffi::CString::new(s).unwrap_or_default()
        };
        ch(data, msg.as_ptr());
    }
}

/// Print the input context around the current error position to the generic
/// error channel.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlParserPrintFileContext(struct _xmlParserInput *input);
/// ```
///
/// # SAFETY
///
/// - `input` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlParserPrintFileContext(input: *mut _xmlParserInput) {
    if input.is_null() || (*input).cur.is_null() {
        return;
    }
    unsafe {
        let channel: Option<xmlGenericErrorFunc> = globals::get_generic_error_func();
        let data = globals::get_generic_error_ctx();
        let Some(ch) = channel else { return };

        let pi = &*input;
        let cur = pi.cur;
        let base = pi.base;
        let end = pi.end;

        // Build a window of up to 80 bytes ending at `cur`.
        let before = if base.is_null() {
            0
        } else {
            (cur as usize).saturating_sub(base as usize)
        };
        let take = before.min(LINE_LEN);
        let start = cur.sub(take);
        let n = (end as usize).saturating_sub(start as usize).min(LINE_LEN);

        let mut content = vec![0u8; n];
        if n > 0 {
            ptr::copy_nonoverlapping(start, content.as_mut_ptr(), n);
        }
        let line = std::ffi::CString::new(content.clone()).unwrap_or_default();
        ch(data, line.as_ptr());

        // Caret line pointing at the current character.
        let mut caret = vec![b' '; take];
        if take < LINE_LEN + 1 {
            caret.push(b'^');
        }
        let caret_c = std::ffi::CString::new(caret).unwrap_or_default();
        ch(data, caret_c.as_ptr());
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SAX/DTD parse front-ends
// ═══════════════════════════════════════════════════════════════════════════════

/// Handle an entity reference by pushing the entity's content as a new input
/// stream (deprecated internal API).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlHandleEntity(xmlParserCtxtPtr ctxt, xmlEntityPtr entity);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `entity` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlHandleEntity(ctxt: *mut _xmlParserCtxt, entity: *mut c_void) {
    if ctxt.is_null() {
        return;
    }
    unsafe {
        let ent = entity as *mut _xmlEntity;
        if ent.is_null() {
            return;
        }
        // Unparsed entities cannot be included by reference.
        if (*ent).etype == xmlEntityType::XML_EXTERNAL_GENERAL_UNPARSED_ENTITY as c_int {
            return;
        }

        let mut input = ptr::null_mut();
        if !(*ent).content.is_null() {
            // Internal entity: push its replacement text as a new stream.
            let content = (*ent).content;
            let pi = xmlNewInputStream(ctxt);
            if pi.is_null() {
                return;
            }
            let len = string::xml_strlen(content);
            (*pi).base = content;
            (*pi).cur = content;
            (*pi).end = content.add(len);
            (*pi).length = len as c_int;
            (*pi).entity = ent;
            input = pi;
        } else if !(*ent).URI.is_null() {
            // External parsed entity: load it through the entity loader.
            input = xmlLoadExternalEntity(
                (*ent).URI as *const c_char,
                (*ent).ExternalID as *const c_char,
                ctxt,
            );
            if !input.is_null() {
                (*input).entity = ent;
            }
        }

        if input.is_null() {
            return;
        }
        xmlPushInput(ctxt, input);
    }
}

/// Load and parse a DTD, returning the resulting `xmlDtd` (detached from any
/// document).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDtdPtr xmlSAXParseDTD(xmlSAXHandlerPtr sax, const xmlChar *publicId,
///                          const xmlChar *systemId);
/// ```
///
/// # SAFETY
///
/// - `sax` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `publicId`, `systemId` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSAXParseDTD(
    sax: *mut _xmlSAXHandler,
    publicId: *const xmlChar,
    systemId: *const xmlChar,
) -> *mut _xmlDtd {
    if publicId.is_null() && systemId.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let ctxt = xmlNewSAXParserCtxt(sax, ptr::null_mut());
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        apply_options(ctxt, XML_PARSE_DTDLOAD);

        // Resolve via the SAX resolveEntity callback when available, else
        // load the system ID directly.
        let mut input = ptr::null_mut();
        if !sax.is_null() {
            if let Some(resolve) = (*sax).resolveEntity {
                input = resolve((*ctxt).userData, publicId, systemId);
            }
        }
        if input.is_null() {
            if systemId.is_null() {
                helpers::free_parser_ctxt(ctxt);
                return ptr::null_mut();
            }
            input = xmlLoadExternalEntity(systemId as *const c_char, ptr::null(), ctxt);
        }
        if input.is_null() {
            helpers::free_parser_ctxt(ctxt);
            return ptr::null_mut();
        }

        // Materialise the DTD text before freeing the input struct.
        let data: Vec<u8> = {
            let pi = &*input;
            if !pi.base.is_null() && !pi.end.is_null() && pi.end >= pi.base {
                let len = (pi.end as usize).saturating_sub(pi.base as usize);
                core::slice::from_raw_parts(pi.base, len).to_vec()
            } else if !pi.buf.is_null() {
                input_buffer_data(pi.buf)
            } else {
                Vec::new()
            }
        };
        helpers::free_parser_input(input);

        let dtd = parse_dtd_text(ctxt, &data, publicId, systemId);
        helpers::free_parser_ctxt(ctxt);
        dtd
    }
}

/// Load and parse a DTD from an input buffer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDtdPtr xmlIOParseDTD(xmlSAXHandlerPtr sax, xmlParserInputBufferPtr input,
///                         xmlCharEncoding enc);
/// ```
///
/// # SAFETY
///
/// - `sax`, `input` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlIOParseDTD(
    sax: *mut _xmlSAXHandler,
    input: *mut _xmlParserInputBuffer,
    enc: c_int,
) -> *mut _xmlDtd {
    if input.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let ctxt = xmlNewSAXParserCtxt(sax, ptr::null_mut());
        if ctxt.is_null() {
            io::input_buffer_free(input);
            return ptr::null_mut();
        }
        apply_options(ctxt, XML_PARSE_DTDLOAD);
        if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int {
            (*ctxt).charset = enc;
        }

        // Materialise the data from the input buffer.
        let data: Vec<u8> = input_buffer_data(input);
        io::input_buffer_free(input);

        let dtd = parse_dtd_text(ctxt, &data, ptr::null(), ptr::null());
        helpers::free_parser_ctxt(ctxt);
        dtd
    }
}

/// Extract the buffered data of an input buffer as an owned byte vector.
unsafe fn input_buffer_data(buf: *mut _xmlParserInputBuffer) -> Vec<u8> {
    unsafe {
        if buf.is_null() {
            return Vec::new();
        }
        let b = &*buf;
        if let Some(read) = b.readcallback {
            let mut out = Vec::new();
            let mut tmp = [0u8; 4096];
            loop {
                let n = read(
                    b.context,
                    tmp.as_mut_ptr() as *mut c_char,
                    tmp.len() as c_int,
                );
                if n <= 0 {
                    break;
                }
                out.extend_from_slice(&tmp[..n as usize]);
            }
            return out;
        }
        if !b.buffer.is_null() {
            let xbuf = &*(b.buffer as *mut _xmlBuffer);
            if !xbuf.content.is_null() && xbuf.use_ > 0 {
                return core::slice::from_raw_parts(xbuf.content, xbuf.use_ as usize).to_vec();
            }
        }
        Vec::new()
    }
}

/// Parse an external general entity and build a tree.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlSAXParseEntity(xmlSAXHandlerPtr sax, const char *filename);
/// ```
///
/// # SAFETY
///
/// - `sax` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlSAXParseEntity(
    sax: *mut _xmlSAXHandler,
    filename: *const c_char,
) -> *mut _xmlDoc {
    if filename.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        let ctxt = xmlNewSAXParserCtxt(sax, ptr::null_mut());
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        let input = match open_filename_routed(filename, ctxt) {
            RoutedFileOpen::Loaded(i) => i,
            RoutedFileOpen::Failed => {
                emit_io_warning(ctxt, io_load_failure_message(filename));
                helpers::free_parser_ctxt(ctxt);
                return ptr::null_mut();
            }
            RoutedFileOpen::EntityLoaderFailed => {
                helpers::free_parser_ctxt(ctxt);
                return ptr::null_mut();
            }
            RoutedFileOpen::Builtin => match helpers::input_from_file(filename) {
                Ok(i) => i,
                Err(_) => {
                    helpers::free_parser_ctxt(ctxt);
                    return ptr::null_mut();
                }
            },
        };
        helpers::setup_parser_input(ctxt, input);
        let rc = helpers::parse_document(ctxt);
        let doc = (*ctxt).myDoc;
        (*ctxt).myDoc = ptr::null_mut();
        if rc != 0 || (*ctxt).wellFormed == 0 {
            if !doc.is_null() {
                tree::free_doc(doc);
            }
            helpers::free_parser_ctxt(ctxt);
            return ptr::null_mut();
        }
        helpers::free_parser_ctxt(ctxt);
        doc
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// C14N: xmlC14NDocSave
// ═══════════════════════════════════════════════════════════════════════════════

/// Canonicalise a document (or node set) and save it to a file.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlC14NDocSave(xmlDocPtr doc, xmlNodeSetPtr nodes, int mode,
///                    xmlChar **inclusive_ns_prefixes, int with_comments,
///                    const char *filename, int compression);
/// ```
///
/// # SAFETY
///
/// - `doc`, `nodes`, `inclusive_ns_prefixes` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `filename` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlC14NDocSave(
    doc: *mut _xmlDoc,
    nodes: *mut _xmlNodeSet,
    mode: c_int,
    inclusive_ns_prefixes: *mut *mut xmlChar,
    with_comments: c_int,
    filename: *const c_char,
    compression: c_int,
) -> c_int {
    if filename.is_null() {
        return -1;
    }
    unsafe {
        let output = io::output_buffer_create_filename(filename, ptr::null_mut(), compression);
        if output.is_null() {
            return -1;
        }
        let ret = crate::xml::c14n::xmlC14NDocSaveTo(
            doc,
            nodes,
            mode,
            inclusive_ns_prefixes,
            with_comments,
            output,
        );
        if ret < 0 {
            io::output_buffer_close(output);
            return -1;
        }
        let close_ret = io::output_buffer_close(output);
        if close_ret < 0 {
            -1
        } else {
            ret
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A read-callback state pair mirroring PHP's streams IO loader: the
    /// registered `xmlParserInputBufferCreateFilenameDefault` serves bytes
    /// through an `xmlParserInputBufferCreateIO` buffer (php builds exactly
    /// this shape with php_libxml_streams_IO_read/close over a php_stream).
    /// The loader reaches the state through a thread-local pointer (the
    /// loader slot itself is per-thread TLS, so there is no cross-thread
    /// aliasing).
    struct ServeState {
        data: &'static [u8],
        pos: usize,
        closed: bool,
    }

    thread_local! {
        static SERVE_STATE: std::cell::Cell<*mut ServeState> =
            std::cell::Cell::new(std::ptr::null_mut());
    }

    unsafe extern "C" fn serve_read(ctx: *mut c_void, buffer: *mut c_char, len: c_int) -> c_int {
        // SAFETY: ctx is the ServeState set up by the test; buffer is a
        // writable len-byte region per the xmlInputReadCallback contract.
        let st = unsafe { &mut *(ctx as *mut ServeState) };
        if st.pos >= st.data.len() {
            return 0;
        }
        let n = (len as usize).min(st.data.len() - st.pos);
        unsafe {
            core::ptr::copy_nonoverlapping(st.data.as_ptr().add(st.pos), buffer as *mut u8, n);
        }
        st.pos += n;
        n as c_int
    }

    unsafe extern "C" fn serve_close(ctx: *mut c_void) -> c_int {
        // SAFETY: ctx is the ServeState set up by the test.
        let st = unsafe { &mut *(ctx as *mut ServeState) };
        st.closed = true;
        0
    }

    /// The php-shaped loader: build an IO buffer over the thread-local serve
    /// state. `uri` is deliberately ignored — php's loader opens whatever the
    /// php streams layer resolves, so a "file://" URI or a non-existent path
    /// both reach the stream; this guard proves the ENGINE consults the
    /// loader instead of the built-in path (which would fail on the bogus
    /// URI used here).
    unsafe extern "C" fn serving_loader(
        _uri: *const c_char,
        _enc: c_int,
    ) -> *mut _xmlParserInputBuffer {
        SERVE_STATE.with(|cell| {
            let st = cell.get();
            if st.is_null() {
                return ptr::null_mut();
            }
            crate::abi::exports_xml2::xmlParserInputBufferCreateIO(
                Some(serve_read as xmlInputReadCallback),
                Some(serve_close as xmlInputCloseCallback),
                st as *mut c_void,
                xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int,
            )
        })
    }

    unsafe extern "C" fn record_message(ctx: *mut c_void, err: *const _xmlError) {
        if err.is_null() {
            return;
        }
        // SAFETY: ctx is the recording Vec set up by the test; the error is
        // live for the call and its message is NUL-terminated.
        let out = unsafe { &mut *(ctx as *mut Vec<u8>) };
        let msg = unsafe { (*err).message };
        if !msg.is_null() {
            // SAFETY: message is a NUL-terminated C string for the call.
            let bytes = unsafe { std::ffi::CStr::from_ptr(msg) }.to_bytes();
            out.extend_from_slice(bytes);
        }
    }

    /// SP-14.3.2 S8 / dom-L2 (bug79971_1): a registered
    /// `xmlParserInputBufferCreateFilenameDefault` (PHP's streams loader) is
    /// consulted by the main-document file open (`xmlReadFile`/
    /// `xmlCtxtReadFile` -> xmlNewInputFromFile -> xmlNewInputFromUrl): its
    /// bytes are parsed even when the URI is not a real file, and a NULL
    /// loader result reports the xmlCtxtErrIO "failed to load" warning with
    /// NO built-in fallback.
    ///
    /// # Safety
    ///
    /// - the callbacks and stack state are valid for the duration of each
    ///   call; the loader/generic-handler TLS slots are restored before the
    ///   test ends (serialized via the error-handler test lock).
    #[test]
    fn test_main_doc_open_consults_registered_input_loader() {
        use crate::xml::globals::ERROR_HANDLER_TEST_LOCK;

        // Serialize against the handler-slot tests (the generic func slot is
        // shared global state); the loader slot is this thread's TLS but it
        // is restored so later engine state stays pristine.
        let _guard = ERROR_HANDLER_TEST_LOCK.lock();
        let old_loader = globals::get_parser_input_buffer_create_filename_value();
        let old_struct = globals::get_structured_error_func();
        let old_struct_ctx = globals::get_structured_error_ctx();

        let mut captured: Vec<u8> = Vec::new();
        let captured_ptr = &mut captured as *mut Vec<u8> as *mut c_void;
        // SAFETY: set/restore of the handler slots is serialized under
        // ERROR_HANDLER_TEST_LOCK for the test's duration.
        unsafe {
            globals::set_structured_error_func(
                captured_ptr,
                Some(record_message as xmlStructuredErrorFunc),
            );
        }

        unsafe {
            let mut serve = ServeState {
                data: b"<root><a>1</a></root>",
                pos: 0,
                closed: false,
            };
            SERVE_STATE.with(|cell| cell.set(&mut serve as *mut ServeState));
            globals::set_parser_input_buffer_create_filename_value(Some(serving_loader));

            // The URI names no real file — only the loader can satisfy it.
            let ctxt = helpers::create_parser_ctxt();
            assert!(!ctxt.is_null());
            let doc = xmlCtxtReadFile(
                ctxt,
                c"file:///definitely-not-a-file.xml".as_ptr(),
                ptr::null(),
                0,
            );
            assert!(
                !doc.is_null(),
                "registered loader must be consulted for the main document open"
            );
            let root = (*doc).children;
            assert!(
                !root.is_null() && !(*root).name.is_null(),
                "served document must produce a root element"
            );
            assert_eq!(
                crate::xml::string::xmlstr_to_bytes((*root).name as *const u8),
                b"root",
                "document served by the loader must be parsed"
            );
            assert!(serve.closed, "loader stream must be closed exactly once");
            tree::free_doc(doc);
            helpers::free_parser_ctxt(ctxt);

            // A loader result of NULL is XML_IO_ENOENT: the built-in open is
            // NOT attempted and the xmlCtxtErrIO ENOENT report ("failed to
            // load") reaches the structured handler.
            globals::set_parser_input_buffer_create_filename_value(None);
            SERVE_STATE.with(|cell| cell.set(ptr::null_mut()));
            unsafe extern "C" fn null_loader(
                _uri: *const c_char,
                _enc: c_int,
            ) -> *mut _xmlParserInputBuffer {
                ptr::null_mut()
            }
            globals::set_parser_input_buffer_create_filename_value(Some(null_loader));
            let ctxt2 = helpers::create_parser_ctxt();
            assert!(!ctxt2.is_null());
            let doc2 = xmlCtxtReadFile(
                ctxt2,
                c"file:///definitely-not-a-file.xml".as_ptr(),
                ptr::null(),
                0,
            );
            assert!(doc2.is_null(), "NULL loader result must fail the open");
            let got = String::from_utf8_lossy(&captured);
            assert!(
                got.contains("failed to load"),
                "xmlCtxtErrIO report must reach the error channel: {got:?}"
            );
            helpers::free_parser_ctxt(ctxt2);
        }

        // Restore both slots.
        unsafe {
            globals::set_parser_input_buffer_create_filename_value(old_loader);
            globals::set_structured_error_func(old_struct_ctx, old_struct);
        }
    }
}