libxml-rs 0.1.0-alpha.23

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 correlated to upstream commits; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure (xmlXPath*, xmlTextReader*, xmlTextWriter*, catalogs, serialization, data globals, chvalid, encoding, the full libxslt surface) — parity ledger at 0 missing for both libxml2 and libxslt. 1135 tests passing.
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
//! Canonical XML implementation (§28, §85 Phase 7).
//!
//! Inclusive and exclusive canonicalization, comments, namespace propagation,
//! attribute ordering, character escaping, subsets, node sets.
//! Must be byte-exact compared to oracle.
//!
//! References:
//! - XML Canonicalization (C14N) — inclusive: <https://www.w3.org/TR/xml-c14n11/>
//! - Exclusive XML Canonicalization (C14N): <https://www.w3.org/2001/10/xml-exc-c14n>

#![allow(
    missing_docs,
    non_snake_case,
    non_camel_case_types,
    non_upper_case_globals,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_ptr_alignment,
    clippy::missing_safety_doc,
    clippy::too_many_lines,
    clippy::type_complexity
)]

use core::ffi::c_void;
use core::ptr;
use std::collections::HashSet;
use std::os::raw::{c_char, c_int};

use crate::abi::structs::*;
use crate::abi::types::xmlElementType::*;
use crate::abi::types::*;
use crate::xml::io;
use crate::xml::tree;

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

/// The XML namespace prefix string "xml".
const XML_XML_PREFIX: &[xmlChar] = b"xml\0";

/// The XML namespace URI string.
const XML_XML_NS_URI: &[xmlChar] = b"http://www.w3.org/XML/1998/namespace\0";

/// The xmlns namespace URI.
const _XMLNS_NS_URI: &[xmlChar] = b"http://www.w3.org/2000/xmlns/\0";

/// The xmlns prefix string.
const _XMLNS_PREFIX: &[xmlChar] = b"xmlns\0";

// ═══════════════════════════════════════════════════════════════════════════════
// C14N Mode
// ═══════════════════════════════════════════════════════════════════════════════

/// Canonicalization mode flags.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// typedef enum {
///     XML_C14N_1_0 = 0,       /* C14N 1.0 (inclusive) */
///     XML_C14N_EXCLUSIVE_1_0 = 1, /* Exclusive C14N 1.0 */
///     XML_C14N_1_1 = 2,       /* C14N 1.1 */
///     XML_C14N_1_0_WITH_COMMENTS = 3, /* C14N 1.0 with comments */
///     XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS = 4, /* Exclusive with comments */
///     XML_C14N_1_1_WITH_COMMENTS = 5  /* C14N 1.1 with comments */
/// } xmlC14NMode;
/// ```
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum C14nMode {
    XML_C14N_1_0 = 0,
    XML_C14N_EXCLUSIVE_1_0 = 1,
    XML_C14N_1_1 = 2,
    XML_C14N_1_0_WITH_COMMENTS = 3,
    XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS = 4,
    XML_C14N_1_1_WITH_COMMENTS = 5,
}

impl C14nMode {
    /// Returns true if this mode includes comments in the output.
    fn with_comments(self) -> bool {
        matches!(
            self,
            C14nMode::XML_C14N_1_0_WITH_COMMENTS
                | C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS
                | C14nMode::XML_C14N_1_1_WITH_COMMENTS
        )
    }

    /// Returns true if this mode is exclusive.
    fn is_exclusive(self) -> bool {
        matches!(
            self,
            C14nMode::XML_C14N_EXCLUSIVE_1_0 | C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// C14N Context
// ═══════════════════════════════════════════════════════════════════════════════

/// Namespace entry for the context stack.
#[allow(dead_code)]
#[derive(Debug, Clone)]
struct NsEntry {
    /// The prefix (NULL for default namespace).
    prefix: *const xmlChar,
    /// The namespace URI (NULL for undeclaration).
    href: *const xmlChar,
    /// Whether this namespace was rendered in the output.
    rendered: bool,
}

/// C14N serialization context.
///
/// Tracks namespace propagation state, visited prefixes, and
/// document-level state during canonicalization.
#[derive(Debug)]
pub struct C14nContext {
    /// The canonicalization mode.
    pub mode: C14nMode,
    /// Stack of in-scope namespace declarations per depth.
    ns_stack: Vec<Vec<NsEntry>>,
    /// Set of inclusive namespace prefixes (for exclusive C14N).
    #[allow(dead_code)]
    inclusive_ns_prefixes: Option<HashSet<String>>,
    /// The document being canonicalized.
    #[allow(dead_code)]
    doc: *mut _xmlDoc,
}

impl C14nContext {
    /// Create a new C14N context.
    ///
    /// # SAFETY
    ///
    /// - `doc` must be a valid pointer to an `_xmlDoc` or NULL.
    pub unsafe fn new(
        doc: *mut _xmlDoc,
        mode: C14nMode,
        inclusive_ns_prefixes: Option<HashSet<String>>,
    ) -> Self {
        let mut ctx = C14nContext {
            mode,
            ns_stack: Vec::new(),
            inclusive_ns_prefixes,
            doc,
        };
        // Push the initial (document-level) namespace scope, which contains
        // the implicit `xml` namespace.
        let xml_prefix = XML_XML_PREFIX.as_ptr() as *const xmlChar;
        let xml_href = XML_XML_NS_URI.as_ptr() as *const xmlChar;
        ctx.ns_stack.push(vec![NsEntry {
            prefix: xml_prefix,
            href: xml_href,
            rendered: false,
        }]);
        ctx
    }

    /// Enter a new namespace scope (depth + 1).
    #[allow(dead_code)]
    fn push_scope(&mut self) {
        // Clone the current top scope as the base for the new scope
        let base = if let Some(top) = self.ns_stack.last() {
            top.clone()
        } else {
            Vec::new()
        };
        self.ns_stack.push(base);
    }

    /// Exit the current namespace scope (depth - 1).
    #[allow(dead_code)]
    fn pop_scope(&mut self) {
        self.ns_stack.pop();
    }

    /// Add a namespace declaration to the current scope.
    #[allow(dead_code)]
    fn add_namespace(&mut self, prefix: *const xmlChar, href: *const xmlChar) {
        if let Some(top) = self.ns_stack.last_mut() {
            // Check if this prefix already exists in the current scope
            if !top
                .iter()
                .any(|e| unsafe { crate::abi::exports_xml2::xmlStrEqual(e.prefix, prefix) != 0 })
            {
                top.push(NsEntry {
                    prefix,
                    href,
                    rendered: false,
                });
            } else {
                // Update the existing entry
                if let Some(existing) = top.iter_mut().find(|e| unsafe {
                    crate::abi::exports_xml2::xmlStrEqual(e.prefix, prefix) != 0
                }) {
                    existing.href = href;
                    existing.rendered = false;
                }
            }
        }
    }

    /// Check if a prefix is in scope.
    #[allow(dead_code)]
    fn is_prefix_in_scope(&self, prefix: *const xmlChar) -> bool {
        self.ns_stack.iter().rev().any(|scope| {
            scope
                .iter()
                .any(|e| unsafe { crate::abi::exports_xml2::xmlStrEqual(e.prefix, prefix) != 0 })
        })
    }

    /// Get the href for a prefix from the current scope.
    #[allow(dead_code)]
    fn get_href_for_prefix(&self, prefix: *const xmlChar) -> *const xmlChar {
        for scope in self.ns_stack.iter().rev() {
            for entry in scope.iter() {
                if unsafe { crate::abi::exports_xml2::xmlStrEqual(entry.prefix, prefix) != 0 } {
                    return entry.href;
                }
            }
        }
        ptr::null()
    }

    /// Check if a prefix is in the inclusive namespace prefixes list.
    #[allow(dead_code)]
    fn is_inclusive_prefix(&self, prefix: *const xmlChar) -> bool {
        if let Some(ref set) = self.inclusive_ns_prefixes {
            if prefix.is_null() {
                return set.contains("");
            }
            let prefix_str = unsafe {
                let c_str = core::ffi::CStr::from_ptr(prefix as *const c_char);
                match c_str.to_str() {
                    Ok(s) => s.to_string(),
                    Err(_) => return false,
                }
            };
            set.contains(&prefix_str)
        } else {
            false
        }
    }

    /// Mark a namespace as rendered.
    #[allow(dead_code)]
    fn mark_rendered(&mut self, prefix: *const xmlChar) {
        for scope in self.ns_stack.iter_mut().rev() {
            for entry in scope.iter_mut() {
                if unsafe { crate::abi::exports_xml2::xmlStrEqual(entry.prefix, prefix) != 0 } {
                    entry.rendered = true;
                    return;
                }
            }
        }
    }

    /// Check if a namespace is already rendered.
    #[allow(dead_code)]
    fn is_rendered(&self, prefix: *const xmlChar) -> bool {
        for scope in self.ns_stack.iter().rev() {
            for entry in scope.iter() {
                if unsafe { crate::abi::exports_xml2::xmlStrEqual(entry.prefix, prefix) != 0 } {
                    return entry.rendered;
                }
            }
        }
        false
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// C14N Escaping
// ═══════════════════════════════════════════════════════════════════════════════

/// Escape text content per C14N rules.
///
/// Canonical XML requires:
/// - `<` → `&lt;`
/// - `>` → `&gt;`
/// - `&` → `&amp;`
/// - Carriage return `\r` (0x0D) → `&#xD;`
/// - `]]>` → `]]&gt;`
///
/// # SAFETY
///
/// - `buf` must be a valid pointer to a mutable `_xmlBuffer`.
/// - `text` must be a valid pointer to `len` bytes of xmlChar data, or NULL.
unsafe fn c14n_escape_text(buf: *mut _xmlBuffer, text: *const xmlChar, len: c_int) {
    if buf.is_null() || text.is_null() || len <= 0 {
        return;
    }

    let mut i: c_int = 0;
    while i < len {
        let ch = unsafe { *text.add(i as usize) };

        // Check for `]]>` sequence
        if ch == b']'
            && i + 2 < len
            && unsafe { *text.add(i as usize + 1) == b']' }
            && unsafe { *text.add(i as usize + 2) == b'>' }
        {
            // Write `]]&gt;` — escape the `>` that ends `]]>`
            io::buf_add(buf, b"]]" as *const u8, 2); // write `]]`
            io::buf_add(buf, b"&gt;" as *const u8, 4);
            i += 3;
            continue;
        }

        match ch {
            b'<' => {
                io::buf_add(buf, b"&lt;" as *const u8, 4);
            }
            b'>' => {
                io::buf_add(buf, b"&gt;" as *const u8, 4);
            }
            b'&' => {
                io::buf_add(buf, b"&amp;" as *const u8, 5);
            }
            0x0D => {
                // Carriage return: &#xD;
                io::buf_add(buf, b"&#xD;" as *const u8, 5);
            }
            _ => {
                io::buf_add(buf, &ch as *const u8, 1);
            }
        }
        i += 1;
    }
}

/// Escape attribute values per C14N rules.
///
/// Canonical XML requires:
/// - `<` → `&lt;`
/// - `&` → `&amp;`
/// - `"` → `&quot;`
/// - Tab (0x09) → `&#x9;`
/// - Newline (0x0A) → `&#xA;`
/// - Carriage return (0x0D) → `&#xD;`
/// - `]]>` → `]]&gt;`
///
/// # SAFETY
///
/// - `buf` must be a valid pointer to a mutable `_xmlBuffer`.
/// - `text` must be a valid pointer to a null-terminated xmlChar string, or NULL.
unsafe fn c14n_escape_attr(buf: *mut _xmlBuffer, text: *const xmlChar) {
    if buf.is_null() || text.is_null() {
        return;
    }

    let len = tree::xml_strlen(text);
    let mut i: c_int = 0;
    while i < len {
        let ch = unsafe { *text.add(i as usize) };

        // Check for `]]>` sequence
        if ch == b']'
            && i + 2 < len
            && unsafe { *text.add(i as usize + 1) == b']' }
            && unsafe { *text.add(i as usize + 2) == b'>' }
        {
            // Write `]]&gt;`
            io::buf_add(buf, b"]]" as *const u8, 2); // write `]]`
            io::buf_add(buf, b"&gt;" as *const u8, 4);
            i += 3;
            continue;
        }

        match ch {
            b'<' => {
                io::buf_add(buf, b"&lt;" as *const u8, 4);
            }
            b'&' => {
                io::buf_add(buf, b"&amp;" as *const u8, 5);
            }
            b'"' => {
                io::buf_add(buf, b"&quot;" as *const u8, 6);
            }
            0x09 => {
                // Tab
                io::buf_add(buf, b"&#x9;" as *const u8, 5);
            }
            0x0A => {
                // Newline
                io::buf_add(buf, b"&#xA;" as *const u8, 5);
            }
            0x0D => {
                // Carriage return
                io::buf_add(buf, b"&#xD;" as *const u8, 5);
            }
            _ => {
                io::buf_add(buf, &ch as *const u8, 1);
            }
        }
        i += 1;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Namespace Collection
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a collected namespace declaration for output.
#[derive(Debug, Clone)]
struct CollectedNs {
    /// The prefix (NULL for default namespace).
    prefix: *const xmlChar,
    /// The namespace URI.
    href: *const xmlChar,
}

/// Collect visible namespace declarations for a node per inclusive/exclusive rules.
///
/// For **inclusive** C14N:
/// - All namespaces in scope for the node are included.
/// - Namespaces inherited from ancestors are included.
/// - Namespace undeclarations are emitted when needed.
///
/// For **exclusive** C14N:
/// - Only namespaces actually used by the node and its attributes are included.
/// - If an inclusive-ns-prefix list is provided, those prefixes are always included.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `_xmlNode` or NULL.
/// - `ctx` must be a valid pointer to a `C14nContext`.
unsafe fn c14n_collect_namespaces(node: *mut _xmlNode, ctx: &mut C14nContext) -> Vec<CollectedNs> {
    if node.is_null() {
        return Vec::new();
    }

    let n = unsafe { &*node };
    if n.type_ != XML_ELEMENT_NODE as c_int {
        return Vec::new();
    }

    let mut collected: Vec<CollectedNs> = Vec::new();
    let mut seen_prefixes: Vec<*const xmlChar> = Vec::new();

    // NOTE: The `xml` namespace (prefix `xml`, URI `http://www.w3.org/XML/1998/namespace`)
    // is always implicitly available per the XML Namespaces specification.
    // Per C14N, it MUST NOT be explicitly declared in the output.
    // See W3C Canonical XML 1.0 §2.4 and Exclusive XML Canonicalization §2.1.2.

    if ctx.mode.is_exclusive() {
        // ── Exclusive C14N namespace collection ──
        //
        // Only include namespaces actually used by this node and its attributes,
        // plus any prefixes in the inclusive-ns-prefixes list.

        // Collect namespaces used by this node
        let mut used_prefixes: Vec<*const xmlChar> = Vec::new();

        // The node's own namespace
        if !n.ns.is_null() {
            let ns = unsafe { &*n.ns };
            used_prefixes.push(ns.prefix);
        }

        // Namespaces used by attributes
        let mut attr = n.properties;
        while !attr.is_null() {
            let a = unsafe { &*attr };
            if !a.ns.is_null() {
                let ans = unsafe { &*a.ns };
                if !ans.prefix.is_null()
                    && !used_prefixes.iter().any(|p| unsafe {
                        crate::abi::exports_xml2::xmlStrEqual(*p, ans.prefix) != 0
                    })
                {
                    used_prefixes.push(ans.prefix);
                }
            }
            attr = a.next;
        }

        // For each used prefix, find the namespace declaration by walking
        // up the ancestor chain
        for &used_prefix in &used_prefixes {
            let ns = find_ns_declaration(node, used_prefix);
            if !ns.is_null() {
                let ns_ref = unsafe { &*ns };
                if !seen_prefixes.iter().any(|p| unsafe {
                    crate::abi::exports_xml2::xmlStrEqual(*p, ns_ref.prefix) != 0
                }) {
                    collected.push(CollectedNs {
                        prefix: ns_ref.prefix,
                        href: ns_ref.href,
                    });
                    seen_prefixes.push(ns_ref.prefix);
                }
            }
        }

        // Include inclusive namespace prefixes
        if let Some(ref inclusive_set) = ctx.inclusive_ns_prefixes {
            for inc_prefix_str in inclusive_set.iter() {
                let inc_prefix = if inc_prefix_str.is_empty() {
                    ptr::null()
                } else {
                    let c_str = format!("{}\0", inc_prefix_str);
                    c_str.as_ptr() as *const xmlChar
                };

                if !seen_prefixes.iter().any(|p| {
                    if inc_prefix.is_null() {
                        p.is_null()
                    } else {
                        !p.is_null()
                            && unsafe { crate::abi::exports_xml2::xmlStrEqual(*p, inc_prefix) != 0 }
                    }
                }) {
                    let ns = find_ns_declaration(node, inc_prefix);
                    if !ns.is_null() {
                        let ns_ref = unsafe { &*ns };
                        collected.push(CollectedNs {
                            prefix: ns_ref.prefix,
                            href: ns_ref.href,
                        });
                        seen_prefixes.push(ns_ref.prefix);
                    }
                }
            }
        }
    } else {
        // ── Inclusive C14N namespace collection ──
        //
        // Collect ALL namespaces in scope for this node, walking up ancestors.

        let mut cur: *mut _xmlNode = node;
        while !cur.is_null() {
            let cur_node = unsafe { &*cur };
            let mut ns_def = cur_node.nsDef;
            while !ns_def.is_null() {
                let ns = unsafe { &*ns_def };
                let ns_prefix = ns.prefix;

                if !seen_prefixes.iter().any(|p| {
                    if ns_prefix.is_null() && p.is_null() {
                        return true;
                    }
                    if ns_prefix.is_null() || p.is_null() {
                        return false;
                    }
                    unsafe { crate::abi::exports_xml2::xmlStrEqual(*p, ns_prefix) != 0 }
                }) {
                    collected.push(CollectedNs {
                        prefix: ns_prefix,
                        href: ns.href,
                    });
                    seen_prefixes.push(ns_prefix);
                }
                ns_def = ns.next;
            }
            cur = cur_node.parent;
        }
    }

    collected
}

/// Find the namespace declaration for a given prefix by walking up the ancestor chain.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `_xmlNode` or NULL.
unsafe fn find_ns_declaration(node: *mut _xmlNode, prefix: *const xmlChar) -> *mut _xmlNs {
    if node.is_null() {
        return ptr::null_mut();
    }

    let mut cur: *mut _xmlNode = node;
    while !cur.is_null() {
        let cur_node = unsafe { &*cur };
        let mut ns_def = cur_node.nsDef;
        while !ns_def.is_null() {
            let ns = unsafe { &*ns_def };
            let match_found = if prefix.is_null() {
                // Default namespace: prefix should be NULL
                ns.prefix.is_null()
            } else if ns.prefix.is_null() {
                false
            } else {
                unsafe { crate::abi::exports_xml2::xmlStrEqual(ns.prefix, prefix) != 0 }
            };
            if match_found {
                return ns_def;
            }
            ns_def = ns.next;
        }
        cur = cur_node.parent;
    }

    ptr::null_mut()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Namespace Serialization
// ═══════════════════════════════════════════════════════════════════════════════

/// Serialize namespace declarations to the output buffer.
///
/// Outputs namespace declarations in canonical order.
///
/// # SAFETY
///
/// - `buf` must be a valid pointer to a mutable `_xmlBuffer`.
/// - `ns_list` contains raw pointers that must be valid.
unsafe fn c14n_serialize_namespaces(buf: *mut _xmlBuffer, ns_list: &[CollectedNs]) {
    if buf.is_null() || ns_list.is_empty() {
        return;
    }

    for ns in ns_list {
        io::buf_add(buf, b" xmlns" as *const u8, 6);
        if !ns.prefix.is_null() {
            io::buf_ccat(buf, b':');
            io::buf_cat(buf, ns.prefix);
        }
        io::buf_add(buf, b"=\"" as *const u8, 2);
        if !ns.href.is_null() {
            c14n_escape_attr(buf, ns.href);
        }
        io::buf_ccat(buf, b'"');
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Attribute Ordering (Canonical)
// ═══════════════════════════════════════════════════════════════════════════════

/// Compare two attribute pointers for canonical ordering.
///
/// Canonical ordering: lexicographic by namespace URI (with empty namespace
/// coming first), then by local name.
///
/// Returns negative, zero, or positive.
///
/// # SAFETY
///
/// - `a` and `b` must be valid pointers to `_xmlAttr`.
unsafe fn compare_attrs(a: *const _xmlAttr, b: *const _xmlAttr) -> std::cmp::Ordering {
    let attr_a = unsafe { &*a };
    let attr_b = unsafe { &*b };

    // Get namespace URIs (empty string if no namespace)
    let ns_uri_a = if !attr_a.ns.is_null() {
        unsafe { &*attr_a.ns }.href
    } else {
        ptr::null()
    };
    let ns_uri_b = if !attr_b.ns.is_null() {
        unsafe { &*attr_b.ns }.href
    } else {
        ptr::null()
    };

    // Namespace URI comparison: NULL (no namespace) sorts before any URI
    if ns_uri_a.is_null() && !ns_uri_b.is_null() {
        return std::cmp::Ordering::Less;
    }
    if !ns_uri_a.is_null() && ns_uri_b.is_null() {
        return std::cmp::Ordering::Greater;
    }
    if !ns_uri_a.is_null() && !ns_uri_b.is_null() {
        let cmp = unsafe { crate::abi::exports_xml2::xmlStrcmp(ns_uri_a, ns_uri_b) };
        if cmp != 0 {
            return cmp.cmp(&0);
        }
    }

    // Local name comparison
    let name_a = attr_a.name;
    let name_b = attr_b.name;
    if name_a.is_null() && name_b.is_null() {
        return std::cmp::Ordering::Equal;
    }
    if name_a.is_null() {
        return std::cmp::Ordering::Less;
    }
    if name_b.is_null() {
        return std::cmp::Ordering::Greater;
    }
    let cmp = unsafe { crate::abi::exports_xml2::xmlStrcmp(name_a, name_b) };
    cmp.cmp(&0)
}

/// Serialize attributes in canonical order.
///
/// Attributes are sorted lexicographically by namespace URI then local name.
/// The `xmlns:*` attributes are NOT included here — they are handled separately
/// by `c14n_serialize_namespaces`.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `_xmlNode` or NULL.
/// - `buf` must be a valid pointer to a mutable `_xmlBuffer`.
unsafe fn c14n_serialize_attributes(node: *mut _xmlNode, buf: *mut _xmlBuffer) {
    if node.is_null() || buf.is_null() {
        return;
    }

    let n = unsafe { &*node };
    if n.type_ != XML_ELEMENT_NODE as c_int {
        return;
    }

    // Collect attributes into a vector for sorting
    let mut attrs: Vec<*mut _xmlAttr> = Vec::new();
    let mut cur_attr = n.properties;
    while !cur_attr.is_null() {
        attrs.push(cur_attr);
        cur_attr = unsafe { (*cur_attr).next };
    }

    // Sort attributes canonically
    attrs.sort_by(|a, b| unsafe { compare_attrs(*a, *b) });

    // Serialize each attribute
    for &attr in &attrs {
        let a = unsafe { &*attr };

        io::buf_ccat(buf, b' ');

        // Write attribute name with optional namespace prefix
        if !a.ns.is_null() {
            let ans = unsafe { &*a.ns };
            if !ans.prefix.is_null() {
                io::buf_cat(buf, ans.prefix);
                io::buf_ccat(buf, b':');
            }
        }
        if !a.name.is_null() {
            io::buf_cat(buf, a.name);
        }

        io::buf_add(buf, b"=\"" as *const u8, 2);

        // Attribute value from child text node
        if !a.children.is_null() {
            let child = unsafe { &*a.children };
            if child.type_ == XML_TEXT_NODE as c_int && !child.content.is_null() {
                c14n_escape_attr(buf, child.content);
            }
        }

        io::buf_ccat(buf, b'"');
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Node Serialization (Canonical)
// ═══════════════════════════════════════════════════════════════════════════════

/// Serialize a single node in canonical form.
///
/// This is the core recursive canonical serialization function.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `_xmlNode` or NULL.
/// - `ctx` must be a valid pointer to a `C14nContext`.
/// - `buf` must be a valid pointer to a mutable `_xmlBuffer`.
unsafe fn c14n_serialize_node(node: *mut _xmlNode, ctx: &mut C14nContext, buf: *mut _xmlBuffer) {
    if node.is_null() || buf.is_null() {
        return;
    }

    let n = unsafe { &*node };

    match n.type_ {
        t if t == XML_ELEMENT_NODE as c_int => {
            c14n_serialize_element(node, ctx, buf);
        }
        t if t == XML_TEXT_NODE as c_int => {
            if !n.content.is_null() {
                c14n_escape_text(buf, n.content, tree::xml_strlen(n.content));
            }
        }
        t if t == XML_CDATA_SECTION_NODE as c_int => {
            // C14N converts CDATA sections to text
            if !n.content.is_null() {
                c14n_escape_text(buf, n.content, tree::xml_strlen(n.content));
            }
        }
        t if t == XML_COMMENT_NODE as c_int => {
            if ctx.mode.with_comments() {
                io::buf_add(buf, b"<!--" as *const u8, 4);
                if !n.content.is_null() {
                    io::buf_cat(buf, n.content);
                }
                io::buf_add(buf, b"-->" as *const u8, 3);
            }
        }
        t if t == XML_PI_NODE as c_int => {
            io::buf_add(buf, b"<?" as *const u8, 2);
            if !n.name.is_null() {
                io::buf_cat(buf, n.name);
            }
            if !n.content.is_null() && unsafe { *n.content != 0 } {
                io::buf_ccat(buf, b' ');
                io::buf_cat(buf, n.content);
            }
            io::buf_add(buf, b"?>" as *const u8, 2);
        }
        t if t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int => {
            // Serialize children of the document node (skip XML declaration)
            let mut child = n.children;
            while !child.is_null() {
                c14n_serialize_node(child, ctx, buf);
                child = unsafe { (*child).next };
            }
        }
        t if t == XML_DTD_NODE as c_int || t == XML_DOCUMENT_TYPE_NODE as c_int => {
            // Skip DTD nodes in C14N output
        }
        t if t == XML_ENTITY_REF_NODE as c_int => {
            // Entity references are not expanded in canonical XML;
            // instead, the reference itself is output.
            if !n.name.is_null() {
                io::buf_ccat(buf, b'&');
                io::buf_cat(buf, n.name);
                io::buf_ccat(buf, b';');
            }
        }
        _ => {
            // For unknown types, write content if present
            if !n.content.is_null() {
                c14n_escape_text(buf, n.content, tree::xml_strlen(n.content));
            }
        }
    }
}

/// Serialize an element node in canonical form.
///
/// This handles namespace collection, attribute ordering, and recursive
/// child serialization.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `_xmlNode` or NULL.
/// - `ctx` must be a valid pointer to a `C14nContext`.
/// - `buf` must be a valid pointer to a mutable `_xmlBuffer`.
unsafe fn c14n_serialize_element(node: *mut _xmlNode, ctx: &mut C14nContext, buf: *mut _xmlBuffer) {
    if node.is_null() || buf.is_null() {
        return;
    }

    let n = unsafe { &*node };

    // Push a new namespace scope for this element
    ctx.push_scope();

    // Collect namespaces for this element
    let ns_list = c14n_collect_namespaces(node, ctx);

    // Open element: `<`
    io::buf_ccat(buf, b'<');

    // Write element name with optional namespace prefix
    if !n.ns.is_null() {
        let ns = unsafe { &*n.ns };
        if !ns.prefix.is_null() {
            io::buf_cat(buf, ns.prefix);
            io::buf_ccat(buf, b':');
        }
    }
    if !n.name.is_null() {
        io::buf_cat(buf, n.name);
    }

    // Write namespace declarations
    c14n_serialize_namespaces(buf, &ns_list);

    // Write attributes in canonical order
    c14n_serialize_attributes(node, buf);

    if n.children.is_null() {
        // Self-closing tag for empty elements
        io::buf_add(buf, b"/>" as *const u8, 2);
    } else {
        io::buf_ccat(buf, b'>');

        // Serialize children
        let mut child = n.children;
        while !child.is_null() {
            c14n_serialize_node(child, ctx, buf);
            child = unsafe { (*child).next };
        }

        // Close element: `</name>`
        io::buf_add(buf, b"</" as *const u8, 2);
        if !n.ns.is_null() {
            let ns = unsafe { &*n.ns };
            if !ns.prefix.is_null() {
                io::buf_cat(buf, ns.prefix);
                io::buf_ccat(buf, b':');
            }
        }
        if !n.name.is_null() {
            io::buf_cat(buf, n.name);
        }
        io::buf_ccat(buf, b'>');
    }

    // Pop namespace scope
    ctx.pop_scope();
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API — Document-level canonicalization
// ═══════════════════════════════════════════════════════════════════════════════

/// Canonicalize a document (or a subset of nodes) to an xmlBuffer.
///
/// If `nodes` is non-NULL, it is a NULL-terminated array of node pointers
/// that form the subset to canonicalize. If NULL, the entire document is
/// canonicalized.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an `_xmlDoc` or NULL.
/// - `nodes` may be NULL (meaning the entire document) or a NULL-terminated
///   array of `_xmlNode` pointers.
/// - `buf` must be a valid pointer to a mutable `_xmlBuffer`.
/// - `inclusive_ns_prefixes` is a comma-separated list of prefixes or NULL.
pub unsafe fn c14n_doc_dump_memory(
    doc: *mut _xmlDoc,
    nodes: *mut *mut _xmlNode,
    mode: C14nMode,
    inclusive_ns_prefixes: *const xmlChar,
    with_comments: c_int,
    result: *mut *mut xmlChar,
) -> c_int {
    if doc.is_null() || result.is_null() {
        return -1;
    }

    // Determine the effective mode, considering with_comments flag
    let effective_mode = if with_comments != 0 {
        match mode {
            C14nMode::XML_C14N_1_0 => C14nMode::XML_C14N_1_0_WITH_COMMENTS,
            C14nMode::XML_C14N_EXCLUSIVE_1_0 => C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS,
            C14nMode::XML_C14N_1_1 => C14nMode::XML_C14N_1_1_WITH_COMMENTS,
            _ => mode,
        }
    } else {
        mode
    };

    // Parse inclusive namespace prefixes
    let inclusive_set = parse_inclusive_prefixes(inclusive_ns_prefixes);

    let mut ctx = C14nContext::new(doc, effective_mode, inclusive_set);

    // Create output buffer
    let buf = io::buf_create(-1);
    if buf.is_null() {
        return -1;
    }

    if nodes.is_null() {
        // Canonicalize entire document
        let doc_node = doc as *mut _xmlNode;
        let d = unsafe { &*doc_node };
        let mut child = d.children;
        while !child.is_null() {
            c14n_serialize_node(child, &mut ctx, buf);
            child = unsafe { (*child).next };
        }
    } else {
        // Canonicalize a subset of nodes in document order
        // First, collect and sort nodes in document order
        let mut node_vec: Vec<*mut _xmlNode> = Vec::new();
        let mut i = 0;
        loop {
            let n = unsafe { *nodes.add(i) };
            if n.is_null() {
                break;
            }
            node_vec.push(n);
            i += 1;
        }

        // Sort nodes in document order
        node_vec.sort_by(|a, b| unsafe { cmp_document_order(*a, *b) });

        for &n in &node_vec {
            c14n_serialize_node(n, &mut ctx, buf);
        }
    }

    // Extract result string
    let content = io::buf_content(buf);
    let len = io::buf_length(buf);
    if content.is_null() || len < 0 {
        io::buf_free(buf);
        return -1;
    }

    // Duplicate the content for the caller
    let result_str = crate::abi::exports_xml2::xmlStrdup(content);
    io::buf_free(buf);

    if result_str.is_null() {
        return -1;
    }

    unsafe {
        *result = result_str;
    }

    len
}

/// Canonicalize a document to an output buffer via callback.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an `_xmlDoc` or NULL.
/// - `callback` must be a valid function pointer.
/// - `inclusive_ns_prefixes` is a comma-separated list of prefixes or NULL.
pub unsafe fn c14n_execute(
    doc: *mut _xmlDoc,
    mode: C14nMode,
    inclusive_ns_prefixes: *const xmlChar,
    with_comments: c_int,
    callback: Option<
        unsafe extern "C" fn(ctx: *mut c_void, data: *const c_char, len: c_int) -> c_int,
    >,
    callback_data: *mut c_void,
) -> c_int {
    if doc.is_null() || callback.is_none() {
        return -1;
    }

    let callback = callback.unwrap();

    // Determine effective mode
    let effective_mode = if with_comments != 0 {
        match mode {
            C14nMode::XML_C14N_1_0 => C14nMode::XML_C14N_1_0_WITH_COMMENTS,
            C14nMode::XML_C14N_EXCLUSIVE_1_0 => C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS,
            C14nMode::XML_C14N_1_1 => C14nMode::XML_C14N_1_1_WITH_COMMENTS,
            _ => mode,
        }
    } else {
        mode
    };

    // Parse inclusive namespace prefixes
    let inclusive_set = parse_inclusive_prefixes(inclusive_ns_prefixes);

    let mut ctx = C14nContext::new(doc, effective_mode, inclusive_set);

    // Create output buffer
    let buf = io::buf_create(-1);
    if buf.is_null() {
        return -1;
    }

    // Canonicalize entire document
    let doc_node = doc as *mut _xmlNode;
    let d = unsafe { &*doc_node };
    let mut child = d.children;
    while !child.is_null() {
        c14n_serialize_node(child, &mut ctx, buf);
        child = unsafe { (*child).next };
    }

    // Call the callback with the result
    let content = io::buf_content(buf);
    let len = io::buf_length(buf);
    if content.is_null() || len < 0 {
        io::buf_free(buf);
        return -1;
    }

    let ret = unsafe { callback(callback_data, content as *const c_char, len) };

    io::buf_free(buf);
    ret
}

/// Canonicalize a document and save to an output buffer.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an `_xmlDoc` or NULL.
/// - `output` must be a valid pointer to an `_xmlOutputBuffer` or NULL.
/// - `inclusive_ns_prefixes` is a comma-separated list of prefixes or NULL.
pub unsafe fn c14n_doc_save_to(
    doc: *mut _xmlDoc,
    nodes: *mut *mut _xmlNode,
    mode: C14nMode,
    inclusive_ns_prefixes: *const xmlChar,
    with_comments: c_int,
    output: *mut _xmlOutputBuffer,
) -> c_int {
    if doc.is_null() || output.is_null() {
        return -1;
    }

    // Determine effective mode
    let effective_mode = if with_comments != 0 {
        match mode {
            C14nMode::XML_C14N_1_0 => C14nMode::XML_C14N_1_0_WITH_COMMENTS,
            C14nMode::XML_C14N_EXCLUSIVE_1_0 => C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS,
            C14nMode::XML_C14N_1_1 => C14nMode::XML_C14N_1_1_WITH_COMMENTS,
            _ => mode,
        }
    } else {
        mode
    };

    // Parse inclusive namespace prefixes
    let inclusive_set = parse_inclusive_prefixes(inclusive_ns_prefixes);

    let mut ctx = C14nContext::new(doc, effective_mode, inclusive_set);

    // Create buffer for serialization
    let buf = io::buf_create(-1);
    if buf.is_null() {
        return -1;
    }

    if nodes.is_null() {
        // Canonicalize entire document
        let doc_node = doc as *mut _xmlNode;
        let d = unsafe { &*doc_node };
        let mut child = d.children;
        while !child.is_null() {
            c14n_serialize_node(child, &mut ctx, buf);
            child = unsafe { (*child).next };
        }
    } else {
        // Canonicalize a subset of nodes in document order
        let mut node_vec: Vec<*mut _xmlNode> = Vec::new();
        let mut i = 0;
        loop {
            let n = unsafe { *nodes.add(i) };
            if n.is_null() {
                break;
            }
            node_vec.push(n);
            i += 1;
        }

        node_vec.sort_by(|a, b| unsafe { cmp_document_order(*a, *b) });

        for &n in &node_vec {
            c14n_serialize_node(n, &mut ctx, buf);
        }
    }

    // Write to output buffer
    let content = io::buf_content(buf);
    let len = io::buf_length(buf);
    if content.is_null() || len < 0 {
        io::buf_free(buf);
        return -1;
    }

    let written = io::output_buffer_write(output, len, content as *const c_char);
    io::buf_free(buf);

    // Flush the output buffer to ensure data reaches the underlying target
    let flush_ret = io::output_buffer_flush(output);
    if flush_ret < 0 {
        return written;
    }

    written
}

// ═══════════════════════════════════════════════════════════════════════════════
// Helper Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse a comma-separated list of inclusive namespace prefixes.
///
/// Returns `None` if the input is NULL (meaning no inclusive prefixes).
fn parse_inclusive_prefixes(input: *const xmlChar) -> Option<HashSet<String>> {
    if input.is_null() {
        return None;
    }

    let input_str = unsafe {
        let c_str = core::ffi::CStr::from_ptr(input as *const c_char);
        match c_str.to_str() {
            Ok(s) => s.to_string(),
            Err(_) => return None,
        }
    };

    if input_str.is_empty() {
        return None;
    }

    let mut set = HashSet::new();
    for prefix in input_str.split(',') {
        let trimmed = prefix.trim();
        if !trimmed.is_empty() {
            set.insert(trimmed.to_string());
        }
    }

    if set.is_empty() {
        None
    } else {
        Some(set)
    }
}

/// Compare two nodes in document order.
///
/// Returns negative if `a` comes before `b`, positive if `a` comes after `b`.
///
/// # SAFETY
///
/// - `a` and `b` must be valid pointers to `_xmlNode`.
unsafe fn cmp_document_order(a: *mut _xmlNode, b: *mut _xmlNode) -> std::cmp::Ordering {
    if a == b {
        return std::cmp::Ordering::Equal;
    }

    // Build ancestor chains
    let mut ancestors_a: Vec<*mut _xmlNode> = Vec::new();
    let mut cur = a;
    while !cur.is_null() {
        ancestors_a.push(cur);
        cur = unsafe { (*cur).parent };
    }

    let mut ancestors_b: Vec<*mut _xmlNode> = Vec::new();
    let mut cur = b;
    while !cur.is_null() {
        ancestors_b.push(cur);
        cur = unsafe { (*cur).parent };
    }

    // Find the lowest common ancestor
    let mut i = ancestors_a.len();
    let mut j = ancestors_b.len();

    while i > 0 && j > 0 && ancestors_a[i - 1] == ancestors_b[j - 1] {
        i -= 1;
        j -= 1;
    }

    if i == 0 || j == 0 {
        // One is an ancestor of the other
        if i == 0 {
            return std::cmp::Ordering::Less;
        }
        return std::cmp::Ordering::Greater;
    }

    // The nodes at i-1 and j-1 are siblings under the common ancestor.
    // Determine their order by walking the sibling chain.
    let sibling_a = ancestors_a[i - 1];
    let sibling_b = ancestors_b[j - 1];

    // Walk forward from sibling_a to see if we find sibling_b
    let mut walk = sibling_a;
    while !walk.is_null() {
        if walk == sibling_b {
            return std::cmp::Ordering::Less;
        }
        walk = unsafe { (*walk).next };
    }

    // sibling_b must be before sibling_a
    std::cmp::Ordering::Greater
}

// ═══════════════════════════════════════════════════════════════════════════════
// C ABI Exports
// ═══════════════════════════════════════════════════════════════════════════════

/// Serialize canonical XML to a memory buffer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlC14NDocDumpMemory(
///     xmlDocPtr doc,
///     xmlNodeSetPtr nodes,
///     int mode,
///     xmlChar **inclusive_ns_prefixes,
///     int with_comments,
///     xmlChar **result
/// );
/// ```
///
/// Serializes `doc` (or a subset of `nodes`) to canonical XML.
/// The result is allocated with `xmlMalloc` and must be freed by the caller
/// with `xmlFree`.
///
/// Returns the length of the result string in bytes, or -1 on error.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an `_xmlDoc` or NULL.
/// - `nodes` may be NULL (entire document) or a NULL-terminated array of `_xmlNode` pointers.
/// - `result` must be a valid pointer to a `xmlChar*` that will receive the result.
#[no_mangle]
pub unsafe extern "C" fn xmlC14NDocDumpMemory(
    doc: *mut _xmlDoc,
    nodes: *mut *mut _xmlNode,
    mode: c_int,
    inclusive_ns_prefixes: *mut *mut xmlChar,
    with_comments: c_int,
    result: *mut *mut xmlChar,
) -> c_int {
    // SAFETY: Delegates to the safe internal implementation.
    // The caller must provide valid pointers or NULL as documented.

    let c14n_mode = match mode {
        0 => C14nMode::XML_C14N_1_0,
        1 => C14nMode::XML_C14N_EXCLUSIVE_1_0,
        2 => C14nMode::XML_C14N_1_1,
        3 => C14nMode::XML_C14N_1_0_WITH_COMMENTS,
        4 => C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS,
        5 => C14nMode::XML_C14N_1_1_WITH_COMMENTS,
        _ => return -1,
    };

    // The inclusive_ns_prefixes parameter in the upstream API is a
    // NULL-terminated array of xmlChar* strings. We join them with commas
    // for our internal parser.
    let joined_prefixes = if !inclusive_ns_prefixes.is_null() {
        let mut parts: Vec<*mut xmlChar> = Vec::new();
        let mut i = 0;
        loop {
            let p = unsafe { *inclusive_ns_prefixes.add(i) };
            if p.is_null() {
                break;
            }
            parts.push(p);
            i += 1;
        }

        if parts.is_empty() {
            ptr::null()
        } else {
            // Build comma-separated string
            let mut result_str = Vec::<u8>::new();
            for (idx, &part) in parts.iter().enumerate() {
                if idx > 0 {
                    result_str.push(b',');
                }
                let len = tree::xml_strlen(part);
                let part_slice = unsafe { core::slice::from_raw_parts(part, len as usize) };
                result_str.extend_from_slice(part_slice);
            }
            result_str.push(0); // null-terminate
            result_str.as_ptr() as *const xmlChar
        }
    } else {
        ptr::null()
    };

    unsafe {
        c14n_doc_dump_memory(
            doc,
            nodes,
            c14n_mode,
            joined_prefixes,
            with_comments,
            result,
        )
    }
}

/// Canonicalize XML with a callback for output.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlC14NExecute(
///     xmlDocPtr doc,
///     int mode,
///     xmlChar **inclusive_ns_prefixes,
///     int with_comments,
///     xmlC14NIOWriteCallback callback,
///     void *callback_data
/// );
/// ```
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an `_xmlDoc` or NULL.
/// - `callback` must be a valid function pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlC14NExecute(
    doc: *mut _xmlDoc,
    mode: c_int,
    inclusive_ns_prefixes: *mut *mut xmlChar,
    with_comments: c_int,
    callback: Option<
        unsafe extern "C" fn(ctx: *mut c_void, data: *const c_char, len: c_int) -> c_int,
    >,
    callback_data: *mut c_void,
) -> c_int {
    // SAFETY: Delegates to the safe internal implementation.

    let c14n_mode = match mode {
        0 => C14nMode::XML_C14N_1_0,
        1 => C14nMode::XML_C14N_EXCLUSIVE_1_0,
        2 => C14nMode::XML_C14N_1_1,
        3 => C14nMode::XML_C14N_1_0_WITH_COMMENTS,
        4 => C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS,
        5 => C14nMode::XML_C14N_1_1_WITH_COMMENTS,
        _ => return -1,
    };

    let joined_prefixes = if !inclusive_ns_prefixes.is_null() {
        let mut parts: Vec<*mut xmlChar> = Vec::new();
        let mut i = 0;
        loop {
            let p = unsafe { *inclusive_ns_prefixes.add(i) };
            if p.is_null() {
                break;
            }
            parts.push(p);
            i += 1;
        }

        if parts.is_empty() {
            ptr::null()
        } else {
            let mut result_str = Vec::<u8>::new();
            for (idx, &part) in parts.iter().enumerate() {
                if idx > 0 {
                    result_str.push(b',');
                }
                let len = tree::xml_strlen(part);
                let part_slice = unsafe { core::slice::from_raw_parts(part, len as usize) };
                result_str.extend_from_slice(part_slice);
            }
            result_str.push(0);
            result_str.as_ptr() as *const xmlChar
        }
    } else {
        ptr::null()
    };

    unsafe {
        c14n_execute(
            doc,
            c14n_mode,
            joined_prefixes,
            with_comments,
            callback,
            callback_data,
        )
    }
}

/// Save canonical XML to an output buffer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlC14NDocSaveTo(
///     xmlDocPtr doc,
///     xmlNodeSetPtr nodes,
///     int mode,
///     xmlChar **inclusive_ns_prefixes,
///     int with_comments,
///     xmlOutputBufferPtr output
/// );
/// ```
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an `_xmlDoc` or NULL.
/// - `output` must be a valid pointer to an `_xmlOutputBuffer` or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlC14NDocSaveTo(
    doc: *mut _xmlDoc,
    nodes: *mut *mut _xmlNode,
    mode: c_int,
    inclusive_ns_prefixes: *mut *mut xmlChar,
    with_comments: c_int,
    output: *mut _xmlOutputBuffer,
) -> c_int {
    // SAFETY: Delegates to the safe internal implementation.

    let c14n_mode = match mode {
        0 => C14nMode::XML_C14N_1_0,
        1 => C14nMode::XML_C14N_EXCLUSIVE_1_0,
        2 => C14nMode::XML_C14N_1_1,
        3 => C14nMode::XML_C14N_1_0_WITH_COMMENTS,
        4 => C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS,
        5 => C14nMode::XML_C14N_1_1_WITH_COMMENTS,
        _ => return -1,
    };

    let joined_prefixes: Option<Vec<u8>> = if !inclusive_ns_prefixes.is_null() {
        let mut parts: Vec<*mut xmlChar> = Vec::new();
        let mut i = 0;
        loop {
            let p = unsafe { *inclusive_ns_prefixes.add(i) };
            if p.is_null() {
                break;
            }
            parts.push(p);
            i += 1;
        }

        if parts.is_empty() {
            None
        } else {
            let mut result_str = Vec::<u8>::new();
            for (idx, &part) in parts.iter().enumerate() {
                if idx > 0 {
                    result_str.push(b',');
                }
                let len = tree::xml_strlen(part);
                let part_slice = unsafe { core::slice::from_raw_parts(part, len as usize) };
                result_str.extend_from_slice(part_slice);
            }
            result_str.push(0);
            Some(result_str)
        }
    } else {
        None
    };

    let joined_ptr = joined_prefixes
        .as_ref()
        .map(|v| v.as_ptr() as *const xmlChar)
        .unwrap_or(ptr::null());

    unsafe { c14n_doc_save_to(doc, nodes, c14n_mode, joined_ptr, with_comments, output) }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abi::allocator::xmlFreeImpl;
    use crate::xml::io;
    use crate::xml::tree;
    use core::ptr;
    use std::os::raw::c_int;

    /// Helper: create a simple document for testing.
    ///
    /// Creates: `<root><child attr="value">text</child></root>`
    unsafe fn create_simple_doc() -> *mut _xmlDoc {
        let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
        assert!(!doc.is_null());

        let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
        assert!(!root.is_null());
        tree::doc_set_root_element(doc, root);

        let child = tree::new_node(ptr::null_mut(), b"child\0" as *const u8 as *const xmlChar);
        assert!(!child.is_null());
        tree::add_child(root, child);

        // Set attribute
        tree::set_prop(
            child,
            b"attr\0" as *const u8 as *const xmlChar,
            b"value\0" as *const u8 as *const xmlChar,
        );

        // Set text content
        let text = tree::new_text(b"text\0" as *const u8 as *const xmlChar);
        assert!(!text.is_null());
        tree::add_child(child, text);

        doc
    }

    /// Helper: canonicalize a document and return the result as a String.
    unsafe fn canonicalize_doc(doc: *mut _xmlDoc, mode: C14nMode, with_comments: c_int) -> String {
        let mut result: *mut xmlChar = ptr::null_mut();
        let len = c14n_doc_dump_memory(
            doc,
            ptr::null_mut(),
            mode,
            ptr::null(),
            with_comments,
            &mut result as *mut *mut xmlChar,
        );
        assert!(len >= 0);
        assert!(!result.is_null());

        let s = {
            let slice = core::slice::from_raw_parts(result, len as usize);
            String::from_utf8_lossy(slice).to_string()
        };
        xmlFreeImpl(result as *mut c_void);
        s
    }

    // ── Basic document canonicalization ──

    #[test]
    fn test_c14n_basic_document() {
        unsafe {
            let doc = create_simple_doc();
            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(
                result.contains("<root>"),
                "Result should contain <root>, got: {}",
                result
            );
            assert!(
                result.contains("<child"),
                "Result should contain <child>, got: {}",
                result
            );
            assert!(
                result.contains("attr=\"value\""),
                "Result should contain attr=\"value\", got: {}",
                result
            );
            assert!(
                result.contains("text"),
                "Result should contain text, got: {}",
                result
            );
            assert!(
                result.contains("</child>"),
                "Result should contain </child>, got: {}",
                result
            );
            assert!(
                result.contains("</root>"),
                "Result should contain </root>, got: {}",
                result
            );
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_basic_empty_element() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());
            let root = tree::new_node(ptr::null_mut(), b"empty\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            // Empty element should be self-closing
            assert!(
                result.contains("<empty/>"),
                "Empty element should be self-closing, got: {}",
                result
            );
            tree::free_doc(doc);
        }
    }

    // ── Namespace propagation ──

    #[test]
    fn test_c14n_namespace_propagation() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let ns = tree::new_ns(
                ptr::null_mut(),
                b"http://example.com/ns\0" as *const u8 as *const xmlChar,
                b"ex\0" as *const u8 as *const xmlChar,
            );
            assert!(!ns.is_null());

            let root = tree::new_node(ns, b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            // Re-attach the namespace to the root node
            tree::new_ns(
                root,
                b"http://example.com/ns\0" as *const u8 as *const xmlChar,
                b"ex\0" as *const u8 as *const xmlChar,
            );

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(
                result.contains("xmlns:ex=\"http://example.com/ns\""),
                "Result should contain namespace declaration, got: {}",
                result
            );
            assert!(
                result.contains("<ex:root"),
                "Result should contain <ex:root, got: {}",
                result
            );
            tree::free_doc(doc);
        }
    }

    // ── Attribute ordering ──

    #[test]
    fn test_c14n_attribute_ordering() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            // Set attributes in reverse alphabetical order
            tree::set_prop(
                root,
                b"zeta\0" as *const u8 as *const xmlChar,
                b"1\0" as *const u8 as *const xmlChar,
            );
            tree::set_prop(
                root,
                b"alpha\0" as *const u8 as *const xmlChar,
                b"2\0" as *const u8 as *const xmlChar,
            );
            tree::set_prop(
                root,
                b"beta\0" as *const u8 as *const xmlChar,
                b"3\0" as *const u8 as *const xmlChar,
            );

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);

            // Find the position of each attribute in the output
            let alpha_pos = result.find("alpha=\"2\"");
            let beta_pos = result.find("beta=\"3\"");
            let zeta_pos = result.find("zeta=\"1\"");

            assert!(alpha_pos.is_some(), "alpha attribute should be present");
            assert!(beta_pos.is_some(), "beta attribute should be present");
            assert!(zeta_pos.is_some(), "zeta attribute should be present");

            // alpha should come before beta, beta before zeta
            assert!(
                alpha_pos.unwrap() < beta_pos.unwrap(),
                "alpha should come before beta"
            );
            assert!(
                beta_pos.unwrap() < zeta_pos.unwrap(),
                "beta should come before zeta"
            );

            tree::free_doc(doc);
        }
    }

    // ── Character escaping ──

    #[test]
    fn test_c14n_character_escaping_text() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            // Text with special characters
            let text = tree::new_text(b"a < b & c > d\r\0" as *const u8 as *const xmlChar);
            assert!(!text.is_null());
            tree::add_child(root, text);

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(result.contains("&lt;"), "Should escape <, got: {}", result);
            assert!(result.contains("&amp;"), "Should escape &, got: {}", result);
            assert!(result.contains("&gt;"), "Should escape >, got: {}", result);
            assert!(
                result.contains("&#xD;"),
                "Should escape CR, got: {}",
                result
            );

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_character_escaping_attr() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            // Attribute value with special characters including tab, newline, CR
            tree::set_prop(
                root,
                b"test\0" as *const u8 as *const xmlChar,
                b"a < b & c \" d\t\n\r\0" as *const u8 as *const xmlChar,
            );

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(
                result.contains("&lt;"),
                "Should escape < in attr, got: {}",
                result
            );
            assert!(
                result.contains("&amp;"),
                "Should escape & in attr, got: {}",
                result
            );
            assert!(
                result.contains("&quot;"),
                "Should escape \" in attr, got: {}",
                result
            );
            assert!(
                result.contains("&#x9;"),
                "Should escape tab in attr, got: {}",
                result
            );
            assert!(
                result.contains("&#xA;"),
                "Should escape newline in attr, got: {}",
                result
            );
            assert!(
                result.contains("&#xD;"),
                "Should escape CR in attr, got: {}",
                result
            );

            tree::free_doc(doc);
        }
    }

    // ── With comments ──

    #[test]
    fn test_c14n_with_comments() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            let comment = tree::new_comment(b" a comment \0" as *const u8 as *const xmlChar);
            assert!(!comment.is_null());
            tree::add_child(root, comment);

            // Without comments
            let result_no_comments = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(
                !result_no_comments.contains("<!--"),
                "Without comments: should not contain comments, got: {}",
                result_no_comments
            );

            // With comments
            let result_with_comments =
                canonicalize_doc(doc, C14nMode::XML_C14N_1_0_WITH_COMMENTS, 0);
            assert!(
                result_with_comments.contains("<!--"),
                "With comments: should contain comments, got: {}",
                result_with_comments
            );

            tree::free_doc(doc);
        }
    }

    // ── Exclusive vs inclusive ──

    #[test]
    fn test_c14n_exclusive_vs_inclusive() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            // Create root with a namespace
            tree::new_ns(
                ptr::null_mut(),
                b"http://example.com/ns1\0" as *const u8 as *const xmlChar,
                b"ns1\0" as *const u8 as *const xmlChar,
            );
            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);
            tree::new_ns(
                root,
                b"http://example.com/ns1\0" as *const u8 as *const xmlChar,
                b"ns1\0" as *const u8 as *const xmlChar,
            );

            // Child without any namespace usage
            let child = tree::new_node(ptr::null_mut(), b"child\0" as *const u8 as *const xmlChar);
            assert!(!child.is_null());
            tree::add_child(root, child);

            // Inclusive C14N should include the ns1 namespace on child
            let result_inclusive = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            // The inclusive output will include namespace declarations from ancestors
            // on each element.

            // Exclusive C14N should NOT include the ns1 namespace on child
            // since the child doesn't use it
            let _result_exclusive = canonicalize_doc(doc, C14nMode::XML_C14N_EXCLUSIVE_1_0, 0);

            // In inclusive mode, the namespace should be visible
            // In exclusive mode, it should NOT be on the child (which doesn't use ns1)
            // The root element in exclusive mode still has ns1 declared on it

            // Both should contain the ns1 namespace somewhere
            assert!(
                result_inclusive.contains("ns1"),
                "Inclusive should have ns1, got: {}",
                result_inclusive
            );

            tree::free_doc(doc);
        }
    }

    // ── XML declaration handling ──

    #[test]
    fn test_c14n_no_xml_declaration() {
        unsafe {
            let doc = create_simple_doc();
            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            // C14N output should NOT include the XML declaration
            assert!(
                !result.contains("<?xml"),
                "C14N output should not contain XML declaration, got: {}",
                result
            );
            tree::free_doc(doc);
        }
    }

    // ── Empty document ──

    #[test]
    fn test_c14n_empty_document() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(
                result.is_empty(),
                "Empty document should produce empty output, got: {}",
                result
            );

            tree::free_doc(doc);
        }
    }

    // ── Edge cases ──

    #[test]
    fn test_c14n_null_doc() {
        unsafe {
            let mut result: *mut xmlChar = ptr::null_mut();
            let len = c14n_doc_dump_memory(
                ptr::null_mut(),
                ptr::null_mut(),
                C14nMode::XML_C14N_1_0,
                ptr::null(),
                0,
                &mut result as *mut *mut xmlChar,
            );
            assert_eq!(len, -1, "Null doc should return -1");
        }
    }

    #[test]
    fn test_c14n_text_node() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            // Text node with various content
            let text = tree::new_text(b"Hello World\0" as *const u8 as *const xmlChar);
            assert!(!text.is_null());
            tree::add_child(root, text);

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(
                result.contains("Hello World"),
                "Should contain text content, got: {}",
                result
            );

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_cdata_section() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            // CDATA section content is represented as a text node in the tree
            // For C14N, CDATA sections are converted to text
            let cdata =
                tree::new_text(b"<greeting>Hello</greeting>\0" as *const u8 as *const xmlChar);
            assert!(!cdata.is_null());
            tree::add_child(root, cdata);

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(
                result.contains("&lt;greeting&gt;"),
                "CDATA should be converted to escaped text, got: {}",
                result
            );

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_pi_node() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            let pi = tree::new_pi(
                b"xml-model\0" as *const u8 as *const xmlChar,
                b"href=\"schema.xsd\"\0" as *const u8 as *const xmlChar,
            );
            assert!(!pi.is_null());
            tree::add_child(root, pi);

            let result = canonicalize_doc(doc, C14nMode::XML_C14N_1_0, 0);
            assert!(result.contains("<?"), "Should contain PI, got: {}", result);

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_with_comments_flag() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            let comment = tree::new_comment(b"test\0" as *const u8 as *const xmlChar);
            assert!(!comment.is_null());
            tree::add_child(root, comment);

            // Using the with_comments flag with the base mode
            let mut result: *mut xmlChar = ptr::null_mut();
            let len = c14n_doc_dump_memory(
                doc,
                ptr::null_mut(),
                C14nMode::XML_C14N_1_0,
                ptr::null(),
                1, // with_comments = true
                &mut result as *mut *mut xmlChar,
            );
            assert!(len >= 0);
            let s = {
                let slice = core::slice::from_raw_parts(result, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            xmlFreeImpl(result as *mut c_void);

            assert!(
                s.contains("<!--"),
                "With comments flag should include comments, got: {}",
                s
            );

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_mode_enum_values() {
        // Verify mode enum values match upstream constants
        assert_eq!(C14nMode::XML_C14N_1_0 as c_int, 0);
        assert_eq!(C14nMode::XML_C14N_EXCLUSIVE_1_0 as c_int, 1);
        assert_eq!(C14nMode::XML_C14N_1_1 as c_int, 2);
        assert_eq!(C14nMode::XML_C14N_1_0_WITH_COMMENTS as c_int, 3);
        assert_eq!(C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS as c_int, 4);
        assert_eq!(C14nMode::XML_C14N_1_1_WITH_COMMENTS as c_int, 5);
    }

    #[test]
    fn test_c14n_with_comments_property() {
        assert!(C14nMode::XML_C14N_1_0_WITH_COMMENTS.with_comments());
        assert!(C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS.with_comments());
        assert!(C14nMode::XML_C14N_1_1_WITH_COMMENTS.with_comments());
        assert!(!C14nMode::XML_C14N_1_0.with_comments());
        assert!(!C14nMode::XML_C14N_EXCLUSIVE_1_0.with_comments());
        assert!(!C14nMode::XML_C14N_1_1.with_comments());
    }

    #[test]
    fn test_c14n_is_exclusive_property() {
        assert!(C14nMode::XML_C14N_EXCLUSIVE_1_0.is_exclusive());
        assert!(C14nMode::XML_C14N_EXCLUSIVE_1_0_WITH_COMMENTS.is_exclusive());
        assert!(!C14nMode::XML_C14N_1_0.is_exclusive());
        assert!(!C14nMode::XML_C14N_1_0_WITH_COMMENTS.is_exclusive());
        assert!(!C14nMode::XML_C14N_1_1.is_exclusive());
    }

    #[test]
    fn test_c14n_escape_text_cr() {
        unsafe {
            let buf = io::buf_create(-1);
            assert!(!buf.is_null());

            let text = b"line1\r\nline2\r\0" as *const u8 as *const xmlChar;
            c14n_escape_text(buf, text, 13);

            let content = io::buf_content(buf);
            let len = io::buf_length(buf);
            let s = {
                let slice = core::slice::from_raw_parts(content, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            assert!(
                s.contains("&#xD;"),
                "CR should be escaped as &#xD;, got: {}",
                s
            );
            assert!(s.contains("\n"), "LF should remain as-is, got: {}", s);

            io::buf_free(buf);
        }
    }

    #[test]
    fn test_c14n_escape_attr_tab_nl_cr() {
        unsafe {
            let buf = io::buf_create(-1);
            assert!(!buf.is_null());

            let text = b"a\tb\nc\rd\0" as *const u8 as *const xmlChar;
            c14n_escape_attr(buf, text);

            let content = io::buf_content(buf);
            let len = io::buf_length(buf);
            let s = {
                let slice = core::slice::from_raw_parts(content, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            assert!(
                s.contains("&#x9;"),
                "Tab should be escaped as &#x9;, got: {}",
                s
            );
            assert!(
                s.contains("&#xA;"),
                "NL should be escaped as &#xA;, got: {}",
                s
            );
            assert!(
                s.contains("&#xD;"),
                "CR should be escaped as &#xD;, got: {}",
                s
            );

            io::buf_free(buf);
        }
    }

    #[test]
    fn test_c14n_parse_inclusive_prefixes() {
        // Test NULL input
        assert!(parse_inclusive_prefixes(ptr::null()).is_none());

        // Test empty string
        let empty = b"\0" as *const u8 as *const xmlChar;
        assert!(parse_inclusive_prefixes(empty).is_none());

        // Test single prefix
        let single = b"foo\0" as *const u8 as *const xmlChar;
        let result = parse_inclusive_prefixes(single);
        assert!(result.is_some());
        assert!(result.unwrap().contains("foo"));

        // Test multiple prefixes
        let multi = b"foo,bar,baz\0" as *const u8 as *const xmlChar;
        let result = parse_inclusive_prefixes(multi);
        assert!(result.is_some());
        let set = result.unwrap();
        assert!(set.contains("foo"));
        assert!(set.contains("bar"));
        assert!(set.contains("baz"));
        assert_eq!(set.len(), 3);
    }

    #[test]
    fn test_c14n_document_order() {
        unsafe {
            let doc = tree::new_doc(b"1.0\0" as *const u8 as *const xmlChar);
            assert!(!doc.is_null());

            let root = tree::new_node(ptr::null_mut(), b"root\0" as *const u8 as *const xmlChar);
            assert!(!root.is_null());
            tree::doc_set_root_element(doc, root);

            let child1 =
                tree::new_node(ptr::null_mut(), b"child1\0" as *const u8 as *const xmlChar);
            assert!(!child1.is_null());
            tree::add_child(root, child1);

            let child2 =
                tree::new_node(ptr::null_mut(), b"child2\0" as *const u8 as *const xmlChar);
            assert!(!child2.is_null());
            tree::add_child(root, child2);

            // child1 should come before child2
            assert_eq!(
                cmp_document_order(child1, child2),
                std::cmp::Ordering::Less,
                "child1 should be before child2"
            );
            assert_eq!(
                cmp_document_order(child2, child1),
                std::cmp::Ordering::Greater,
                "child2 should be after child1"
            );
            assert_eq!(
                cmp_document_order(child1, child1),
                std::cmp::Ordering::Equal,
                "Same node should be equal"
            );

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_escape_text_gt() {
        unsafe {
            let buf = io::buf_create(-1);
            assert!(!buf.is_null());

            let text = b"a > b\0" as *const u8 as *const xmlChar;
            c14n_escape_text(buf, text, 5);

            let content = io::buf_content(buf);
            let len = io::buf_length(buf);
            let s = {
                let slice = core::slice::from_raw_parts(content, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            assert!(
                s.contains("&gt;"),
                "> should be escaped as &gt;, got: {}",
                s
            );

            io::buf_free(buf);
        }
    }

    #[test]
    fn test_c14n_escape_text_cdata_end() {
        unsafe {
            let buf = io::buf_create(-1);
            assert!(!buf.is_null());

            let text = b"a]]>b\0" as *const u8 as *const xmlChar;
            c14n_escape_text(buf, text, 5);

            let content = io::buf_content(buf);
            let len = io::buf_length(buf);
            let s = {
                let slice = core::slice::from_raw_parts(content, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            // The `]]>` sequence should become `]]&gt;`
            assert!(
                s.contains("]]&gt;"),
                "]]> should be escaped as ]]&gt;, got: {}",
                s
            );

            io::buf_free(buf);
        }
    }

    #[test]
    fn test_c14n_execute_callback() {
        unsafe {
            let doc = create_simple_doc();

            // Use a heap-allocated Vec passed through the callback context
            let output_vec = Box::into_raw(Box::new(Vec::<u8>::new()));

            unsafe extern "C" fn test_callback(
                ctx: *mut c_void,
                data: *const c_char,
                len: c_int,
            ) -> c_int {
                let slice = unsafe { core::slice::from_raw_parts(data as *const u8, len as usize) };
                let output = unsafe { &mut *(ctx as *mut Vec<u8>) };
                output.extend_from_slice(slice);
                len
            }

            let ret = c14n_execute(
                doc,
                C14nMode::XML_C14N_1_0,
                ptr::null(),
                0,
                Some(
                    test_callback
                        as unsafe extern "C" fn(*mut c_void, *const c_char, c_int) -> c_int,
                ),
                output_vec as *mut c_void,
            );

            assert!(ret >= 0, "c14n_execute should succeed");
            let output = Box::from_raw(output_vec);
            let output_str = String::from_utf8_lossy(&output);
            assert!(
                output_str.contains("<root>"),
                "Callback output should contain <root>, got: {}",
                output_str
            );

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_save_to_output_buffer() {
        unsafe {
            let doc = create_simple_doc();

            // Create an output buffer
            let buf = io::buf_create(-1);
            assert!(!buf.is_null());

            let output = io::output_buffer_create_buffer(buf, ptr::null_mut());
            assert!(!output.is_null());

            let ret = c14n_doc_save_to(
                doc,
                ptr::null_mut(),
                C14nMode::XML_C14N_1_0,
                ptr::null(),
                0,
                output,
            );

            assert!(ret >= 0, "c14n_doc_save_to should succeed");

            let content = io::buf_content(buf);
            let len = io::buf_length(buf);
            let s = {
                let slice = core::slice::from_raw_parts(content, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            assert!(
                s.contains("<root>"),
                "Output buffer should contain <root>, got: {}",
                s
            );

            io::output_buffer_close(output);
            io::buf_free(buf);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_c_abi_doc_dump_memory() {
        unsafe {
            let doc = create_simple_doc();

            let mut result: *mut xmlChar = ptr::null_mut();
            let len = xmlC14NDocDumpMemory(
                doc,
                ptr::null_mut(),
                0, // XML_C14N_1_0
                ptr::null_mut(),
                0, // no comments
                &mut result as *mut *mut xmlChar,
            );

            assert!(len >= 0, "xmlC14NDocDumpMemory should succeed");
            assert!(!result.is_null());

            let s = {
                let slice = core::slice::from_raw_parts(result, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            assert!(
                s.contains("<root>"),
                "C ABI export should produce canonical output, got: {}",
                s
            );

            xmlFreeImpl(result as *mut c_void);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_c_abi_execute() {
        unsafe {
            let doc = create_simple_doc();

            let output_vec = Box::into_raw(Box::new(Vec::<u8>::new()));

            unsafe extern "C" fn test_callback(
                ctx: *mut c_void,
                data: *const c_char,
                len: c_int,
            ) -> c_int {
                let slice = unsafe { core::slice::from_raw_parts(data as *const u8, len as usize) };
                let output = unsafe { &mut *(ctx as *mut Vec<u8>) };
                output.extend_from_slice(slice);
                len
            }

            let ret = xmlC14NExecute(
                doc,
                0, // XML_C14N_1_0
                ptr::null_mut(),
                0,
                Some(
                    test_callback
                        as unsafe extern "C" fn(*mut c_void, *const c_char, c_int) -> c_int,
                ),
                output_vec as *mut c_void,
            );

            assert!(ret >= 0, "xmlC14NExecute should succeed");
            let output = Box::from_raw(output_vec);
            let output_str = String::from_utf8_lossy(&output);
            assert!(
                output_str.contains("<root>"),
                "C ABI execute should produce canonical output, got: {}",
                output_str
            );

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_c14n_c_abi_save_to() {
        unsafe {
            let doc = create_simple_doc();

            let buf = io::buf_create(-1);
            assert!(!buf.is_null());

            let output = io::output_buffer_create_buffer(buf, ptr::null_mut());
            assert!(!output.is_null());

            let ret = xmlC14NDocSaveTo(
                doc,
                ptr::null_mut(),
                0, // XML_C14N_1_0
                ptr::null_mut(),
                0,
                output,
            );

            assert!(ret >= 0, "xmlC14NDocSaveTo should succeed");

            let content = io::buf_content(buf);
            let len = io::buf_length(buf);
            let s = {
                let slice = core::slice::from_raw_parts(content, len as usize);
                String::from_utf8_lossy(slice).to_string()
            };
            assert!(
                s.contains("<root>"),
                "C ABI save_to should produce canonical output, got: {}",
                s
            );

            io::output_buffer_close(output);
            io::buf_free(buf);
            tree::free_doc(doc);
        }
    }
}