exml 0.7.3-deprecated

Pure Rust XML library based on libxml2
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
// Copyright of the original code is the following.
// --------
// Summary: interfaces for tree manipulation
// Description: this module describes the structures found in an tree resulting
//              from an XML or HTML parsing, as well as the API provided for
//              various processing on that tree
//
// Copy: See Copyright for the status of this software.
//
// Author: Daniel Veillard
// --------
// tree.c : implementation of access function for an XML tree.
//
// References:
//   XHTML 1.0 W3C REC: http://www.w3.org/TR/2002/REC-xhtml1-20020801/
//
// See Copyright for the status of this software.
//
// daniel@veillard.com

use std::{os::raw::c_void, ptr::null_mut};

use crate::{
    libxml::globals::{xml_free, xml_malloc},
    valid::{xml_add_id, xml_is_id, xml_remove_id},
};

use super::{
    NodeCommon, XML_LOCAL_NAMESPACE, XmlAttr, XmlAttrPtr, XmlAttributeType, XmlDocPtr,
    XmlElementType, XmlGenericNodePtr, XmlNode, XmlNodePtr, XmlNs, XmlNsPtr, xml_free_ns,
    xml_get_doc_entity, xml_new_ns, xml_search_ns_by_namespace_strict,
    xml_search_ns_by_prefix_strict, xml_tree_err_memory, xml_tree_nslist_lookup_by_prefix,
};

/// A function called to acquire namespaces (xmlNs) from the wrapper.
///
/// Returns an xmlNsPtr or NULL in case of an error.
#[doc(alias = "xmlDOMWrapAcquireNsFunction")]
pub type XmlDOMWrapAcquireNsFunction = unsafe fn(
    ctxt: XmlDOMWrapCtxtPtr,
    node: Option<XmlGenericNodePtr>,
    ns_name: Option<&str>,
    ns_prefix: Option<&str>,
) -> Option<XmlNsPtr>;

/// Context for DOM wrapper-operations.
pub type XmlDOMWrapCtxtPtr = *mut XmlDOMWrapCtxt;
#[repr(C)]
pub struct XmlDOMWrapCtxt {
    pub(super) _private: *mut c_void,
    /// The type of this context, just in case we need specialized
    /// contexts in the future.
    pub(super) typ: i32,
    /// Internal namespace map used for various operations.
    pub(super) namespace_map: *mut c_void,
    /// Use this one to acquire an xmlNsPtr intended for node->ns.  
    /// (Note that this is not intended for elem->nsDef).
    pub(super) get_ns_for_node_func: Option<XmlDOMWrapAcquireNsFunction>,
}

impl Default for XmlDOMWrapCtxt {
    fn default() -> Self {
        Self {
            _private: null_mut(),
            typ: 0,
            namespace_map: null_mut(),
            get_ns_for_node_func: None,
        }
    }
}

pub type XmlNsMapItemPtr = *mut XmlNsMapItem;
#[repr(C)]
pub struct XmlNsMapItem {
    next: XmlNsMapItemPtr,
    prev: XmlNsMapItemPtr,
    old_ns: Option<XmlNsPtr>, /* old ns decl reference */
    new_ns: Option<XmlNsPtr>, /* new ns decl reference */
    shadow_depth: i32,        /* Shadowed at this depth */
    /// depth:
    /// `>= 0` == @node's ns-decls
    /// `-1`   == @parent's ns-decls
    /// `-2`   == the (*doc).oldNs XML ns-decl
    /// `-3`   == the (*doc).oldNs storage ns-decls
    /// `-4`   == ns-decls provided via custom ns-handling
    depth: i32,
}

impl Default for XmlNsMapItem {
    fn default() -> Self {
        Self {
            next: null_mut(),
            prev: null_mut(),
            old_ns: None,
            new_ns: None,
            shadow_depth: 0,
            depth: 0,
        }
    }
}

pub type XmlNsMapPtr = *mut XmlNsMap;
#[repr(C)]
pub struct XmlNsMap {
    first: XmlNsMapItemPtr,
    last: XmlNsMapItemPtr,
    pool: XmlNsMapItemPtr,
}

impl Default for XmlNsMap {
    fn default() -> Self {
        Self {
            first: null_mut(),
            last: null_mut(),
            pool: null_mut(),
        }
    }
}

/// Allocates and initializes a new DOM-wrapper context.
///
/// Returns the xmlDOMWrapCtxtPtr or null_mut() in case of an internal error.
#[doc(alias = "xmlDOMWrapNewCtxt")]
pub unsafe fn xml_dom_wrap_new_ctxt() -> XmlDOMWrapCtxtPtr {
    unsafe {
        let ret: XmlDOMWrapCtxtPtr = xml_malloc(size_of::<XmlDOMWrapCtxt>()) as _;
        if ret.is_null() {
            xml_tree_err_memory("allocating DOM-wrapper context");
            return null_mut();
        }
        std::ptr::write(&mut *ret, XmlDOMWrapCtxt::default());
        ret
    }
}

/// Frees the ns-map
#[doc(alias = "xmlDOMWrapNsMapFree")]
unsafe fn xml_dom_wrap_ns_map_free(nsmap: XmlNsMapPtr) {
    unsafe {
        let mut cur: XmlNsMapItemPtr;
        let mut tmp: XmlNsMapItemPtr;

        if nsmap.is_null() {
            return;
        }
        cur = (*nsmap).pool;
        while !cur.is_null() {
            tmp = cur;
            cur = (*cur).next;
            xml_free(tmp as _);
        }
        cur = (*nsmap).first;
        while !cur.is_null() {
            tmp = cur;
            cur = (*cur).next;
            xml_free(tmp as _);
        }
        xml_free(nsmap as _);
    }
}

/// Frees the DOM-wrapper context.
#[doc(alias = "xmlDOMWrapFreeCtxt")]
pub unsafe fn xml_dom_wrap_free_ctxt(ctxt: XmlDOMWrapCtxtPtr) {
    unsafe {
        if ctxt.is_null() {
            return;
        }
        if !(*ctxt).namespace_map.is_null() {
            xml_dom_wrap_ns_map_free((*ctxt).namespace_map as _);
        }
        // TODO: Store the namespace map in the context.
        xml_free(ctxt as _);
    }
}

macro_rules! XML_NSMAP_NOTEMPTY {
    ($m:expr) => {
        !$m.is_null() && !(*$m).first.is_null()
    };
}

macro_rules! XML_NSMAP_FOREACH {
    ($m:expr, $i:expr, $b:block) => {
        let mut __initialized = false;
        $i = (*$m).first;
        while {
            if !__initialized {
                __initialized = true;
            } else {
                $i = (*$i).next;
            }
            !$i.is_null()
        } {
            $b;
        }
    };
}

macro_rules! XML_NSMAP_POP {
    ($m:expr, $i:expr) => {
        $i = (*$m).last;
        (*$m).last = (*$i).prev;
        if (*$m).last.is_null() {
            (*$m).first = null_mut();
        } else {
            (*(*$m).last).next = null_mut();
        }
        (*$i).next = (*$m).pool;
        (*$m).pool = $i;
    };
}

#[repr(C)]
enum XmlDomreconcileNsoptions {
    XmlDomReconnsRemoveredund = 1 << 0,
}

const XML_TREE_NSMAP_PARENT: i32 = -1;
// const XML_TREE_NSMAP_XML: i32 = -2;
const XML_TREE_NSMAP_DOC: i32 = -3;
const XML_TREE_NSMAP_CUSTOM: i32 = -4;

/// Adds an ns-mapping item.
#[doc(alias = "xmlDOMWrapNsMapAddItem")]
unsafe fn xml_dom_wrap_ns_map_add_item(
    nsmap: *mut XmlNsMapPtr,
    position: i32,
    old_ns: Option<XmlNsPtr>,
    new_ns: Option<XmlNsPtr>,
    depth: i32,
) -> XmlNsMapItemPtr {
    unsafe {
        let ret: XmlNsMapItemPtr;
        let mut map: XmlNsMapPtr;

        if nsmap.is_null() {
            return null_mut();
        }
        if position != -1 && position != 0 {
            return null_mut();
        }
        map = *nsmap;

        if map.is_null() {
            // Create the ns-map.
            map = xml_malloc(size_of::<XmlNsMap>()) as _;
            if map.is_null() {
                xml_tree_err_memory("allocating namespace map");
                return null_mut();
            }
            std::ptr::write(&mut *map, XmlNsMap::default());
            *nsmap = map;
        }

        if !(*map).pool.is_null() {
            // Reuse an item from the pool.
            ret = (*map).pool;
            (*map).pool = (*ret).next;
            std::ptr::write(&mut *ret, XmlNsMapItem::default());
        } else {
            // Create a new item.
            ret = xml_malloc(size_of::<XmlNsMapItem>()) as _;
            if ret.is_null() {
                xml_tree_err_memory("allocating namespace map item");
                return null_mut();
            }
            std::ptr::write(&mut *ret, XmlNsMapItem::default());
        }

        if (*map).first.is_null() {
            // First ever.
            (*map).first = ret;
            (*map).last = ret;
        } else if position == -1 {
            // Append.
            (*ret).prev = (*map).last;
            (*(*map).last).next = ret;
            (*map).last = ret;
        } else if position == 0 {
            // Set on first position.
            (*(*map).first).prev = ret;
            (*ret).next = (*map).first;
            (*map).first = ret;
        }

        (*ret).old_ns = old_ns;
        (*ret).new_ns = new_ns;
        (*ret).shadow_depth = -1;
        (*ret).depth = depth;
        ret
    }
}

/// Puts in-scope namespaces into the ns-map.
///
/// Returns 0 on success, -1 on API or internal errors.
#[doc(alias = "xmlDOMWrapNSNormGatherInScopeNs")]
unsafe fn xml_dom_wrap_ns_norm_gather_in_scope_ns(
    map: *mut XmlNsMapPtr,
    node: Option<XmlGenericNodePtr>,
) -> i32 {
    unsafe {
        let mut mi: XmlNsMapItemPtr;
        let mut shadowed: i32;

        if map.is_null() || !(*map).is_null() {
            return -1;
        }
        // In original libxml2, check if element type is not XmlNamespaceDecl.
        let Some(node) = node else {
            return -1;
        };
        // Get in-scope ns-decls of @parent.
        let mut cur = Some(node);
        while let Some(cur_node) =
            cur.filter(|&cur| Some(cur) != cur.document().map(|doc| doc.into()))
        {
            if let Ok(cur_node) = XmlNodePtr::try_from(cur_node) {
                if matches!(cur_node.element_type(), XmlElementType::XmlElementNode)
                    && cur_node.ns_def.is_some()
                {
                    let mut ns = cur_node.ns_def;
                    while let Some(now) = ns {
                        shadowed = 0;
                        if XML_NSMAP_NOTEMPTY!(*map) {
                            // Skip shadowed prefixes.
                            XML_NSMAP_FOREACH!(*map, mi, {
                                if now.prefix() == (*mi).new_ns.unwrap().prefix() {
                                    shadowed = 1;
                                    break;
                                }
                            });
                        }
                        // Insert mapping.
                        mi = xml_dom_wrap_ns_map_add_item(
                            map,
                            0,
                            None,
                            Some(now),
                            XML_TREE_NSMAP_PARENT,
                        );
                        if mi.is_null() {
                            return -1;
                        }
                        if shadowed != 0 {
                            (*mi).shadow_depth = 0;
                        }
                        ns = now.next;
                    }
                }
            }
            cur = cur_node.parent();
        }
        0
    }
}

/// For internal use. Adds a ns-decl mapping.
///
/// Returns 0 on success, -1 on internal errors.
#[doc(alias = "xmlDOMWrapNSNormAddNsMapItem2")]
unsafe fn xml_dom_wrap_ns_norm_add_ns_map_item2(
    list: &mut Vec<XmlNsPtr>,
    // size: *mut i32,
    number: *mut i32,
    old_ns: XmlNsPtr,
    new_ns: XmlNsPtr,
) -> i32 {
    unsafe {
        list.push(old_ns);
        list.push(new_ns);
        (*number) += 1;
        0
    }
}

/// Creates or reuses an xmlNs struct on (*doc).oldNs with
/// the given prefix and namespace name.
///
/// Returns the acquired ns struct or null_mut() in case of an API or internal error.
#[doc(alias = "xmlDOMWrapStoreNs")]
fn xml_dom_wrap_store_ns(
    mut doc: XmlDocPtr,
    ns_name: Option<&str>,
    prefix: Option<&str>,
) -> Option<XmlNsPtr> {
    let mut ns = doc.ensure_xmldecl()?;
    if let Some(next) = ns.next {
        if next.prefix().as_deref() == prefix && next.href.as_deref() == ns_name {
            return Some(next);
        }
        ns = next;
        while let Some(next) = ns.next {
            if next.prefix().as_deref() == prefix && next.href.as_deref() == ns_name {
                return Some(next);
            }
            ns = next;
        }
    }
    // Create.
    ns.next = xml_new_ns(None, ns_name, prefix);
    ns.next
}

/// Declares a new namespace on @elem. It tries to use the
/// given @prefix; if a ns-decl with the given prefix is already existent
/// on @elem, it will generate an other prefix.
///
/// Returns 1 if a ns-decl was found, 0 if not and -1 on API and internal errors.
#[doc(alias = "xmlDOMWrapNSNormDeclareNsForced")]
fn xml_dom_wrap_nsnorm_declare_ns_forced(
    doc: XmlDocPtr,
    mut elem: XmlNodePtr,
    ns_name: Option<&str>,
    prefix: Option<&str>,
    check_shadow: i32,
) -> Option<XmlNsPtr> {
    let mut counter: i32 = 0;

    // let doc = doc?;
    // let elem = elem?;
    if !matches!(elem.element_type(), XmlElementType::XmlElementNode) {
        return None;
    }
    // Create a ns-decl on @anchor.
    let mut pref = prefix.map(|prefix| prefix.to_owned());
    loop {
        // Lookup whether the prefix is unused in elem's ns-decls.
        if elem.ns_def.is_some()
            && xml_tree_nslist_lookup_by_prefix(elem.ns_def, pref.as_deref()).is_some()
        {
            // goto ns_next_prefix;
        } else {
            // Does it shadow ancestor ns-decls?
            if check_shadow != 0
                && elem
                    .parent()
                    .filter(|&p| {
                        Some(p) != p.document().map(|doc| doc.into())
                            && xml_search_ns_by_prefix_strict(doc, p, pref.as_deref(), None) == 1
                    })
                    .is_some()
            {
                // goto ns_next_prefix;
            } else {
                let ret = xml_new_ns(None, ns_name, pref.as_deref())?;
                if let Some(ns_def) = elem.ns_def {
                    let mut ns2 = ns_def;
                    while let Some(next) = ns2.next {
                        ns2 = next;
                    }
                    ns2.next = Some(ret);
                } else {
                    elem.ns_def = Some(ret);
                }
                return Some(ret);
            }
        }
        // ns_next_prefix:
        counter += 1;
        if counter > 1000 {
            return None;
        }
        let buf = if let Some(prefix) = prefix {
            format!("{prefix}_{counter}")
        } else {
            format!("ns_{counter}")
        };
        pref = Some(buf);
    }
}

/// Searches for a matching ns-name in the ns-decls of @nsMap, if not
/// found it will either declare it on @elem, or store it in (*doc).oldNs.
/// If a new ns-decl needs to be declared on @elem, it tries to use the
/// @ns.prefix for it, if this prefix is already in use on @elem, it will
/// change the prefix or the new ns-decl.
///
/// Returns 0 if succeeded, -1 otherwise and on API/internal errors.
#[allow(clippy::too_many_arguments)]
#[doc(alias = "xmlDOMWrapNSNormAcquireNormalizedNs")]
unsafe fn xml_dom_wrap_ns_norm_acquire_normalized_ns(
    mut doc: XmlDocPtr,
    elem: Option<XmlNodePtr>,
    ns: XmlNsPtr,
    ret_ns: &mut Option<XmlNsPtr>,
    ns_map: *mut XmlNsMapPtr,
    depth: i32,
    ancestors_only: i32,
    prefixed: i32,
) -> i32 {
    unsafe {
        let mut mi: XmlNsMapItemPtr;

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

        *ret_ns = None;
        // Handle XML namespace.
        if ns.prefix().as_deref() == Some("xml") {
            // Insert XML namespace mapping.
            *ret_ns = doc.ensure_xmldecl();
            if (*ret_ns).is_none() {
                return -1;
            }
            return 0;
        }
        // If the search should be done in ancestors only and no
        // @elem (the first ancestor) was specified, then skip the search.
        if XML_NSMAP_NOTEMPTY!(*ns_map) && !(ancestors_only != 0 && elem.is_none()) {
            // Try to find an equal ns-name in in-scope ns-decls.
            XML_NSMAP_FOREACH!(*ns_map, mi, {
                if ((*mi).depth >= XML_TREE_NSMAP_PARENT)
                    // ancestorsOnly: This should be turned on to gain speed,
                    // if one knows that the branch itself was already
                    // ns-wellformed and no stale references existed.
                    // I.e. it searches in the ancestor axis only.
                    && (ancestors_only == 0 || (*mi).depth == XML_TREE_NSMAP_PARENT)
                    // Skip shadowed prefixes.
                    && (*mi).shadow_depth == -1
                    // Skip xmlns="" or xmlns:foo="".
                    && (*mi)
                        .new_ns
                        .unwrap()
                        .href
                        .as_deref()
                        .is_some_and(|href| !href.is_empty())
                    // Ensure a prefix if wanted.
                    && (prefixed == 0 || (*mi).new_ns.unwrap().prefix().is_some())
                    // Equal ns name
                    && (*mi).new_ns.unwrap().href == ns.href
                {
                    // Set the mapping.
                    (*mi).old_ns = Some(ns);
                    *ret_ns = (*mi).new_ns;
                    return 0;
                }
            });
        }
        // No luck, the namespace is out of scope or shadowed.
        if let Some(elem) = elem {
            let Some(tmpns) = xml_dom_wrap_nsnorm_declare_ns_forced(
                doc,
                elem,
                ns.href.as_deref(),
                ns.prefix.as_deref(),
                0,
            ) else {
                return -1;
            };

            if !(*ns_map).is_null() {
                // Does it shadow ancestor ns-decls?
                XML_NSMAP_FOREACH!(*ns_map, mi, {
                    if ((*mi).depth < depth)
                        && (*mi).shadow_depth == -1
                        && ns.prefix() == (*mi).new_ns.unwrap().prefix()
                    {
                        // Shadows.
                        (*mi).shadow_depth = depth;
                        break;
                    }
                });
            }
            if xml_dom_wrap_ns_map_add_item(ns_map, -1, Some(ns), Some(tmpns), depth).is_null() {
                xml_free_ns(tmpns);
                return -1;
            }
            *ret_ns = Some(tmpns);
        } else {
            // Store ns-decls in "oldNs" of the document-node.
            let Some(tmpns) =
                xml_dom_wrap_store_ns(doc, ns.href.as_deref(), ns.prefix().as_deref())
            else {
                return -1;
            };
            // Insert mapping.
            if xml_dom_wrap_ns_map_add_item(ns_map, -1, Some(ns), Some(tmpns), XML_TREE_NSMAP_DOC)
                .is_null()
            {
                xml_free_ns(tmpns);
                return -1;
            }
            *ret_ns = Some(tmpns);
        }
        0
    }
}

/// Ensures that ns-references point to ns-decls hold on element-nodes.
/// Ensures that the tree is namespace wellformed by creating additional
/// ns-decls where needed. Note that, since prefixes of already existent
/// ns-decls can be shadowed by this process, it could break QNames in
/// attribute values or element content.
///
/// NOTE: This function was not intensively tested.
///
/// Returns 0 if succeeded, -1 otherwise and on API/internal errors.
#[doc(alias = "xmlDOMWrapReconcileNamespaces")]
pub unsafe fn xml_dom_wrap_reconcile_namespaces(
    _ctxt: XmlDOMWrapCtxtPtr,
    elem: XmlNodePtr,
    options: i32,
) -> i32 {
    unsafe {
        let mut depth: i32 = -1;
        let mut adoptns: i32;
        let mut parnsdone: i32 = 0;
        let mut ns_map: XmlNsMapPtr = null_mut();
        let mut mi: XmlNsMapItemPtr;
        // @ancestorsOnly should be set by an option flag.
        let ancestors_only: i32 = 0;
        let opt_remove_redundant_ns: i32 =
            if options & XmlDomreconcileNsoptions::XmlDomReconnsRemoveredund as i32 != 0 {
                1
            } else {
                0
            };
        let mut list_redund = vec![];
        let mut nb_redund: i32 = 0;

        // if elem.is_null() {
        //     return -1;
        // }
        if !matches!(elem.element_type(), XmlElementType::XmlElementNode) {
            return -1;
        }

        let Some(doc) = elem.doc else {
            return -1;
        };
        let ret;
        let mut cur = XmlGenericNodePtr::from(elem);
        let mut cur_elem = None;
        'exit: {
            'internal_error: {
                'main: loop {
                    match cur.element_type() {
                        XmlElementType::XmlElementNode => {
                            let mut cur_node = XmlNodePtr::try_from(cur).unwrap();
                            adoptns = 1;
                            cur_elem = Some(cur_node);
                            depth += 1;
                            // Namespace declarations.
                            if cur_node.ns_def.is_some() {
                                let mut prevns = None::<XmlNsPtr>;
                                let mut ns = cur_node.ns_def;
                                'b: while let Some(cur_ns) = ns {
                                    if parnsdone == 0 {
                                        if let Some(parent) = elem.parent().filter(|&p| {
                                            Some(p) != p.document().map(|doc| doc.into())
                                        }) {
                                            // Gather ancestor in-scope ns-decls.
                                            if xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                                &raw mut ns_map,
                                                Some(parent),
                                            ) == -1
                                            {
                                                break 'internal_error;
                                            }
                                        }
                                        parnsdone = 1;
                                    }

                                    // Lookup the ns ancestor-axis for equal ns-decls in scope.
                                    if opt_remove_redundant_ns != 0 && XML_NSMAP_NOTEMPTY!(ns_map) {
                                        XML_NSMAP_FOREACH!(ns_map, mi, {
                                            if (*mi).depth >= XML_TREE_NSMAP_PARENT
                                                && (*mi).shadow_depth == -1
                                                && cur_ns.prefix() == (*mi).new_ns.unwrap().prefix()
                                                && cur_ns.href() == (*mi).new_ns.unwrap().href()
                                            {
                                                // A redundant ns-decl was found.
                                                // Add it to the list of redundant ns-decls.
                                                if xml_dom_wrap_ns_norm_add_ns_map_item2(
                                                    &mut list_redund,
                                                    // &raw mut size_redund,
                                                    &raw mut nb_redund,
                                                    cur_ns,
                                                    (*mi).new_ns.unwrap(),
                                                ) == -1
                                                {
                                                    break 'internal_error;
                                                }
                                                // Remove the ns-decl from the element-node.
                                                if let Some(mut prevns) = prevns {
                                                    prevns.next = cur_ns.next;
                                                } else {
                                                    cur_node.ns_def = cur_ns.next;
                                                }
                                                // goto next_ns_decl;
                                                ns = cur_ns.next;
                                                continue 'b;
                                            }
                                        });
                                    }

                                    // Skip ns-references handling if the referenced
                                    // ns-decl is declared on the same element.
                                    if cur_node.ns.is_some()
                                        && adoptns != 0
                                        && cur_node.ns == Some(cur_ns)
                                    {
                                        adoptns = 0;
                                    }
                                    // Does it shadow any ns-decl?
                                    if XML_NSMAP_NOTEMPTY!(ns_map) {
                                        XML_NSMAP_FOREACH!(ns_map, mi, {
                                            if (*mi).depth >= XML_TREE_NSMAP_PARENT
                                                && (*mi).shadow_depth == -1
                                                && cur_ns.prefix() == (*mi).new_ns.unwrap().prefix()
                                            {
                                                (*mi).shadow_depth = depth;
                                            }
                                        });
                                    }
                                    // Push mapping.
                                    if xml_dom_wrap_ns_map_add_item(
                                        &raw mut ns_map,
                                        -1,
                                        Some(cur_ns),
                                        Some(cur_ns),
                                        depth,
                                    )
                                    .is_null()
                                    {
                                        break 'internal_error;
                                    }

                                    prevns = Some(cur_ns);
                                    // next_ns_decl:
                                    ns = cur_ns.next;
                                }
                            }
                            if adoptns == 0 {
                                // goto ns_end;
                                if matches!(cur_node.element_type(), XmlElementType::XmlElementNode)
                                {
                                    if let Some(prop) = cur_node.properties {
                                        // Process attributes.
                                        cur = prop.into();
                                        continue 'main;
                                    }
                                }
                            }

                            // No ns, no fun.
                            if cur_node.ns.is_none() {
                                // goto ns_end;
                                if matches!(cur_node.element_type(), XmlElementType::XmlElementNode)
                                {
                                    if let Some(prop) = cur_node.properties {
                                        // Process attributes.
                                        cur = prop.into();
                                        continue 'main;
                                    }
                                }
                            }

                            if parnsdone == 0 {
                                if (*elem)
                                    .parent()
                                    .filter(|&p| {
                                        Some(p) != p.document().map(|doc| doc.into())
                                            && xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                                &raw mut ns_map,
                                                Some(p),
                                            ) == -1
                                    })
                                    .is_some()
                                {
                                    break 'internal_error;
                                }
                                parnsdone = 1;
                            }
                            // Adjust the reference if this was a redundant ns-decl.
                            for (_, j) in (0..nb_redund).zip((0..).step_by(2)) {
                                if cur_node.ns == Some(list_redund[j]) {
                                    cur_node.ns = Some(list_redund[j + 1]);
                                    break;
                                }
                            }
                            // Adopt ns-references.
                            if XML_NSMAP_NOTEMPTY!(ns_map) {
                                // Search for a mapping.
                                XML_NSMAP_FOREACH!(ns_map, mi, {
                                    if (*mi).shadow_depth == -1 && cur_node.ns == (*mi).old_ns {
                                        cur_node.ns = (*mi).new_ns;
                                        // goto ns_end;
                                        if matches!(
                                            cur.element_type(),
                                            XmlElementType::XmlElementNode
                                        ) {
                                            if let Some(prop) = cur_node.properties {
                                                // Process attributes.
                                                cur = prop.into();
                                                continue 'main;
                                            }
                                        }
                                    }
                                });
                            }
                            // Acquire a normalized ns-decl and add it to the map.
                            let mut ns = None;
                            if xml_dom_wrap_ns_norm_acquire_normalized_ns(
                                doc,
                                cur_elem,
                                cur_node.ns.unwrap(),
                                &mut ns,
                                &raw mut ns_map,
                                depth,
                                ancestors_only,
                                matches!(cur.element_type(), XmlElementType::XmlAttributeNode)
                                    as i32,
                            ) == -1
                            {
                                break 'internal_error;
                            }
                            cur_node.ns = ns;

                            // ns_end:
                            if matches!(cur.element_type(), XmlElementType::XmlElementNode) {
                                if let Some(prop) = cur_node.properties {
                                    // Process attributes.
                                    cur = prop.into();
                                    continue 'main;
                                }
                            }
                        }
                        XmlElementType::XmlAttributeNode => {
                            let mut cur_attr = XmlAttrPtr::try_from(cur).unwrap();
                            if parnsdone == 0 {
                                if elem
                                    .parent()
                                    .filter(|&p| {
                                        Some(p) != p.document().map(|doc| doc.into())
                                            && xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                                &raw mut ns_map,
                                                Some(p),
                                            ) == -1
                                    })
                                    .is_some()
                                {
                                    break 'internal_error;
                                }
                                parnsdone = 1;
                            }
                            // Adjust the reference if this was a redundant ns-decl.
                            for (_, j) in (0..nb_redund).zip((0..).step_by(2)) {
                                if cur_attr.ns == Some(list_redund[j]) {
                                    cur_attr.ns = Some(list_redund[j + 1]);
                                    break;
                                }
                            }
                            // Adopt ns-references.
                            if XML_NSMAP_NOTEMPTY!(ns_map) {
                                // Search for a mapping.
                                XML_NSMAP_FOREACH!(ns_map, mi, {
                                    if (*mi).shadow_depth == -1 && cur_attr.ns == (*mi).old_ns {
                                        cur_attr.ns = (*mi).new_ns;
                                    }
                                });
                            }
                            // Acquire a normalized ns-decl and add it to the map.
                            let mut ns = None;
                            if xml_dom_wrap_ns_norm_acquire_normalized_ns(
                                doc,
                                cur_elem,
                                cur_attr.ns.unwrap(),
                                &mut ns,
                                &raw mut ns_map,
                                depth,
                                ancestors_only,
                                matches!(cur.element_type(), XmlElementType::XmlAttributeNode)
                                    as i32,
                            ) == -1
                            {
                                break 'internal_error;
                            }
                            cur_attr.ns = ns;
                        }
                        _ => {
                            // goto next_sibling;
                            'next_sibling: loop {
                                if cur == XmlGenericNodePtr::from(elem) {
                                    break 'main;
                                }
                                if matches!(cur.element_type(), XmlElementType::XmlElementNode) {
                                    if XML_NSMAP_NOTEMPTY!(ns_map) {
                                        // Pop mappings.
                                        while !(*ns_map).last.is_null()
                                            && (*(*ns_map).last).depth >= depth
                                        {
                                            XML_NSMAP_POP!(ns_map, mi);
                                        }
                                        // Unshadow.
                                        XML_NSMAP_FOREACH!(ns_map, mi, {
                                            if (*mi).shadow_depth >= depth {
                                                (*mi).shadow_depth = -1;
                                            }
                                        });
                                    }
                                    depth -= 1;
                                }
                                if let Some(next) = cur.next() {
                                    cur = next;
                                } else {
                                    if matches!(
                                        cur.element_type(),
                                        XmlElementType::XmlAttributeNode
                                    ) {
                                        cur = cur.parent().unwrap();
                                        // goto into_content;
                                        break 'next_sibling;
                                    }
                                    cur = cur.parent().unwrap();
                                    // goto next_sibling;
                                    continue 'next_sibling;
                                }

                                continue 'main;
                            }
                        }
                    }
                    // into_content:
                    'into_content: loop {
                        if let Some(children) = cur.children().filter(|_| {
                            matches!(cur.element_type(), XmlElementType::XmlElementNode)
                        }) {
                            // Process content of element-nodes only.
                            cur = children;
                            continue;
                        }
                        // next_sibling:
                        'next_sibling: loop {
                            if cur == XmlGenericNodePtr::from(elem) {
                                break 'main;
                            }
                            if matches!(cur.element_type(), XmlElementType::XmlElementNode) {
                                if XML_NSMAP_NOTEMPTY!(ns_map) {
                                    // Pop mappings.
                                    while !(*ns_map).last.is_null()
                                        && (*(*ns_map).last).depth >= depth
                                    {
                                        XML_NSMAP_POP!(ns_map, mi);
                                    }
                                    // Unshadow.
                                    XML_NSMAP_FOREACH!(ns_map, mi, {
                                        if (*mi).shadow_depth >= depth {
                                            (*mi).shadow_depth = -1;
                                        }
                                    });
                                }
                                depth -= 1;
                            }
                            if let Some(next) = cur.next() {
                                cur = next;
                            } else {
                                if matches!(cur.element_type(), XmlElementType::XmlAttributeNode) {
                                    cur = cur.parent().unwrap();
                                    // goto into_content;
                                    continue 'into_content;
                                }
                                cur = cur.parent().unwrap();
                                // goto next_sibling;
                                continue 'next_sibling;
                            }
                            break 'next_sibling;
                        }

                        break 'into_content;
                    }
                }

                ret = 0;
                break 'exit;
            }
            // internal_error:
            ret = -1;
        }
        // exit:
        for (_, j) in (0..nb_redund).zip((0..).step_by(2)) {
            xml_free_ns(list_redund[j]);
        }
        if !ns_map.is_null() {
            xml_dom_wrap_ns_map_free(ns_map);
        }
        ret
    }
}

/// Ensures that ns-references point to @destDoc: either to
/// elements->nsDef entries if @destParent is given, or to
/// @(*destDoc).oldNs otherwise.
/// If @destParent is given, it ensures that the tree is namespace
/// wellformed by creating additional ns-decls where needed.
/// Note that, since prefixes of already existent ns-decls can be
/// shadowed by this process, it could break QNames in attribute
/// values or element content.
///
/// NOTE: This function was not intensively tested.
///
/// Returns 0 if succeeded, -1 otherwise and on API/internal errors.
#[doc(alias = "xmlDOMWrapAdoptBranch")]
unsafe fn xml_dom_wrap_adopt_branch(
    ctxt: XmlDOMWrapCtxtPtr,
    source_doc: Option<XmlDocPtr>,
    node: XmlNodePtr,
    dest_doc: XmlDocPtr,
    dest_parent: Option<XmlNodePtr>,
    _options: i32,
) -> i32 {
    unsafe {
        let mut ret: i32 = 0;
        let mut cur_elem = None;
        let mut ns_map: XmlNsMapPtr = null_mut();
        let mut mi: XmlNsMapItemPtr;
        let mut depth: i32 = -1;
        // gather @parent's ns-decls.
        let mut parnsdone: i32;
        // @ancestorsOnly should be set per option.
        let ancestors_only: i32 = 0;

        // Get the ns-map from the context if available.
        if !ctxt.is_null() {
            ns_map = (*ctxt).namespace_map as _;
        }
        // Disable search for ns-decls in the parent-axis of the
        // destination element, if:
        // 1) there's no destination parent
        // 2) custom ns-reference handling is used
        if dest_parent.is_none() || (!ctxt.is_null() && (*ctxt).get_ns_for_node_func.is_some()) {
            parnsdone = 1;
        } else {
            parnsdone = 0;
        }

        'exit: {
            'internal_error: {
                let mut cur = Some(XmlGenericNodePtr::from(node));

                'main: while let Some(mut cur_node) = cur {
                    let mut leave_node = false;

                    // Paranoid source-doc sanity check.
                    if cur_node.document() != source_doc {
                        // We'll assume XIncluded nodes if the doc differs.
                        // TODO: Do we need to reconciliate XIncluded nodes?
                        // This here skips XIncluded nodes and tries to handle
                        // broken sequences.
                        if cur_node.next().is_some() {
                            let mut next = cur_node.next();
                            while let Some(now) = next.filter(|now| {
                                !matches!(now.element_type(), XmlElementType::XmlXIncludeEnd)
                                    && now.document() != node.doc
                            }) {
                                cur_node = now;
                                next = now.next();
                            }

                            if cur_node.document() != node.doc {
                                // goto leave_node;
                                leave_node = true;
                            }
                        } else {
                            // goto leave_node;
                            leave_node = true;
                        }
                    }

                    if !leave_node {
                        cur_node.set_document(Some(dest_doc));
                        match cur_node.element_type() {
                            XmlElementType::XmlXIncludeStart | XmlElementType::XmlXIncludeEnd => {
                                // TODO
                                return -1;
                            }
                            XmlElementType::XmlElementNode => {
                                let mut node = XmlNodePtr::try_from(cur_node).unwrap();
                                cur_elem = Some(node);
                                depth += 1;
                                // Namespace declarations.
                                // - ns.href and ns.prefix are never in the dict, so
                                //   we need not move the values over to the destination dict.
                                // - Note that for custom handling of ns-references,
                                //   the ns-decls need not be stored in the ns-map,
                                //   since they won't be referenced by (*node).ns.
                                if node.ns_def.is_some()
                                    && (ctxt.is_null() || (*ctxt).get_ns_for_node_func.is_none())
                                {
                                    if parnsdone == 0 {
                                        // Gather @parent's in-scope ns-decls.
                                        if xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                            &raw mut ns_map,
                                            dest_parent.map(|d| d.into()),
                                        ) == -1
                                        {
                                            break 'internal_error;
                                        }

                                        parnsdone = 1;
                                    }
                                    let mut ns = node.ns_def;
                                    while let Some(now) = ns {
                                        // Does it shadow any ns-decl?
                                        if XML_NSMAP_NOTEMPTY!(ns_map) {
                                            XML_NSMAP_FOREACH!(ns_map, mi, {
                                                if (*mi).depth >= XML_TREE_NSMAP_PARENT
                                                    && (*mi).shadow_depth == -1
                                                    && now.prefix()
                                                        == (*mi).new_ns.unwrap().prefix()
                                                {
                                                    (*mi).shadow_depth = depth;
                                                }
                                            });
                                        }
                                        // Push mapping.
                                        if xml_dom_wrap_ns_map_add_item(
                                            &raw mut ns_map,
                                            -1,
                                            Some(now),
                                            Some(now),
                                            depth,
                                        )
                                        .is_null()
                                        {
                                            break 'internal_error;
                                        }
                                        ns = now.next;
                                    }
                                }
                                // No namespace, no fun.
                                if node.ns.is_some() {
                                    if parnsdone == 0 {
                                        if xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                            &raw mut ns_map,
                                            dest_parent.map(|d| d.into()),
                                        ) == -1
                                        {
                                            break 'internal_error;
                                        }
                                        parnsdone = 1;
                                    }
                                    // Adopt ns-references.
                                    let mut ns_end = false;
                                    if XML_NSMAP_NOTEMPTY!(ns_map) {
                                        // Search for a mapping.
                                        XML_NSMAP_FOREACH!(ns_map, mi, {
                                            if (*mi).shadow_depth == -1 && node.ns == (*mi).old_ns {
                                                node.ns = (*mi).new_ns;
                                                // goto ns_end;
                                                ns_end = true;
                                                break;
                                            }
                                        });
                                    }

                                    if !ns_end {
                                        // No matching namespace in scope. We need a new one.
                                        if !ctxt.is_null() && (*ctxt).get_ns_for_node_func.is_some()
                                        {
                                            // User-defined behaviour.
                                            let ns = ((*ctxt).get_ns_for_node_func.unwrap())(
                                                ctxt,
                                                Some(node.into()),
                                                node.ns.unwrap().href.as_deref(),
                                                node.ns.unwrap().prefix.as_deref(),
                                            );
                                            // Insert mapping if ns is available; it's the users fault
                                            // if not.
                                            if xml_dom_wrap_ns_map_add_item(
                                                &raw mut ns_map,
                                                -1,
                                                node.ns,
                                                ns,
                                                XML_TREE_NSMAP_CUSTOM,
                                            )
                                            .is_null()
                                            {
                                                break 'internal_error;
                                            }
                                            node.ns = ns;
                                        } else {
                                            // Acquire a normalized ns-decl and add it to the map.
                                            let mut ns = None;
                                            if xml_dom_wrap_ns_norm_acquire_normalized_ns(
                                                dest_doc,
                                                // ns-decls on curElem or on (*destDoc).oldNs
                                                dest_parent.and(cur_elem),
                                                node.ns.unwrap(),
                                                &mut ns,
                                                &raw mut ns_map,
                                                depth,
                                                ancestors_only,
                                                // ns-decls must be prefixed for attributes.
                                                matches!(
                                                    node.element_type(),
                                                    XmlElementType::XmlAttributeNode
                                                )
                                                    as i32,
                                            ) == -1
                                            {
                                                break 'internal_error;
                                            }
                                            node.ns = ns;
                                        }
                                    }
                                }
                                // ns_end:
                                // Further node properties.
                                // TODO: Is this all?
                                node.psvi = null_mut();
                                node.line = 0;
                                node.extra = 0;
                                // Walk attributes.
                                if let Some(prop) = node.properties {
                                    // Process first attribute node.
                                    cur = Some(prop.into());
                                    continue;
                                }
                            }
                            XmlElementType::XmlAttributeNode => {
                                let mut attr = XmlAttrPtr::try_from(cur_node).unwrap();
                                // No namespace, no fun.
                                if attr.ns.is_some() {
                                    if parnsdone == 0 {
                                        if xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                            &raw mut ns_map,
                                            dest_parent.map(|d| d.into()),
                                        ) == -1
                                        {
                                            break 'internal_error;
                                        }
                                        parnsdone = 1;
                                    }
                                    // Adopt ns-references.
                                    let mut ns_end = false;
                                    if XML_NSMAP_NOTEMPTY!(ns_map) {
                                        // Search for a mapping.
                                        XML_NSMAP_FOREACH!(ns_map, mi, {
                                            if (*mi).shadow_depth == -1 && attr.ns == (*mi).old_ns {
                                                attr.ns = (*mi).new_ns;
                                                // goto ns_end;
                                                ns_end = true;
                                                break;
                                            }
                                        });
                                    }

                                    if !ns_end {
                                        // No matching namespace in scope. We need a new one.
                                        if !ctxt.is_null() && (*ctxt).get_ns_for_node_func.is_some()
                                        {
                                            // User-defined behaviour.
                                            let ns = ((*ctxt).get_ns_for_node_func.unwrap())(
                                                ctxt,
                                                Some(attr.into()),
                                                attr.ns.unwrap().href.as_deref(),
                                                attr.ns.unwrap().prefix.as_deref(),
                                            );
                                            // Insert mapping if ns is available; it's the users fault
                                            // if not.
                                            if xml_dom_wrap_ns_map_add_item(
                                                &raw mut ns_map,
                                                -1,
                                                attr.ns,
                                                ns,
                                                XML_TREE_NSMAP_CUSTOM,
                                            )
                                            .is_null()
                                            {
                                                break 'internal_error;
                                            }
                                            attr.ns = ns;
                                        } else {
                                            // Acquire a normalized ns-decl and add it to the map.
                                            let mut ns = None;
                                            if xml_dom_wrap_ns_norm_acquire_normalized_ns(
                                                dest_doc,
                                                // ns-decls on curElem or on (*destDoc).oldNs
                                                dest_parent.and(cur_elem),
                                                attr.ns.unwrap(),
                                                &mut ns,
                                                &raw mut ns_map,
                                                depth,
                                                ancestors_only,
                                                // ns-decls must be prefixed for attributes.
                                                matches!(
                                                    attr.element_type(),
                                                    XmlElementType::XmlAttributeNode
                                                )
                                                    as i32,
                                            ) == -1
                                            {
                                                break 'internal_error;
                                            }
                                            attr.ns = ns;
                                        }
                                    }
                                }
                                // Further node properties.
                                // TODO: Is this all?
                                // Attributes.
                                if let Some(source_doc) = source_doc.filter(|_| {
                                    matches!(attr.atype, Some(XmlAttributeType::XmlAttributeID))
                                }) {
                                    xml_remove_id(source_doc, attr);
                                }
                                attr.atype = None;
                                attr.psvi = null_mut();
                            }
                            XmlElementType::XmlTextNode | XmlElementType::XmlCDATASectionNode => {
                                // goto leave_node;
                                leave_node = true;
                            }
                            XmlElementType::XmlEntityRefNode => {
                                let mut cur = XmlNodePtr::try_from(cur_node).unwrap();
                                // Remove reference to the entity-node.
                                cur.content = None;
                                cur.set_children(None);
                                cur.set_last(None);
                                if dest_doc.int_subset.is_some() || dest_doc.ext_subset.is_some() {
                                    // Assign new entity-node if available.
                                    let ent =
                                        xml_get_doc_entity(Some(dest_doc), &cur.name().unwrap());
                                    if let Some(ent) = ent {
                                        cur.content =
                                            ent.content.as_deref().map(|cont| cont.to_owned());
                                        cur.set_children(Some(ent.into()));
                                        cur.set_last(Some(ent.into()));
                                    }
                                }
                                // goto leave_node;
                                leave_node = true;
                            }
                            XmlElementType::XmlPINode => {}
                            XmlElementType::XmlCommentNode => {}
                            _ => {
                                break 'internal_error;
                            }
                        }

                        if !leave_node {
                            // Walk the tree.
                            if let Some(children) = cur_node.children() {
                                cur = Some(children);
                                continue;
                            }
                        }
                    }

                    // leave_node:
                    'leave_node: loop {
                        if cur_node == XmlGenericNodePtr::from(node) {
                            break 'main;
                        }
                        if matches!(
                            cur_node.element_type(),
                            XmlElementType::XmlElementNode
                                | XmlElementType::XmlXIncludeStart
                                | XmlElementType::XmlXIncludeEnd
                        ) {
                            // TODO: Do we expect nsDefs on xmlElementType::XML_XINCLUDE_START?
                            if XML_NSMAP_NOTEMPTY!(ns_map) {
                                // Pop mappings.
                                while !(*ns_map).last.is_null() && (*(*ns_map).last).depth >= depth
                                {
                                    XML_NSMAP_POP!(ns_map, mi);
                                }
                                // Unshadow.
                                XML_NSMAP_FOREACH!(ns_map, mi, {
                                    if (*mi).shadow_depth >= depth {
                                        (*mi).shadow_depth = -1;
                                    }
                                });
                            }
                            depth -= 1;
                        }
                        if let Some(next) = cur_node.next() {
                            cur_node = next;
                        } else if let Some(children) = cur_node.parent().and_then(|p| {
                            p.children().filter(|_| {
                                matches!(cur_node.element_type(), XmlElementType::XmlAttributeNode)
                            })
                        }) {
                            cur_node = children;
                        } else {
                            cur_node = cur_node.parent().unwrap();
                            // goto leave_node;
                            continue 'leave_node;
                        }

                        cur = Some(cur_node);
                        break;
                    }
                }
                break 'exit;
            }
            // internal_error:
            ret = -1;
        }

        // exit:
        // Cleanup.
        if !ns_map.is_null() {
            if !ctxt.is_null() && (*ctxt).namespace_map == ns_map as _ {
                // Just cleanup the map but don't free.
                if !(*ns_map).first.is_null() {
                    if !(*ns_map).pool.is_null() {
                        (*(*ns_map).last).next = (*ns_map).pool;
                    }
                    (*ns_map).pool = (*ns_map).first;
                    (*ns_map).first = null_mut();
                }
            } else {
                xml_dom_wrap_ns_map_free(ns_map);
            }
        }
        ret
    }
}

/// @attr is adopted by @destDoc.
/// Ensures that ns-references point to @destDoc: either to
/// elements->nsDef entries if @destParent is given, or to
/// @(*destDoc).oldNs otherwise.
///
/// Returns 0 if succeeded, -1 otherwise and on API/internal errors.
#[doc(alias = "xmlDOMWrapAdoptAttr")]
fn xml_dom_wrap_adopt_attr(
    ctxt: XmlDOMWrapCtxtPtr,
    _source_doc: Option<XmlDocPtr>,
    mut attr: XmlAttrPtr,
    mut dest_doc: XmlDocPtr,
    dest_parent: Option<XmlNodePtr>,
    _options: i32,
) -> i32 {
    attr.doc = Some(dest_doc);
    if let Some(attr_ns) = attr.ns {
        let mut ns = None;

        if !ctxt.is_null() { /* TODO: User defined. */ }
        // XML Namespace.
        if attr_ns.prefix().as_deref() == Some("xml") {
            ns = dest_doc.ensure_xmldecl();
        } else if let Some(dest_parent) = dest_parent {
            // Declare on @destParent.
            if xml_search_ns_by_namespace_strict(
                dest_doc,
                dest_parent.into(),
                attr_ns.href.as_deref().unwrap(),
                &mut ns,
                1,
            ) == -1
            {
                // goto internal_error;
                return -1;
            }
            if ns.is_none() {
                ns = xml_dom_wrap_nsnorm_declare_ns_forced(
                    dest_doc,
                    dest_parent,
                    attr_ns.href.as_deref(),
                    attr_ns.prefix.as_deref(),
                    1,
                );
            }
        } else {
            // Store in @(*destDoc).oldNs.
            ns = xml_dom_wrap_store_ns(
                dest_doc,
                attr_ns.href.as_deref(),
                attr_ns.prefix().as_deref(),
            );
        }
        let Some(ns) = ns else {
            // goto internal_error;
            return -1;
        };
        attr.ns = Some(ns);
    }

    attr.atype = None;
    attr.psvi = null_mut();
    // Walk content.
    let Some(children) = attr.children() else {
        return 0;
    };
    if matches!(children.element_type(), XmlElementType::XmlNamespaceDecl) {
        // goto internal_error;
        return -1;
    }
    let mut cur = Some(children);
    'main: while let Some(mut cur_node) = cur {
        cur_node.set_document(Some(dest_doc));
        match cur_node.element_type() {
            XmlElementType::XmlTextNode | XmlElementType::XmlCDATASectionNode => {}
            XmlElementType::XmlEntityRefNode => {
                let mut cur = XmlNodePtr::try_from(cur_node).unwrap();
                // Remove reference to the entity-node.
                cur.content = None;
                cur.set_children(None);
                cur.set_last(None);
                if dest_doc.int_subset.is_some() || dest_doc.ext_subset.is_some() {
                    // Assign new entity-node if available.
                    let ent = xml_get_doc_entity(Some(dest_doc), &cur.name().unwrap());
                    if let Some(ent) = ent {
                        cur.content = ent.content.as_deref().map(|cont| cont.to_owned());
                        cur.set_children(Some(ent.into()));
                        cur.set_last(Some(ent.into()));
                    }
                }
            }
            _ => {}
        }
        if let Some(children) = cur_node.children() {
            cur = Some(children);
            continue;
        }
        // next_sibling:
        'next_sibling: loop {
            if cur_node == XmlGenericNodePtr::from(attr) {
                break 'main;
            }
            if let Some(next) = cur_node.next() {
                cur_node = next;
            } else {
                cur_node = cur_node.parent().unwrap();
                // goto next_sibling;
                continue 'next_sibling;
            }

            cur = Some(cur_node);
            break 'next_sibling;
        }
    }
    0
    // internal_error:
    //     return -1;
}

/// References of out-of scope ns-decls are remapped to point to @destDoc:
/// 1) If @destParent is given, then nsDef entries on element-nodes are used
/// 2) If *no* @destParent is given, then @(*destDoc).oldNs entries are used
///    This is the case when you have an unlinked node and just want to move it
///    to the context of
///
/// If @destParent is given, it ensures that the tree is namespace
/// wellformed by creating additional ns-decls where needed.
/// Note that, since prefixes of already existent ns-decls can be
/// shadowed by this process, it could break QNames in attribute
/// values or element content.
/// NOTE: This function was not intensively tested.
///
/// Returns 0 if the operation succeeded,
///         1 if a node of unsupported type was given,
///         2 if a node of not yet supported type was given and
///         -1 on API/internal errors.
#[doc(alias = "xmlDOMWrapAdoptNode")]
pub unsafe fn xml_dom_wrap_adopt_node(
    ctxt: XmlDOMWrapCtxtPtr,
    source_doc: Option<XmlDocPtr>,
    mut node: XmlGenericNodePtr,
    dest_doc: XmlDocPtr,
    dest_parent: Option<XmlNodePtr>,
    options: i32,
) -> i32 {
    unsafe {
        if matches!(node.element_type(), XmlElementType::XmlNamespaceDecl)
            || dest_parent.is_some_and(|dest_parent| dest_parent.doc != Some(dest_doc))
        {
            return -1;
        }
        // Check node.doc sanity.
        if node.document().is_some_and(|doc| Some(doc) != source_doc) && source_doc.is_some() {
            // Might be an XIncluded node.
            return -1;
        }
        let source_doc = source_doc.or(node.document());
        if source_doc == Some(dest_doc) {
            return -1;
        }
        match node.element_type() {
            XmlElementType::XmlElementNode
            | XmlElementType::XmlAttributeNode
            | XmlElementType::XmlTextNode
            | XmlElementType::XmlCDATASectionNode
            | XmlElementType::XmlEntityRefNode
            | XmlElementType::XmlPINode
            | XmlElementType::XmlCommentNode => {}
            XmlElementType::XmlDocumentFragNode => {
                // TODO: Support document-fragment-nodes.
                return 2;
            }
            _ => {
                return 1;
            }
        }
        // Unlink only if @node was not already added to @destParent.
        if node
            .parent()
            .filter(|&p| Some(p) != dest_parent.map(|d| d.into()))
            .is_some()
        {
            node.unlink();
        }

        if let Some(node) = XmlNodePtr::try_from(node)
            .ok()
            .filter(|node| matches!(node.element_type(), XmlElementType::XmlElementNode))
        {
            return xml_dom_wrap_adopt_branch(
                ctxt,
                source_doc,
                node,
                dest_doc,
                dest_parent,
                options,
            );
        } else if let Ok(attr) = XmlAttrPtr::try_from(node) {
            return xml_dom_wrap_adopt_attr(ctxt, source_doc, attr, dest_doc, dest_parent, options);
        } else {
            node.set_document(Some(dest_doc));
            match node.element_type() {
                XmlElementType::XmlTextNode | XmlElementType::XmlCDATASectionNode => {}
                XmlElementType::XmlEntityRefNode => {
                    let mut node = XmlNodePtr::try_from(node).unwrap();
                    // Remove reference to the entity-node.
                    node.content = None;
                    node.set_children(None);
                    node.set_last(None);
                    if dest_doc.int_subset.is_some() || dest_doc.ext_subset.is_some() {
                        // Assign new entity-node if available.
                        let ent = xml_get_doc_entity(Some(dest_doc), &node.name().unwrap());
                        if let Some(ent) = ent {
                            node.content = ent.content.as_deref().map(|cont| cont.to_owned());
                            node.set_children(Some(ent.into()));
                            node.set_last(Some(ent.into()));
                        }
                    }
                }
                XmlElementType::XmlPINode => {}
                _ => {}
            }
        }
        0
    }
}

/// Unlinks the given node from its owner.
/// This will substitute ns-references to (*node).nsDef for
/// ns-references to (*doc).oldNs, thus ensuring the removed
/// branch to be autark wrt ns-references.
///
/// NOTE: This function was not intensively tested.
///
/// Returns 0 on success, 1 if the node is not supported,
///         -1 on API and internal errors.
#[doc(alias = "xmlDOMWrapRemoveNode")]
pub unsafe fn xml_dom_wrap_remove_node(
    ctxt: XmlDOMWrapCtxtPtr,
    doc: XmlDocPtr,
    mut node: XmlGenericNodePtr,
    _options: i32,
) -> i32 {
    unsafe {
        let mut list = vec![];
        let mut nb_list: i32 = 0;

        if node.document() != Some(doc) {
            return -1;
        }

        // TODO: 0 or -1 ?
        if node.parent().is_none() {
            return 0;
        }

        match node.element_type() {
            XmlElementType::XmlTextNode
            | XmlElementType::XmlCDATASectionNode
            | XmlElementType::XmlEntityRefNode
            | XmlElementType::XmlPINode
            | XmlElementType::XmlCommentNode => {
                node.unlink();
                return 0;
            }
            XmlElementType::XmlElementNode | XmlElementType::XmlAttributeNode => {}
            _ => {
                return 1;
            }
        }
        node.unlink();
        // Save out-of-scope ns-references in (*doc).oldNs.
        'main: loop {
            match node.element_type() {
                XmlElementType::XmlElementNode => {
                    let mut cur_node = XmlNodePtr::try_from(node).unwrap();
                    if ctxt.is_null() && cur_node.ns_def.is_some() {
                        let mut ns = cur_node.ns_def;
                        while let Some(now) = ns {
                            if xml_dom_wrap_ns_norm_add_ns_map_item2(
                                &mut list,
                                // &raw mut size_list,
                                &raw mut nb_list,
                                now,
                                now,
                            ) == -1
                            {
                                // goto internal_error;
                                return -1;
                            }
                            ns = now.next;
                        }
                    }

                    if cur_node.ns.is_some() {
                        // Find a mapping.
                        for (_, j) in (0..nb_list).zip((0..).step_by(2)) {
                            if cur_node.ns == Some(list[j]) {
                                cur_node.ns = Some(list[j + 1]);
                                // goto next_node;
                                if let Some(children) = cur_node.children().filter(|_| {
                                    matches!(
                                        cur_node.element_type(),
                                        XmlElementType::XmlElementNode
                                    )
                                }) {
                                    node = children;
                                    continue 'main;
                                }
                                // next_sibling:
                                'next_sibling: loop {
                                    if let Some(next) = node.next() {
                                        node = next;
                                    } else {
                                        let Some(parent) = node.parent() else {
                                            break 'main;
                                        };
                                        node = parent;
                                        // goto next_sibling;
                                        continue 'next_sibling;
                                    }

                                    continue 'main;
                                }
                            }
                        }
                        let mut ns = None;
                        if !ctxt.is_null() {
                            // User defined.
                        } else {
                            // Add to doc's oldNs.
                            ns = xml_dom_wrap_store_ns(
                                doc,
                                cur_node.ns.unwrap().href.as_deref(),
                                cur_node.ns.unwrap().prefix().as_deref(),
                            );
                            if ns.is_none() {
                                // goto internal_error;
                                return -1;
                            }
                        }
                        if let Some(ns) = ns {
                            // Add mapping.
                            if xml_dom_wrap_ns_norm_add_ns_map_item2(
                                &mut list,
                                // &raw mut size_list,
                                &raw mut nb_list,
                                cur_node.ns.unwrap(),
                                ns,
                            ) == -1
                            {
                                // goto internal_error;
                                return -1;
                            }
                        }
                        cur_node.ns = ns;
                    }
                    if matches!(node.element_type(), XmlElementType::XmlElementNode) {
                        if let Some(prop) = cur_node.properties {
                            node = XmlGenericNodePtr::from(prop);
                            continue;
                        }
                    }
                }
                XmlElementType::XmlAttributeNode => {
                    let mut attr = XmlAttrPtr::try_from(node).unwrap();
                    if attr.ns.is_some() {
                        // Find a mapping.
                        for (_, j) in (0..nb_list).zip((0..).step_by(2)) {
                            if attr.ns == Some(list[j]) {
                                attr.ns = Some(list[j + 1]);
                                // goto next_node;
                                if let Some(children) = attr.children().filter(|_| {
                                    matches!(attr.element_type(), XmlElementType::XmlElementNode)
                                }) {
                                    node = children;
                                    continue 'main;
                                }
                                // next_sibling:
                                'next_sibling: loop {
                                    if let Some(next) = node.next() {
                                        node = next;
                                    } else {
                                        let Some(parent) = node.parent() else {
                                            break 'main;
                                        };
                                        node = parent;
                                        // goto next_sibling;
                                        continue 'next_sibling;
                                    }

                                    continue 'main;
                                }
                            }
                        }
                        let mut ns = None;
                        if !ctxt.is_null() {
                            // User defined.
                        } else {
                            // Add to doc's oldNs.
                            ns = xml_dom_wrap_store_ns(
                                doc,
                                attr.ns.unwrap().href.as_deref(),
                                attr.ns.unwrap().prefix().as_deref(),
                            );
                            if ns.is_none() {
                                // goto internal_error;
                                return -1;
                            }
                        }
                        if let Some(ns) = ns {
                            // Add mapping.
                            if xml_dom_wrap_ns_norm_add_ns_map_item2(
                                &mut list,
                                // &raw mut size_list,
                                &raw mut nb_list,
                                attr.ns.unwrap(),
                                ns,
                            ) == -1
                            {
                                // goto internal_error;
                                return -1;
                            }
                        }
                        attr.ns = ns;
                    }
                }
                _ => {
                    'next_sibling: loop {
                        if let Some(next) = node.next() {
                            node = next;
                        } else {
                            let Some(parent) = node.parent() else {
                                break 'main;
                            };
                            node = parent;
                            // goto next_sibling;
                            continue 'next_sibling;
                        }

                        continue 'main;
                    }
                }
            }
            // next_node:
            if let Some(children) = node
                .children()
                .filter(|_| matches!(node.element_type(), XmlElementType::XmlElementNode))
            {
                node = children;
                continue;
            }
            // next_sibling:
            'next_sibling: loop {
                if let Some(next) = node.next() {
                    node = next;
                } else {
                    let Some(parent) = node.parent() else {
                        break 'main;
                    };
                    node = parent;
                    // goto next_sibling;
                    continue 'next_sibling;
                }

                continue 'main;
            }
        }

        0

        // internal_error:
        // if !list.is_null() {
        // 	xml_free(list as _);
        // }
        // return -1;
    }
}

/// References of out-of scope ns-decls are remapped to point to @destDoc:
/// 1) If @destParent is given, then nsDef entries on element-nodes are used
/// 2) If *no* @destParent is given, then @(*destDoc).oldNs entries are used.
///    This is the case when you don't know already where the cloned branch
///    will be added to.
///
/// If @destParent is given, it ensures that the tree is namespace
/// wellformed by creating additional ns-decls where needed.
/// Note that, since prefixes of already existent ns-decls can be
/// shadowed by this process, it could break QNames in attribute
/// values or element content.
/// TODO:
///   1) What to do with XInclude? Currently this returns an error for XInclude.
///
/// Returns 0 if the operation succeeded,
///         1 if a node of unsupported (or not yet supported) type was given,
///         -1 on API/internal errors.
#[doc(alias = "xmlDOMWrapCloneNode")]
#[allow(clippy::too_many_arguments)]
pub unsafe fn xml_dom_wrap_clone_node(
    ctxt: XmlDOMWrapCtxtPtr,
    source_doc: Option<XmlDocPtr>,
    node: XmlGenericNodePtr,
    res_node: &mut Option<XmlGenericNodePtr>,
    dest_doc: XmlDocPtr,
    dest_parent: Option<XmlGenericNodePtr>,
    deep: i32,
    _options: i32,
) -> i32 {
    unsafe {
        let mut ret: i32 = 0;
        let mut cur_elem = None;
        let mut ns_map: XmlNsMapPtr = null_mut();
        let mut mi: XmlNsMapItemPtr;
        let mut depth: i32 = -1;
        // gather @parent's ns-decls.
        let mut parnsdone: i32 = 0;
        // @ancestorsOnly:
        // TODO: @ancestorsOnly should be set per option.
        let ancestors_only: i32 = 0;
        let mut result_clone: Option<XmlGenericNodePtr> = None;
        let mut parent_clone: Option<XmlGenericNodePtr> = None;
        let mut prev_clone: Option<XmlGenericNodePtr> = None;

        // TODO: Initially we support only element-nodes.
        if !matches!(node.element_type(), XmlElementType::XmlElementNode) {
            return 1;
        }
        // Check node.doc sanity.
        if node.document().is_some_and(|doc| Some(doc) != source_doc) && source_doc.is_some() {
            // Might be an XIncluded node.
            return -1;
        }
        let Some(source_doc) = source_doc.or(node.document()) else {
            return -1;
        };

        // Reuse the namespace map of the context.
        if !ctxt.is_null() {
            ns_map = (*ctxt).namespace_map as _;
        }

        *res_node = None;

        let mut cur = Some(node);
        'exit: {
            'internal_error: {
                'main: while let Some(cur_node) = cur {
                    if cur_node.document() != Some(source_doc) {
                        // We'll assume XIncluded nodes if the doc differs.
                        // TODO: Do we need to reconciliate XIncluded nodes?
                        // TODO: This here returns -1 in this case.
                        break 'internal_error;
                    }
                    // Create a new node.
                    let mut clone = match cur_node.element_type() {
                        XmlElementType::XmlXIncludeStart | XmlElementType::XmlXIncludeEnd => {
                            // TODO: What to do with XInclude?
                            break 'internal_error;
                        }
                        XmlElementType::XmlElementNode
                        | XmlElementType::XmlTextNode
                        | XmlElementType::XmlCDATASectionNode
                        | XmlElementType::XmlCommentNode
                        | XmlElementType::XmlPINode
                        | XmlElementType::XmlDocumentFragNode
                        | XmlElementType::XmlEntityRefNode
                        | XmlElementType::XmlEntityNode => {
                            let cur_node = XmlNodePtr::try_from(cur_node).unwrap();
                            // Nodes of xmlNode structure.
                            let Some(mut new) = XmlNodePtr::new(XmlNode::default()) else {
                                xml_tree_err_memory("xmlDOMWrapCloneNode(): allocating a node");
                                break 'internal_error;
                            };
                            new.typ = cur_node.element_type();
                            // Set hierarchical links.
                            if result_clone.is_some() {
                                new.set_parent(parent_clone);
                                if let Some(mut prev_clone) = prev_clone {
                                    prev_clone.set_next(Some(new.into()));
                                    new.set_prev(Some(prev_clone));
                                } else {
                                    parent_clone.unwrap().set_children(Some(new.into()));
                                }
                            } else {
                                result_clone = Some(XmlGenericNodePtr::from(new));
                            }
                            // Clone the name of the node if any.
                            new.name = cur_node.name.clone();
                            XmlGenericNodePtr::from(new)
                        }
                        XmlElementType::XmlAttributeNode => {
                            let cur_node = XmlAttrPtr::try_from(cur_node).unwrap();
                            // Attributes (xmlAttr).
                            // Use xmlRealloc to avoid -Warray-bounds warning
                            let Some(mut new) = XmlAttrPtr::new(XmlAttr::default()) else {
                                xml_tree_err_memory(
                                    "xmlDOMWrapCloneNode(): allocating an attr-node",
                                );
                                break 'internal_error;
                            };
                            new.typ = cur_node.element_type();
                            // Set hierarchical links.
                            // TODO: Change this to add to the end of attributes.
                            if result_clone.is_some() {
                                new.set_parent(parent_clone);
                                if let Some(mut prev_clone) = prev_clone {
                                    prev_clone.set_next(Some(new.into()));
                                    new.prev = XmlAttrPtr::try_from(prev_clone).ok();
                                } else {
                                    XmlNodePtr::try_from(parent_clone.unwrap())
                                        .unwrap()
                                        .properties = Some(new);
                                }
                            } else {
                                result_clone = Some(new.into());
                            }
                            // Clone the name of the node if any.
                            new.name = cur_node.name.clone();

                            XmlGenericNodePtr::from(new)
                        }
                        _ => {
                            // TODO QUESTION: Any other nodes expected?
                            break 'internal_error;
                        }
                    };
                    clone.set_document(Some(dest_doc));

                    let mut leave_node = false;
                    match cur_node.element_type() {
                        XmlElementType::XmlXIncludeStart | XmlElementType::XmlXIncludeEnd => {
                            // TODO
                            return -1;
                        }
                        XmlElementType::XmlElementNode => {
                            let cur_node = XmlNodePtr::try_from(cur_node).unwrap();
                            cur_elem = Some(cur_node);
                            depth += 1;
                            // Namespace declarations.
                            if cur_node.ns_def.is_some() {
                                if parnsdone == 0 {
                                    if dest_parent.is_some() && ctxt.is_null() {
                                        // Gather @parent's in-scope ns-decls.
                                        if xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                            &raw mut ns_map,
                                            dest_parent,
                                        ) == -1
                                        {
                                            break 'internal_error;
                                        }
                                    }
                                    parnsdone = 1;
                                }
                                // Clone namespace declarations.
                                let mut clone_ns_def_slot = None::<XmlNsPtr>;
                                let mut ns = cur_node.ns_def;
                                while let Some(now) = ns {
                                    // Create a new xmlNs.
                                    let Some(mut new) = XmlNsPtr::new(XmlNs {
                                        typ: XML_LOCAL_NAMESPACE,
                                        ..Default::default()
                                    }) else {
                                        xml_tree_err_memory(
                                            "xmlDOMWrapCloneNode(): allocating namespace",
                                        );
                                        return -1;
                                    };

                                    new.href = now.href.clone();
                                    new.prefix = now.prefix.clone();

                                    if let Some(mut last) = clone_ns_def_slot {
                                        last.next = Some(new);
                                        clone_ns_def_slot = Some(new);
                                    } else {
                                        clone_ns_def_slot = Some(new);
                                        XmlNodePtr::try_from(clone).unwrap().ns_def = Some(new);
                                    }

                                    // Note that for custom handling of ns-references,
                                    // the ns-decls need not be stored in the ns-map,
                                    // since they won't be referenced by (*node).ns.
                                    if ctxt.is_null() || (*ctxt).get_ns_for_node_func.is_none() {
                                        // Does it shadow any ns-decl?
                                        if XML_NSMAP_NOTEMPTY!(ns_map) {
                                            XML_NSMAP_FOREACH!(ns_map, mi, {
                                                if ((*mi).depth >= XML_TREE_NSMAP_PARENT)
                                                    && (*mi).shadow_depth == -1
                                                    && now.prefix()
                                                        == (*mi).new_ns.unwrap().prefix()
                                                {
                                                    // Mark as shadowed at the current depth.
                                                    (*mi).shadow_depth = depth;
                                                }
                                            });
                                        }
                                        // Push mapping.
                                        if xml_dom_wrap_ns_map_add_item(
                                            &raw mut ns_map,
                                            -1,
                                            Some(now),
                                            Some(new),
                                            depth,
                                        )
                                        .is_null()
                                        {
                                            break 'internal_error;
                                        }
                                    }
                                    ns = now.next;
                                }
                            }
                            // cur_node.ns will be processed further down.
                        }
                        XmlElementType::XmlAttributeNode => {
                            // IDs will be processed further down.
                            // cur_node.ns will be processed further down.
                        }
                        XmlElementType::XmlTextNode | XmlElementType::XmlCDATASectionNode => {
                            let cur_node = XmlNodePtr::try_from(cur_node).unwrap();
                            // Note that this will also cover the values of attributes.
                            XmlNodePtr::try_from(clone).unwrap().content = cur_node.content.clone();
                            // goto leave_node;
                            leave_node = true;
                        }
                        XmlElementType::XmlEntityNode => {
                            // TODO: What to do here?
                            // goto leave_node;
                            leave_node = true;
                        }
                        XmlElementType::XmlEntityRefNode => {
                            let cur_node = XmlNodePtr::try_from(cur_node).unwrap();
                            if source_doc != dest_doc {
                                if dest_doc.int_subset.is_some() || dest_doc.ext_subset.is_some() {
                                    // Different doc: Assign new entity-node if available.
                                    let ent = xml_get_doc_entity(
                                        Some(dest_doc),
                                        &cur_node.name().unwrap(),
                                    );
                                    if let Some(ent) = ent {
                                        XmlNodePtr::try_from(clone).unwrap().content =
                                            ent.content.as_deref().map(|cont| cont.to_owned());
                                        clone.set_children(Some(ent.into()));
                                        clone.set_last(Some(ent.into()));
                                    }
                                }
                            } else {
                                // Same doc: Use the current node's entity declaration and value.
                                XmlNodePtr::try_from(clone).unwrap().content =
                                    cur_node.content.clone();
                                clone.set_children(cur_node.children());
                                clone.set_last(cur_node.last());
                            }
                            // goto leave_node;
                            leave_node = true;
                        }
                        XmlElementType::XmlPINode => {
                            let cur_node = XmlNodePtr::try_from(cur_node).unwrap();
                            XmlNodePtr::try_from(clone).unwrap().content = cur_node.content.clone();
                            // goto leave_node;
                            leave_node = true;
                        }
                        XmlElementType::XmlCommentNode => {
                            let cur_node = XmlNodePtr::try_from(cur_node).unwrap();
                            XmlNodePtr::try_from(clone).unwrap().content = cur_node.content.clone();
                            // goto leave_node;
                            leave_node = true;
                        }
                        _ => {
                            break 'internal_error;
                        }
                    }

                    if !leave_node {
                        let cur_ns = if let Ok(node) = XmlNodePtr::try_from(node) {
                            node.ns
                        } else {
                            XmlAttrPtr::try_from(node).unwrap().ns
                        };
                        if let Some(cur_ns) = cur_ns {
                            // handle_ns_reference:
                            // The following will take care of references to ns-decls
                            // and is intended only for element- and attribute-nodes.
                            //
                            if parnsdone == 0 {
                                if dest_parent.is_some()
                                    && ctxt.is_null()
                                    && xml_dom_wrap_ns_norm_gather_in_scope_ns(
                                        &raw mut ns_map,
                                        dest_parent,
                                    ) == -1
                                {
                                    break 'internal_error;
                                }
                                parnsdone = 1;
                            }
                            // Adopt ns-references.
                            let mut end_ns_reference = false;
                            if XML_NSMAP_NOTEMPTY!(ns_map) {
                                // Search for a mapping.
                                XML_NSMAP_FOREACH!(ns_map, mi, {
                                    if (*mi).shadow_depth == -1 && Some(cur_ns) == (*mi).old_ns {
                                        // This is the nice case: a mapping was found.
                                        XmlNodePtr::try_from(clone).unwrap().ns = (*mi).new_ns;
                                        // goto end_ns_reference;
                                        end_ns_reference = true;
                                        break;
                                    }
                                });
                            }

                            if !end_ns_reference {
                                // No matching namespace in scope. We need a new one.
                                if !ctxt.is_null() && (*ctxt).get_ns_for_node_func.is_some() {
                                    // User-defined behaviour.
                                    let ns = ((*ctxt).get_ns_for_node_func.unwrap())(
                                        ctxt,
                                        Some(cur_node),
                                        cur_ns.href.as_deref(),
                                        cur_ns.prefix.as_deref(),
                                    );
                                    // Add user's mapping.
                                    if xml_dom_wrap_ns_map_add_item(
                                        &raw mut ns_map,
                                        -1,
                                        Some(cur_ns),
                                        ns,
                                        XML_TREE_NSMAP_CUSTOM,
                                    )
                                    .is_null()
                                    {
                                        break 'internal_error;
                                    }
                                    XmlNodePtr::try_from(clone).unwrap().ns = ns;
                                } else {
                                    // Acquire a normalized ns-decl and add it to the map.
                                    let mut ns = None;
                                    if xml_dom_wrap_ns_norm_acquire_normalized_ns(
                                        dest_doc,
                                        // ns-decls on curElem or on (*destDoc).oldNs
                                        dest_parent.and(cur_elem),
                                        cur_ns,
                                        &mut ns,
                                        &raw mut ns_map,
                                        depth,
                                        // if we need to search only in the ancestor-axis
                                        ancestors_only,
                                        // ns-decls must be prefixed for attributes.
                                        matches!(
                                            cur_node.element_type(),
                                            XmlElementType::XmlAttributeNode
                                        ) as i32,
                                    ) == -1
                                    {
                                        break 'internal_error;
                                    }
                                    XmlNodePtr::try_from(clone).unwrap().ns = ns;
                                }
                            }
                        }

                        // Some post-processing.
                        //
                        // Handle ID attributes.
                        if matches!(clone.element_type(), XmlElementType::XmlAttributeNode)
                            && clone.parent().is_some()
                            && xml_is_id(
                                Some(dest_doc),
                                Some(XmlNodePtr::try_from(clone.parent().unwrap()).unwrap()),
                                XmlAttrPtr::try_from(clone).ok(),
                            ) != 0
                        {
                            let children = cur_node.children();
                            if let Some(id_val) =
                                children.and_then(|c| c.get_string(cur_node.document(), 1))
                            {
                                if xml_add_id(
                                    None,
                                    dest_doc,
                                    &id_val,
                                    XmlAttrPtr::try_from(cur_node).unwrap(),
                                )
                                .is_none()
                                {
                                    // TODO: error message.
                                    break 'internal_error;
                                }
                            }
                        }
                        // The following will traverse the tree **************************
                        //
                        // Walk the element's attributes before descending into child-nodes.
                        if matches!(cur_node.element_type(), XmlElementType::XmlElementNode) {
                            let cur_node = XmlNodePtr::try_from(cur_node).unwrap();
                            if let Some(prop) = cur_node.properties {
                                prev_clone = None;
                                parent_clone = Some(clone);
                                cur = Some(prop.into());
                                continue 'main;
                            }
                        }
                        // into_content:
                        // Descend into child-nodes.
                        if let Some(children) = cur_node.children().filter(|_| {
                            deep != 0
                                || matches!(
                                    cur_node.element_type(),
                                    XmlElementType::XmlAttributeNode
                                )
                        }) {
                            prev_clone = None;
                            parent_clone = Some(clone);
                            cur = Some(children);
                            continue 'main;
                        }
                    }

                    // leave_node:
                    'leave_node: loop {
                        // At this point we are done with the node, its content
                        // and an element-nodes's attribute-nodes.
                        if cur == Some(node) {
                            break 'main;
                        }
                        let cur_node = cur.unwrap();
                        if matches!(cur_node.element_type(), XmlElementType::XmlElementNode)
                            || matches!(cur_node.element_type(), XmlElementType::XmlXIncludeStart)
                            || matches!(cur_node.element_type(), XmlElementType::XmlXIncludeEnd)
                        {
                            // TODO: Do we expect nsDefs on xmlElementType::XML_XINCLUDE_START?
                            if XML_NSMAP_NOTEMPTY!(ns_map) {
                                // Pop mappings.
                                while !(*ns_map).last.is_null() && (*(*ns_map).last).depth >= depth
                                {
                                    XML_NSMAP_POP!(ns_map, mi);
                                }
                                // Unshadow.
                                XML_NSMAP_FOREACH!(ns_map, mi, {
                                    if (*mi).shadow_depth >= depth {
                                        (*mi).shadow_depth = -1;
                                    }
                                });
                            }
                            depth -= 1;
                        }
                        if let Some(next) = cur_node.next() {
                            prev_clone = Some(clone);
                            cur = Some(next);
                        } else if !matches!(
                            cur_node.element_type(),
                            XmlElementType::XmlAttributeNode
                        ) {
                            // Set clone.last.
                            if let Some(mut parent) = clone.parent() {
                                parent.set_last(Some(clone));
                            }
                            clone = clone.parent().unwrap();
                            parent_clone = clone.parent();
                            // Process parent --> next;
                            cur = cur_node.parent();
                            // goto leave_node;
                            continue 'leave_node;
                        } else {
                            // This is for attributes only.
                            clone = clone.parent().unwrap();
                            parent_clone = clone.parent();
                            // Process parent-element --> children.
                            cur = cur_node.parent();
                            // goto into_content;
                            // Descend into child-nodes.
                            if let Some(children) = cur_node.children().filter(|_| {
                                deep != 0
                                    || matches!(
                                        cur_node.element_type(),
                                        XmlElementType::XmlAttributeNode
                                    )
                            }) {
                                prev_clone = None;
                                parent_clone = Some(clone);
                                cur = Some(children);
                                continue 'main;
                            }
                            continue 'leave_node;
                        }

                        break;
                    }
                }
                break 'exit;
            }

            // internal_error:
            ret = -1;
        }
        // exit:
        // Cleanup.
        if !ns_map.is_null() {
            if !ctxt.is_null() && (*ctxt).namespace_map == ns_map as _ {
                // Just cleanup the map but don't free.
                if !(*ns_map).first.is_null() {
                    if !(*ns_map).pool.is_null() {
                        (*(*ns_map).last).next = (*ns_map).pool;
                    }
                    (*ns_map).pool = (*ns_map).first;
                    (*ns_map).first = null_mut();
                }
            } else {
                xml_dom_wrap_ns_map_free(ns_map);
            }
        }
        // TODO: Should we try a cleanup of the cloned node in case of a fatal error?
        *res_node = result_clone;
        ret
    }
}