libxml-rs 0.1.0-alpha.4

Phase 3: I/O, encoding, URI, catalog, serialization, HTML. Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. 357 tests passing, full encoding subsystem, URI parser, OASIS catalog, HTML parser/serializer, tree serialization, custom I/O buffers.
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
//! Custom I/O and resource loaders (§59, §85 Phase 4).
//!
//! Input/output callback infrastructure: buffers, file I/O, encoding
//! integration, input/output buffer management, and helper utilities.
//!
//! This module implements the libxml2 I/O subsystem in native Rust.
//! No C dependencies beyond `libc` for file operations.

#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_ptr_alignment,
    clippy::missing_safety_doc
)]

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

use libc;

use crate::abi::allocator::{xmlFree, xmlMalloc, xmlRealloc};
use crate::abi::callbacks::{
    xmlInputCloseCallback, xmlInputReadCallback, xmlOutputCloseCallback, xmlOutputWriteCallback,
};
use crate::abi::structs::{
    _xmlBuf, _xmlBuffer, _xmlCharEncodingHandler, _xmlOutputBuffer, _xmlParserInputBuffer,
};
use crate::abi::types::{xmlChar, xmlCharEncoding, xmlCharPtr};
use crate::xml::encoding;

// ═══════════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════════

/// Default buffer size for new buffers.
const DEFAULT_BUFFER_SIZE: c_uint = 4000;

/// Minimum buffer size.
const MIN_BUFFER_SIZE: c_uint = 256;

/// Buffer allocation scheme: double the size on growth.
const XML_BUFFER_ALLOC_DOUBLEIT: c_int = 0;

/// Buffer allocation scheme: exact size on growth.
const XML_BUFFER_ALLOC_EXACT: c_int = 1;

/// Buffer allocation scheme: immutable (no growth, no free of content).
const XML_BUFFER_ALLOC_IMMUTABLE: c_int = 2;

// ═══════════════════════════════════════════════════════════════════════════════
// 1. xmlBuffer operations (deprecated)
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a new xmlBuffer with the given initial size.
///
/// If `size` <= 0, a default buffer size is used.
/// The buffer content is initialized to an empty null-terminated string.
///
/// Returns a pointer to the new buffer, or NULL on allocation failure.
pub(crate) fn buf_create(size: c_int) -> *mut _xmlBuffer {
    let buf_size = if size <= 0 {
        DEFAULT_BUFFER_SIZE
    } else {
        size as c_uint
    };

    // Ensure minimum size
    let buf_size = buf_size.max(MIN_BUFFER_SIZE);

    let buf = unsafe { xmlMalloc(size_of::<_xmlBuffer>()) as *mut _xmlBuffer };
    if buf.is_null() {
        return ptr::null_mut();
    }

    let content = unsafe { xmlMalloc(buf_size as usize) as *mut xmlChar };
    if content.is_null() {
        unsafe { xmlFree(buf as *mut c_void) };
        return ptr::null_mut();
    }

    // Initialize: null-terminate the empty buffer
    unsafe {
        ptr::write(content, 0);
    }

    unsafe {
        ptr::write(
            buf,
            _xmlBuffer {
                content,
                use_: 0,
                size: buf_size,
                alloc: XML_BUFFER_ALLOC_DOUBLEIT,
                contentIO: content, // Track original allocation for I/O mode
            },
        );
    }

    buf
}

/// Create a new xmlBuffer from a static string.
///
/// The buffer's content points directly to `str` (no copy is made).
/// The buffer's allocation scheme is set to IMMUTABLE, meaning the
/// content will not be freed when the buffer is freed.
///
/// If `size` <= 0, the length is determined by `xmlStrlen` (scanning for null).
pub(crate) fn buf_create_static(str: *const xmlChar, size: c_int) -> *mut _xmlBuffer {
    if str.is_null() {
        return ptr::null_mut();
    }

    let len = if size <= 0 {
        // Calculate length by scanning for null terminator
        let mut len: c_uint = 0;
        unsafe {
            while *str.add(len as usize) != 0 {
                len += 1;
            }
        }
        len
    } else {
        size as c_uint
    };

    let buf = unsafe { xmlMalloc(size_of::<_xmlBuffer>()) as *mut _xmlBuffer };
    if buf.is_null() {
        return ptr::null_mut();
    }

    unsafe {
        ptr::write(
            buf,
            _xmlBuffer {
                content: str as *mut xmlChar,
                use_: len,
                size: len + 1, // Include space for null terminator
                alloc: XML_BUFFER_ALLOC_IMMUTABLE,
                contentIO: ptr::null_mut(),
            },
        );
    }

    buf
}

/// Free an xmlBuffer.
///
/// If the buffer's allocation scheme is not IMMUTABLE, the content is freed.
/// The contentIO pointer (if non-NULL and different from content) is also freed.
pub(crate) fn buf_free(buf: *mut _xmlBuffer) {
    if buf.is_null() {
        return;
    }

    unsafe {
        let alloc = (*buf).alloc;
        let content = (*buf).content;
        let content_io = (*buf).contentIO;

        if alloc != XML_BUFFER_ALLOC_IMMUTABLE {
            // contentIO is the original allocation base (set in I/O mode).
            // content may have been advanced during reads.
            // Free the base pointer, not the possibly-advanced content.
            let base = if !content_io.is_null() {
                content_io
            } else {
                content
            };
            if !base.is_null() {
                xmlFree(base as *mut c_void);
            }
        }

        xmlFree(buf as *mut c_void);
    }
}

/// Empty an xmlBuffer (reset `use_` to 0).
///
/// The content is kept allocated but the first byte is set to null terminator.
pub(crate) fn buf_empty(buf: *mut _xmlBuffer) {
    if buf.is_null() {
        return;
    }

    unsafe {
        (*buf).use_ = 0;
        if !(*buf).content.is_null() {
            ptr::write((*buf).content, 0);
        }
    }
}

/// Get the content of an xmlBuffer.
pub(crate) fn buf_content(buf: *mut _xmlBuffer) -> *mut xmlChar {
    if buf.is_null() {
        return ptr::null_mut();
    }
    unsafe { (*buf).content }
}

/// Get the used length of an xmlBuffer.
pub(crate) fn buf_length(buf: *mut _xmlBuffer) -> c_int {
    if buf.is_null() {
        return -1;
    }
    unsafe { (*buf).use_ as c_int }
}

/// Write `len` bytes from `str` to an xmlBuffer.
///
/// Grows the buffer if needed. Always maintains null termination.
/// Returns the number of bytes written, or -1 on error.
pub(crate) fn buf_add(buf: *mut _xmlBuffer, str: *const xmlChar, len: c_int) -> c_int {
    if buf.is_null() || str.is_null() || len <= 0 {
        return 0;
    }

    let len = len as c_uint;
    let b = unsafe { &mut *buf };

    // IMMUTABLE buffers cannot be written to
    if b.alloc == XML_BUFFER_ALLOC_IMMUTABLE {
        return -1;
    }

    // Ensure capacity: need use_ + len + 1 (for null terminator)
    let needed = b.use_.saturating_add(len).saturating_add(1);
    if needed > b.size {
        // Grow buffer
        let new_size = if b.alloc == XML_BUFFER_ALLOC_EXACT {
            needed
        } else {
            // DOUBLEIT or default: double until big enough
            let mut doubled = b.size.saturating_mul(2).max(MIN_BUFFER_SIZE);
            while doubled < needed {
                doubled = doubled.saturating_mul(2);
            }
            doubled
        };

        let new_content =
            unsafe { xmlRealloc(b.content as *mut c_void, new_size as usize) as *mut xmlChar };
        if new_content.is_null() {
            return -1;
        }
        b.content = new_content;
        b.contentIO = new_content; // Track reallocated base
        b.size = new_size;
    }

    // Copy data
    unsafe {
        ptr::copy_nonoverlapping(str, b.content.add(b.use_ as usize), len as usize);
    }
    b.use_ = b.use_.saturating_add(len);

    // Null-terminate
    unsafe {
        ptr::write(b.content.add(b.use_ as usize), 0);
    }

    len as c_int
}

/// Cat a null-terminated string to an xmlBuffer.
pub(crate) fn buf_cat(buf: *mut _xmlBuffer, str: *const xmlChar) -> c_int {
    if buf.is_null() || str.is_null() {
        return -1;
    }

    // Calculate length of the null-terminated string
    let len = unsafe {
        let mut i: c_uint = 0;
        while *str.add(i as usize) != 0 {
            i += 1;
        }
        i
    };

    buf_add(buf, str, len as c_int)
}

/// Write a single character to an xmlBuffer.
pub(crate) fn buf_ccat(buf: *mut _xmlBuffer, c: xmlChar) -> c_int {
    buf_add(buf, &c as *const xmlChar, 1)
}

/// Shrink an xmlBuffer by `len` bytes from the end.
///
/// If `len` exceeds the used length, the buffer is emptied.
/// Returns the new used length, or -1 on error.
pub(crate) fn buf_shrink(buf: *mut _xmlBuffer, len: c_uint) -> c_int {
    if buf.is_null() {
        return -1;
    }

    let b = unsafe { &mut *buf };
    if b.use_ == 0 {
        return 0;
    }

    b.use_ = if len >= b.use_ { 0 } else { b.use_ - len };

    // Null-terminate
    unsafe {
        ptr::write(b.content.add(b.use_ as usize), 0);
    }

    b.use_ as c_int
}

/// Grow an xmlBuffer to at least `size` bytes of capacity.
///
/// Returns 0 on success, -1 on failure.
/// Add data at the head of a buffer.
///
/// Returns 0 on success, -1 on error.
pub(crate) fn buf_add_head(buf: *mut _xmlBuffer, str: *const xmlChar, len: c_int) -> c_int {
    if buf.is_null() || str.is_null() || len <= 0 {
        return -1;
    }
    let len = len as c_uint;
    unsafe {
        let b = &mut *buf;
        let needed = b.use_.saturating_add(len).saturating_add(1);
        if needed > b.size {
            let new_size = needed.saturating_mul(2).max(MIN_BUFFER_SIZE);
            let new_content =
                xmlRealloc(b.content as *mut c_void, new_size as usize) as *mut xmlChar;
            if new_content.is_null() {
                return -1;
            }
            b.content = new_content;
            b.contentIO = new_content;
            b.size = new_size;
        }
        // Shift existing content right by len bytes
        if b.use_ > 0 {
            core::ptr::copy(b.content, b.content.add(len as usize), b.use_ as usize);
        }
        // Copy new content to the beginning
        core::ptr::copy_nonoverlapping(str, b.content, len as usize);
        b.use_ = b.use_.saturating_add(len);
        *b.content.add(b.use_ as usize) = 0;
    }
    0
}

pub(crate) fn buf_grow(buf: *mut _xmlBuffer, size: c_uint) -> c_int {
    if buf.is_null() {
        return -1;
    }

    let b = unsafe { &mut *buf };

    if size <= b.size {
        return 0; // Already big enough
    }

    let new_content =
        unsafe { xmlRealloc(b.content as *mut c_void, size as usize) as *mut xmlChar };
    if new_content.is_null() {
        return -1;
    }

    b.content = new_content;
    b.contentIO = new_content;
    b.size = size;

    0
}

// ═══════════════════════════════════════════════════════════════════════════════
// 2. xmlBuf operations (modern replacement)
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a new xmlBuf with the given initial size.
///
/// If `size` <= 0, a default buffer size is used.
/// Returns a pointer to the new buffer, or NULL on allocation failure.
pub(crate) fn xml_buf_create(size: c_int) -> *mut _xmlBuf {
    let buf_size = if size <= 0 {
        DEFAULT_BUFFER_SIZE
    } else {
        size as c_uint
    };
    let buf_size = buf_size.max(MIN_BUFFER_SIZE);

    let buf = unsafe { xmlMalloc(size_of::<_xmlBuf>()) as *mut _xmlBuf };
    if buf.is_null() {
        return ptr::null_mut();
    }

    let content = unsafe { xmlMalloc(buf_size as usize) as *mut xmlChar };
    if content.is_null() {
        unsafe { xmlFree(buf as *mut c_void) };
        return ptr::null_mut();
    }

    unsafe {
        ptr::write(content, 0);
    }

    unsafe {
        ptr::write(
            buf,
            _xmlBuf {
                content,
                use_: 0,
                size: buf_size,
                alloc: XML_BUFFER_ALLOC_DOUBLEIT,
                error: 0,
                buffer: 0,
                io: 0,
            },
        );
    }

    buf
}

/// Free an xmlBuf.
///
/// Frees the content and the buffer struct itself.
pub(crate) fn xml_buf_free(buf: *mut _xmlBuf) {
    if buf.is_null() {
        return;
    }

    unsafe {
        if !(*buf).content.is_null() {
            xmlFree((*buf).content as *mut c_void);
        }
        xmlFree(buf as *mut c_void);
    }
}

/// Get the content of an xmlBuf.
pub(crate) fn xml_buf_content(buf: *mut _xmlBuf) -> *mut xmlChar {
    if buf.is_null() {
        return ptr::null_mut();
    }
    unsafe { (*buf).content }
}

/// Get the used length of an xmlBuf.
pub(crate) fn xml_buf_length(buf: *mut _xmlBuf) -> c_int {
    if buf.is_null() {
        return -1;
    }
    unsafe { (*buf).use_ as c_int }
}

/// Add `len` bytes from `str` to an xmlBuf.
///
/// Returns the number of bytes added, or -1 on error.
pub(crate) fn xml_buf_add(buf: *mut _xmlBuf, str: *const xmlChar, len: c_int) -> c_int {
    if buf.is_null() || str.is_null() || len <= 0 {
        return 0;
    }

    let len = len as c_uint;
    let b = unsafe { &mut *buf };

    let needed = b.use_.saturating_add(len).saturating_add(1);
    if needed > b.size {
        let new_size = needed.saturating_mul(2).max(MIN_BUFFER_SIZE);
        let new_content =
            unsafe { xmlRealloc(b.content as *mut c_void, new_size as usize) as *mut xmlChar };
        if new_content.is_null() {
            return -1;
        }
        b.content = new_content;
        b.size = new_size;
    }

    unsafe {
        ptr::copy_nonoverlapping(str, b.content.add(b.use_ as usize), len as usize);
    }
    b.use_ = b.use_.saturating_add(len);

    unsafe {
        ptr::write(b.content.add(b.use_ as usize), 0);
    }

    len as c_int
}

/// Cat a null-terminated string to an xmlBuf.
pub(crate) fn xml_buf_cat(buf: *mut _xmlBuf, str: *const xmlChar) -> c_int {
    if buf.is_null() || str.is_null() {
        return -1;
    }

    let len = unsafe {
        let mut i: c_uint = 0;
        while *str.add(i as usize) != 0 {
            i += 1;
        }
        i
    };

    xml_buf_add(buf, str, len as c_int)
}

/// Grow an xmlBuf to at least `size` bytes of capacity.
///
/// Returns 0 on success, -1 on failure.
pub(crate) fn xml_buf_grow(buf: *mut _xmlBuf, size: c_uint) -> c_int {
    if buf.is_null() {
        return -1;
    }

    let b = unsafe { &mut *buf };
    if size <= b.size {
        return 0;
    }

    let new_content =
        unsafe { xmlRealloc(b.content as *mut c_void, size as usize) as *mut xmlChar };
    if new_content.is_null() {
        return -1;
    }

    b.content = new_content;
    b.size = size;
    0
}

/// Shrink an xmlBuf by `len` bytes from the end.
///
/// Returns the new used length, or -1 on error.
pub(crate) fn xml_buf_shrink(buf: *mut _xmlBuf, len: c_uint) -> c_int {
    if buf.is_null() {
        return -1;
    }

    let b = unsafe { &mut *buf };
    if b.use_ == 0 {
        return 0;
    }

    b.use_ = if len >= b.use_ { 0 } else { b.use_ - len };

    unsafe {
        ptr::write(b.content.add(b.use_ as usize), 0);
    }

    b.use_ as c_int
}

// ═══════════════════════════════════════════════════════════════════════════════
// 3. Input buffer operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Convert a `c_int` encoding value to an `xmlCharEncoding` enum.
fn encoding_from_int(enc: c_int) -> xmlCharEncoding {
    match enc {
        -1 => xmlCharEncoding::XML_CHAR_ENCODING_ERROR,
        0 => xmlCharEncoding::XML_CHAR_ENCODING_NONE,
        1 => xmlCharEncoding::XML_CHAR_ENCODING_UTF8,
        2 => xmlCharEncoding::XML_CHAR_ENCODING_UTF16LE,
        3 => xmlCharEncoding::XML_CHAR_ENCODING_UTF16BE,
        4 => xmlCharEncoding::XML_CHAR_ENCODING_UCS4LE,
        5 => xmlCharEncoding::XML_CHAR_ENCODING_UCS4BE,
        6 => xmlCharEncoding::XML_CHAR_ENCODING_EBCDIC,
        7 => xmlCharEncoding::XML_CHAR_ENCODING_UCS4_2143,
        8 => xmlCharEncoding::XML_CHAR_ENCODING_UCS4_3412,
        9 => xmlCharEncoding::XML_CHAR_ENCODING_UCS2,
        10 => xmlCharEncoding::XML_CHAR_ENCODING_8859_1,
        11 => xmlCharEncoding::XML_CHAR_ENCODING_8859_2,
        12 => xmlCharEncoding::XML_CHAR_ENCODING_8859_3,
        13 => xmlCharEncoding::XML_CHAR_ENCODING_8859_4,
        14 => xmlCharEncoding::XML_CHAR_ENCODING_8859_5,
        15 => xmlCharEncoding::XML_CHAR_ENCODING_8859_6,
        16 => xmlCharEncoding::XML_CHAR_ENCODING_8859_7,
        17 => xmlCharEncoding::XML_CHAR_ENCODING_8859_8,
        18 => xmlCharEncoding::XML_CHAR_ENCODING_8859_9,
        19 => xmlCharEncoding::XML_CHAR_ENCODING_2022_JP,
        20 => xmlCharEncoding::XML_CHAR_ENCODING_SHIFT_JIS,
        21 => xmlCharEncoding::XML_CHAR_ENCODING_EUC_JP,
        22 => xmlCharEncoding::XML_CHAR_ENCODING_ASCII,
        _ => xmlCharEncoding::XML_CHAR_ENCODING_ERROR,
    }
}

/// Find an encoding handler for the given encoding integer.
///
/// Returns a pointer to the handler, or NULL if not found or if the
/// encoding is NONE or UTF-8 (which don't need conversion).
fn find_handler_for_encoding(enc: c_int) -> *mut _xmlCharEncodingHandler {
    let enc_enum = encoding_from_int(enc);
    if enc_enum == xmlCharEncoding::XML_CHAR_ENCODING_NONE
        || enc_enum == xmlCharEncoding::XML_CHAR_ENCODING_UTF8
        || enc_enum == xmlCharEncoding::XML_CHAR_ENCODING_ERROR
    {
        return ptr::null_mut();
    }

    // Get the encoding name and create a null-terminated version for lookup
    if let Some(name) = encoding::encoding_name(enc_enum) {
        // Create a null-terminated copy on the stack if small, or heap
        let mut name_nul = name.to_vec();
        name_nul.push(0);
        let handler = encoding::find_encoding_handler(name_nul.as_ptr() as *const xmlChar);
        if !handler.is_null() {
            return handler;
        }
    }

    ptr::null_mut()
}

/// Internal helper: create an _xmlParserInputBuffer struct.
///
/// Allocates the struct and initializes all fields to zero/NULL.
/// The caller is responsible for setting the specific fields.
fn allocate_input_buffer() -> *mut _xmlParserInputBuffer {
    let buf =
        unsafe { xmlMalloc(size_of::<_xmlParserInputBuffer>()) as *mut _xmlParserInputBuffer };
    if buf.is_null() {
        return ptr::null_mut();
    }

    unsafe {
        ptr::write(
            buf,
            _xmlParserInputBuffer {
                context: ptr::null_mut(),
                readcallback: None,
                closecallback: None,
                encoder: ptr::null_mut(),
                buffer: ptr::null_mut(),
                raw: ptr::null_mut(),
                compressed: 0,
                error: 0,
                rawconsumed: 0,
            },
        );
    }

    buf
}

/// Create an input buffer from memory.
///
/// The data is copied into the input buffer's internal storage.
/// If `enc` specifies a non-UTF-8 encoding, the data is converted to UTF-8.
pub(crate) fn input_buffer_create_mem(
    buffer: *const c_char,
    size: c_int,
    enc: c_int,
) -> *mut _xmlParserInputBuffer {
    if buffer.is_null() || size <= 0 {
        return ptr::null_mut();
    }

    let buf = allocate_input_buffer();
    if buf.is_null() {
        return ptr::null_mut();
    }

    // Create the raw buffer containing the input data
    let raw_buf = buf_create(size);
    if raw_buf.is_null() {
        unsafe { xmlFree(buf as *mut c_void) };
        return ptr::null_mut();
    }

    // Copy data into the raw buffer
    buf_add(raw_buf, buffer as *const xmlChar, size);

    // Check if encoding conversion is needed
    let handler = find_handler_for_encoding(enc);
    if !handler.is_null() {
        // Encoding conversion needed
        // Create the output (UTF-8) buffer
        let out_buf = buf_create((size as c_uint).saturating_mul(3).max(MIN_BUFFER_SIZE) as c_int);
        if out_buf.is_null() {
            buf_free(raw_buf);
            unsafe { xmlFree(buf as *mut c_void) };
            return ptr::null_mut();
        }

        // Convert raw data to UTF-8
        let written = encoding::char_enc_in(handler, out_buf, raw_buf);
        if written < 0 {
            buf_free(raw_buf);
            buf_free(out_buf);
            unsafe { xmlFree(buf as *mut c_void) };
            return ptr::null_mut();
        }

        unsafe {
            (*buf).encoder = handler as *mut c_void;
            (*buf).buffer = out_buf as *mut c_void;
            (*buf).raw = raw_buf as *mut c_void;
        }
    } else {
        // No encoding conversion needed — data is (or will be treated as) UTF-8
        unsafe {
            (*buf).buffer = raw_buf as *mut c_void;
            (*buf).raw = raw_buf as *mut c_void;
        }
    }

    buf
}

// ── File I/O callbacks ──────────────────────────────────────────────────────

/// Read callback for file descriptor-based input.
unsafe extern "C" fn file_read_callback(
    context: *mut c_void,
    buffer: *mut c_char,
    len: c_int,
) -> c_int {
    if context.is_null() || buffer.is_null() || len <= 0 {
        return -1;
    }

    let fd = context as c_int;
    let ret = libc::read(fd, buffer as *mut c_void, len as usize);
    if ret < 0 {
        return -1;
    }
    ret as c_int
}

/// Close callback for file descriptor-based input.
unsafe extern "C" fn file_close_callback(context: *mut c_void) -> c_int {
    if context.is_null() {
        return -1;
    }

    let fd = context as c_int;
    libc::close(fd)
}

/// Create an input buffer from a file.
///
/// Opens the file, reads its contents into memory, and creates a memory-based
/// input buffer. The file is closed after reading.
pub(crate) fn input_buffer_create_file(
    filename: *const c_char,
    enc: c_int,
) -> *mut _xmlParserInputBuffer {
    if filename.is_null() {
        return ptr::null_mut();
    }

    // Get filename as a Rust string
    let filename_str = unsafe {
        match CStr::from_ptr(filename).to_str() {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        }
    };

    // Open the file
    let fd = unsafe {
        let path_c = std::ffi::CString::new(filename_str).unwrap_or_default();
        libc::open(path_c.as_ptr(), libc::O_RDONLY)
    };

    if fd < 0 {
        return ptr::null_mut();
    }

    // Stat the file to get its size
    let mut stat_buf: libc::stat = unsafe { std::mem::zeroed() };
    let stat_ret = unsafe {
        let path_c = std::ffi::CString::new(filename_str).unwrap_or_default();
        libc::stat(path_c.as_ptr(), &mut stat_buf)
    };

    let file_size = if stat_ret == 0 {
        stat_buf.st_size as usize
    } else {
        // Fall back to reading in chunks
        0
    };

    // Read the file contents
    let read_size = if file_size > 0 {
        file_size
    } else {
        4096 // Default chunk
    };

    let mut data = vec![0u8; read_size];
    let mut total_read: isize = 0;

    loop {
        let remaining = read_size.saturating_sub(total_read as usize);
        if remaining == 0 {
            // Grow buffer
            let new_size = read_size.saturating_mul(2);
            data.resize(new_size, 0u8);
        }

        let ret = unsafe {
            libc::read(
                fd,
                data.as_mut_ptr().add(total_read as usize) as *mut c_void,
                remaining,
            )
        };

        if ret < 0 {
            // Error
            unsafe { libc::close(fd) };
            return ptr::null_mut();
        }

        if ret == 0 {
            // EOF
            break;
        }

        total_read += ret as isize;
    }

    unsafe { libc::close(fd) };

    data.truncate(total_read as usize);

    if data.is_empty() {
        return ptr::null_mut();
    }

    // Create a memory-based input buffer from the data
    input_buffer_create_mem(data.as_ptr() as *const c_char, data.len() as c_int, enc)
}

/// Create an input buffer from I/O callbacks.
///
/// The `ioread` callback is called to fill the raw buffer.
/// The `ioclose` callback is called when the buffer is freed.
pub(crate) fn input_buffer_create_io(
    ioread: Option<xmlInputReadCallback>,
    ioclose: Option<xmlInputCloseCallback>,
    ioctx: *mut c_void,
    enc: c_int,
) -> *mut _xmlParserInputBuffer {
    let buf = allocate_input_buffer();
    if buf.is_null() {
        return ptr::null_mut();
    }

    // Create the raw buffer (used for reading from callback)
    let raw_buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if raw_buf.is_null() {
        unsafe { xmlFree(buf as *mut c_void) };
        return ptr::null_mut();
    }

    unsafe {
        (*buf).context = ioctx;
        (*buf).readcallback = ioread;
        (*buf).closecallback = ioclose;
        (*buf).raw = raw_buf as *mut c_void;
    }

    // Set up encoder if needed
    let handler = find_handler_for_encoding(enc);
    if !handler.is_null() {
        let out_buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
        if out_buf.is_null() {
            buf_free(raw_buf);
            unsafe { xmlFree(buf as *mut c_void) };
            return ptr::null_mut();
        }
        unsafe {
            (*buf).encoder = handler as *mut c_void;
            (*buf).buffer = out_buf as *mut c_void;
        }
    } else {
        unsafe {
            (*buf).buffer = raw_buf as *mut c_void;
        }
    }

    buf
}

/// Create an input buffer from a file descriptor.
///
/// The buffer uses read/close callbacks that wrap `libc::read` and `libc::close`.
pub(crate) fn input_buffer_create_fd(fd: c_int, enc: c_int) -> *mut _xmlParserInputBuffer {
    if fd < 0 {
        return ptr::null_mut();
    }

    input_buffer_create_io(
        Some(file_read_callback as xmlInputReadCallback),
        Some(file_close_callback as xmlInputCloseCallback),
        fd as *mut c_void,
        enc,
    )
}

/// Free an input buffer.
///
/// Calls the close callback if one is set, frees all internal buffers,
/// then frees the input buffer struct itself.
pub(crate) fn input_buffer_free(buf: *mut _xmlParserInputBuffer) {
    if buf.is_null() {
        return;
    }

    unsafe {
        // Call the close callback if one is set
        if let Some(close_cb) = (*buf).closecallback {
            close_cb((*buf).context);
        }

        // Free the raw buffer
        if !(*buf).raw.is_null() {
            buf_free((*buf).raw as *mut _xmlBuffer);
        }

        // Free the (converted) buffer if different from raw
        if !(*buf).buffer.is_null() && (*buf).buffer != (*buf).raw {
            buf_free((*buf).buffer as *mut _xmlBuffer);
        }

        // Note: the encoder is owned by the encoding module, not by us.
        // We do NOT free it here.

        xmlFree(buf as *mut c_void);
    }
}

/// Read from an input buffer.
///
/// If the buffer has a read callback, the callback is called to fill the raw
/// buffer, then the data is converted (if an encoder is set) and copied to
/// `buffer`. If no read callback is set (memory-based input), data is read
/// directly from the internal buffer.
///
/// Returns the number of bytes read, or -1 on error.
pub(crate) fn input_buffer_read(
    buf: *mut _xmlParserInputBuffer,
    buffer: *mut c_char,
    len: c_int,
) -> c_int {
    if buf.is_null() || buffer.is_null() || len <= 0 {
        return -1;
    }

    let b = unsafe { &mut *buf };

    if b.error != 0 {
        return -1;
    }

    if let Some(read_cb) = b.readcallback {
        // Callback-based input: read into raw buffer, then convert
        // Read a chunk
        let raw_buf = b.raw as *mut _xmlBuffer;
        if raw_buf.is_null() {
            return -1;
        }

        // Read up to `len` bytes into a temporary buffer
        let mut tmp = vec![0u8; len as usize];
        let ret = unsafe { read_cb(b.context, tmp.as_mut_ptr() as *mut c_char, len) };

        if ret < 0 {
            b.error = 1;
            return -1;
        }

        if ret == 0 {
            // EOF
            return 0;
        }

        // Add read data to raw buffer
        buf_add(raw_buf, tmp.as_ptr() as *const xmlChar, ret);

        // If encoder is set, convert raw -> buffer
        if !b.encoder.is_null() {
            let out_buf = b.buffer as *mut _xmlBuffer;
            if out_buf.is_null() {
                return -1;
            }

            let handler = b.encoder as *mut _xmlCharEncodingHandler;
            let conv_ret = encoding::char_enc_in(handler, out_buf, raw_buf);
            if conv_ret < 0 {
                b.error = 1;
                return -1;
            }

            // Read from the converted buffer
            let out_b = unsafe { &*out_buf };
            let to_copy = (out_b.use_ as c_int).min(len);
            if to_copy > 0 {
                unsafe {
                    ptr::copy_nonoverlapping(
                        out_b.content,
                        buffer as *mut xmlChar,
                        to_copy as usize,
                    );
                }
                // Remove the copied bytes from the output buffer
                buf_shrink(out_buf, to_copy as c_uint);
            }
            return to_copy;
        }

        // No encoder: read from raw buffer directly
        let raw_b = unsafe { &*raw_buf };
        let to_copy = (raw_b.use_ as c_int).min(len);
        if to_copy > 0 {
            unsafe {
                ptr::copy_nonoverlapping(raw_b.content, buffer as *mut xmlChar, to_copy as usize);
            }
            buf_shrink(raw_buf, to_copy as c_uint);
        }
        return to_copy;
    }

    // Memory-based input: read directly from the buffer
    let src_buf = b.buffer as *mut _xmlBuffer;
    if src_buf.is_null() {
        return -1;
    }

    let src = unsafe { &mut *src_buf };
    if src.content.is_null() || src.use_ == 0 {
        return 0;
    }

    let to_copy = (src.use_ as c_int).min(len);
    if to_copy > 0 {
        unsafe {
            ptr::copy_nonoverlapping(src.content, buffer as *mut xmlChar, to_copy as usize);
        }
        // Advance the content pointer and reduce use_
        unsafe {
            src.content = src.content.add(to_copy as usize);
        }
        src.use_ = src.use_.saturating_sub(to_copy as c_uint);
    }

    to_copy
}

/// Push data into an input buffer (for push parser).
///
/// The data is appended to the raw buffer and, if an encoder is set,
/// converted to UTF-8 in the buffer.
pub(crate) fn input_buffer_push(
    buf: *mut _xmlParserInputBuffer,
    buffer: *const c_char,
    len: c_int,
) -> c_int {
    if buf.is_null() || buffer.is_null() || len <= 0 {
        return -1;
    }

    let b = unsafe { &mut *buf };

    if b.error != 0 {
        return -1;
    }

    // Append to raw buffer
    let raw_buf = b.raw as *mut _xmlBuffer;
    if raw_buf.is_null() {
        return -1;
    }

    buf_add(raw_buf, buffer as *const xmlChar, len);

    // If encoder is set, convert raw -> buffer
    if !b.encoder.is_null() {
        let out_buf = b.buffer as *mut _xmlBuffer;
        if out_buf.is_null() {
            return -1;
        }

        let handler = b.encoder as *mut _xmlCharEncodingHandler;
        let ret = encoding::char_enc_in(handler, out_buf, raw_buf);
        if ret < 0 {
            b.error = 1;
            return -1;
        }
    }

    len
}

/// Update input buffer encoding.
///
/// Sets the encoder for an input buffer. The handler must already be
/// properly initialized.
pub(crate) fn input_buffer_set_encoder(
    buf: *mut _xmlParserInputBuffer,
    handler: *mut _xmlCharEncodingHandler,
) {
    if buf.is_null() {
        return;
    }

    unsafe {
        (*buf).encoder = handler as *mut c_void;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 4. Output buffer operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Write callback for file descriptor-based output.
unsafe extern "C" fn file_write_callback(
    context: *mut c_void,
    buffer: *const c_char,
    len: c_int,
) -> c_int {
    if context.is_null() || buffer.is_null() || len <= 0 {
        return -1;
    }

    let fd = context as c_int;
    let ret = libc::write(fd, buffer as *const c_void, len as usize);
    if ret < 0 {
        return -1;
    }
    ret as c_int
}

/// Close callback for file descriptor-based output.
unsafe extern "C" fn file_close_output_callback(context: *mut c_void) -> c_int {
    if context.is_null() {
        return -1;
    }

    let fd = context as c_int;
    libc::close(fd)
}

/// Write callback for buffer-based output (writes into an xmlBuffer).
unsafe extern "C" fn buffer_write_callback(
    context: *mut c_void,
    buffer: *const c_char,
    len: c_int,
) -> c_int {
    if context.is_null() || buffer.is_null() || len <= 0 {
        return -1;
    }

    let target_buf = context as *mut _xmlBuffer;
    buf_add(target_buf, buffer as *const xmlChar, len)
}

/// Internal helper: create an _xmlOutputBuffer struct.
///
/// Allocates the struct and initializes all fields to zero/NULL.
fn allocate_output_buffer() -> *mut _xmlOutputBuffer {
    let buf = unsafe { xmlMalloc(size_of::<_xmlOutputBuffer>()) as *mut _xmlOutputBuffer };
    if buf.is_null() {
        return ptr::null_mut();
    }

    unsafe {
        ptr::write(
            buf,
            _xmlOutputBuffer {
                context: ptr::null_mut(),
                writecallback: None,
                closecallback: None,
                encoder: ptr::null_mut(),
                buffer: ptr::null_mut(),
                conv: ptr::null_mut(),
                written: 0,
                error: 0,
            },
        );
    }

    buf
}

/// Create an output buffer for a filename.
///
/// Opens the file for writing and sets up write/close callbacks.
/// If `compression` is nonzero, future versions may support compression.
pub(crate) fn output_buffer_create_filename(
    URI: *const c_char,
    encoder: *mut _xmlCharEncodingHandler,
    compression: c_int,
) -> *mut _xmlOutputBuffer {
    if URI.is_null() {
        return ptr::null_mut();
    }

    let path_str = unsafe {
        match CStr::from_ptr(URI).to_str() {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        }
    };

    let path_c = std::ffi::CString::new(path_str).unwrap_or_default();

    // Open file for writing (create/truncate)
    let fd = unsafe {
        libc::open(
            path_c.as_ptr(),
            libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC,
            0o644,
        )
    };

    if fd < 0 {
        return ptr::null_mut();
    }

    let obuf = allocate_output_buffer();
    if obuf.is_null() {
        unsafe { libc::close(fd) };
        return ptr::null_mut();
    }

    let buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if buf.is_null() {
        unsafe {
            libc::close(fd);
            xmlFree(obuf as *mut c_void);
        }
        return ptr::null_mut();
    }

    let conv_buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if conv_buf.is_null() {
        unsafe {
            libc::close(fd);
            buf_free(buf);
            xmlFree(obuf as *mut c_void);
        }
        return ptr::null_mut();
    }

    unsafe {
        (*obuf).context = fd as *mut c_void;
        (*obuf).writecallback = Some(file_write_callback as xmlOutputWriteCallback);
        (*obuf).closecallback = Some(file_close_output_callback as xmlOutputCloseCallback);
        (*obuf).encoder = encoder as *mut c_void;
        (*obuf).buffer = buf as *mut c_void;
        (*obuf).conv = conv_buf as *mut c_void;
        (*obuf).written = 0;
        (*obuf).error = 0;
    }

    obuf
}

/// Create an output buffer for a file descriptor.
pub(crate) fn output_buffer_create_fd(
    fd: c_int,
    encoder: *mut _xmlCharEncodingHandler,
) -> *mut _xmlOutputBuffer {
    if fd < 0 {
        return ptr::null_mut();
    }

    let obuf = allocate_output_buffer();
    if obuf.is_null() {
        return ptr::null_mut();
    }

    let buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if buf.is_null() {
        unsafe { xmlFree(obuf as *mut c_void) };
        return ptr::null_mut();
    }

    let conv_buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if conv_buf.is_null() {
        unsafe {
            buf_free(buf);
            xmlFree(obuf as *mut c_void);
        }
        return ptr::null_mut();
    }

    unsafe {
        (*obuf).context = fd as *mut c_void;
        (*obuf).writecallback = Some(file_write_callback as xmlOutputWriteCallback);
        (*obuf).closecallback = Some(file_close_output_callback as xmlOutputCloseCallback);
        (*obuf).encoder = encoder as *mut c_void;
        (*obuf).buffer = buf as *mut c_void;
        (*obuf).conv = conv_buf as *mut c_void;
        (*obuf).written = 0;
        (*obuf).error = 0;
    }

    obuf
}

/// Create an output buffer from I/O callbacks.
pub(crate) fn output_buffer_create_io(
    iowrite: Option<xmlOutputWriteCallback>,
    ioclose: Option<xmlOutputCloseCallback>,
    ioctx: *mut c_void,
    encoder: *mut _xmlCharEncodingHandler,
) -> *mut _xmlOutputBuffer {
    let obuf = allocate_output_buffer();
    if obuf.is_null() {
        return ptr::null_mut();
    }

    let buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if buf.is_null() {
        unsafe { xmlFree(obuf as *mut c_void) };
        return ptr::null_mut();
    }

    let conv_buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if conv_buf.is_null() {
        unsafe {
            buf_free(buf);
            xmlFree(obuf as *mut c_void);
        }
        return ptr::null_mut();
    }

    unsafe {
        (*obuf).context = ioctx;
        (*obuf).writecallback = iowrite;
        (*obuf).closecallback = ioclose;
        (*obuf).encoder = encoder as *mut c_void;
        (*obuf).buffer = buf as *mut c_void;
        (*obuf).conv = conv_buf as *mut c_void;
        (*obuf).written = 0;
        (*obuf).error = 0;
    }

    obuf
}

/// Create an output buffer from a pre-existing xmlBuffer.
///
/// Writes to the output buffer will be appended to the given `_xmlBuffer`.
pub(crate) fn output_buffer_create_buffer(
    target_buf: *mut _xmlBuffer,
    encoder: *mut _xmlCharEncodingHandler,
) -> *mut _xmlOutputBuffer {
    if target_buf.is_null() {
        return ptr::null_mut();
    }

    let obuf = allocate_output_buffer();
    if obuf.is_null() {
        return ptr::null_mut();
    }

    // Internal buffer for buffering writes before flush
    let internal_buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if internal_buf.is_null() {
        unsafe { xmlFree(obuf as *mut c_void) };
        return ptr::null_mut();
    }

    // Conversion buffer (used when encoder is present)
    let conv_buf = buf_create(DEFAULT_BUFFER_SIZE as c_int);
    if conv_buf.is_null() {
        unsafe {
            buf_free(internal_buf);
            xmlFree(obuf as *mut c_void);
        }
        return ptr::null_mut();
    }

    unsafe {
        (*obuf).context = target_buf as *mut c_void;
        (*obuf).writecallback = Some(buffer_write_callback as xmlOutputWriteCallback);
        (*obuf).closecallback = None;
        (*obuf).encoder = encoder as *mut c_void;
        (*obuf).buffer = internal_buf as *mut c_void;
        (*obuf).conv = conv_buf as *mut c_void;
        (*obuf).written = 0;
        (*obuf).error = 0;
    }

    obuf
}

/// Flush an output buffer.
///
/// Encodes the buffered data (if an encoder is set) and writes it via the
/// write callback. Resets the internal buffer after writing.
///
/// Returns the number of bytes written, or -1 on error.
pub(crate) fn output_buffer_flush(out: *mut _xmlOutputBuffer) -> c_int {
    if out.is_null() {
        return -1;
    }

    let ob = unsafe { &mut *out };

    if ob.error != 0 {
        return -1;
    }

    let buf = ob.buffer as *mut _xmlBuffer;
    if buf.is_null() {
        return 0;
    }

    let b = unsafe { &*buf };
    if b.use_ == 0 {
        return 0;
    }

    let write_cb = match ob.writecallback {
        Some(cb) => cb,
        None => {
            // No write callback — just clear the buffer
            buf_empty(buf);
            return 0;
        }
    };

    let total_written = if !ob.encoder.is_null() {
        // Convert buffer content via encoder
        let handler = ob.encoder as *mut _xmlCharEncodingHandler;
        let conv = ob.conv as *mut _xmlBuffer;

        // Ensure conv buffer is empty before converting
        buf_empty(conv);

        let ret = encoding::char_enc_out(handler, conv, buf);
        if ret < 0 {
            ob.error = 1;
            return -1;
        }

        // Write converted data via callback
        let conv_b = unsafe { &*conv };
        if conv_b.use_ > 0 {
            let written = unsafe {
                write_cb(
                    ob.context,
                    conv_b.content as *const c_char,
                    conv_b.use_ as c_int,
                )
            };

            if written < 0 {
                ob.error = 1;
                return -1;
            }

            ob.written = ob.written.saturating_add(written);
            buf_empty(conv);
            written
        } else {
            0
        }
    } else {
        // No encoder: write buffer content directly
        let written = unsafe { write_cb(ob.context, b.content as *const c_char, b.use_ as c_int) };

        if written < 0 {
            ob.error = 1;
            return -1;
        }

        ob.written = ob.written.saturating_add(written);
        written
    };

    // Clear the buffer after writing
    buf_empty(buf);

    total_written
}

/// Free an output buffer.
///
/// Flushes any pending data, calls the close callback if set,
/// frees all internal buffers, then frees the output buffer struct.
pub(crate) fn output_buffer_close(out: *mut _xmlOutputBuffer) -> c_int {
    if out.is_null() {
        return -1;
    }

    let ob = unsafe { &mut *out };

    // Flush any pending data
    let flush_ret = output_buffer_flush(out);

    // Call the close callback
    if let Some(close_cb) = ob.closecallback {
        unsafe {
            close_cb(ob.context);
        }
    }

    // Free internal buffers
    if !ob.buffer.is_null() {
        buf_free(ob.buffer as *mut _xmlBuffer);
    }
    if !ob.conv.is_null() {
        buf_free(ob.conv as *mut _xmlBuffer);
    }

    // Note: encoder is owned by the caller/encoding module, not by us

    unsafe { xmlFree(out as *mut c_void) };

    flush_ret
}

/// Write to an output buffer.
///
/// The data is appended to the internal buffer. Use `output_buffer_flush`
/// to write the buffered data via the callback.
///
/// Returns the number of bytes written (always `len` on success), or -1 on error.
pub(crate) fn output_buffer_write(
    out: *mut _xmlOutputBuffer,
    len: c_int,
    data: *const c_char,
) -> c_int {
    if out.is_null() || data.is_null() || len <= 0 {
        return -1;
    }

    let ob = unsafe { &mut *out };

    if ob.error != 0 {
        return -1;
    }

    let buf = ob.buffer as *mut _xmlBuffer;
    if buf.is_null() {
        return -1;
    }

    let ret = buf_add(buf, data as *const xmlChar, len);
    if ret < 0 {
        ob.error = 1;
        return -1;
    }

    len
}

/// Write a null-terminated string to an output buffer.
pub(crate) fn output_buffer_write_string(out: *mut _xmlOutputBuffer, str: *const c_char) -> c_int {
    if out.is_null() || str.is_null() {
        return -1;
    }

    let len = unsafe {
        let mut i: c_int = 0;
        while *str.add(i as usize) != 0 {
            i += 1;
        }
        i
    };

    output_buffer_write(out, len, str)
}

/// Write a single character to an output buffer.
pub(crate) fn output_buffer_write_char(out: *mut _xmlOutputBuffer, c: c_char) -> c_int {
    output_buffer_write(out, 1, &c as *const c_char)
}

/// Get the content of an output buffer's internal buffer.
///
/// Returns a pointer to the internal buffer's content, or NULL on error.
pub(crate) fn output_buffer_get_content(out: *mut _xmlOutputBuffer) -> *const xmlChar {
    if out.is_null() {
        return ptr::null();
    }

    let ob = unsafe { &*out };
    let buf = ob.buffer as *mut _xmlBuffer;
    if buf.is_null() {
        return ptr::null();
    }

    buf_content(buf)
}

// ═══════════════════════════════════════════════════════════════════════════════
// 5. I/O helper functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Check if a file exists.
///
/// Returns 1 if the file exists, 0 if not, -1 on error.
pub(crate) fn check_file_exists(filename: *const c_char) -> c_int {
    if filename.is_null() {
        return -1;
    }

    let path_str = unsafe {
        match CStr::from_ptr(filename).to_str() {
            Ok(s) => s,
            Err(_) => return -1,
        }
    };

    let path_c = match std::ffi::CString::new(path_str) {
        Ok(c) => c,
        Err(_) => return -1,
    };

    let mut stat_buf: libc::stat = unsafe { std::mem::zeroed() };
    let ret = unsafe { libc::stat(path_c.as_ptr(), &mut stat_buf) };

    if ret == 0 {
        1
    } else {
        0
    }
}

/// Read a file into memory.
///
/// Reads the entire file contents into a newly allocated buffer.
/// Returns a pointer to the buffer, or NULL on failure.
/// The size of the buffer is stored in `size` if it's non-NULL.
///
/// The returned buffer must be freed with `xmlFree`.
pub(crate) fn read_file_to_memory(filename: *const c_char, size: *mut c_int) -> *mut c_char {
    if filename.is_null() {
        return ptr::null_mut();
    }

    let path_str = unsafe {
        match CStr::from_ptr(filename).to_str() {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        }
    };

    let path_c = match std::ffi::CString::new(path_str) {
        Ok(c) => c,
        Err(_) => return ptr::null_mut(),
    };

    let fd = unsafe { libc::open(path_c.as_ptr(), libc::O_RDONLY) };
    if fd < 0 {
        return ptr::null_mut();
    }

    // Stat to get file size
    let mut stat_buf: libc::stat = unsafe { std::mem::zeroed() };
    let file_size = if unsafe { libc::stat(path_c.as_ptr(), &mut stat_buf) } == 0 {
        stat_buf.st_size as usize
    } else {
        0
    };

    // Read in chunks
    let chunk_size = 4096usize;
    let initial_capacity = if file_size > 0 { file_size } else { chunk_size };

    let mut data = Vec::with_capacity(initial_capacity);
    let mut buf = vec![0u8; chunk_size];

    loop {
        let ret = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, chunk_size) };

        if ret < 0 {
            unsafe { libc::close(fd) };
            return ptr::null_mut();
        }

        if ret == 0 {
            break; // EOF
        }

        data.extend_from_slice(&buf[..ret as usize]);
    }

    unsafe { libc::close(fd) };

    if data.is_empty() {
        return ptr::null_mut();
    }

    // Allocate via xmlMalloc and copy
    let result = unsafe { xmlMalloc(data.len()) as *mut c_char };
    if result.is_null() {
        return ptr::null_mut();
    }

    unsafe {
        ptr::copy_nonoverlapping(data.as_ptr(), result as *mut u8, data.len());
    }

    if !size.is_null() {
        unsafe {
            *size = data.len() as c_int;
        }
    }

    result
}

/// Write memory to a file.
///
/// Creates or truncates the file and writes `size` bytes from `data`.
/// Returns 0 on success, -1 on error.
pub(crate) fn write_memory_to_file(
    filename: *const c_char,
    data: *const c_char,
    size: c_int,
) -> c_int {
    if filename.is_null() || data.is_null() || size <= 0 {
        return -1;
    }

    let path_str = unsafe {
        match CStr::from_ptr(filename).to_str() {
            Ok(s) => s,
            Err(_) => return -1,
        }
    };

    let path_c = match std::ffi::CString::new(path_str) {
        Ok(c) => c,
        Err(_) => return -1,
    };

    let fd = unsafe {
        libc::open(
            path_c.as_ptr(),
            libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC,
            0o644,
        )
    };

    if fd < 0 {
        return -1;
    }

    let mut remaining = size as usize;
    let mut offset: usize = 0;

    while remaining > 0 {
        let ret = unsafe {
            libc::write(
                fd,
                (data as *const u8).add(offset) as *const c_void,
                remaining,
            )
        };

        if ret < 0 {
            unsafe { libc::close(fd) };
            return -1;
        }

        let written = ret as usize;
        remaining -= written;
        offset += written;
    }

    unsafe { libc::close(fd) };
    0
}

/// Get the current working directory.
///
/// Returns a newly allocated null-terminated string, or NULL on failure.
/// The returned pointer must be freed with `xmlFree`.
pub(crate) fn get_cwd() -> *mut c_char {
    // Use a reasonable initial buffer size
    let mut size: usize = 1024;

    loop {
        let buf = unsafe { xmlMalloc(size) as *mut c_char };
        if buf.is_null() {
            return ptr::null_mut();
        }

        let ret = unsafe { libc::getcwd(buf as *mut c_char, size) };
        if !ret.is_null() {
            return buf;
        }

        unsafe { xmlFree(buf as *mut c_void) };

        // Check if the error was ERANGE (buffer too small)
        let err = std::io::Error::last_os_error();
        if err.raw_os_error() == Some(libc::ERANGE) {
            size = size.saturating_mul(2);
            if size > 65536 {
                return ptr::null_mut(); // Sanity cap
            }
        } else {
            return ptr::null_mut();
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::CString;
    use std::os::raw::c_char;

    // ── Helpers ────────────────────────────────────────────────────────────

    fn c(s: &str) -> CString {
        CString::new(s).unwrap()
    }

    /// Create a CString from raw bytes (may contain non-ASCII).
    unsafe fn c_bytes(bytes: &[u8]) -> CString {
        CString::from_vec_unchecked(bytes.to_vec())
    }

    /// Interpret a &[u8] as &[i8] for comparison with c_char buffers.
    fn i8_slice(s: &[u8]) -> &[i8] {
        unsafe { std::slice::from_raw_parts(s.as_ptr() as *const i8, s.len()) }
    }

    // ── xmlBuffer tests ────────────────────────────────────────────────────

    #[test]
    fn test_buf_create_free() {
        let buf = buf_create(100);
        assert!(!buf.is_null());

        let b = unsafe { &*buf };
        assert!(!b.content.is_null());
        assert_eq!(b.use_, 0);
        assert!(b.size >= 100);
        assert_eq!(b.alloc, XML_BUFFER_ALLOC_DOUBLEIT);

        // Content should be null-terminated empty string
        unsafe {
            assert_eq!(*b.content, 0);
        }

        buf_free(buf);
    }

    #[test]
    fn test_buf_create_default_size() {
        let buf = buf_create(0);
        assert!(!buf.is_null());

        let b = unsafe { &*buf };
        assert!(b.size >= MIN_BUFFER_SIZE);

        buf_free(buf);
    }

    #[test]
    fn test_buf_create_static() {
        let s: &[u8] = b"hello\0";
        let buf = buf_create_static(s.as_ptr() as *const xmlChar, 5);
        assert!(!buf.is_null());

        let b = unsafe { &*buf };
        assert_eq!(b.use_, 5);
        assert_eq!(b.alloc, XML_BUFFER_ALLOC_IMMUTABLE);

        // Content should point to the original string
        unsafe {
            assert_eq!(*b.content.offset(0), b'h');
            assert_eq!(*b.content.offset(4), b'o');
            assert_eq!(*b.content.offset(5), 0);
        }

        buf_free(buf); // Should not free the static content
    }

    #[test]
    fn test_buf_add() {
        let buf = buf_create(10);
        assert!(!buf.is_null());

        let s1: &[u8] = b"Hello\0";
        let ret = buf_add(buf, s1.as_ptr() as *const xmlChar, 5);
        assert_eq!(ret, 5);

        let b = unsafe { &*buf };
        assert_eq!(b.use_, 5);
        unsafe {
            assert_eq!(*b.content.offset(0), b'H');
            assert_eq!(*b.content.offset(4), b'o');
            assert_eq!(*b.content.offset(5), 0); // null-terminated
        }

        // Add more to trigger growth
        let s2: &[u8] = b" World!\0";
        let ret = buf_add(buf, s2.as_ptr() as *const xmlChar, 7);
        assert_eq!(ret, 7);

        let b = unsafe { &*buf };
        assert_eq!(b.use_, 12);
        unsafe {
            assert_eq!(*b.content.offset(6), b'W');
            assert_eq!(*b.content.offset(11), b'!');
            assert_eq!(*b.content.offset(12), 0);
        }

        buf_free(buf);
    }

    #[test]
    fn test_buf_add_null() {
        let buf = buf_create(10);
        let ret = buf_add(buf, ptr::null(), 5);
        assert_eq!(ret, 0);
        buf_free(buf);
    }

    #[test]
    fn test_buf_cat() {
        let buf = buf_create(10);
        let s: &[u8] = b"Hello\0";
        let ret = buf_cat(buf, s.as_ptr() as *const xmlChar);
        assert_eq!(ret, 5);

        let b = unsafe { &*buf };
        assert_eq!(b.use_, 5);

        buf_free(buf);
    }

    #[test]
    fn test_buf_ccat() {
        let buf = buf_create(10);
        let ret = buf_ccat(buf, b'A' as xmlChar);
        assert_eq!(ret, 1);

        let b = unsafe { &*buf };
        assert_eq!(b.use_, 1);
        unsafe {
            assert_eq!(*b.content, b'A');
        }

        buf_free(buf);
    }

    #[test]
    fn test_buf_empty() {
        let buf = buf_create(10);
        let s: &[u8] = b"Hello\0";
        buf_add(buf, s.as_ptr() as *const xmlChar, 5);
        assert_eq!(unsafe { &*buf }.use_, 5);

        buf_empty(buf);
        let b = unsafe { &*buf };
        assert_eq!(b.use_, 0);
        unsafe {
            assert_eq!(*b.content, 0);
        }

        buf_free(buf);
    }

    #[test]
    fn test_buf_content() {
        let buf = buf_create(10);
        let content = buf_content(buf);
        assert!(!content.is_null());
        buf_free(buf);
    }

    #[test]
    fn test_buf_length() {
        let buf = buf_create(10);
        assert_eq!(buf_length(buf), 0);

        let s: &[u8] = b"Hi\0";
        buf_add(buf, s.as_ptr() as *const xmlChar, 2);
        assert_eq!(buf_length(buf), 2);

        buf_free(buf);
    }

    #[test]
    fn test_buf_shrink() {
        let buf = buf_create(10);
        let s: &[u8] = b"Hello World\0";
        buf_add(buf, s.as_ptr() as *const xmlChar, 11);
        assert_eq!(buf_length(buf), 11);

        buf_shrink(buf, 5);
        assert_eq!(buf_length(buf), 6);

        let b = unsafe { &*buf };
        unsafe {
            assert_eq!(*b.content.offset(6), 0); // null-terminated
        }

        // Shrink more than available
        buf_shrink(buf, 100);
        assert_eq!(buf_length(buf), 0);

        buf_free(buf);
    }

    #[test]
    fn test_buf_grow() {
        let buf = buf_create(10);
        assert!(unsafe { &*buf }.size >= 10);

        let ret = buf_grow(buf, 1000);
        assert_eq!(ret, 0);
        assert!(unsafe { &*buf }.size >= 1000);

        buf_free(buf);
    }

    #[test]
    fn test_buf_free_null() {
        buf_free(ptr::null_mut()); // Should not crash
    }

    // ── xmlBuf tests ───────────────────────────────────────────────────────

    #[test]
    fn test_xml_buf_create_free() {
        let buf = xml_buf_create(100);
        assert!(!buf.is_null());

        let b = unsafe { &*buf };
        assert!(!b.content.is_null());
        assert_eq!(b.use_, 0);
        assert!(b.size >= 100);
        assert_eq!(b.error, 0);
        assert_eq!(b.buffer, 0);
        assert_eq!(b.io, 0);

        xml_buf_free(buf);
    }

    #[test]
    fn test_xml_buf_add() {
        let buf = xml_buf_create(10);
        let s: &[u8] = b"Hello\0";
        let ret = xml_buf_add(buf, s.as_ptr() as *const xmlChar, 5);
        assert_eq!(ret, 5);

        let b = unsafe { &*buf };
        assert_eq!(b.use_, 5);

        xml_buf_free(buf);
    }

    #[test]
    fn test_xml_buf_cat() {
        let buf = xml_buf_create(10);
        let s: &[u8] = b"Hello\0";
        let ret = xml_buf_cat(buf, s.as_ptr() as *const xmlChar);
        assert_eq!(ret, 5);

        xml_buf_free(buf);
    }

    #[test]
    fn test_xml_buf_content() {
        let buf = xml_buf_create(10);
        let content = xml_buf_content(buf);
        assert!(!content.is_null());
        xml_buf_free(buf);
    }

    #[test]
    fn test_xml_buf_length() {
        let buf = xml_buf_create(10);
        assert_eq!(xml_buf_length(buf), 0);

        let s: &[u8] = b"Hi\0";
        xml_buf_add(buf, s.as_ptr() as *const xmlChar, 2);
        assert_eq!(xml_buf_length(buf), 2);

        xml_buf_free(buf);
    }

    #[test]
    fn test_xml_buf_grow() {
        let buf = xml_buf_create(10);
        let ret = xml_buf_grow(buf, 500);
        assert_eq!(ret, 0);
        assert!(unsafe { &*buf }.size >= 500);

        xml_buf_free(buf);
    }

    #[test]
    fn test_xml_buf_shrink() {
        let buf = xml_buf_create(10);
        let s: &[u8] = b"Hello\0";
        xml_buf_add(buf, s.as_ptr() as *const xmlChar, 5);
        assert_eq!(xml_buf_length(buf), 5);

        xml_buf_shrink(buf, 3);
        assert_eq!(xml_buf_length(buf), 2);

        xml_buf_free(buf);
    }

    // ── Input buffer tests ─────────────────────────────────────────────────

    #[test]
    fn test_input_buffer_create_mem() {
        let data = c("Hello XML");
        let buf = input_buffer_create_mem(data.as_ptr(), 9, 0); // NONE encoding
        assert!(!buf.is_null());

        let b = unsafe { &*buf };
        assert!(b.readcallback.is_none());
        assert!(!b.buffer.is_null());
        assert_eq!(b.error, 0);

        // Read back
        let mut out = [0i8; 16];
        let ret = input_buffer_read(buf, out.as_mut_ptr(), 16);
        assert_eq!(ret, 9);
        assert_eq!(&out[..9], i8_slice(b"Hello XML"));

        input_buffer_free(buf);
    }

    #[test]
    fn test_input_buffer_create_mem_empty() {
        let buf = input_buffer_create_mem(ptr::null(), 0, 0);
        assert!(buf.is_null());
    }

    #[test]
    fn test_input_buffer_read_partial() {
        let data = c("Hello XML World");
        let buf = input_buffer_create_mem(data.as_ptr(), 15, 0);
        assert!(!buf.is_null());

        // Read in two parts
        let mut out1 = [0i8; 5];
        let ret = input_buffer_read(buf, out1.as_mut_ptr(), 5);
        assert_eq!(ret, 5);
        assert_eq!(&out1[..5], i8_slice(b"Hello"));

        let mut out2 = [0i8; 10];
        let ret = input_buffer_read(buf, out2.as_mut_ptr(), 10);
        assert_eq!(ret, 10);
        assert_eq!(&out2[..10], i8_slice(b" XML World"));

        input_buffer_free(buf);
    }

    #[test]
    fn test_input_buffer_push() {
        let buf = input_buffer_create_io(None, None, ptr::null_mut(), 0);
        assert!(!buf.is_null());

        let data1 = c("<root>");
        let ret = input_buffer_push(buf, data1.as_ptr(), 6);
        assert_eq!(ret, 6);

        let data2 = c("</root>");
        let ret = input_buffer_push(buf, data2.as_ptr(), 7);
        assert_eq!(ret, 7);

        // Read back the pushed data
        let mut out = [0i8; 32];
        let ret = input_buffer_read(buf, out.as_mut_ptr(), 32);
        assert_eq!(ret, 13);
        assert_eq!(&out[..13], i8_slice(b"<root></root>"));

        input_buffer_free(buf);
    }

    #[test]
    fn test_input_buffer_set_encoder() {
        let buf = input_buffer_create_mem(ptr::null(), 0, 0);
        // Create a fresh buffer
        let data = c("test");
        let buf = input_buffer_create_mem(data.as_ptr(), 4, 0);
        assert!(!buf.is_null());

        // Set encoder to null (no encoding)
        input_buffer_set_encoder(buf, ptr::null_mut());
        let b = unsafe { &*buf };
        assert!(b.encoder.is_null());

        input_buffer_free(buf);
    }

    // ── Output buffer tests ────────────────────────────────────────────────

    #[test]
    fn test_output_buffer_create_buffer() {
        let internal_buf = buf_create(100);
        assert!(!internal_buf.is_null());

        let obuf = output_buffer_create_buffer(internal_buf, ptr::null_mut());
        assert!(!obuf.is_null());

        // Write data
        let data = c("Hello Output");
        let ret = output_buffer_write(obuf, 12, data.as_ptr());
        assert_eq!(ret, 12);

        // Flush - this writes buffered data via callback to the target buffer
        let flushed = output_buffer_flush(obuf);
        assert_eq!(flushed, 12);

        // After flush, the internal buffer should be empty again
        let content = output_buffer_get_content(obuf);
        assert!(content.is_null() || unsafe { *content } == 0);

        // The data was written via callback to the context buffer (internal_buf)
        let ctx = unsafe { (*obuf).context as *mut _xmlBuffer };
        let ctx_b = unsafe { &*ctx };
        assert_eq!(ctx_b.use_, 12);
        unsafe {
            assert_eq!(*ctx_b.content.offset(0), b'H' as xmlChar);
        }

        // NOTE: output_buffer_close frees all internal buffers including
        // the internal_buf passed as target. Don't free it again here.
        output_buffer_close(obuf);
    }

    #[test]
    fn test_output_buffer_write_string() {
        let internal_buf = buf_create(100);
        let obuf = output_buffer_create_buffer(internal_buf, ptr::null_mut());
        assert!(!obuf.is_null());

        let s = c("Hello");
        let ret = output_buffer_write_string(obuf, s.as_ptr());
        assert_eq!(ret, 5);

        // output_buffer_close frees internal_buf via obuf.buffer
        output_buffer_close(obuf);
    }

    #[test]
    fn test_output_buffer_write_char() {
        let internal_buf = buf_create(100);
        let obuf = output_buffer_create_buffer(internal_buf, ptr::null_mut());
        assert!(!obuf.is_null());

        let ret = output_buffer_write_char(obuf, b'X' as c_char);
        assert_eq!(ret, 1);

        output_buffer_close(obuf);
    }

    #[test]
    fn test_output_buffer_get_content() {
        let internal_buf = buf_create(100);
        let obuf = output_buffer_create_buffer(internal_buf, ptr::null_mut());
        assert!(!obuf.is_null());

        let content = output_buffer_get_content(obuf);
        assert!(!content.is_null());

        output_buffer_close(obuf);
    }

    // ── File I/O tests ─────────────────────────────────────────────────────

    #[test]
    fn test_check_file_exists() {
        // This file should exist
        let exists = check_file_exists(c("/dev/null").as_ptr());
        assert!(exists == 1);

        // This file should not exist
        let not_exists = check_file_exists(c("/tmp/__nonexistent_file_xyz123__").as_ptr());
        assert!(not_exists == 0);
    }

    #[test]
    fn test_read_write_file() {
        let tmpfile = c("/tmp/libxml_rs_test_io_file.txt");

        // Write data to file
        let data = c("Hello File I/O!");
        let ret = write_memory_to_file(tmpfile.as_ptr(), data.as_ptr(), 15);
        assert_eq!(ret, 0);

        // Check it exists
        assert!(check_file_exists(tmpfile.as_ptr()) == 1);

        // Read it back
        let mut size: c_int = 0;
        let read_data = read_file_to_memory(tmpfile.as_ptr(), &mut size as *mut c_int);
        assert!(!read_data.is_null());
        assert_eq!(size, 15);

        unsafe {
            let slice = std::slice::from_raw_parts(read_data as *const u8, size as usize);
            assert_eq!(slice, b"Hello File I/O!");
        }

        unsafe { xmlFree(read_data as *mut c_void) };

        // Clean up
        std::fs::remove_file("/tmp/libxml_rs_test_io_file.txt").ok();
    }

    #[test]
    fn test_read_file_nonexistent() {
        let result = read_file_to_memory(
            c("/tmp/__nonexistent_file_xyz456__").as_ptr(),
            ptr::null_mut(),
        );
        assert!(result.is_null());
    }

    #[test]
    fn test_write_file_null() {
        let ret = write_memory_to_file(ptr::null(), c("data").as_ptr(), 4);
        assert_eq!(ret, -1);
    }

    #[test]
    fn test_get_cwd() {
        let cwd = get_cwd();
        assert!(!cwd.is_null());
        unsafe {
            let s = CStr::from_ptr(cwd);
            assert!(!s.to_bytes().is_empty());
            xmlFree(cwd as *mut c_void);
        }
    }

    // ── Edge case tests ────────────────────────────────────────────────────

    #[test]
    fn test_buf_add_large_data() {
        let buf = buf_create(10);
        let mut large_data = Vec::new();
        large_data.resize(5000, b'X');
        large_data.push(0);

        let ret = buf_add(buf, large_data.as_ptr() as *const xmlChar, 5000);
        assert_eq!(ret, 5000);

        let b = unsafe { &*buf };
        assert_eq!(b.use_, 5000);
        assert!(b.size >= 5001);

        buf_free(buf);
    }

    #[test]
    fn test_input_buffer_free_null() {
        input_buffer_free(ptr::null_mut()); // Should not crash
    }

    #[test]
    fn test_output_buffer_close_null() {
        let ret = output_buffer_close(ptr::null_mut());
        assert_eq!(ret, -1);
    }

    #[test]
    fn test_buf_add_to_immutable() {
        let s: &[u8] = b"static\0";
        let buf = buf_create_static(s.as_ptr() as *const xmlChar, 6);
        assert!(!buf.is_null());

        // Try to add to immutable buffer
        let data: &[u8] = b"more\0";
        let ret = buf_add(buf, data.as_ptr() as *const xmlChar, 4);
        assert_eq!(ret, -1); // Should fail

        buf_free(buf);
    }

    // ── Encoding integration test ──────────────────────────────────────────

    #[test]
    fn test_encoding_from_int() {
        assert_eq!(
            encoding_from_int(0),
            xmlCharEncoding::XML_CHAR_ENCODING_NONE
        );
        assert_eq!(
            encoding_from_int(1),
            xmlCharEncoding::XML_CHAR_ENCODING_UTF8
        );
        assert_eq!(
            encoding_from_int(10),
            xmlCharEncoding::XML_CHAR_ENCODING_8859_1
        );
        assert_eq!(
            encoding_from_int(22),
            xmlCharEncoding::XML_CHAR_ENCODING_ASCII
        );
        assert_eq!(
            encoding_from_int(999),
            xmlCharEncoding::XML_CHAR_ENCODING_ERROR
        );
    }

    #[test]
    fn test_find_handler_for_encoding() {
        // UTF-8 should return null (no conversion needed)
        let handler = find_handler_for_encoding(1);
        assert!(handler.is_null());

        // NONE should return null
        let handler = find_handler_for_encoding(0);
        assert!(handler.is_null());

        // ERROR should return null
        let handler = find_handler_for_encoding(-1);
        assert!(handler.is_null());
    }

    #[test]
    fn test_input_buffer_with_encoding_latin1() {
        // Initialize encodings
        encoding::init_encodings();

        // Latin-1 byte 0xE9 = é in Latin-1, which is U+00E9 = 0xC3 0xA9 in UTF-8
        let latin1_data: &[u8] = &[0x48, 0x65, 0x6C, 0x6C, 0xF6, 0x00]; // "Hellö" in Latin-1

        let buf = input_buffer_create_mem(
            latin1_data.as_ptr() as *const c_char,
            5,
            10, // ISO-8859-1
        );
        assert!(!buf.is_null());

        // Read back as UTF-8
        let mut out = [0i8; 16];
        let ret = input_buffer_read(buf, out.as_mut_ptr(), 16);
        assert!(ret > 0);

        // The output should be UTF-8 encoded "Hellö" = b"Hell\xC3\xB6"
        let expected = b"Hell\xC3\xB6";
        assert_eq!(&out[..ret as usize], i8_slice(expected));

        input_buffer_free(buf);
    }

    #[test]
    fn test_output_buffer_with_encoding() {
        // Initialize encodings
        encoding::init_encodings();

        // Find Latin-1 encoder
        let enc_name: &[u8] = b"ISO-8859-1\0";
        let handler = encoding::find_encoding_handler(enc_name.as_ptr() as *const xmlChar);
        assert!(!handler.is_null(), "Latin-1 handler should be available");

        let internal_buf = buf_create(100);
        let obuf = output_buffer_create_buffer(internal_buf, handler);
        assert!(!obuf.is_null());

        // Write UTF-8 "Hellö" = [0x48, 0x65, 0x6C, 0x6C, 0xC3, 0xB6]
        let utf8_data = unsafe { c_bytes(&[0x48, 0x65, 0x6C, 0x6C, 0xC3, 0xB6]) };
        let ret = output_buffer_write(obuf, 6, utf8_data.as_ptr());
        assert_eq!(ret, 6);

        // Flush - this should convert via Latin-1 encoder
        let flushed = output_buffer_flush(obuf);
        assert!(flushed > 0);

        // The context buffer should have the Latin-1 encoded data
        let ctx = unsafe { (*obuf).context as *mut _xmlBuffer };
        let ctx_b = unsafe { &*ctx };
        // Latin-1 "Hellö" = [0x48, 0x65, 0x6C, 0x6C, 0xF6]
        assert_eq!(ctx_b.use_, 5);
        unsafe {
            assert_eq!(*ctx_b.content.offset(0), 0x48); // 'H'
            assert_eq!(*ctx_b.content.offset(4), 0xF6); // 'ö'
        }

        // output_buffer_close frees the internal buffer, but NOT the
        // context buffer (internal_buf) since that's the user's buffer.
        // Actually it frees obuf.buffer (a separate internal buffer) and
        // obuf.conv. The context buffer is NOT freed by output_buffer_close.
        // However, obuf.buffer was set to internal_buf in the OLD code.
        // With the fix, obuf.buffer is a separate internal buffer, so
        // we still need to free internal_buf ourselves.
        //
        // Wait -- let me check what output_buffer_close frees:
        // - ob.buffer: this is the internal buffer (SEPARATE from internal_buf)
        // - ob.conv: the conversion buffer
        // - The context (internal_buf) is NOT freed by output_buffer_close
        //
        // Actually, let me re-read the function...
        // output_buffer_close frees ob.buffer and ob.conv.
        // The context is the user's buffer (internal_buf), which is NOT freed.
        // So we DO need to free internal_buf here.
        output_buffer_close(obuf);
        buf_free(internal_buf);
    }

    // ── Input buffer from fd (requires /dev/null) ──────────────────────────

    #[test]
    fn test_input_buffer_create_fd() {
        // Open /dev/null and create an fd-based input buffer
        let fd =
            unsafe { libc::open(b"/dev/null\0" as *const u8 as *const c_char, libc::O_RDONLY) };
        assert!(fd >= 0);

        let buf = input_buffer_create_fd(fd, 0);
        assert!(!buf.is_null());

        // Reading from /dev/null should return 0 (EOF)
        let mut out = [0i8; 16];
        let ret = input_buffer_read(buf, out.as_mut_ptr(), 16);
        assert_eq!(ret, 0);

        input_buffer_free(buf); // This will also close the fd via closecallback
    }

    // ── Input buffer create_io ─────────────────────────────────────────────

    #[test]
    fn test_input_buffer_create_io() {
        // Create a simple callback that provides data
        static mut TEST_DATA: &[u8] = b"Hello from callback!";
        static mut CALLED: bool = false;

        unsafe extern "C" fn test_read(
            _ctx: *mut c_void,
            buffer: *mut c_char,
            len: c_int,
        ) -> c_int {
            if CALLED {
                return 0; // EOF on second call
            }
            CALLED = true;
            let data = TEST_DATA;
            let to_copy = (data.len() as c_int).min(len);
            if to_copy > 0 {
                std::ptr::copy_nonoverlapping(data.as_ptr(), buffer as *mut u8, to_copy as usize);
            }
            to_copy
        }

        unsafe extern "C" fn test_close(_ctx: *mut c_void) -> c_int {
            0
        }

        let buf = input_buffer_create_io(
            Some(test_read as xmlInputReadCallback),
            Some(test_close as xmlInputCloseCallback),
            ptr::null_mut(),
            0,
        );
        assert!(!buf.is_null());

        let mut out = [0i8; 32];
        let ret = input_buffer_read(buf, out.as_mut_ptr(), 32);
        assert!(ret > 0);

        input_buffer_free(buf);
    }
}