Skip to main content

libxml_rs/abi/
exports_xml2.rs

1//! C ABI exports for libxml2.so.2 — no_mangle extern "C" functions (§1, §16).
2//!
3//! This module contains all `#[no_mangle] pub extern "C"` function definitions
4//! that form the public ABI of libxml2.so.2. Every function here corresponds to
5//! a function in the upstream libxml2 headers.
6//!
7//! # Phase 1 status
8//!
9//! Complete — all major ABI entry points are implemented. Functions that require
10//! modules not yet implemented (tree, parser, etc.) call into those modules,
11//! which will be filled in as Phase 1 continues.
12//!
13//! # Organization
14//!
15//! Exports are grouped by subsystem in the order they appear in upstream headers:
16//!
17//! 1. Initialization / Cleanup
18//! 2. Version
19//! 3. Memory / Allocator
20//! 4. Error handling
21//! 5. String utilities
22//! 6. Tree (document, node, attribute, namespace, DTD, entity)
23//! 7. Parser (SAX, DOM, push, reader)
24//! 8. I/O
25//! 9. Dictionary
26//! 10. Hash table
27//! 11. List
28//! 12. Buffer
29//! 13. Encoding
30//! 14. XPath
31//! 15. XInclude
32//! 16. Catalog
33//! 17. HTML
34//! 18. Debug/misc
35
36#![allow(non_snake_case)]
37#![allow(unused_variables)]
38#![allow(clippy::missing_safety_doc)]
39#![allow(clippy::not_unsafe_ptr_arg_deref)]
40
41use core::ffi::c_void;
42use core::ptr;
43use once_cell::sync::Lazy;
44use parking_lot::Mutex;
45use std::collections::HashMap;
46use std::ffi::{CStr, CString};
47use std::mem::size_of;
48use std::os::raw::{c_char, c_int, c_uint, c_ulong};
49
50use crate::xml::xinclude;
51use crate::xml::xpath::ast::CompiledExpr;
52use crate::xml::xpath::context::XPathContext;
53use crate::xml::xpath::types::{NodeSet, XPathValue};
54use crate::xml::xpointer;
55
56use crate::abi::allocator::*;
57use crate::abi::callbacks::*;
58use crate::abi::structs::*;
59use crate::abi::types::*;
60
61// ═══════════════════════════════════════════════════════════════════════════════
62// 1. Initialization / Cleanup
63// ═══════════════════════════════════════════════════════════════════════════════
64
65/// Initialize the parser library.
66///
67/// Must be called before any other libxml2 functions.
68/// Safe to call multiple times (reference-counted in modern libxml2).
69///
70/// # UPSTREAM-PARITY
71///
72/// ```c
73/// void xmlInitParser(void);
74/// ```
75#[no_mangle]
76pub unsafe extern "C" fn xmlInitParser() {
77    crate::internal::globals::init_parser();
78}
79
80/// Initialize the global variables module (upstream globals.h).
81///
82/// # UPSTREAM-PARITY
83///
84/// ```c
85/// void xmlInitGlobals(void);
86/// ```
87///
88/// Upstream `xmlInitGlobals` (globals.c) is called once to initialize the
89/// global variable defaults. The candidate's globals are initialized
90/// statically/on first use, so this is a no-op that exists for ABI
91/// compatibility.
92#[no_mangle]
93pub unsafe extern "C" fn xmlInitGlobals() {
94    // Globals are statically initialized in the candidate.
95}
96
97/// Upstream `xmlInitializeGlobalState` (globals.c) — initializes a
98/// `xmlGlobalState` struct; the candidate keeps no global-state struct, so
99/// this is a no-op for ABI compatibility.
100///
101/// # UPSTREAM-PARITY
102///
103/// ```c
104/// void xmlInitializeGlobalState(xmlGlobalStatePtr gs);
105/// ```
106#[no_mangle]
107pub unsafe extern "C" fn xmlInitializeGlobalState(_gs: *mut c_void) {
108    // No-op: the candidate's globals are statically initialized.
109}
110
111/// Upstream `xmlInitializeDict` (dict.c) — ensures the dictionary
112/// subsystem is initialized; no-op in the candidate (lazy init).
113///
114/// # UPSTREAM-PARITY
115///
116/// ```c
117/// int xmlInitializeDict(void);
118/// ```
119#[no_mangle]
120pub extern "C" fn xmlInitializeDict() -> c_int {
121    0
122}
123
124/// Upstream `xmlInitializePredefinedEntities` (entities.c) — the
125/// predefined entities (& < > " ') are built lazily by
126/// the candidate; no-op.
127///
128/// # UPSTREAM-PARITY
129///
130/// ```c
131/// void xmlInitializePredefinedEntities(void);
132/// ```
133#[no_mangle]
134pub extern "C" fn xmlInitializePredefinedEntities() {
135    // No-op: predefined entities are resolved on demand.
136}
137
138/// Upstream `xmlCleanupPredefinedEntities` (entities.c) — no-op in the
139/// candidate (no global entity table to release).
140///
141/// # UPSTREAM-PARITY
142///
143/// ```c
144/// void xmlCleanupPredefinedEntities(void);
145/// ```
146#[no_mangle]
147pub extern "C" fn xmlCleanupPredefinedEntities() {
148    // No-op.
149}
150
151/// Upstream `xmlDefaultSAXHandlerInit` (SAX2.c) — fills the
152/// `xmlDefaultSAXHandler` global. The candidate's default handler is built
153/// on demand; this initializes the exported default-handler global when it
154/// is added (currently tracked in R-000135). No-op for now.
155///
156/// # UPSTREAM-PARITY
157///
158/// ```c
159/// void xmlDefaultSAXHandlerInit(void);
160/// ```
161#[no_mangle]
162pub extern "C" fn xmlDefaultSAXHandlerInit() {
163    // The candidate builds default handlers on demand; the exported
164    // xmlDefaultSAXHandler global is part of the R-000135 data closure.
165}
166
167/// Set the default SAX version (upstream SAX2.c `xmlSAXDefaultVersion`):
168/// returns the previous default; -1 when the version is not 1 or 2.
169///
170/// # UPSTREAM-PARITY
171///
172/// ```c
173/// int xmlSAXDefaultVersion(int version);
174/// ```
175static SAX2_DEFAULT_VERSION: core::sync::atomic::AtomicI32 = core::sync::atomic::AtomicI32::new(2);
176#[no_mangle]
177pub extern "C" fn xmlSAXDefaultVersion(version: c_int) -> c_int {
178    use core::sync::atomic::Ordering;
179    let ret = SAX2_DEFAULT_VERSION.load(Ordering::Relaxed);
180    if version != 1 && version != 2 {
181        return -1;
182    }
183    SAX2_DEFAULT_VERSION.store(version, Ordering::Relaxed);
184    ret
185}
186
187/// Initialize a SAX handler for a given SAX version (upstream SAX2.c
188/// `xmlSAXVersion`): fills the handler with the default callbacks and sets
189/// `initialized` (XML_SAX2_MAGIC for version 2, 1 for version 1).
190///
191/// # UPSTREAM-PARITY
192///
193/// ```c
194/// int xmlSAXVersion(xmlSAXHandler *hdlr, int version);
195/// ```
196#[no_mangle]
197pub unsafe extern "C" fn xmlSAXVersion(
198    hdlr: *mut crate::abi::structs::_xmlSAXHandler,
199    version: c_int,
200) -> c_int {
201    if hdlr.is_null() {
202        return -1;
203    }
204    if version != 1 && version != 2 {
205        return -1;
206    }
207    // SAFETY: hdlr is non-NULL and writable.
208    unsafe {
209        crate::xml::sax::dispatch::xmlSAX2InitDefaultSAXHandler(hdlr);
210        let h = &mut *hdlr;
211        if version == 2 {
212            h.initialized = crate::abi::constants::XML_SAX2_MAGIC as c_uint;
213        } else {
214            h.initialized = 1;
215        }
216    }
217    0
218}
219
220/// Upstream `xmlHasFeature` (parser.c): returns 1 when the library was
221/// compiled with the requested feature. The candidate enables the full
222/// feature set (see include/libxml/xmlversion.h), so every known feature
223/// reports 1; unknown features report 0.
224///
225/// # UPSTREAM-PARITY
226///
227/// ```c
228/// int xmlHasFeature(xmlFeature feature);
229/// ```
230#[no_mangle]
231pub extern "C" fn xmlHasFeature(feature: c_int) -> c_int {
232    // xmlFeature enum values (upstream xmlversion.h): XML_WITH_* run 1..24
233    // (XML_WITH_THREAD=1 ... XML_WITH_MODULES=24).
234    if (1..=24).contains(&feature) {
235        1
236    } else {
237        0
238    }
239}
240
241/// Clean up the global variables module (upstream globals.h).
242///
243/// # UPSTREAM-PARITY
244///
245/// ```c
246/// void xmlCleanupGlobals(void);
247/// ```
248///
249/// Upstream `xmlCleanupGlobals` frees the global defaults. The candidate
250/// keeps globals alive for the process lifetime (repeated init/cleanup is
251/// reference-counted); no-op for ABI compatibility.
252#[no_mangle]
253pub unsafe extern "C" fn xmlCleanupGlobals() {
254    // The candidate's globals are process-lifetime statics.
255}
256
257/// Clean up the parser library.
258///
259/// Should be called when the library is no longer needed.
260///
261/// # UPSTREAM-PARITY
262///
263/// ```c
264/// void xmlCleanupParser(void);
265/// ```
266#[no_mangle]
267pub unsafe extern "C" fn xmlCleanupParser() {
268    crate::internal::globals::cleanup_parser();
269}
270
271/// Create a simple mutex (upstream threads.h).
272///
273/// # UPSTREAM-PARITY
274///
275/// ```c
276/// xmlMutexPtr xmlNewMutex(void);
277/// ```
278#[no_mangle]
279pub extern "C" fn xmlNewMutex() -> *mut c_void {
280    crate::xml::threads::new_mutex()
281}
282
283/// Free a simple mutex (upstream threads.h).
284///
285/// # UPSTREAM-PARITY
286///
287/// ```c
288/// void xmlFreeMutex(xmlMutexPtr tok);
289/// ```
290#[no_mangle]
291pub unsafe extern "C" fn xmlFreeMutex(tok: *mut c_void) {
292    crate::xml::threads::free_mutex(tok);
293}
294
295/// Lock a simple mutex (upstream threads.h).
296///
297/// # UPSTREAM-PARITY
298///
299/// ```c
300/// void xmlMutexLock(xmlMutexPtr tok);
301/// ```
302#[no_mangle]
303pub unsafe extern "C" fn xmlMutexLock(tok: *mut c_void) {
304    crate::xml::threads::mutex_lock(tok);
305}
306
307/// Unlock a simple mutex (upstream threads.h).
308///
309/// # UPSTREAM-PARITY
310///
311/// ```c
312/// void xmlMutexUnlock(xmlMutexPtr tok);
313/// ```
314#[no_mangle]
315pub unsafe extern "C" fn xmlMutexUnlock(tok: *mut c_void) {
316    crate::xml::threads::mutex_unlock(tok);
317}
318
319/// Create a recursive mutex (upstream threads.h).
320///
321/// # UPSTREAM-PARITY
322///
323/// ```c
324/// xmlRMutexPtr xmlNewRMutex(void);
325/// ```
326#[no_mangle]
327pub extern "C" fn xmlNewRMutex() -> *mut c_void {
328    crate::xml::threads::new_rmutex()
329}
330
331/// Free a recursive mutex (upstream threads.h).
332///
333/// # UPSTREAM-PARITY
334///
335/// ```c
336/// void xmlFreeRMutex(xmlRMutexPtr tok);
337/// ```
338#[no_mangle]
339pub unsafe extern "C" fn xmlFreeRMutex(tok: *mut c_void) {
340    crate::xml::threads::free_rmutex(tok);
341}
342
343/// Lock a recursive mutex (upstream threads.h).
344///
345/// # UPSTREAM-PARITY
346///
347/// ```c
348/// void xmlRMutexLock(xmlRMutexPtr tok);
349/// ```
350#[no_mangle]
351pub unsafe extern "C" fn xmlRMutexLock(tok: *mut c_void) {
352    crate::xml::threads::rmutex_lock(tok);
353}
354
355/// Unlock a recursive mutex (upstream threads.h).
356///
357/// # UPSTREAM-PARITY
358///
359/// ```c
360/// void xmlRMutexUnlock(xmlRMutexPtr tok);
361/// ```
362#[no_mangle]
363pub unsafe extern "C" fn xmlRMutexUnlock(tok: *mut c_void) {
364    crate::xml::threads::rmutex_unlock(tok);
365}
366
367/// Check the thread-local storage (upstream threads.h `xmlCheckThreadLocalStorage`):
368/// returns 0 when TLS is functional, -1 otherwise. The candidate uses Rust
369/// thread-locals which are always functional.
370///
371/// # UPSTREAM-PARITY
372///
373/// ```c
374/// int xmlCheckThreadLocalStorage(void);
375/// ```
376#[no_mangle]
377pub extern "C" fn xmlCheckThreadLocalStorage() -> c_int {
378    0
379}
380
381/// Initialize threading support.
382///
383/// # UPSTREAM-PARITY
384///
385/// ```c
386/// int xmlInitThreads(void);
387/// ```
388///
389/// Returns 0 on success.
390#[no_mangle]
391pub unsafe extern "C" fn xmlInitThreads() -> c_int {
392    crate::internal::globals::init_threads()
393}
394
395/// Clean up threading support.
396///
397/// # UPSTREAM-PARITY
398///
399/// ```c
400/// void xmlCleanupThreads(void);
401/// ```
402#[no_mangle]
403pub unsafe extern "C" fn xmlCleanupThreads() {
404    crate::xml::threads::cleanup_threads();
405}
406
407/// Check whether the library has been initialized.
408///
409/// # UPSTREAM-PARITY
410///
411/// ```c
412/// int xmlIsInitialized(void);
413/// ```
414#[no_mangle]
415pub extern "C" fn xmlIsInitialized() -> c_int {
416    if crate::abi::versioning::is_initialized() {
417        1
418    } else {
419        0
420    }
421}
422
423/// Initialize a set of threads (libxml2 compat).
424///
425/// # UPSTREAM-PARITY
426///
427/// ```c
428/// int xmlInitThreads(void);
429/// ```
430/// This is an alias.
431#[no_mangle]
432pub unsafe extern "C" fn xmlLockLibrary() {
433    crate::xml::threads::lock_library();
434}
435
436/// Unlock the library (libxml2 compat).
437///
438/// # UPSTREAM-PARITY
439///
440/// ```c
441/// void xmlUnlockLibrary(void);
442/// ```
443#[no_mangle]
444pub unsafe extern "C" fn xmlUnlockLibrary() {
445    crate::xml::threads::unlock_library();
446}
447
448// ═══════════════════════════════════════════════════════════════════════════════
449// 4. Error Handling
450// ═══════════════════════════════════════════════════════════════════════════════
451
452/// Set the generic error handler.
453///
454/// # UPSTREAM-PARITY
455///
456/// ```c
457/// void xmlSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler);
458/// ```
459///
460/// # SAFETY
461///
462/// - `handler` must be a valid function pointer or NULL (to reset to default).
463/// - If non-NULL, the handler may be called at any time with `ctx`.
464#[no_mangle]
465pub unsafe extern "C" fn xmlSetGenericErrorFunc(
466    ctx: *mut c_void,
467    handler: Option<xmlGenericErrorFunc>,
468) {
469    // SAFETY: Delegates to xml::errors with same safety contract.
470    unsafe { crate::xml::errors::set_generic_error_func(ctx, handler) };
471}
472
473/// Set the structured error handler.
474///
475/// # UPSTREAM-PARITY
476///
477/// ```c
478/// void xmlSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler);
479/// ```
480///
481/// # SAFETY
482///
483/// - `handler` must be a valid function pointer or NULL.
484#[no_mangle]
485pub unsafe extern "C" fn xmlSetStructuredErrorFunc(
486    ctx: *mut c_void,
487    handler: Option<xmlStructuredErrorFunc>,
488) {
489    // SAFETY: Delegates to xml::errors with same safety contract.
490    unsafe { crate::xml::errors::set_structured_error_func(ctx, handler) };
491}
492
493/// Get the last error for the current thread.
494///
495/// # UPSTREAM-PARITY
496///
497/// ```c
498/// xmlErrorPtr xmlGetLastError(void);
499/// ```
500///
501/// Returns a pointer to the last error, or NULL if no error occurred.
502/// The returned pointer is valid until the next libxml2 call in this thread.
503#[no_mangle]
504pub extern "C" fn xmlGetLastError() -> *mut _xmlError {
505    crate::xml::errors::get_last_error()
506}
507
508/// Get a copy of the last error for the current thread.
509///
510/// # UPSTREAM-PARITY
511///
512/// ```c
513/// xmlErrorPtr xmlCopyError(xmlErrorPtr from, xmlErrorPtr to);
514/// ```
515///
516/// Copies `from` into `to`. Returns 0 on success, -1 on error.
517///
518/// # SAFETY
519///
520/// - `from` and `to` must be valid pointers to `_xmlError` structs, or NULL.
521#[no_mangle]
522pub unsafe extern "C" fn xmlCopyError(from: *const _xmlError, to: *mut _xmlError) -> c_int {
523    // SAFETY: Delegates to xml::errors with same safety contract.
524    unsafe { crate::xml::errors::copy_error(from, to) }
525}
526
527/// Reset an error structure.
528///
529/// # UPSTREAM-PARITY
530///
531/// ```c
532/// void xmlResetError(xmlErrorPtr err);
533/// ```
534///
535/// # SAFETY
536///
537/// - `err` must be a valid pointer to `_xmlError`, or NULL.
538#[no_mangle]
539pub unsafe extern "C" fn xmlResetError(err: *mut _xmlError) {
540    // SAFETY: Delegates to xml::errors with same safety contract.
541    unsafe { crate::xml::errors::reset_error(err) };
542}
543
544/// Raise a structured error.
545///
546/// This is called internally when an error occurs. It updates the last error
547/// and invokes the structured error handler if one is set.
548///
549/// # SAFETY
550///
551/// - `ctxt` may be NULL (context of the error).
552/// - `domain`, `code`, `level`: valid error codes.
553/// - `msg` must be a valid C string or NULL.
554/// - `file` must be a valid C string or NULL.
555/// - `str1`, `str2`, `str3`: error-related strings (may be NULL).
556#[no_mangle]
557pub unsafe extern "C" fn xmlRaiseError(
558    ctxt: *mut c_void,
559    ctxt2: *mut c_void,
560    ctxt3: *mut c_void,
561    ctxt4: *mut c_void,
562    ctxt5: *mut c_void,
563    domain: c_int,
564    code: c_int,
565    level: c_int,
566    file: *const c_char,
567    line: c_int,
568    str1: *const c_char,
569    str2: *const c_char,
570    str3: *const c_char,
571    int1: c_int,
572    int2: c_int,
573    msg: *const c_char,
574) {
575    // SAFETY: Delegates to xml::errors with same safety contract.
576    unsafe {
577        crate::xml::errors::raise_error(
578            ctxt, ctxt2, ctxt3, ctxt4, ctxt5, domain, code, level, file, line, str1, str2, str3,
579            int1, int2, msg,
580        );
581    }
582}
583
584/// Remove any error from the last error stack.
585///
586/// # UPSTREAM-PARITY
587///
588/// ```c
589/// void xmlResetLastError(void);
590/// ```
591#[no_mangle]
592pub extern "C" fn xmlResetLastError() {
593    crate::xml::errors::reset_last_error();
594}
595
596// ═══════════════════════════════════════════════════════════════════════════════
597// 5. String Utilities
598// ═══════════════════════════════════════════════════════════════════════════════
599
600/// Duplicate a string using xmlChar.
601///
602/// # UPSTREAM-PARITY
603///
604/// ```c
605/// xmlChar *xmlStrdup(const xmlChar *cur);
606/// ```
607///
608/// # SAFETY
609///
610/// - `cur` must be a valid null-terminated xmlChar string or NULL.
611#[no_mangle]
612pub unsafe extern "C" fn xmlStrdup(cur: *const xmlChar) -> *mut xmlChar {
613    if cur.is_null() {
614        return ptr::null_mut();
615    }
616    let len = unsafe { xmlStrlen(cur) };
617    let size = len + 1;
618    let new_ptr = unsafe { xmlMalloc(size as usize) };
619    if new_ptr.is_null() {
620        return ptr::null_mut();
621    }
622    unsafe {
623        ptr::copy_nonoverlapping(cur as *const u8, new_ptr as *mut u8, size as usize);
624    }
625    new_ptr as *mut xmlChar
626}
627
628/// Duplicate a substring.
629///
630/// # UPSTREAM-PARITY
631///
632/// ```c
633/// xmlChar *xmlStrndup(const xmlChar *cur, int len);
634/// ```
635///
636/// # SAFETY
637///
638/// - `cur` must be a valid pointer or NULL.
639#[no_mangle]
640pub unsafe extern "C" fn xmlStrndup(cur: *const xmlChar, len: c_int) -> *mut xmlChar {
641    if cur.is_null() || len <= 0 {
642        return ptr::null_mut();
643    }
644    let size = len as usize + 1;
645    let new_ptr = unsafe { xmlMalloc(size) };
646    if new_ptr.is_null() {
647        return ptr::null_mut();
648    }
649    unsafe {
650        ptr::copy_nonoverlapping(cur as *const u8, new_ptr as *mut u8, len as usize);
651        *(new_ptr.add(len as usize) as *mut u8) = 0;
652    }
653    new_ptr as *mut xmlChar
654}
655
656/// Get the length of an xmlChar string.
657///
658/// # UPSTREAM-PARITY
659///
660/// ```c
661/// int xmlStrlen(const xmlChar *str);
662/// ```
663///
664/// # SAFETY
665///
666/// - `str` must be a valid null-terminated string or NULL (returns 0).
667#[no_mangle]
668pub unsafe extern "C" fn xmlStrlen(str: *const xmlChar) -> c_int {
669    if str.is_null() {
670        return 0;
671    }
672    unsafe { libc::strlen(str as *const c_char) as c_int }
673}
674
675/// Find the first occurrence of a character in a string (upstream tree.c
676/// `xmlStrchr`): returns a pointer to the first occurrence or NULL.
677///
678/// # UPSTREAM-PARITY
679///
680/// ```c
681/// const xmlChar *xmlStrchr(const xmlChar *str, xmlChar val);
682/// ```
683///
684/// # SAFETY
685///
686/// - `str` must be a valid null-terminated string or NULL.
687#[no_mangle]
688pub unsafe extern "C" fn xmlStrchr(str: *const xmlChar, val: xmlChar) -> *const xmlChar {
689    if str.is_null() {
690        return ptr::null();
691    }
692    unsafe {
693        let mut cur = str;
694        while *cur != 0 {
695            if *cur == val {
696                return cur;
697            }
698            cur = cur.add(1);
699        }
700        ptr::null()
701    }
702}
703
704/// Compare two xmlChar strings.
705///
706/// # UPSTREAM-PARITY
707///
708/// ```c
709/// int xmlStrcmp(const xmlChar *str1, const xmlChar *str2);
710/// ```
711///
712/// Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2.
713/// NULL-safe: NULL sorts before any non-NULL string.
714#[no_mangle]
715pub unsafe extern "C" fn xmlStrcmp(str1: *const xmlChar, str2: *const xmlChar) -> c_int {
716    if str1.is_null() && str2.is_null() {
717        return 0;
718    }
719    if str1.is_null() {
720        return -1;
721    }
722    if str2.is_null() {
723        return 1;
724    }
725    unsafe { libc::strcmp(str1 as *const c_char, str2 as *const c_char) as c_int }
726}
727
728/// Compare two xmlChar strings up to a given length.
729///
730/// # UPSTREAM-PARITY
731///
732/// ```c
733/// int xmlStrncmp(const xmlChar *str1, const xmlChar *str2, int len);
734/// ```
735#[no_mangle]
736pub unsafe extern "C" fn xmlStrncmp(
737    str1: *const xmlChar,
738    str2: *const xmlChar,
739    len: c_int,
740) -> c_int {
741    if len <= 0 {
742        return 0;
743    }
744    if str1.is_null() && str2.is_null() {
745        return 0;
746    }
747    if str1.is_null() {
748        return -1;
749    }
750    if str2.is_null() {
751        return 1;
752    }
753    unsafe { libc::strncmp(str1 as *const c_char, str2 as *const c_char, len as usize) as c_int }
754}
755
756/// Case-insensitive comparison of two xmlChar strings.
757///
758/// # UPSTREAM-PARITY
759///
760/// ```c
761/// int xmlStrcasecmp(const xmlChar *str1, const xmlChar *str2);
762/// ```
763#[no_mangle]
764pub unsafe extern "C" fn xmlStrcasecmp(str1: *const xmlChar, str2: *const xmlChar) -> c_int {
765    if str1.is_null() && str2.is_null() {
766        return 0;
767    }
768    if str1.is_null() {
769        return -1;
770    }
771    if str2.is_null() {
772        return 1;
773    }
774    unsafe { libc::strcasecmp(str1 as *const c_char, str2 as *const c_char) as c_int }
775}
776
777/// Case-insensitive comparison with length limit.
778///
779/// # UPSTREAM-PARITY
780///
781/// ```c
782/// int xmlStrncasecmp(const xmlChar *str1, const xmlChar *str2, int len);
783/// ```
784#[no_mangle]
785pub unsafe extern "C" fn xmlStrncasecmp(
786    str1: *const xmlChar,
787    str2: *const xmlChar,
788    len: c_int,
789) -> c_int {
790    if len <= 0 {
791        return 0;
792    }
793    if str1.is_null() && str2.is_null() {
794        return 0;
795    }
796    if str1.is_null() {
797        return -1;
798    }
799    if str2.is_null() {
800        return 1;
801    }
802    unsafe {
803        libc::strncasecmp(str1 as *const c_char, str2 as *const c_char, len as usize) as c_int
804    }
805}
806
807/// Check if two xmlChar strings are equal.
808///
809/// # UPSTREAM-PARITY
810///
811/// ```c
812/// int xmlStrEqual(const xmlChar *str1, const xmlChar *str2);
813/// ```
814///
815/// Returns 1 if equal, 0 if not. NULL-safe.
816#[no_mangle]
817pub unsafe extern "C" fn xmlStrEqual(str1: *const xmlChar, str2: *const xmlChar) -> c_int {
818    if str1.is_null() && str2.is_null() {
819        return 1;
820    }
821    if str1.is_null() || str2.is_null() {
822        return 0;
823    }
824    unsafe { (libc::strcmp(str1 as *const c_char, str2 as *const c_char) == 0) as c_int }
825}
826
827/// Build a QName (upstream tree.h).
828///
829/// # UPSTREAM-PARITY
830///
831/// ```c
832/// xmlChar *xmlBuildQName(const xmlChar *ncname, const xmlChar *prefix,
833///                        xmlChar *memory, int len);
834/// ```
835#[no_mangle]
836pub unsafe extern "C" fn xmlBuildQName(
837    ncname: *const xmlChar,
838    prefix: *const xmlChar,
839    memory: *mut xmlChar,
840    len: c_int,
841) -> *mut xmlChar {
842    crate::xml::string::build_qname(ncname, prefix, memory, len)
843}
844
845/// Split a QName into prefix + local part (upstream tree.h).
846///
847/// # UPSTREAM-PARITY
848///
849/// ```c
850/// xmlChar *xmlSplitQName2(const xmlChar *name, xmlChar **prefix);
851/// ```
852#[no_mangle]
853pub unsafe extern "C" fn xmlSplitQName2(
854    name: *const xmlChar,
855    prefix: *mut *mut xmlChar,
856) -> *mut xmlChar {
857    crate::xml::string::split_qname2(name, prefix)
858}
859
860/// Return the prefix length of a QName (upstream tree.h).
861///
862/// # UPSTREAM-PARITY
863///
864/// ```c
865/// int xmlSplitQName3(const xmlChar *name, int *len);
866/// ```
867#[no_mangle]
868pub unsafe extern "C" fn xmlSplitQName3(name: *const xmlChar, len: *mut c_int) -> c_int {
869    crate::xml::string::split_qname3(name, len)
870}
871
872/// Deprecated alias of `xmlSplitQName2` (upstream tree.h `xmlSplitQName`).
873#[no_mangle]
874pub unsafe extern "C" fn xmlSplitQName(
875    name: *const xmlChar,
876    prefix: *mut *mut xmlChar,
877) -> *mut xmlChar {
878    crate::xml::string::split_qname2(name, prefix)
879}
880
881/// Count UTF-8 characters (upstream xmlstring.h).
882///
883/// # UPSTREAM-PARITY
884///
885/// ```c
886/// int xmlUTF8Strlen(const xmlChar *utf);
887/// ```
888#[no_mangle]
889pub unsafe extern "C" fn xmlUTF8Strlen(utf: *const xmlChar) -> c_int {
890    crate::xml::string::utf8_strlen(utf)
891}
892
893/// Size in bytes of a UTF-8 sequence (upstream xmlstring.h).
894///
895/// # UPSTREAM-PARITY
896///
897/// ```c
898/// int xmlUTF8Size(const xmlChar *utf);
899/// ```
900#[no_mangle]
901pub unsafe extern "C" fn xmlUTF8Size(utf: *const xmlChar) -> c_int {
902    crate::xml::string::utf8_size(utf)
903}
904
905/// Check UTF-8 validity (upstream xmlstring.h).
906///
907/// # UPSTREAM-PARITY
908///
909/// ```c
910/// int xmlCheckUTF8(const unsigned char *utf);
911/// ```
912#[no_mangle]
913pub unsafe extern "C" fn xmlCheckUTF8(utf: *const xmlChar) -> c_int {
914    crate::xml::string::check_utf8(utf)
915}
916
917/// Check if an xmlChar string equals a qualified name.
918///
919/// # UPSTREAM-PARITY
920///
921/// ```c
922/// int xmlStrQEqual(const xmlChar *pref, const xmlChar *name, const xmlChar *str);
923/// ```
924///
925/// Returns 1 if `pref:name` equals `str`, 0 otherwise.
926/// `pref` may be NULL (compares only name).
927#[no_mangle]
928pub unsafe extern "C" fn xmlStrQEqual(
929    pref: *const xmlChar,
930    name: *const xmlChar,
931    str: *const xmlChar,
932) -> c_int {
933    if name.is_null() || str.is_null() {
934        return 0;
935    }
936    if pref.is_null() {
937        return unsafe { xmlStrEqual(name, str) };
938    }
939    // Compare "pref:name" with str
940    let pref_len = unsafe { xmlStrlen(pref) };
941    let name_len = unsafe { xmlStrlen(name) };
942    let total_len = pref_len + 1 + name_len;
943    let str_len = unsafe { xmlStrlen(str) };
944    if total_len != str_len {
945        return 0;
946    }
947    // Compare prefix part
948    if unsafe {
949        libc::strncmp(
950            pref as *const c_char,
951            str as *const c_char,
952            pref_len as usize,
953        )
954    } != 0
955    {
956        return 0;
957    }
958    // Check colon
959    if unsafe { *str.add(pref_len as usize) } != b':' as xmlChar {
960        return 0;
961    }
962    // Compare name part
963    (unsafe {
964        libc::strncmp(
965            name as *const c_char,
966            str.add((pref_len + 1) as usize) as *const c_char,
967            name_len as usize,
968        ) == 0
969    }) as c_int
970}
971
972/// Concatenate two strings.
973///
974/// # UPSTREAM-PARITY
975///
976/// ```c
977/// xmlChar *xmlStrcat(xmlChar *cur, const xmlChar *add);
978/// ```
979///
980/// # SAFETY
981///
982/// - `cur` must be a valid xmlMalloc'd string or NULL.
983/// - `add` must be a valid string or NULL.
984/// - If `cur` is NULL, behaves like xmlStrdup(add).
985#[no_mangle]
986pub unsafe extern "C" fn xmlStrcat(cur: *mut xmlChar, add: *const xmlChar) -> *mut xmlChar {
987    if add.is_null() {
988        return cur;
989    }
990    if cur.is_null() {
991        return unsafe { xmlStrdup(add) };
992    }
993    let cur_len = unsafe { xmlStrlen(cur) } as usize;
994    let add_len = unsafe { xmlStrlen(add) } as usize;
995    let new_size = cur_len + add_len + 1;
996    let new_ptr = unsafe { xmlRealloc(cur as *mut c_void, new_size) };
997    if new_ptr.is_null() {
998        return ptr::null_mut();
999    }
1000    unsafe {
1001        ptr::copy_nonoverlapping(add as *const u8, (new_ptr as *mut u8).add(cur_len), add_len);
1002        *((new_ptr as *mut u8).add(cur_len + add_len)) = 0;
1003    }
1004    new_ptr as *mut xmlChar
1005}
1006
1007/// Concatenate up to `len` characters.
1008///
1009/// # UPSTREAM-PARITY
1010///
1011/// ```c
1012/// xmlChar *xmlStrncat(xmlChar *cur, const xmlChar *add, int len);
1013/// ```
1014///
1015/// # SAFETY
1016///
1017/// Same as xmlStrcat, but only copies up to `len` characters from `add`.
1018#[no_mangle]
1019pub unsafe extern "C" fn xmlStrncat(
1020    cur: *mut xmlChar,
1021    add: *const xmlChar,
1022    len: c_int,
1023) -> *mut xmlChar {
1024    if add.is_null() || len <= 0 {
1025        return cur;
1026    }
1027    let len = len as usize;
1028    if cur.is_null() {
1029        return unsafe { xmlStrndup(add, len as c_int) };
1030    }
1031    let cur_len = unsafe { xmlStrlen(cur) } as usize;
1032    let new_size = cur_len + len + 1;
1033    let new_ptr = unsafe { xmlRealloc(cur as *mut c_void, new_size) };
1034    if new_ptr.is_null() {
1035        return ptr::null_mut();
1036    }
1037    unsafe {
1038        ptr::copy_nonoverlapping(add as *const u8, (new_ptr as *mut u8).add(cur_len), len);
1039        *((new_ptr as *mut u8).add(cur_len + len)) = 0;
1040    }
1041    new_ptr as *mut xmlChar
1042}
1043
1044/// Create a new string by concatenating up to `len` characters.
1045///
1046/// # UPSTREAM-PARITY
1047///
1048/// ```c
1049/// xmlChar *xmlStrncatNew(const xmlChar *str1, const xmlChar *str2, int len);
1050/// ```
1051#[no_mangle]
1052pub unsafe extern "C" fn xmlStrncatNew(
1053    str1: *const xmlChar,
1054    str2: *const xmlChar,
1055    len: c_int,
1056) -> *mut xmlChar {
1057    let mut result: *mut xmlChar = ptr::null_mut();
1058    if !str1.is_null() {
1059        result = unsafe { xmlStrdup(str1) };
1060    }
1061    if !str2.is_null() && len > 0 {
1062        result = unsafe { xmlStrncat(result, str2, len) };
1063    }
1064    result
1065}
1066
1067/// Copy a string.
1068///
1069/// # UPSTREAM-PARITY
1070///
1071/// ```c
1072/// xmlChar *xmlStrcpy(xmlChar *dst, const xmlChar *src);
1073/// ```
1074///
1075/// # SAFETY
1076///
1077/// - `dst` must be a valid xmlMalloc'd buffer large enough to hold `src`.
1078/// - `src` must be a valid string.
1079#[no_mangle]
1080pub unsafe extern "C" fn xmlStrcpy(dst: *mut xmlChar, src: *const xmlChar) -> *mut xmlChar {
1081    if dst.is_null() || src.is_null() {
1082        return dst;
1083    }
1084    let len = unsafe { xmlStrlen(src) } as usize + 1;
1085    unsafe {
1086        ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len);
1087    }
1088    dst
1089}
1090
1091/// Copy up to `len` characters.
1092///
1093/// # UPSTREAM-PARITY
1094///
1095/// ```c
1096/// xmlChar *xmlStrncpy(xmlChar *dst, const xmlChar *src, int len);
1097/// ```
1098#[no_mangle]
1099pub unsafe extern "C" fn xmlStrncpy(
1100    dst: *mut xmlChar,
1101    src: *const xmlChar,
1102    len: c_int,
1103) -> *mut xmlChar {
1104    if dst.is_null() || src.is_null() || len <= 0 {
1105        return dst;
1106    }
1107    let len = len as usize;
1108    let src_len = unsafe { xmlStrlen(src) } as usize;
1109    let copy_len = if src_len < len { src_len } else { len - 1 };
1110    unsafe {
1111        ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, copy_len);
1112        *dst.add(copy_len) = 0;
1113    }
1114    dst
1115}
1116
1117/// Extract a substring.
1118///
1119/// # UPSTREAM-PARITY
1120///
1121/// ```c
1122/// xmlChar *xmlStrsub(const xmlChar *str, int start, int len);
1123/// ```
1124///
1125/// Returns a newly allocated substring, or NULL on error.
1126#[no_mangle]
1127pub unsafe extern "C" fn xmlStrsub(str: *const xmlChar, start: c_int, len: c_int) -> *mut xmlChar {
1128    if str.is_null() || start < 0 || len < 0 {
1129        return ptr::null_mut();
1130    }
1131    let str_len = unsafe { xmlStrlen(str) };
1132    if start >= str_len {
1133        return unsafe { xmlStrdup(b"\0" as *const u8 as *const xmlChar) };
1134    }
1135    let actual_len = if start + len > str_len {
1136        str_len - start
1137    } else {
1138        len
1139    };
1140    unsafe { xmlStrndup(str.add(start as usize), actual_len) }
1141}
1142
1143// ═══════════════════════════════════════════════════════════════════════════════
1144// 6. Tree — Document, Node, Attribute, Namespace, DTD, Entity
1145// ═══════════════════════════════════════════════════════════════════════════════
1146
1147/// Create a new document.
1148///
1149/// # UPSTREAM-PARITY
1150///
1151/// ```c
1152/// xmlDocPtr xmlNewDoc(const xmlChar *version);
1153/// ```
1154///
1155/// # SAFETY
1156///
1157/// - `version` must be a valid string or NULL (defaults to "1.0").
1158/// - Returns a newly allocated document. Caller must free with `xmlFreeDoc`.
1159#[no_mangle]
1160pub unsafe extern "C" fn xmlNewDoc(version: *const xmlChar) -> *mut _xmlDoc {
1161    crate::xml::tree::new_doc(version)
1162}
1163
1164/// Free a document.
1165///
1166/// # UPSTREAM-PARITY
1167///
1168/// ```c
1169/// void xmlFreeDoc(xmlDocPtr doc);
1170/// ```
1171///
1172/// # SAFETY
1173///
1174/// - `doc` must be a valid document pointer or NULL.
1175#[no_mangle]
1176pub unsafe extern "C" fn xmlFreeDoc(doc: *mut _xmlDoc) {
1177    crate::xml::tree::free_doc(doc);
1178}
1179
1180/// Get the compression mode of a document (upstream tree.h).
1181///
1182/// # UPSTREAM-PARITY
1183///
1184/// ```c
1185/// int xmlGetDocCompressMode(const xmlDoc *doc);
1186/// ```
1187///
1188/// Returns the compression level (0-9) or -1 if `doc` is NULL.
1189#[no_mangle]
1190pub unsafe extern "C" fn xmlGetDocCompressMode(doc: *mut _xmlDoc) -> c_int {
1191    crate::xml::tree::xmlGetDocCompressMode(doc)
1192}
1193
1194/// Set the compression mode of a document (upstream tree.h).
1195///
1196/// # UPSTREAM-PARITY
1197///
1198/// ```c
1199/// void xmlSetDocCompressMode(xmlDocPtr doc, int mode);
1200/// ```
1201#[no_mangle]
1202pub unsafe extern "C" fn xmlSetDocCompressMode(doc: *mut _xmlDoc, mode: c_int) {
1203    crate::xml::tree::xmlSetDocCompressMode(doc, mode);
1204}
1205
1206/// Create a new node.
1207///
1208/// # UPSTREAM-PARITY
1209///
1210/// ```c
1211/// xmlNodePtr xmlNewNode(xmlNsPtr ns, const xmlChar *name);
1212/// ```
1213///
1214/// # SAFETY
1215///
1216/// - `ns` may be NULL.
1217/// - `name` must be a valid string.
1218/// - Returns a newly allocated node. Caller must free with `xmlFreeNode`.
1219#[no_mangle]
1220pub unsafe extern "C" fn xmlNewNode(ns: *mut _xmlNs, name: *const xmlChar) -> *mut _xmlNode {
1221    crate::xml::tree::new_node(ns, name)
1222}
1223
1224/// Free a node.
1225///
1226/// # UPSTREAM-PARITY
1227///
1228/// ```c
1229/// void xmlFreeNode(xmlNodePtr node);
1230/// ```
1231///
1232/// # SAFETY
1233///
1234/// - `node` must be a valid node pointer or NULL.
1235/// - The node must NOT be part of a document tree (must be unlinked first).
1236#[no_mangle]
1237pub unsafe extern "C" fn xmlFreeNode(node: *mut _xmlNode) {
1238    crate::xml::tree::free_node(node);
1239}
1240
1241/// Free a linked list of nodes (upstream tree.h).
1242///
1243/// # UPSTREAM-PARITY
1244///
1245/// ```c
1246/// void xmlFreeNodeList(xmlNodePtr node);
1247/// ```
1248///
1249/// Frees the node and all its siblings (following `next` pointers),
1250/// recursively freeing children. Matches upstream `xmlFreeNodeList`
1251/// (tree.c): a NULL argument is a no-op.
1252///
1253/// # SAFETY
1254///
1255/// - `node` must be a valid node pointer or NULL.
1256/// - The list must NOT be part of a document tree (must be unlinked first).
1257#[no_mangle]
1258pub unsafe extern "C" fn xmlFreeNodeList(node: *mut _xmlNode) {
1259    crate::xml::tree::free_node_list(node);
1260}
1261
1262/// Unlink a node from its tree.
1263///
1264/// # UPSTREAM-PARITY
1265///
1266/// ```c
1267/// void xmlUnlinkNode(xmlNodePtr node);
1268/// ```
1269///
1270/// # SAFETY
1271///
1272/// - `node` must be a valid node pointer or NULL.
1273#[no_mangle]
1274pub unsafe extern "C" fn xmlUnlinkNode(node: *mut _xmlNode) {
1275    crate::xml::tree::unlink_node(node);
1276}
1277
1278/// Initialize a SAX handler with the default SAX2 callbacks (upstream SAX2.h).
1279///
1280/// # UPSTREAM-PARITY
1281///
1282/// ```c
1283/// void xmlSAX2InitDefaultSAXHandler(xmlSAXHandler *hdlr, int warning);
1284/// ```
1285///
1286/// The `warning` parameter controls whether the warning callback is set in
1287/// upstream; the candidate always sets it (the parser dispatches warnings
1288/// identically) — a documented safe divergence tracked in the parity ledger.
1289///
1290/// # SAFETY
1291///
1292/// - `handler` must be a valid writable `_xmlSAXHandler` or NULL.
1293#[no_mangle]
1294pub unsafe extern "C" fn xmlSAX2InitDefaultSAXHandler(
1295    handler: *mut crate::abi::structs::_xmlSAXHandler,
1296    _warning: c_int,
1297) {
1298    crate::xml::sax::dispatch::xmlSAX2InitDefaultSAXHandler(handler);
1299}
1300
1301/// Initialize a SAX handler with the default HTML callbacks (upstream SAX2.h).
1302///
1303/// # UPSTREAM-PARITY
1304///
1305/// ```c
1306/// void xmlSAX2InitHtmlDefaultSAXHandler(xmlSAXHandler *hdlr);
1307/// ```
1308///
1309/// Upstream (SAX2.c `xmlSAX2InitHtmlDefaultSAXHandler`) fills the handler
1310/// with the SAX2 defaults minus the DTD-declaration callbacks
1311/// (resolveEntity/getParameterEntity/entityDecl/attributeDecl/elementDecl/
1312/// notationDecl/unparsedEntityDecl/reference/externalSubset are NULL) and
1313/// sets `initialized = 1` (not XML_SAX2_MAGIC). The candidate mirrors that
1314/// exactly.
1315///
1316/// # SAFETY
1317///
1318/// - `handler` must be a valid writable `_xmlSAXHandler` or NULL.
1319#[no_mangle]
1320pub unsafe extern "C" fn xmlSAX2InitHtmlDefaultSAXHandler(
1321    handler: *mut crate::abi::structs::_xmlSAXHandler,
1322) {
1323    use crate::abi::callbacks::*;
1324    use crate::abi::structs::_xmlSAXHandler;
1325    if handler.is_null() {
1326        return;
1327    }
1328    // SAFETY: handler is non-NULL and writable.
1329    unsafe {
1330        // The DTD-ish callbacks are not part of the HTML default set.
1331        if (*handler).initialized != 0 {
1332            return;
1333        }
1334        crate::xml::sax::dispatch::xmlSAX2InitDefaultSAXHandler(handler);
1335        let h = &mut *handler;
1336        h.resolveEntity = None;
1337        h.getParameterEntity = None;
1338        h.entityDecl = None;
1339        h.attributeDecl = None;
1340        h.elementDecl = None;
1341        h.notationDecl = None;
1342        h.unparsedEntityDecl = None;
1343        h.reference = None;
1344        h.externalSubset = None;
1345        h.initialized = 1;
1346    }
1347}
1348
1349/// Add a child node.
1350///
1351/// # UPSTREAM-PARITY
1352///
1353/// ```c
1354/// xmlNodePtr xmlAddChild(xmlNodePtr parent, xmlNodePtr cur);
1355/// ```
1356///
1357/// # SAFETY
1358///
1359/// - `parent` must be a valid node.
1360/// - `cur` must be a valid node (ownership transfers to parent).
1361/// - Returns pointer to the added child (borrowed).
1362#[no_mangle]
1363pub unsafe extern "C" fn xmlAddChild(parent: *mut _xmlNode, cur: *mut _xmlNode) -> *mut _xmlNode {
1364    crate::xml::tree::add_child(parent, cur)
1365}
1366
1367/// Add a sibling node.
1368///
1369/// # UPSTREAM-PARITY
1370///
1371/// ```c
1372/// xmlNodePtr xmlAddSibling(xmlNodePtr cur, xmlNodePtr sibling);
1373/// ```
1374///
1375/// # SAFETY
1376///
1377/// Same as xmlAddChild, but adds after `cur` instead of as a child.
1378#[no_mangle]
1379pub unsafe extern "C" fn xmlAddSibling(
1380    cur: *mut _xmlNode,
1381    sibling: *mut _xmlNode,
1382) -> *mut _xmlNode {
1383    crate::xml::tree::add_sibling(cur, sibling)
1384}
1385
1386/// Create a new child element.
1387///
1388/// # UPSTREAM-PARITY
1389///
1390/// ```c
1391/// xmlNodePtr xmlNewChild(xmlNodePtr parent, xmlNsPtr ns,
1392///                        const xmlChar *name, const xmlChar *content);
1393/// ```
1394///
1395/// Creates a new element node, adds it as a child of `parent`, and
1396/// sets its content if `content` is non-NULL.
1397///
1398/// # SAFETY
1399///
1400/// - `parent` must be a valid node (may be NULL).
1401/// - `ns` may be NULL.
1402/// - `name` must be a valid string.
1403/// - Returns a newly allocated node (owned by parent).
1404#[no_mangle]
1405pub unsafe extern "C" fn xmlNewChild(
1406    parent: *mut _xmlNode,
1407    ns: *mut _xmlNs,
1408    name: *const xmlChar,
1409    content: *const xmlChar,
1410) -> *mut _xmlNode {
1411    crate::xml::tree::new_child(parent, ns, name)
1412}
1413
1414/// Set the root element of a document.
1415///
1416/// # UPSTREAM-PARITY
1417///
1418/// ```c
1419/// xmlNodePtr xmlDocSetRootElement(xmlDocPtr doc, xmlNodePtr root);
1420/// ```
1421///
1422/// Returns the old root element (if any), which the caller must free.
1423///
1424/// # SAFETY
1425///
1426/// - `doc` must be a valid document.
1427/// - `root` must be a valid node (ownership transfers to doc).
1428#[no_mangle]
1429pub unsafe extern "C" fn xmlDocSetRootElement(
1430    doc: *mut _xmlDoc,
1431    root: *mut _xmlNode,
1432) -> *mut _xmlNode {
1433    crate::xml::tree::doc_set_root_element(doc, root)
1434}
1435
1436/// Get the root element of a document.
1437///
1438/// # UPSTREAM-PARITY
1439///
1440/// ```c
1441/// xmlNodePtr xmlDocGetRootElement(const xmlDoc *doc);
1442/// ```
1443///
1444/// Returns a borrowed pointer (do not free).
1445#[no_mangle]
1446pub extern "C" fn xmlDocGetRootElement(doc: *const _xmlDoc) -> *mut _xmlNode {
1447    crate::xml::tree::doc_get_root_element(doc as *mut _xmlDoc)
1448}
1449
1450/// Copy a node.
1451///
1452/// # UPSTREAM-PARITY
1453///
1454/// ```c
1455/// xmlNodePtr xmlCopyNode(const xmlNodePtr node, int extended);
1456/// ```
1457///
1458/// If `extended` is 1, copies recursively (deep copy).
1459/// If `extended` is 0, copies only the node itself (shallow copy).
1460///
1461/// Returns a newly allocated copy. Caller must free with `xmlFreeNode`.
1462#[no_mangle]
1463pub unsafe extern "C" fn xmlCopyNode(node: *const _xmlNode, extended: c_int) -> *mut _xmlNode {
1464    crate::xml::tree::copy_node(node, extended)
1465}
1466
1467/// Copy a document.
1468///
1469/// # UPSTREAM-PARITY
1470///
1471/// ```c
1472/// xmlDocPtr xmlCopyDoc(const xmlDocPtr doc, int recursive);
1473/// ```
1474///
1475/// Returns a newly allocated copy. Caller must free with `xmlFreeDoc`.
1476#[no_mangle]
1477pub unsafe extern "C" fn xmlCopyDoc(doc: *const _xmlDoc, recursive: c_int) -> *mut _xmlDoc {
1478    crate::xml::tree::copy_doc(doc, recursive)
1479}
1480
1481/// Create a text node.
1482///
1483/// # UPSTREAM-PARITY
1484///
1485/// ```c
1486/// xmlNodePtr xmlNewText(const xmlChar *content);
1487/// ```
1488///
1489/// Creates a new text node with the given content.
1490/// If `content` is NULL, creates an empty text node.
1491#[no_mangle]
1492pub unsafe extern "C" fn xmlNewText(content: *const xmlChar) -> *mut _xmlNode {
1493    crate::xml::tree::new_text(content)
1494}
1495
1496/// Create a new comment node.
1497///
1498/// # UPSTREAM-PARITY
1499///
1500/// ```c
1501/// xmlNodePtr xmlNewComment(const xmlChar *content);
1502/// ```
1503#[no_mangle]
1504pub unsafe extern "C" fn xmlNewComment(content: *const xmlChar) -> *mut _xmlNode {
1505    crate::xml::tree::new_comment(content)
1506}
1507
1508/// Create a new PI node.
1509///
1510/// # UPSTREAM-PARITY
1511///
1512/// ```c
1513/// xmlNodePtr xmlNewPI(const xmlChar *name, const xmlChar *content);
1514/// ```
1515#[no_mangle]
1516pub unsafe extern "C" fn xmlNewPI(name: *const xmlChar, content: *const xmlChar) -> *mut _xmlNode {
1517    crate::xml::tree::new_pi(name, content)
1518}
1519
1520/// Create a new CDATA node.
1521///
1522/// # UPSTREAM-PARITY
1523///
1524/// ```c
1525/// xmlNodePtr xmlNewCDataBlock(xmlDocPtr doc, const xmlChar *content, int len);
1526/// ```
1527#[no_mangle]
1528pub unsafe extern "C" fn xmlNewCDataBlock(
1529    doc: *mut _xmlDoc,
1530    content: *const xmlChar,
1531    len: c_int,
1532) -> *mut _xmlNode {
1533    crate::xml::tree::new_cdata_block(doc, content, len)
1534}
1535
1536/// Create a new namespace definition.
1537///
1538/// # UPSTREAM-PARITY
1539///
1540/// ```c
1541/// xmlNsPtr xmlNewNs(xmlNodePtr node, const xmlChar *href, const xmlChar *prefix);
1542/// ```
1543///
1544/// # SAFETY
1545///
1546/// - `node` may be NULL.
1547/// - `href` and `prefix` are copied.
1548/// - Returns a borrowed pointer (namespace is owned by the node).
1549#[no_mangle]
1550pub unsafe extern "C" fn xmlNewNs(
1551    node: *mut _xmlNode,
1552    href: *const xmlChar,
1553    prefix: *const xmlChar,
1554) -> *mut _xmlNs {
1555    crate::xml::tree::new_ns(node, href, prefix)
1556}
1557
1558/// Set the namespace of a node.
1559///
1560/// # UPSTREAM-PARITY
1561///
1562/// ```c
1563/// void xmlSetNs(xmlNodePtr node, xmlNsPtr ns);
1564/// ```
1565#[no_mangle]
1566pub unsafe extern "C" fn xmlSetNs(node: *mut _xmlNode, ns: *mut _xmlNs) {
1567    crate::xml::tree::set_ns(node, ns);
1568}
1569
1570/// Get the namespace of a node.
1571///
1572/// # UPSTREAM-PARITY
1573///
1574/// ```c
1575/// xmlNsPtr xmlGetNsList(xmlDocPtr doc, const xmlNode *node);
1576/// ```
1577#[no_mangle]
1578pub unsafe extern "C" fn xmlGetNsList(
1579    doc: *mut _xmlDoc,
1580    node: *const _xmlNode,
1581) -> *mut *mut _xmlNs {
1582    crate::xml::tree::get_ns_list(doc, node as *mut _xmlNode)
1583}
1584
1585/// Search for a namespace by href.
1586///
1587/// # UPSTREAM-PARITY
1588///
1589/// ```c
1590/// xmlNsPtr xmlSearchNs(xmlDocPtr doc, xmlNodePtr node, const xmlChar *nameSpace);
1591/// ```
1592#[no_mangle]
1593pub unsafe extern "C" fn xmlSearchNs(
1594    doc: *mut _xmlDoc,
1595    node: *mut _xmlNode,
1596    nameSpace: *const xmlChar,
1597) -> *mut _xmlNs {
1598    crate::xml::tree::search_ns(doc, node, nameSpace)
1599}
1600
1601/// Search for a namespace by href, using the full in-scope chain.
1602///
1603/// # UPSTREAM-PARITY
1604///
1605/// ```c
1606/// xmlNsPtr xmlSearchNsByHref(xmlDocPtr doc, xmlNodePtr node, const xmlChar *href);
1607/// ```
1608#[no_mangle]
1609pub unsafe extern "C" fn xmlSearchNsByHref(
1610    doc: *mut _xmlDoc,
1611    node: *mut _xmlNode,
1612    href: *const xmlChar,
1613) -> *mut _xmlNs {
1614    crate::xml::tree::search_ns_by_href(doc, node, href)
1615}
1616
1617/// Set a property (attribute) on a node.
1618///
1619/// # UPSTREAM-PARITY
1620///
1621/// ```c
1622/// xmlAttrPtr xmlSetProp(xmlNodePtr node, const xmlChar *name, const xmlChar *value);
1623/// ```
1624///
1625/// If the attribute already exists, its value is updated.
1626/// Returns a borrowed pointer to the attribute.
1627///
1628/// # SAFETY
1629///
1630/// - `node` must be a valid element node.
1631/// - `name` must be a valid string.
1632/// - `value` may be NULL.
1633#[no_mangle]
1634pub unsafe extern "C" fn xmlSetProp(
1635    node: *mut _xmlNode,
1636    name: *const xmlChar,
1637    value: *const xmlChar,
1638) -> *mut _xmlAttr {
1639    crate::xml::tree::set_prop(node, name, value)
1640}
1641
1642/// Get a property value by name.
1643///
1644/// # UPSTREAM-PARITY
1645///
1646/// ```c
1647/// xmlChar *xmlGetProp(const xmlNode *node, const xmlChar *name);
1648/// ```
1649///
1650/// Returns a newly allocated string. Caller must free with `xmlFree`.
1651#[no_mangle]
1652pub unsafe extern "C" fn xmlGetProp(node: *const _xmlNode, name: *const xmlChar) -> *mut xmlChar {
1653    crate::xml::tree::get_prop(node as *mut _xmlNode, name)
1654}
1655
1656/// Get a namespaced property value.
1657///
1658/// # UPSTREAM-PARITY
1659///
1660/// ```c
1661/// xmlChar *xmlGetNsProp(const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace);
1662/// ```
1663#[no_mangle]
1664pub unsafe extern "C" fn xmlGetNsProp(
1665    node: *const _xmlNode,
1666    name: *const xmlChar,
1667    nameSpace: *const xmlChar,
1668) -> *mut xmlChar {
1669    crate::xml::tree::get_ns_prop(node as *mut _xmlNode, name, nameSpace)
1670}
1671
1672/// Set a namespaced property.
1673///
1674/// # UPSTREAM-PARITY
1675///
1676/// ```c
1677/// xmlAttrPtr xmlSetNsProp(xmlNodePtr node, xmlNsPtr ns,
1678///                         const xmlChar *name, const xmlChar *value);
1679/// ```
1680#[no_mangle]
1681pub unsafe extern "C" fn xmlSetNsProp(
1682    node: *mut _xmlNode,
1683    ns: *mut _xmlNs,
1684    name: *const xmlChar,
1685    value: *const xmlChar,
1686) -> *mut _xmlAttr {
1687    crate::xml::tree::set_ns_prop(node, ns, name, value)
1688}
1689
1690/// Remove a property by name.
1691///
1692/// # UPSTREAM-PARITY
1693///
1694/// ```c
1695/// int xmlRemoveProp(xmlAttrPtr attr);
1696/// ```
1697///
1698/// Returns 0 on success, -1 on error.
1699#[no_mangle]
1700pub unsafe extern "C" fn xmlRemoveProp(attr: *mut _xmlAttr) -> c_int {
1701    crate::xml::tree::remove_prop(attr)
1702}
1703
1704/// Check whether a node has a property (upstream tree.h).
1705///
1706/// # UPSTREAM-PARITY
1707///
1708/// ```c
1709/// xmlAttrPtr xmlHasProp(const xmlNode *node, const xmlChar *name);
1710/// ```
1711///
1712/// Returns the attribute pointer or NULL.
1713#[no_mangle]
1714pub unsafe extern "C" fn xmlHasProp(node: *const _xmlNode, name: *const xmlChar) -> *mut _xmlAttr {
1715    crate::xml::tree::has_prop(node as *mut _xmlNode, name)
1716}
1717
1718/// Check whether a node has a namespaced property (upstream tree.h).
1719///
1720/// # UPSTREAM-PARITY
1721///
1722/// ```c
1723/// xmlAttrPtr xmlHasNsProp(const xmlNode *node, const xmlChar *name,
1724///                         const xmlChar *nameSpace);
1725/// ```
1726#[no_mangle]
1727pub unsafe extern "C" fn xmlHasNsProp(
1728    node: *const _xmlNode,
1729    name: *const xmlChar,
1730    nameSpace: *const xmlChar,
1731) -> *mut _xmlAttr {
1732    crate::xml::tree::has_ns_prop(node as *mut _xmlNode, name, nameSpace)
1733}
1734
1735/// Remove a property by name (upstream tree.h).
1736///
1737/// # UPSTREAM-PARITY
1738///
1739/// ```c
1740/// int xmlUnsetProp(xmlNodePtr node, const xmlChar *name);
1741/// ```
1742///
1743/// Returns 0 on success, -1 if not found.
1744#[no_mangle]
1745pub unsafe extern "C" fn xmlUnsetProp(node: *mut _xmlNode, name: *const xmlChar) -> c_int {
1746    crate::xml::tree::unset_prop(node, name)
1747}
1748
1749/// Remove a namespaced property by name (upstream tree.h).
1750///
1751/// # UPSTREAM-PARITY
1752///
1753/// ```c
1754/// int xmlUnsetNsProp(xmlNodePtr node, const xmlChar *name,
1755///                    const xmlChar *nameSpace);
1756/// ```
1757#[no_mangle]
1758pub unsafe extern "C" fn xmlUnsetNsProp(
1759    node: *mut _xmlNode,
1760    name: *const xmlChar,
1761    nameSpace: *const xmlChar,
1762) -> c_int {
1763    crate::xml::tree::unset_ns_prop(node, name, nameSpace)
1764}
1765
1766/// Return the first child element (upstream tree.h).
1767///
1768/// # UPSTREAM-PARITY
1769///
1770/// ```c
1771/// xmlNodePtr xmlFirstElementChild(xmlNodePtr parent);
1772/// ```
1773#[no_mangle]
1774pub unsafe extern "C" fn xmlFirstElementChild(parent: *mut _xmlNode) -> *mut _xmlNode {
1775    crate::xml::tree::first_element_child(parent)
1776}
1777
1778/// Return the last child element (upstream tree.h).
1779#[no_mangle]
1780pub unsafe extern "C" fn xmlLastElementChild(parent: *mut _xmlNode) -> *mut _xmlNode {
1781    crate::xml::tree::last_element_child(parent)
1782}
1783
1784/// Return the next element sibling (upstream tree.h).
1785#[no_mangle]
1786pub unsafe extern "C" fn xmlNextElementSibling(node: *mut _xmlNode) -> *mut _xmlNode {
1787    crate::xml::tree::next_element_sibling(node)
1788}
1789
1790/// Return the previous element sibling (upstream tree.h).
1791#[no_mangle]
1792pub unsafe extern "C" fn xmlPreviousElementSibling(node: *mut _xmlNode) -> *mut _xmlNode {
1793    crate::xml::tree::previous_element_sibling(node)
1794}
1795
1796/// Count the child elements (upstream tree.h).
1797///
1798/// # UPSTREAM-PARITY
1799///
1800/// ```c
1801/// unsigned long xmlChildElementCount(xmlNodePtr parent);
1802/// ```
1803#[no_mangle]
1804pub unsafe extern "C" fn xmlChildElementCount(parent: *mut _xmlNode) -> c_ulong {
1805    crate::xml::tree::child_element_count(parent)
1806}
1807
1808/// Concatenate text to a node (upstream tree.h).
1809///
1810/// # UPSTREAM-PARITY
1811///
1812/// ```c
1813/// int xmlTextConcat(xmlNodePtr node, const xmlChar *content, int len);
1814/// ```
1815#[no_mangle]
1816pub unsafe extern "C" fn xmlTextConcat(
1817    node: *mut _xmlNode,
1818    content: *const xmlChar,
1819    len: c_int,
1820) -> c_int {
1821    crate::xml::tree::text_concat(node, content, len)
1822}
1823
1824/// Merge two text nodes (upstream tree.h).
1825///
1826/// # UPSTREAM-PARITY
1827///
1828/// ```c
1829/// xmlNodePtr xmlTextMerge(xmlNodePtr first, xmlNodePtr second);
1830/// ```
1831#[no_mangle]
1832pub unsafe extern "C" fn xmlTextMerge(
1833    first: *mut _xmlNode,
1834    second: *mut _xmlNode,
1835) -> *mut _xmlNode {
1836    crate::xml::tree::text_merge(first, second)
1837}
1838
1839/// Get a DTD from a document, creating one if needed.
1840///
1841/// # UPSTREAM-PARITY
1842///
1843/// ```c
1844/// xmlDtdPtr xmlGetIntSubset(const xmlDoc *doc);
1845/// ```
1846#[no_mangle]
1847pub extern "C" fn xmlGetIntSubset(doc: *const _xmlDoc) -> *mut _xmlDtd {
1848    crate::xml::tree::get_int_subset(doc)
1849}
1850
1851/// Create a new DTD.
1852///
1853/// # UPSTREAM-PARITY
1854///
1855/// ```c
1856/// xmlDtdPtr xmlNewDtd(xmlDocPtr doc, const xmlChar *name,
1857///                     const xmlChar *ExternalID, const xmlChar *SystemID);
1858/// ```
1859#[no_mangle]
1860pub unsafe extern "C" fn xmlNewDtd(
1861    doc: *mut _xmlDoc,
1862    name: *const xmlChar,
1863    ExternalID: *const xmlChar,
1864    SystemID: *const xmlChar,
1865) -> *mut _xmlDtd {
1866    crate::xml::tree::new_dtd(doc, name, ExternalID, SystemID)
1867}
1868
1869/// Create a new entity.
1870///
1871/// # UPSTREAM-PARITY
1872///
1873/// ```c
1874/// xmlEntityPtr xmlNewEntity(xmlDocPtr doc, const xmlChar *name, int type,
1875///                           const xmlChar *ExternalID, const xmlChar *SystemID,
1876///                           const xmlChar *content);
1877/// ```
1878#[no_mangle]
1879pub unsafe extern "C" fn xmlNewEntity(
1880    doc: *mut _xmlDoc,
1881    name: *const xmlChar,
1882    type_: c_int,
1883    ExternalID: *const xmlChar,
1884    SystemID: *const xmlChar,
1885    content: *const xmlChar,
1886) -> *mut _xmlEntity {
1887    crate::xml::tree::new_entity(doc, name, type_, ExternalID, SystemID, content)
1888}
1889
1890/// Get an entity by name.
1891///
1892/// # UPSTREAM-PARITY
1893///
1894/// ```c
1895/// xmlEntityPtr xmlGetDocEntity(const xmlDoc *doc, const xmlChar *name);
1896/// ```
1897#[no_mangle]
1898pub unsafe extern "C" fn xmlGetDocEntity(
1899    doc: *const _xmlDoc,
1900    name: *const xmlChar,
1901) -> *mut _xmlEntity {
1902    crate::xml::tree::get_doc_entity(doc, name)
1903}
1904
1905/// Get a parameter entity by name.
1906///
1907/// # UPSTREAM-PARITY
1908///
1909/// ```c
1910/// xmlEntityPtr xmlGetParameterEntity(const xmlDoc *doc, const xmlChar *name);
1911/// ```
1912#[no_mangle]
1913pub unsafe extern "C" fn xmlGetParameterEntity(
1914    doc: *const _xmlDoc,
1915    name: *const xmlChar,
1916) -> *mut _xmlEntity {
1917    crate::xml::tree::get_parameter_entity(doc, name)
1918}
1919
1920// ── DTD Declaration Exports ────────────────────────────────────────────
1921
1922/// Create an internal subset (DTD).
1923///
1924/// # UPSTREAM-PARITY
1925///
1926/// ```c
1927/// xmlDtdPtr xmlCreateIntSubset(xmlDocPtr doc, const xmlChar *name,
1928///                              const xmlChar *ExternalID, const xmlChar *SystemID);
1929/// ```
1930#[no_mangle]
1931pub unsafe extern "C" fn xmlCreateIntSubset(
1932    doc: *mut _xmlDoc,
1933    name: *const xmlChar,
1934    ExternalID: *const xmlChar,
1935    SystemID: *const xmlChar,
1936) -> *mut _xmlDtd {
1937    crate::xml::dtd::create_int_subset(doc, name, ExternalID, SystemID)
1938}
1939
1940/// Free a DTD.
1941///
1942/// # UPSTREAM-PARITY
1943///
1944/// ```c
1945/// void xmlFreeDtd(xmlDtdPtr dtd);
1946/// ```
1947#[no_mangle]
1948pub unsafe extern "C" fn xmlFreeDtd(dtd: *mut _xmlDtd) {
1949    crate::xml::dtd::free_dtd(dtd);
1950}
1951
1952/// Add a notation declaration.
1953///
1954/// # UPSTREAM-PARITY
1955///
1956/// ```c
1957/// xmlNotationPtr xmlAddNotationDecl(xmlDtdPtr dtd, const xmlChar *name,
1958///                                   const xmlChar *PublicID,
1959///                                   const xmlChar *SystemID);
1960/// ```
1961#[no_mangle]
1962pub unsafe extern "C" fn xmlAddNotationDecl(
1963    dtd: *mut _xmlDtd,
1964    name: *const xmlChar,
1965    PublicID: *const xmlChar,
1966    SystemID: *const xmlChar,
1967) -> *mut _xmlNotation {
1968    crate::xml::dtd::add_notation_decl(dtd, name, PublicID, SystemID)
1969}
1970
1971/// Look up a notation declaration.
1972///
1973/// # UPSTREAM-PARITY
1974///
1975/// ```c
1976/// xmlNotationPtr xmlGetNotationDecl(xmlDtdPtr dtd, const xmlChar *name);
1977/// ```
1978#[no_mangle]
1979pub unsafe extern "C" fn xmlGetNotationDecl(
1980    dtd: *mut _xmlDtd,
1981    name: *const xmlChar,
1982) -> *mut _xmlNotation {
1983    crate::xml::dtd::get_notation_decl(dtd, name)
1984}
1985
1986/// Copy a notation declaration.
1987///
1988/// # UPSTREAM-PARITY
1989///
1990/// ```c
1991/// xmlNotationPtr xmlCopyNotation(xmlNotationPtr notation);
1992/// ```
1993#[no_mangle]
1994pub unsafe extern "C" fn xmlCopyNotation(notation: *mut _xmlNotation) -> *mut _xmlNotation {
1995    crate::xml::dtd::copy_notation(notation)
1996}
1997
1998/// Free a notation declaration.
1999///
2000/// # UPSTREAM-PARITY
2001///
2002/// ```c
2003/// void xmlFreeNotation(xmlNotationPtr notation);
2004/// ```
2005#[no_mangle]
2006pub unsafe extern "C" fn xmlFreeNotation(notation: *mut _xmlNotation) {
2007    crate::xml::dtd::free_notation(notation);
2008}
2009
2010/// Add an element declaration.
2011///
2012/// # UPSTREAM-PARITY
2013///
2014/// ```c
2015/// xmlElementPtr xmlAddElementDecl(xmlDtdPtr dtd, const xmlChar *name, int type,
2016///                                 xmlElementContentPtr content);
2017/// ```
2018#[no_mangle]
2019pub unsafe extern "C" fn xmlAddElementDecl(
2020    dtd: *mut _xmlDtd,
2021    name: *const xmlChar,
2022    type_: c_int,
2023    content: *mut _xmlElementContent,
2024) -> *mut _xmlElement {
2025    crate::xml::dtd::add_element_decl(dtd, name, type_, content)
2026}
2027
2028/// Look up an element declaration.
2029///
2030/// # UPSTREAM-PARITY
2031///
2032/// ```c
2033/// xmlElementPtr xmlGetElementDecl(xmlDtdPtr dtd, const xmlChar *name);
2034/// ```
2035#[no_mangle]
2036pub unsafe extern "C" fn xmlGetElementDecl(
2037    dtd: *mut _xmlDtd,
2038    name: *const xmlChar,
2039) -> *mut _xmlElement {
2040    crate::xml::dtd::get_element_decl(dtd, name)
2041}
2042
2043/// Copy an element declaration.
2044///
2045/// # UPSTREAM-PARITY
2046///
2047/// ```c
2048/// xmlElementPtr xmlCopyElement(xmlElementPtr elem);
2049/// ```
2050#[no_mangle]
2051pub unsafe extern "C" fn xmlCopyElement(elem: *mut _xmlElement) -> *mut _xmlElement {
2052    crate::xml::dtd::copy_element(elem)
2053}
2054
2055/// Free an element declaration.
2056///
2057/// # UPSTREAM-PARITY
2058///
2059/// ```c
2060/// void xmlFreeElement(xmlElementPtr elem);
2061/// ```
2062#[no_mangle]
2063pub unsafe extern "C" fn xmlFreeElement(elem: *mut _xmlElement) {
2064    crate::xml::dtd::free_element(elem);
2065}
2066
2067/// Add an attribute declaration.
2068///
2069/// # UPSTREAM-PARITY
2070///
2071/// ```c
2072/// xmlAttributePtr xmlAddAttributeDecl(xmlDtdPtr dtd, xmlElementPtr elem,
2073///                                     const xmlChar *name, int type, int def,
2074///                                     const xmlChar *defaultValue,
2075///                                     xmlEnumerationPtr tree);
2076/// ```
2077#[no_mangle]
2078pub unsafe extern "C" fn xmlAddAttributeDecl(
2079    dtd: *mut _xmlDtd,
2080    elem: *mut _xmlElement,
2081    name: *const xmlChar,
2082    type_: c_int,
2083    def: c_int,
2084    defaultValue: *const xmlChar,
2085    tree: *mut _xmlEnumeration,
2086) -> *mut _xmlAttribute {
2087    crate::xml::dtd::add_attribute_decl(dtd, elem, name, type_, def, defaultValue, tree)
2088}
2089
2090/// Look up an attribute declaration.
2091///
2092/// # UPSTREAM-PARITY
2093///
2094/// ```c
2095/// xmlAttributePtr xmlGetAttributeDecl(xmlDtdPtr dtd, xmlElementPtr elem,
2096///                                     const xmlChar *name, int namePrefix);
2097/// ```
2098#[no_mangle]
2099pub unsafe extern "C" fn xmlGetAttributeDecl(
2100    dtd: *mut _xmlDtd,
2101    elem: *mut _xmlElement,
2102    name: *const xmlChar,
2103    namePrefix: c_int,
2104) -> *mut _xmlAttribute {
2105    crate::xml::dtd::get_attribute_decl(dtd, elem, name, namePrefix)
2106}
2107
2108/// Copy an attribute declaration.
2109///
2110/// # UPSTREAM-PARITY
2111///
2112/// ```c
2113/// xmlAttributePtr xmlCopyAttribute(xmlAttributePtr attr);
2114/// ```
2115#[no_mangle]
2116pub unsafe extern "C" fn xmlCopyAttribute(attr: *mut _xmlAttribute) -> *mut _xmlAttribute {
2117    crate::xml::dtd::copy_attribute_decl(attr)
2118}
2119
2120/// Free an attribute declaration.
2121///
2122/// # UPSTREAM-PARITY
2123///
2124/// ```c
2125/// void xmlFreeAttribute(xmlAttributePtr attr);
2126/// ```
2127#[no_mangle]
2128pub unsafe extern "C" fn xmlFreeAttribute(attr: *mut _xmlAttribute) {
2129    crate::xml::dtd::free_attribute(attr);
2130}
2131
2132/// Create a new element content model.
2133///
2134/// # UPSTREAM-PARITY
2135///
2136/// ```c
2137/// xmlElementContentPtr xmlNewElementContent(const xmlChar *name, int type);
2138/// ```
2139#[no_mangle]
2140pub unsafe extern "C" fn xmlNewElementContent(
2141    name: *const xmlChar,
2142    type_: c_int,
2143) -> *mut _xmlElementContent {
2144    crate::xml::dtd::create_content_model(name, type_)
2145}
2146
2147/// Copy an element content model.
2148///
2149/// # UPSTREAM-PARITY
2150///
2151/// ```c
2152/// xmlElementContentPtr xmlCopyElementContent(xmlElementContentPtr content);
2153/// ```
2154#[no_mangle]
2155pub unsafe extern "C" fn xmlCopyElementContent(
2156    content: *mut _xmlElementContent,
2157) -> *mut _xmlElementContent {
2158    crate::xml::dtd::copy_content_model(content)
2159}
2160
2161/// Free an element content model.
2162///
2163/// # UPSTREAM-PARITY
2164///
2165/// ```c
2166/// void xmlFreeElementContent(xmlElementContentPtr cur);
2167/// ```
2168#[no_mangle]
2169pub unsafe extern "C" fn xmlFreeElementContent(cur: *mut _xmlElementContent) {
2170    crate::xml::dtd::free_content_model(cur);
2171}
2172
2173// ── Entity Exports ─────────────────────────────────────────────────────
2174
2175/// Add an entity declaration.
2176///
2177/// # UPSTREAM-PARITY
2178///
2179/// ```c
2180/// xmlEntityPtr xmlAddEntity(xmlDtdPtr dtd, const xmlChar *name, int type,
2181///                           const xmlChar *ExternalID, const xmlChar *SystemID,
2182///                           const xmlChar *content);
2183/// ```
2184#[no_mangle]
2185pub unsafe extern "C" fn xmlAddEntity(
2186    dtd: *mut _xmlDtd,
2187    name: *const xmlChar,
2188    type_: c_int,
2189    ExternalID: *const xmlChar,
2190    SystemID: *const xmlChar,
2191    content: *const xmlChar,
2192) -> *mut _xmlEntity {
2193    crate::xml::entities::add_entity(dtd, name, type_, ExternalID, SystemID, content)
2194}
2195
2196/// Add an entity declaration to a document's internal subset (upstream
2197/// entities.c `xmlAddDocEntity`): if the document has no internal subset
2198/// one is created.
2199///
2200/// # UPSTREAM-PARITY
2201///
2202/// ```c
2203/// xmlEntityPtr xmlAddDocEntity(xmlDocPtr doc, const xmlChar *name, int type,
2204///                              const xmlChar *ExternalID, const xmlChar *SystemID,
2205///                              const xmlChar *content);
2206/// ```
2207#[no_mangle]
2208pub unsafe extern "C" fn xmlAddDocEntity(
2209    doc: *mut _xmlDoc,
2210    name: *const xmlChar,
2211    type_: c_int,
2212    ExternalID: *const xmlChar,
2213    SystemID: *const xmlChar,
2214    content: *const xmlChar,
2215) -> *mut _xmlEntity {
2216    crate::xml::tree::add_doc_entity(doc, name, type_, ExternalID, SystemID, content)
2217}
2218
2219/// Add an entity declaration to a document's external subset (upstream
2220/// entities.c `xmlAddDtdEntity`).
2221///
2222/// # UPSTREAM-PARITY
2223///
2224/// ```c
2225/// xmlEntityPtr xmlAddDtdEntity(xmlDocPtr doc, const xmlChar *name, int type,
2226///                              const xmlChar *ExternalID, const xmlChar *SystemID,
2227///                              const xmlChar *content);
2228/// ```
2229#[no_mangle]
2230pub unsafe extern "C" fn xmlAddDtdEntity(
2231    doc: *mut _xmlDoc,
2232    name: *const xmlChar,
2233    type_: c_int,
2234    ExternalID: *const xmlChar,
2235    SystemID: *const xmlChar,
2236    content: *const xmlChar,
2237) -> *mut _xmlEntity {
2238    crate::xml::tree::add_dtd_entity(doc, name, type_, ExternalID, SystemID, content)
2239}
2240
2241/// Get an entity declaration from a DTD (upstream entities.c
2242/// `xmlGetDtdEntity`): searches the internal then external subset.
2243///
2244/// # UPSTREAM-PARITY
2245///
2246/// ```c
2247/// xmlEntityPtr xmlGetDtdEntity(xmlDocPtr doc, const xmlChar *name);
2248/// ```
2249#[no_mangle]
2250pub unsafe extern "C" fn xmlGetDtdEntity(
2251    doc: *mut _xmlDoc,
2252    name: *const xmlChar,
2253) -> *mut _xmlEntity {
2254    crate::xml::tree::get_dtd_entity(doc, name)
2255}
2256
2257/// Get an entity by name.
2258///
2259/// # UPSTREAM-PARITY
2260///
2261/// ```c
2262/// xmlEntityPtr xmlGetEntity(xmlDocPtr doc, const xmlChar *name);
2263/// ```
2264#[no_mangle]
2265pub unsafe extern "C" fn xmlGetEntity(doc: *mut _xmlDoc, name: *const xmlChar) -> *mut _xmlEntity {
2266    crate::xml::entities::get_entity(doc, name)
2267}
2268
2269/// Copy an entity.
2270///
2271/// # UPSTREAM-PARITY
2272///
2273/// ```c
2274/// xmlEntityPtr xmlCopyEntity(xmlEntityPtr entity);
2275/// ```
2276#[no_mangle]
2277pub unsafe extern "C" fn xmlCopyEntity(entity: *mut _xmlEntity) -> *mut _xmlEntity {
2278    crate::xml::entities::copy_entity(entity)
2279}
2280
2281/// Free an entity.
2282///
2283/// # UPSTREAM-PARITY
2284///
2285/// ```c
2286/// void xmlFreeEntity(xmlEntityPtr entity);
2287/// ```
2288#[no_mangle]
2289pub unsafe extern "C" fn xmlFreeEntity(entity: *mut _xmlEntity) {
2290    crate::xml::entities::free_entity(entity);
2291}
2292
2293/// Encode entities for reentrant output.
2294///
2295/// # UPSTREAM-PARITY
2296///
2297/// ```c
2298/// xmlChar *xmlEncodeEntitiesReentrant(xmlDocPtr doc, const xmlChar *input);
2299/// ```
2300#[no_mangle]
2301pub unsafe extern "C" fn xmlEncodeEntitiesReentrant(
2302    doc: *mut _xmlDoc,
2303    input: *const xmlChar,
2304) -> *mut xmlChar {
2305    crate::xml::entities::encode_entities_reentrant(doc, input)
2306}
2307
2308/// Encode special characters in a string (upstream entities.c
2309/// `xmlEncodeSpecialChars`): escapes `<`, `>`, `&`, `"` and `\r`.
2310///
2311/// # UPSTREAM-PARITY
2312///
2313/// ```c
2314/// xmlChar *xmlEncodeSpecialChars(const xmlDoc *doc, const xmlChar *input);
2315/// ```
2316///
2317/// Returns a newly allocated string (free with `xmlFree`) or NULL.
2318#[no_mangle]
2319pub unsafe extern "C" fn xmlEncodeSpecialChars(
2320    _doc: *const _xmlDoc,
2321    input: *const xmlChar,
2322) -> *mut xmlChar {
2323    if input.is_null() {
2324        return ptr::null_mut();
2325    }
2326    unsafe {
2327        let len = crate::xml::string::xml_strlen(input);
2328        // Worst case: every byte becomes a 6-byte entity (&#13; is 5; &quot;
2329        // is 6).
2330        let cap = len * 6 + 1;
2331        let out = crate::abi::allocator::xmlMalloc(cap) as *mut xmlChar;
2332        if out.is_null() {
2333            return ptr::null_mut();
2334        }
2335        let mut o = 0usize;
2336        let mut i = 0usize;
2337        while i < len {
2338            let c = *input.add(i);
2339            let rep: &[u8] = match c {
2340                b'<' => b"&lt;",
2341                b'>' => b"&gt;",
2342                b'&' => b"&amp;",
2343                b'"' => b"&quot;",
2344                b'\r' => b"&#13;",
2345                _ => {
2346                    *out.add(o) = c;
2347                    o += 1;
2348                    i += 1;
2349                    continue;
2350                }
2351            };
2352            core::ptr::copy_nonoverlapping(rep.as_ptr(), out.add(o), rep.len());
2353            o += rep.len();
2354            i += 1;
2355        }
2356        *out.add(o) = 0;
2357        out
2358    }
2359}
2360
2361/// Deprecated entity encoder (upstream 2.15 `xmlEncodeEntities`): the
2362/// symbol still exists for ABI compatibility but emits a one-time
2363/// deprecation warning and returns NULL (verified against the oracle DSO
2364/// disassembly — the 2.15 implementation returns NULL after warning).
2365///
2366/// # UPSTREAM-PARITY
2367///
2368/// ```c
2369/// xmlChar *xmlEncodeEntities(xmlDocPtr doc, const xmlChar *input);
2370/// ```
2371#[no_mangle]
2372pub unsafe extern "C" fn xmlEncodeEntities(
2373    _doc: *mut _xmlDoc,
2374    _input: *const xmlChar,
2375) -> *mut xmlChar {
2376    use core::sync::atomic::{AtomicBool, Ordering};
2377    static WARNED: AtomicBool = AtomicBool::new(false);
2378    if !WARNED.swap(true, Ordering::Relaxed) {
2379        // Match the oracle: one-time "deprecated" diagnostic on stderr.
2380        let msg = b"xmlEncodeEntities is deprecated, use xmlEncodeSpecialChars or xmlEncodeEntitiesReentrant\n";
2381        unsafe {
2382            libc::fwrite(
2383                msg.as_ptr() as *const c_void,
2384                1,
2385                msg.len(),
2386                libc::fdopen(2, b"w\0" as *const u8 as *const c_char) as *mut libc::FILE,
2387            );
2388        }
2389    }
2390    ptr::null_mut()
2391}
2392
2393/// Get the line number of a node.
2394///
2395/// # UPSTREAM-PARITY
2396///
2397/// ```c
2398/// long xmlGetLineNo(const xmlNode *node);
2399/// ```
2400#[no_mangle]
2401pub extern "C" fn xmlGetLineNo(node: *const _xmlNode) -> c_int {
2402    crate::xml::tree::get_line_no(node)
2403}
2404
2405// ═══════════════════════════════════════════════════════════════════════════════
2406// Serialization — xmlNodeDump, xmlDocDump, xmlSaveFile, etc.
2407// ═══════════════════════════════════════════════════════════════════════════════
2408
2409/// Dump a node to a buffer.
2410///
2411/// # UPSTREAM-PARITY
2412///
2413/// ```c
2414/// int xmlNodeDump(xmlBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format);
2415/// ```
2416#[no_mangle]
2417pub unsafe extern "C" fn xmlNodeDump(
2418    buf: *mut _xmlBuffer,
2419    doc: *mut _xmlDoc,
2420    cur: *mut _xmlNode,
2421    level: c_int,
2422    format: c_int,
2423) -> c_int {
2424    if buf.is_null() || cur.is_null() {
2425        return -1;
2426    }
2427    crate::xml::tree::xmlNodeDump(buf, doc, cur, level, format)
2428}
2429
2430/// Dump a document to a file pointer.
2431///
2432/// # UPSTREAM-PARITY
2433///
2434/// ```c
2435/// int xmlDocDump(FILE *f, xmlDocPtr doc);
2436/// ```
2437#[no_mangle]
2438pub unsafe extern "C" fn xmlDocDump(fp: *mut c_void, doc: *mut _xmlDoc) -> c_int {
2439    if fp.is_null() || doc.is_null() {
2440        return -1;
2441    }
2442    crate::xml::tree::xmlDocDump(fp, doc)
2443}
2444
2445/// Dump a document to memory with format.
2446///
2447/// # UPSTREAM-PARITY
2448///
2449/// ```c
2450/// void xmlDocDumpFormatMemory(xmlDocPtr doc, xmlChar **mem, int *size, int format);
2451/// ```
2452#[no_mangle]
2453pub unsafe extern "C" fn xmlDocDumpFormatMemory(
2454    doc: *mut _xmlDoc,
2455    mem: *mut *mut xmlChar,
2456    size: *mut c_int,
2457    format: c_int,
2458) {
2459    if doc.is_null() || mem.is_null() || size.is_null() {
2460        return;
2461    }
2462    crate::xml::tree::xmlDocDumpFormatMemory(doc, mem, size, format)
2463}
2464
2465/// Dump a document to memory (unformatted).
2466///
2467/// # UPSTREAM-PARITY
2468///
2469/// ```c
2470/// void xmlDocDumpMemory(xmlDocPtr doc, xmlChar **mem, int *size);
2471/// ```
2472#[no_mangle]
2473pub unsafe extern "C" fn xmlDocDumpMemory(
2474    doc: *mut _xmlDoc,
2475    mem: *mut *mut xmlChar,
2476    size: *mut c_int,
2477) {
2478    if doc.is_null() || mem.is_null() || size.is_null() {
2479        return;
2480    }
2481    crate::xml::tree::xmlDocDumpMemory(doc, mem, size)
2482}
2483
2484/// Save a document to a file.
2485///
2486/// # UPSTREAM-PARITY
2487///
2488/// ```c
2489/// int xmlSaveFile(const char *filename, xmlDocPtr cur);
2490/// ```
2491#[no_mangle]
2492pub unsafe extern "C" fn xmlSaveFile(filename: *const c_char, cur: *mut _xmlDoc) -> c_int {
2493    if filename.is_null() || cur.is_null() {
2494        return -1;
2495    }
2496    crate::xml::tree::xmlSaveFile(filename, cur)
2497}
2498
2499/// Save a document to a file with encoding.
2500///
2501/// # UPSTREAM-PARITY
2502///
2503/// ```c
2504/// int xmlSaveFileEnc(const char *filename, xmlDocPtr cur, const char *encoding);
2505/// ```
2506#[no_mangle]
2507pub unsafe extern "C" fn xmlSaveFileEnc(
2508    filename: *const c_char,
2509    cur: *mut _xmlDoc,
2510    encoding: *const c_char,
2511) -> c_int {
2512    if filename.is_null() || cur.is_null() {
2513        return -1;
2514    }
2515    crate::xml::tree::xmlSaveFileEnc(filename, cur, encoding)
2516}
2517
2518/// Save a document to a file with format.
2519///
2520/// # UPSTREAM-PARITY
2521///
2522/// ```c
2523/// int xmlSaveFormatFile(const char *filename, xmlDocPtr cur, int format);
2524/// ```
2525#[no_mangle]
2526pub unsafe extern "C" fn xmlSaveFormatFile(
2527    filename: *const c_char,
2528    cur: *mut _xmlDoc,
2529    format: c_int,
2530) -> c_int {
2531    if filename.is_null() || cur.is_null() {
2532        return -1;
2533    }
2534    crate::xml::tree::xmlSaveFormatFile(filename, cur, format)
2535}
2536
2537/// Save a document to a file with encoding and format.
2538///
2539/// # UPSTREAM-PARITY
2540///
2541/// ```c
2542/// int xmlSaveFormatFileEnc(const char *filename, xmlDocPtr cur, const char *encoding, int format);
2543/// ```
2544#[no_mangle]
2545pub unsafe extern "C" fn xmlSaveFormatFileEnc(
2546    filename: *const c_char,
2547    cur: *mut _xmlDoc,
2548    encoding: *const c_char,
2549    format: c_int,
2550) -> c_int {
2551    if filename.is_null() || cur.is_null() {
2552        return -1;
2553    }
2554    crate::xml::tree::xmlSaveFormatFileEnc(filename, cur, encoding, format)
2555}
2556
2557// ═══════════════════════════════════════════════════════════════════════════════
2558// 7. Parser — SAX, DOM, Push, Reader
2559// ═══════════════════════════════════════════════════════════════════════════════
2560
2561/// Read an XML document from a string.
2562///
2563/// # UPSTREAM-PARITY
2564///
2565/// ```c
2566/// xmlDocPtr xmlReadDoc(const xmlChar *cur, const char *URL,
2567///                      const char *encoding, int options);
2568/// ```
2569///
2570/// Returns a parsed document. Caller must free with `xmlFreeDoc`.
2571#[no_mangle]
2572pub unsafe extern "C" fn xmlReadDoc(
2573    cur: *const xmlChar,
2574    URL: *const c_char,
2575    encoding: *const c_char,
2576    options: c_int,
2577) -> *mut _xmlDoc {
2578    // SAFETY: cur must be a valid null-terminated xmlChar string if non-null.
2579    if cur.is_null() {
2580        return ptr::null_mut();
2581    }
2582    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2583    if ctxt.is_null() {
2584        return ptr::null_mut();
2585    }
2586    let len = crate::xml::string::xml_strlen(cur);
2587    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
2588    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2589    (*ctxt).options = options;
2590    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2591        let doc = (*ctxt).myDoc;
2592        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2593        return doc;
2594    }
2595    let doc = (*ctxt).myDoc;
2596    if !doc.is_null() {
2597        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
2598    }
2599    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2600    doc
2601}
2602
2603/// Read an XML document from a file.
2604///
2605/// # UPSTREAM-PARITY
2606///
2607/// ```c
2608/// xmlDocPtr xmlReadFile(const char *URL, const char *encoding, int options);
2609/// ```
2610#[no_mangle]
2611pub unsafe extern "C" fn xmlReadFile(
2612    URL: *const c_char,
2613    encoding: *const c_char,
2614    options: c_int,
2615) -> *mut _xmlDoc {
2616    // SAFETY: URL must be a valid C string or NULL.
2617    if URL.is_null() {
2618        return ptr::null_mut();
2619    }
2620    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2621    if ctxt.is_null() {
2622        return ptr::null_mut();
2623    }
2624    let input = match crate::xml::parser::helpers::input_from_file(URL) {
2625        Ok(input) => input,
2626        Err(_) => {
2627            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2628            return ptr::null_mut();
2629        }
2630    };
2631    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2632    (*ctxt).options = options;
2633    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2634        let doc = (*ctxt).myDoc;
2635        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2636        // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
2637        // partially built document is discarded and NULL is returned; with
2638        // XML_PARSE_RECOVER the partial tree is kept.
2639        if options & 1 << 0 != 0 {
2640            return doc;
2641        }
2642        if !doc.is_null() {
2643            crate::xml::tree::free_doc(doc);
2644        }
2645        return ptr::null_mut();
2646    }
2647    let doc = (*ctxt).myDoc;
2648    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2649    doc
2650}
2651
2652/// Recover-parse a document from a string (upstream parser.h): same as
2653/// `xmlReadDoc` with XML_PARSE_RECOVER forced.
2654///
2655/// # UPSTREAM-PARITY
2656///
2657/// ```c
2658/// xmlDocPtr xmlRecoverDoc(const xmlChar *cur);
2659/// ```
2660#[no_mangle]
2661pub unsafe extern "C" fn xmlRecoverDoc(cur: *const xmlChar) -> *mut _xmlDoc {
2662    unsafe { xmlReadDoc(cur, ptr::null(), ptr::null(), 1 << 0) }
2663}
2664
2665/// Recover-parse a document from a file (upstream parser.h).
2666///
2667/// # UPSTREAM-PARITY
2668///
2669/// ```c
2670/// xmlDocPtr xmlRecoverFile(const char *filename);
2671/// ```
2672#[no_mangle]
2673pub unsafe extern "C" fn xmlRecoverFile(filename: *const c_char) -> *mut _xmlDoc {
2674    unsafe { xmlReadFile(filename, ptr::null(), 1 << 0) }
2675}
2676
2677/// Recover-parse a document from memory (upstream parser.h).
2678///
2679/// # UPSTREAM-PARITY
2680///
2681/// ```c
2682/// xmlDocPtr xmlRecoverMemory(const char *buffer, int size);
2683/// ```
2684#[no_mangle]
2685pub unsafe extern "C" fn xmlRecoverMemory(buffer: *const c_char, size: c_int) -> *mut _xmlDoc {
2686    unsafe { xmlReadMemory(buffer, size, ptr::null(), ptr::null(), 1 << 0) }
2687}
2688
2689/// Read an XML document from a file (upstream parser.h).
2690///
2691/// # UPSTREAM-PARITY
2692///
2693/// ```c
2694/// xmlDocPtr xmlReadMemory(const char *buffer, int size,
2695///                         const char *URL, const char *encoding, int options);
2696/// ```
2697#[no_mangle]
2698pub unsafe extern "C" fn xmlReadMemory(
2699    buffer: *const c_char,
2700    size: c_int,
2701    URL: *const c_char,
2702    encoding: *const c_char,
2703    options: c_int,
2704) -> *mut _xmlDoc {
2705    // SAFETY: buffer must be a valid pointer with at least `size` readable bytes.
2706    if buffer.is_null() || size <= 0 {
2707        return ptr::null_mut();
2708    }
2709    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2710    if ctxt.is_null() {
2711        return ptr::null_mut();
2712    }
2713    // UPSTREAM-PARITY: the URL becomes the input's filename (feeds the
2714    // `file:line:` error prefix and doc->URL).
2715    let input = crate::xml::parser::helpers::input_from_memory_named(buffer, size, URL);
2716    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2717    (*ctxt).options = options;
2718    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2719        let doc = (*ctxt).myDoc;
2720        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2721        // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
2722        // partially built document is discarded and NULL is returned; with
2723        // XML_PARSE_RECOVER the partial tree is kept.
2724        if options & 1 << 0 != 0 {
2725            return doc;
2726        }
2727        if !doc.is_null() {
2728            crate::xml::tree::free_doc(doc);
2729        }
2730        return ptr::null_mut();
2731    }
2732    let doc = (*ctxt).myDoc;
2733    if !doc.is_null() && !URL.is_null() {
2734        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
2735    }
2736    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2737    doc
2738}
2739
2740/// Load a list of catalogs (upstream `xmlLoadCatalogs`).
2741///
2742/// # SAFETY
2743///
2744/// - `catalogs` must be a valid NUL-terminated string or NULL.
2745#[no_mangle]
2746pub unsafe extern "C" fn xmlLoadCatalogs(catalogs: *const c_char) {
2747    if !catalogs.is_null() {
2748        crate::xml::catalog::load_catalog(catalogs);
2749    }
2750}
2751
2752/// Load a single catalog (upstream `xmlLoadCatalog`).
2753///
2754/// # SAFETY
2755///
2756/// - `catalogs` must be a valid NUL-terminated string or NULL.
2757#[no_mangle]
2758pub unsafe extern "C" fn xmlLoadCatalog(catalogs: *const c_char) -> *mut c_void {
2759    crate::xml::catalog::load_catalog(catalogs)
2760}
2761
2762/// Read an XML document from a file descriptor.
2763///
2764/// # UPSTREAM-PARITY
2765///
2766/// ```c
2767/// xmlDocPtr xmlReadFd(int fd, const char *URL, const char *encoding, int options);
2768/// ```
2769#[no_mangle]
2770pub unsafe extern "C" fn xmlReadFd(
2771    fd: c_int,
2772    URL: *const c_char,
2773    encoding: *const c_char,
2774    options: c_int,
2775) -> *mut _xmlDoc {
2776    // SAFETY: fd must be a valid open file descriptor.
2777    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2778    if ctxt.is_null() {
2779        return ptr::null_mut();
2780    }
2781    // Read all data from the fd
2782    let mut buf = Vec::new();
2783    let mut tmp = [0u8; 4096];
2784    loop {
2785        let n = libc::read(fd, tmp.as_mut_ptr() as *mut c_void, tmp.len());
2786        if n <= 0 {
2787            break;
2788        }
2789        buf.extend_from_slice(&tmp[..n as usize]);
2790    }
2791    let input = crate::xml::parser::helpers::input_from_memory(
2792        buf.as_ptr() as *const c_char,
2793        buf.len() as c_int,
2794    );
2795    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2796    (*ctxt).options = options;
2797    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2798        let doc = (*ctxt).myDoc;
2799        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2800        return doc;
2801    }
2802    let doc = (*ctxt).myDoc;
2803    if !doc.is_null() && !URL.is_null() {
2804        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
2805    }
2806    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2807    doc
2808}
2809
2810/// Read an XML document from I/O callbacks.
2811///
2812/// # UPSTREAM-PARITY
2813///
2814/// ```c
2815/// xmlDocPtr xmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
2816///                     void *ioctx, const char *URL, const char *encoding, int options);
2817/// ```
2818#[no_mangle]
2819pub unsafe extern "C" fn xmlReadIO(
2820    ioread: Option<xmlInputReadCallback>,
2821    ioclose: Option<xmlInputCloseCallback>,
2822    ioctx: *mut c_void,
2823    URL: *const c_char,
2824    encoding: *const c_char,
2825    options: c_int,
2826) -> *mut _xmlDoc {
2827    // SAFETY: callbacks must be valid function pointers if non-NULL.
2828    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2829    if ctxt.is_null() {
2830        return ptr::null_mut();
2831    }
2832    let input = crate::xml::parser::helpers::input_from_io(ioread, ioclose, ioctx);
2833    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2834    (*ctxt).options = options;
2835    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2836        let doc = (*ctxt).myDoc;
2837        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2838        return doc;
2839    }
2840    let doc = (*ctxt).myDoc;
2841    if !doc.is_null() && !URL.is_null() {
2842        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
2843    }
2844    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2845    doc
2846}
2847
2848/// Parse an XML document (SAX1).
2849///
2850/// # UPSTREAM-PARITY
2851///
2852/// ```c
2853/// xmlDocPtr xmlSAXParseDoc(xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery);
2854/// ```
2855#[no_mangle]
2856pub unsafe extern "C" fn xmlSAXParseDoc(
2857    sax: *mut _xmlSAXHandler,
2858    cur: *const xmlChar,
2859    recovery: c_int,
2860) -> *mut _xmlDoc {
2861    // SAFETY: cur must be a valid null-terminated xmlChar string.
2862    if cur.is_null() {
2863        return ptr::null_mut();
2864    }
2865    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2866    if ctxt.is_null() {
2867        return ptr::null_mut();
2868    }
2869    if !sax.is_null() {
2870        (*ctxt).sax = sax;
2871        (*ctxt).userData = (*ctxt).sax as *mut c_void;
2872    }
2873    if recovery != 0 {
2874        (*ctxt).recovery = 1;
2875        (*ctxt).options |= 1; // XML_PARSE_RECOVER
2876    }
2877    let len = crate::xml::string::xml_strlen(cur);
2878    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
2879    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2880    crate::xml::parser::helpers::parse_document(ctxt);
2881    let doc = (*ctxt).myDoc;
2882    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2883    doc
2884}
2885
2886/// Parse an XML document (SAX1) with user data (upstream parser.h
2887/// `xmlSAXParseDocWithData`): `user_data` is passed to the SAX callbacks.
2888///
2889/// # UPSTREAM-PARITY
2890///
2891/// ```c
2892/// xmlDocPtr xmlSAXParseDocWithData(xmlSAXHandlerPtr sax, const xmlChar *cur,
2893///                                  int recovery, void *data);
2894/// ```
2895#[no_mangle]
2896pub unsafe extern "C" fn xmlSAXParseDocWithData(
2897    sax: *mut _xmlSAXHandler,
2898    cur: *const xmlChar,
2899    recovery: c_int,
2900    data: *mut c_void,
2901) -> *mut _xmlDoc {
2902    // SAFETY: cur must be a valid null-terminated xmlChar string.
2903    if cur.is_null() {
2904        return ptr::null_mut();
2905    }
2906    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2907    if ctxt.is_null() {
2908        return ptr::null_mut();
2909    }
2910    if !sax.is_null() {
2911        (*ctxt).sax = sax;
2912    }
2913    (*ctxt).userData = data;
2914    if recovery != 0 {
2915        (*ctxt).recovery = 1;
2916        (*ctxt).options |= 1; // XML_PARSE_RECOVER
2917    }
2918    let len = crate::xml::string::xml_strlen(cur);
2919    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
2920    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2921    crate::xml::parser::helpers::parse_document(ctxt);
2922    let doc = (*ctxt).myDoc;
2923    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2924    doc
2925}
2926
2927/// Parse an XML file (SAX1) with user data (upstream parser.h
2928/// `xmlSAXParseFileWithData`).
2929///
2930/// # UPSTREAM-PARITY
2931///
2932/// ```c
2933/// xmlDocPtr xmlSAXParseFileWithData(xmlSAXHandlerPtr sax, const char *filename,
2934///                                   int recovery, void *data);
2935/// ```
2936#[no_mangle]
2937pub unsafe extern "C" fn xmlSAXParseFileWithData(
2938    sax: *mut _xmlSAXHandler,
2939    filename: *const c_char,
2940    recovery: c_int,
2941    data: *mut c_void,
2942) -> *mut _xmlDoc {
2943    // SAFETY: filename must be a valid C string or NULL.
2944    if filename.is_null() {
2945        return ptr::null_mut();
2946    }
2947    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2948    if ctxt.is_null() {
2949        return ptr::null_mut();
2950    }
2951    if !sax.is_null() {
2952        (*ctxt).sax = sax;
2953    }
2954    (*ctxt).userData = data;
2955    if recovery != 0 {
2956        (*ctxt).recovery = 1;
2957        (*ctxt).options |= 1; // XML_PARSE_RECOVER
2958    }
2959    let input = match crate::xml::parser::helpers::input_from_file(filename) {
2960        Ok(input) => input,
2961        Err(_) => {
2962            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2963            return ptr::null_mut();
2964        }
2965    };
2966    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2967    crate::xml::parser::helpers::parse_document(ctxt);
2968    let doc = (*ctxt).myDoc;
2969    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2970    doc
2971}
2972
2973/// Parse an XML document (SAX1) with user data from memory (upstream
2974/// parser.h `xmlSAXParseMemoryWithData`).
2975///
2976/// # UPSTREAM-PARITY
2977///
2978/// ```c
2979/// xmlDocPtr xmlSAXParseMemoryWithData(xmlSAXHandlerPtr sax, const char *buffer,
2980///                                     int size, int recovery, void *data);
2981/// ```
2982#[no_mangle]
2983pub unsafe extern "C" fn xmlSAXParseMemoryWithData(
2984    sax: *mut _xmlSAXHandler,
2985    buffer: *const c_char,
2986    size: c_int,
2987    recovery: c_int,
2988    data: *mut c_void,
2989) -> *mut _xmlDoc {
2990    // SAFETY: buffer must be a valid pointer with `size` readable bytes.
2991    if buffer.is_null() || size <= 0 {
2992        return ptr::null_mut();
2993    }
2994    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2995    if ctxt.is_null() {
2996        return ptr::null_mut();
2997    }
2998    if !sax.is_null() {
2999        (*ctxt).sax = sax;
3000    }
3001    (*ctxt).userData = data;
3002    if recovery != 0 {
3003        (*ctxt).recovery = 1;
3004        (*ctxt).options |= 1; // XML_PARSE_RECOVER
3005    }
3006    let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3007    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3008    crate::xml::parser::helpers::parse_document(ctxt);
3009    let doc = (*ctxt).myDoc;
3010    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3011    doc
3012}
3013
3014/// Parse an XML file (SAX1).
3015///
3016/// # UPSTREAM-PARITY
3017///
3018/// ```c
3019/// xmlDocPtr xmlSAXParseFile(xmlSAXHandlerPtr sax, const char *filename, int recovery);
3020/// ```
3021#[no_mangle]
3022pub unsafe extern "C" fn xmlSAXParseFile(
3023    sax: *mut _xmlSAXHandler,
3024    filename: *const c_char,
3025    recovery: c_int,
3026) -> *mut _xmlDoc {
3027    // SAFETY: filename must be a valid C string.
3028    if filename.is_null() {
3029        return ptr::null_mut();
3030    }
3031    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3032    if ctxt.is_null() {
3033        return ptr::null_mut();
3034    }
3035    if !sax.is_null() {
3036        (*ctxt).sax = sax;
3037        (*ctxt).userData = (*ctxt).sax as *mut c_void;
3038    }
3039    if recovery != 0 {
3040        (*ctxt).recovery = 1;
3041        (*ctxt).options |= 1;
3042    }
3043    let input = match crate::xml::parser::helpers::input_from_file(filename) {
3044        Ok(input) => input,
3045        Err(_) => {
3046            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3047            return ptr::null_mut();
3048        }
3049    };
3050    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3051    crate::xml::parser::helpers::parse_document(ctxt);
3052    let doc = (*ctxt).myDoc;
3053    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3054    doc
3055}
3056
3057/// Parse an XML document from memory (SAX1).
3058///
3059/// # UPSTREAM-PARITY
3060///
3061/// ```c
3062/// xmlDocPtr xmlSAXParseMemory(xmlSAXHandlerPtr sax,
3063///                             const char *buffer, int size, int recovery);
3064/// ```
3065#[no_mangle]
3066pub unsafe extern "C" fn xmlSAXParseMemory(
3067    sax: *mut _xmlSAXHandler,
3068    buffer: *const c_char,
3069    size: c_int,
3070    recovery: c_int,
3071) -> *mut _xmlDoc {
3072    // SAFETY: buffer must be valid with at least `size` bytes.
3073    if buffer.is_null() || size <= 0 {
3074        return ptr::null_mut();
3075    }
3076    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3077    if ctxt.is_null() {
3078        return ptr::null_mut();
3079    }
3080    if !sax.is_null() {
3081        (*ctxt).sax = sax;
3082        (*ctxt).userData = (*ctxt).sax as *mut c_void;
3083    }
3084    if recovery != 0 {
3085        (*ctxt).recovery = 1;
3086        (*ctxt).options |= 1;
3087    }
3088    let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3089    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3090    crate::xml::parser::helpers::parse_document(ctxt);
3091    let doc = (*ctxt).myDoc;
3092    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3093    doc
3094}
3095
3096/// SAX user parse file.
3097///
3098/// # UPSTREAM-PARITY
3099///
3100/// ```c
3101/// int xmlSAXUserParseFile(xmlSAXHandlerPtr sax, void *user_data,
3102///                         const char *filename);
3103/// ```
3104#[no_mangle]
3105pub unsafe extern "C" fn xmlSAXUserParseFile(
3106    sax: *mut _xmlSAXHandler,
3107    user_data: *mut c_void,
3108    filename: *const c_char,
3109) -> c_int {
3110    // SAFETY: filename must be a valid C string. sax and user_data may be NULL.
3111    if filename.is_null() {
3112        return -1;
3113    }
3114    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3115    if ctxt.is_null() {
3116        return -1;
3117    }
3118    if !sax.is_null() {
3119        (*ctxt).sax = sax;
3120    }
3121    (*ctxt).userData = if !user_data.is_null() {
3122        user_data
3123    } else {
3124        ctxt as *mut c_void
3125    };
3126    let input = match crate::xml::parser::helpers::input_from_file(filename) {
3127        Ok(input) => input,
3128        Err(_) => {
3129            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3130            return -1;
3131        }
3132    };
3133    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3134    let ret = crate::xml::parser::helpers::parse_document(ctxt);
3135    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3136    ret
3137}
3138
3139/// SAX user parse memory.
3140///
3141/// # UPSTREAM-PARITY
3142///
3143/// ```c
3144/// int xmlSAXUserParseMemory(xmlSAXHandlerPtr sax, void *user_data,
3145///                           const char *buffer, int size);
3146/// ```
3147#[no_mangle]
3148pub unsafe extern "C" fn xmlSAXUserParseMemory(
3149    sax: *mut _xmlSAXHandler,
3150    user_data: *mut c_void,
3151    buffer: *const c_char,
3152    size: c_int,
3153) -> c_int {
3154    // SAFETY: buffer must be valid with at least `size` bytes.
3155    if buffer.is_null() || size <= 0 {
3156        return -1;
3157    }
3158    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3159    if ctxt.is_null() {
3160        return -1;
3161    }
3162    if !sax.is_null() {
3163        (*ctxt).sax = sax;
3164    }
3165    (*ctxt).userData = if !user_data.is_null() {
3166        user_data
3167    } else {
3168        ctxt as *mut c_void
3169    };
3170    let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3171    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3172    let ret = crate::xml::parser::helpers::parse_document(ctxt);
3173    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3174    ret
3175}
3176
3177/// Parse an XML document from a string (DOM).
3178///
3179/// # UPSTREAM-PARITY
3180///
3181/// ```c
3182/// xmlDocPtr xmlParseDoc(const xmlChar *cur);
3183/// ```
3184#[no_mangle]
3185pub unsafe extern "C" fn xmlParseDoc(cur: *const xmlChar) -> *mut _xmlDoc {
3186    // SAFETY: cur must be a valid null-terminated xmlChar string.
3187    if cur.is_null() {
3188        return ptr::null_mut();
3189    }
3190    xmlReadDoc(cur, ptr::null(), ptr::null(), 0)
3191}
3192
3193/// Parse an XML file (DOM).
3194///
3195/// # UPSTREAM-PARITY
3196///
3197/// ```c
3198/// xmlDocPtr xmlParseFile(const char *filename);
3199/// ```
3200#[no_mangle]
3201pub unsafe extern "C" fn xmlParseFile(filename: *const c_char) -> *mut _xmlDoc {
3202    // SAFETY: filename must be a valid C string.
3203    if filename.is_null() {
3204        return ptr::null_mut();
3205    }
3206    xmlReadFile(filename, ptr::null(), 0)
3207}
3208
3209/// Parse an XML document from memory (DOM).
3210///
3211/// # UPSTREAM-PARITY
3212///
3213/// ```c
3214/// xmlDocPtr xmlParseMemory(const char *buffer, int size);
3215/// ```
3216#[no_mangle]
3217pub unsafe extern "C" fn xmlParseMemory(buffer: *const c_char, size: c_int) -> *mut _xmlDoc {
3218    // SAFETY: buffer must be valid with at least `size` bytes.
3219    if buffer.is_null() || size <= 0 {
3220        return ptr::null_mut();
3221    }
3222    xmlReadMemory(buffer, size, ptr::null(), ptr::null(), 0)
3223}
3224
3225/// Create a file parser context.
3226///
3227/// # UPSTREAM-PARITY
3228///
3229/// ```c
3230/// xmlParserCtxtPtr xmlCreateFileParserCtxt(const char *filename);
3231/// ```
3232#[no_mangle]
3233pub unsafe extern "C" fn xmlCreateFileParserCtxt(filename: *const c_char) -> *mut _xmlParserCtxt {
3234    // SAFETY: filename must be a valid C string.
3235    if filename.is_null() {
3236        return ptr::null_mut();
3237    }
3238    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3239    if ctxt.is_null() {
3240        return ptr::null_mut();
3241    }
3242    let input = match crate::xml::parser::helpers::input_from_file(filename) {
3243        Ok(input) => input,
3244        Err(_) => {
3245            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3246            return ptr::null_mut();
3247        }
3248    };
3249    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3250    ctxt
3251}
3252
3253/// Create a document parser context.
3254///
3255/// # UPSTREAM-PARITY
3256///
3257/// ```c
3258/// xmlParserCtxtPtr xmlCreateDocParserCtxt(const xmlChar *cur);
3259/// ```
3260#[no_mangle]
3261pub unsafe extern "C" fn xmlCreateDocParserCtxt(cur: *const xmlChar) -> *mut _xmlParserCtxt {
3262    // SAFETY: cur must be a valid null-terminated xmlChar string.
3263    if cur.is_null() {
3264        return ptr::null_mut();
3265    }
3266    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3267    if ctxt.is_null() {
3268        return ptr::null_mut();
3269    }
3270    let len = crate::xml::string::xml_strlen(cur);
3271    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
3272    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3273    ctxt
3274}
3275
3276/// Parse a document using an existing parser context.
3277///
3278/// # UPSTREAM-PARITY
3279///
3280/// ```c
3281/// int xmlParseDocument(xmlParserCtxtPtr ctxt);
3282/// ```
3283#[no_mangle]
3284pub unsafe extern "C" fn xmlParseDocument(ctxt: *mut _xmlParserCtxt) -> c_int {
3285    // SAFETY: ctxt must be a valid parser context.
3286    if ctxt.is_null() {
3287        return -1;
3288    }
3289    crate::xml::parser::helpers::parse_document(ctxt)
3290}
3291
3292/// Free a parser context.
3293///
3294/// # UPSTREAM-PARITY
3295///
3296/// ```c
3297/// void xmlFreeParserCtxt(xmlParserCtxtPtr ctxt);
3298/// ```
3299#[no_mangle]
3300pub unsafe extern "C" fn xmlFreeParserCtxt(ctxt: *mut _xmlParserCtxt) {
3301    if ctxt.is_null() {
3302        return;
3303    }
3304    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3305}
3306
3307/// Set parser options.
3308///
3309/// # UPSTREAM-PARITY
3310///
3311/// ```c
3312/// int xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options);
3313/// ```
3314#[no_mangle]
3315pub unsafe extern "C" fn xmlCtxtUseOptions(ctxt: *mut _xmlParserCtxt, options: c_int) -> c_int {
3316    if ctxt.is_null() {
3317        return -1;
3318    }
3319    // Phase 1: STUB
3320    unsafe {
3321        (*ctxt).options = options;
3322    }
3323    0
3324}
3325
3326/// Parse a well-balanced chunk (for push parsing).
3327///
3328/// # UPSTREAM-PARITY
3329///
3330/// ```c
3331/// xmlParserErrors xmlParseChunk(xmlParserCtxtPtr ctxt,
3332///                               const char *chunk, int size, int terminate);
3333/// ```
3334#[no_mangle]
3335pub unsafe extern "C" fn xmlParseChunk(
3336    ctxt: *mut _xmlParserCtxt,
3337    chunk: *const c_char,
3338    size: c_int,
3339    terminate: c_int,
3340) -> c_int {
3341    // SAFETY: ctxt must be a valid parser context.
3342    // chunk may be NULL if terminate is set (finalize without data).
3343    if ctxt.is_null() {
3344        return -1;
3345    }
3346    crate::xml::parser::helpers::parse_chunk(ctxt, chunk, size, terminate)
3347}
3348
3349/// Create a memory parser input buffer.
3350///
3351/// # UPSTREAM-PARITY
3352///
3353/// ```c
3354/// xmlParserInputBufferPtr xmlParserInputBufferCreateMem(const char *buffer, int size, int enc);
3355/// ```
3356#[no_mangle]
3357pub unsafe extern "C" fn xmlParserInputBufferCreateMem(
3358    buffer: *const c_char,
3359    size: c_int,
3360    enc: c_int,
3361) -> *mut _xmlParserInputBuffer {
3362    // SAFETY: buffer must be valid with at least `size` bytes.
3363    if buffer.is_null() || size <= 0 {
3364        return ptr::null_mut();
3365    }
3366    crate::xml::parser::helpers::alloc_parser_input_buffer()
3367}
3368
3369/// Create a file parser input buffer.
3370///
3371/// # UPSTREAM-PARITY
3372///
3373/// ```c
3374/// xmlParserInputBufferPtr xmlParserInputBufferCreateFilename(const char *URI, int enc);
3375/// ```
3376#[no_mangle]
3377pub unsafe extern "C" fn xmlParserInputBufferCreateFilename(
3378    URI: *const c_char,
3379    enc: c_int,
3380) -> *mut _xmlParserInputBuffer {
3381    // SAFETY: URI must be a valid C string or NULL.
3382    if URI.is_null() {
3383        return ptr::null_mut();
3384    }
3385    crate::xml::parser::helpers::alloc_parser_input_buffer()
3386}
3387
3388/// Create an I/O parser input buffer.
3389///
3390/// # UPSTREAM-PARITY
3391///
3392/// ```c
3393/// xmlParserInputBufferPtr xmlParserInputBufferCreateIO(
3394///     xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
3395///     void *ioctx, int enc);
3396/// ```
3397#[no_mangle]
3398pub unsafe extern "C" fn xmlParserInputBufferCreateIO(
3399    ioread: Option<xmlInputReadCallback>,
3400    ioclose: Option<xmlInputCloseCallback>,
3401    ioctx: *mut c_void,
3402    enc: c_int,
3403) -> *mut _xmlParserInputBuffer {
3404    // SAFETY: ioread must be a valid callback if Some. ioctx may be NULL.
3405    let buf = crate::xml::parser::helpers::alloc_parser_input_buffer();
3406    if !buf.is_null() {
3407        (*buf).readcallback = ioread;
3408        (*buf).closecallback = ioclose;
3409        (*buf).context = ioctx;
3410    }
3411    buf
3412}
3413
3414/// Free a parser input buffer.
3415///
3416/// # UPSTREAM-PARITY
3417///
3418/// ```c
3419/// void xmlFreeParserInputBuffer(xmlParserInputBufferPtr buf);
3420/// ```
3421#[no_mangle]
3422pub unsafe extern "C" fn xmlFreeParserInputBuffer(buf: *mut _xmlParserInputBuffer) {
3423    if buf.is_null() {
3424        return;
3425    }
3426    crate::xml::parser::helpers::free_parser_input_buffer(buf);
3427}
3428
3429/// Create a new parser input.
3430///
3431/// # UPSTREAM-PARITY
3432///
3433/// ```c
3434/// xmlParserInputPtr xmlNewInputFromFile(xmlParserCtxtPtr ctxt, const char *filename);
3435/// ```
3436#[no_mangle]
3437pub unsafe extern "C" fn xmlNewInputFromFile(
3438    ctxt: *mut _xmlParserCtxt,
3439    filename: *const c_char,
3440) -> *mut _xmlParserInput {
3441    // SAFETY: filename must be a valid C string. ctxt may be NULL.
3442    // This function allocates a _xmlParserInput. The caller owns it.
3443    // Note: The InputBuffer backing data is NOT leaked here (no ctxt._private
3444    // to store it). Use xmlCreateFileParserCtxt + xmlParseDocument instead.
3445    if filename.is_null() {
3446        return ptr::null_mut();
3447    }
3448    crate::xml::parser::helpers::alloc_parser_input_buffer() as *mut _xmlParserInput
3449}
3450
3451/// Free a parser input.
3452///
3453/// # UPSTREAM-PARITY
3454///
3455/// ```c
3456/// void xmlFreeInputStream(xmlParserInputPtr input);
3457/// ```
3458#[no_mangle]
3459pub unsafe extern "C" fn xmlFreeInputStream(input: *mut _xmlParserInput) {
3460    if input.is_null() {
3461        return;
3462    }
3463    crate::xml::parser::helpers::free_parser_input(input);
3464}
3465
3466// ═══════════════════════════════════════════════════════════════════════════════
3467// 8. I/O
3468// ═══════════════════════════════════════════════════════════════════════════════
3469
3470/// Create an output buffer for a file.
3471///
3472/// # UPSTREAM-PARITY
3473///
3474/// ```c
3475/// xmlOutputBufferPtr xmlOutputBufferCreateFilename(const char *URI,
3476///                                                  xmlCharEncodingHandlerPtr encoder,
3477///                                                  int compression);
3478/// ```
3479#[no_mangle]
3480pub unsafe extern "C" fn xmlOutputBufferCreateFilename(
3481    URI: *const c_char,
3482    encoder: *mut c_void,
3483    compression: c_int,
3484) -> *mut _xmlOutputBuffer {
3485    let _ = compression;
3486    if URI.is_null() {
3487        return ptr::null_mut();
3488    }
3489    crate::xml::io::output_buffer_create_filename(
3490        URI,
3491        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3492        0,
3493    )
3494}
3495
3496/// Create an output buffer for a file descriptor.
3497///
3498/// # UPSTREAM-PARITY
3499///
3500/// ```c
3501/// xmlOutputBufferPtr xmlOutputBufferCreateFd(int fd,
3502///                                            xmlCharEncodingHandlerPtr encoder);
3503/// ```
3504#[no_mangle]
3505pub unsafe extern "C" fn xmlOutputBufferCreateFd(
3506    fd: c_int,
3507    encoder: *mut c_void,
3508) -> *mut _xmlOutputBuffer {
3509    if fd < 0 {
3510        return ptr::null_mut();
3511    }
3512    crate::xml::io::output_buffer_create_fd(
3513        fd,
3514        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3515    )
3516}
3517
3518/// Create an output buffer from I/O callbacks.
3519///
3520/// # UPSTREAM-PARITY
3521///
3522/// ```c
3523/// xmlOutputBufferPtr xmlOutputBufferCreateIO(
3524///     xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose,
3525///     void *ioctx, xmlCharEncodingHandlerPtr encoder);
3526/// ```
3527#[no_mangle]
3528pub unsafe extern "C" fn xmlOutputBufferCreateIO(
3529    iowrite: Option<xmlOutputWriteCallback>,
3530    ioclose: Option<xmlOutputCloseCallback>,
3531    ioctx: *mut c_void,
3532    encoder: *mut c_void,
3533) -> *mut _xmlOutputBuffer {
3534    crate::xml::io::output_buffer_create_io(
3535        iowrite,
3536        ioclose,
3537        ioctx,
3538        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3539    )
3540}
3541
3542/// Free an output buffer.
3543///
3544/// # UPSTREAM-PARITY
3545///
3546/// ```c
3547/// void xmlOutputBufferClose(xmlOutputBufferPtr out);
3548/// ```
3549#[no_mangle]
3550pub unsafe extern "C" fn xmlOutputBufferClose(out: *mut _xmlOutputBuffer) -> c_int {
3551    if out.is_null() {
3552        return -1;
3553    }
3554    crate::xml::io::output_buffer_close(out)
3555}
3556
3557/// Flush an output buffer.
3558///
3559/// # UPSTREAM-PARITY
3560///
3561/// ```c
3562/// int xmlOutputBufferFlush(xmlOutputBufferPtr out);
3563/// ```
3564#[no_mangle]
3565pub unsafe extern "C" fn xmlOutputBufferFlush(out: *mut _xmlOutputBuffer) -> c_int {
3566    if out.is_null() {
3567        return -1;
3568    }
3569    crate::xml::io::output_buffer_flush(out)
3570}
3571
3572/// Write to an output buffer.
3573///
3574/// # UPSTREAM-PARITY
3575///
3576/// ```c
3577/// int xmlOutputBufferWrite(xmlOutputBufferPtr out, int len, const char *data);
3578/// ```
3579#[no_mangle]
3580pub unsafe extern "C" fn xmlOutputBufferWrite(
3581    out: *mut _xmlOutputBuffer,
3582    len: c_int,
3583    data: *const c_char,
3584) -> c_int {
3585    if out.is_null() || data.is_null() || len <= 0 {
3586        return -1;
3587    }
3588    crate::xml::io::output_buffer_write(out, len, data)
3589}
3590
3591/// Write a string to an output buffer.
3592///
3593/// # UPSTREAM-PARITY
3594///
3595/// ```c
3596/// int xmlOutputBufferWriteString(xmlOutputBufferPtr out, const char *str);
3597/// ```
3598#[no_mangle]
3599pub unsafe extern "C" fn xmlOutputBufferWriteString(
3600    out: *mut _xmlOutputBuffer,
3601    str: *const c_char,
3602) -> c_int {
3603    if str.is_null() {
3604        return 0;
3605    }
3606    unsafe { xmlOutputBufferWrite(out, xmlStrlen(str as *const xmlChar), str) }
3607}
3608
3609/// Allocate an output buffer with no I/O target (upstream xmlAllocOutputBuffer).
3610///
3611/// # UPSTREAM-PARITY
3612///
3613/// ```c
3614/// xmlOutputBufferPtr xmlAllocOutputBuffer(xmlCharEncodingHandlerPtr encoder);
3615/// ```
3616#[no_mangle]
3617pub unsafe extern "C" fn xmlAllocOutputBuffer(encoder: *mut c_void) -> *mut _xmlOutputBuffer {
3618    crate::xml::io::output_buffer_create(
3619        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3620    )
3621}
3622
3623/// Create an output buffer that writes into a `_xmlBuffer` (upstream
3624/// xmlOutputBufferCreateBuffer).
3625///
3626/// # UPSTREAM-PARITY
3627///
3628/// ```c
3629/// xmlOutputBufferPtr xmlOutputBufferCreateBuffer(xmlBufferPtr buffer,
3630///                                                xmlCharEncodingHandlerPtr encoder);
3631/// ```
3632///
3633/// # SAFETY
3634///
3635/// - `buffer` must be a valid `_xmlBuffer`.
3636#[no_mangle]
3637pub unsafe extern "C" fn xmlOutputBufferCreateBuffer(
3638    buffer: *mut crate::abi::structs::_xmlBuffer,
3639    encoder: *mut c_void,
3640) -> *mut _xmlOutputBuffer {
3641    crate::xml::io::output_buffer_create_buffer(
3642        buffer,
3643        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3644    )
3645}
3646
3647/// Create an output buffer writing to a `FILE *` (upstream
3648/// xmlOutputBufferCreateFile): the FILE is the I/O context with a
3649/// write callback wrapping `fwrite` and a close callback wrapping `fflush`.
3650///
3651/// # SAFETY
3652///
3653/// - `file` must be a valid `FILE *` or NULL.
3654#[no_mangle]
3655pub unsafe extern "C" fn xmlOutputBufferCreateFile(
3656    file: *mut libc::FILE,
3657    encoder: *mut c_void,
3658) -> *mut _xmlOutputBuffer {
3659    crate::xml::io::output_buffer_create_file(
3660        file,
3661        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3662    )
3663}
3664
3665/// Get the current content of an output buffer (upstream xmlOutputBufferGetContent).
3666///
3667/// # SAFETY
3668///
3669/// - `out` must be a valid output buffer.
3670#[no_mangle]
3671pub unsafe extern "C" fn xmlOutputBufferGetContent(out: *mut _xmlOutputBuffer) -> *const c_char {
3672    crate::xml::io::output_buffer_get_content(out) as *const c_char
3673}
3674
3675/// Get the number of bytes currently in the output buffer (upstream
3676/// xmlOutputBufferGetSize).
3677///
3678/// # SAFETY
3679///
3680/// - `out` must be a valid output buffer.
3681#[no_mangle]
3682pub unsafe extern "C" fn xmlOutputBufferGetSize(out: *mut _xmlOutputBuffer) -> c_int {
3683    crate::xml::io::output_buffer_get_size(out)
3684}
3685
3686/// Write to an output buffer, escaping special characters with the given
3687/// escape function (upstream xmlOutputBufferWriteEscape).
3688///
3689/// # SAFETY
3690///
3691/// - `out` must be a valid output buffer; `str` a NUL-terminated string;
3692///   `escaping` a valid escape callback or NULL.
3693#[no_mangle]
3694pub unsafe extern "C" fn xmlOutputBufferWriteEscape(
3695    out: *mut _xmlOutputBuffer,
3696    str: *const xmlChar,
3697    escaping: Option<xmlCharEncodingOutputFunc>,
3698) -> c_int {
3699    if out.is_null() || str.is_null() {
3700        return -1;
3701    }
3702    crate::xml::io::output_buffer_write_escape(out, str, escaping)
3703}
3704
3705/// Global default `xmlOutputBufferCreateFilename` callback
3706/// (upstream xmlOutputBufferCreateFilenameDefault).
3707static mut OUTPUT_CREATE_FILENAME_DEFAULT: Option<
3708    unsafe extern "C" fn(
3709        *const c_char,
3710        *mut crate::abi::structs::_xmlCharEncodingHandler,
3711        c_int,
3712    ) -> *mut _xmlOutputBuffer,
3713> = None;
3714
3715/// Set/query the default output-buffer filename callback
3716/// (upstream xmlOutputBufferCreateFilenameDefault).
3717///
3718/// # SAFETY
3719///
3720/// - `func` must be a valid function pointer or NULL.
3721#[no_mangle]
3722pub unsafe extern "C" fn xmlOutputBufferCreateFilenameDefault(
3723    func: Option<
3724        unsafe extern "C" fn(
3725            *const c_char,
3726            *mut crate::abi::structs::_xmlCharEncodingHandler,
3727            c_int,
3728        ) -> *mut _xmlOutputBuffer,
3729    >,
3730) -> Option<
3731    unsafe extern "C" fn(
3732        *const c_char,
3733        *mut crate::abi::structs::_xmlCharEncodingHandler,
3734        c_int,
3735    ) -> *mut _xmlOutputBuffer,
3736> {
3737    let old = unsafe { OUTPUT_CREATE_FILENAME_DEFAULT };
3738    if func.is_some() {
3739        unsafe { OUTPUT_CREATE_FILENAME_DEFAULT = func };
3740    }
3741    old
3742}
3743
3744/// `__xmlOutputBufferCreateFilename` — accessor returning a pointer to the
3745/// default callback (upstream xmlIO.c).
3746#[no_mangle]
3747pub unsafe extern "C" fn __xmlOutputBufferCreateFilename() -> *mut Option<
3748    unsafe extern "C" fn(
3749        *const c_char,
3750        *mut crate::abi::structs::_xmlCharEncodingHandler,
3751        c_int,
3752    ) -> *mut _xmlOutputBuffer,
3753> {
3754    unsafe { core::ptr::addr_of_mut!(OUTPUT_CREATE_FILENAME_DEFAULT) }
3755}
3756
3757// ═══════════════════════════════════════════════════════════════════════════════
3758// 9. Dictionary
3759// ═══════════════════════════════════════════════════════════════════════════════
3760
3761/// Create a new dictionary.
3762///
3763/// # UPSTREAM-PARITY
3764///
3765/// ```c
3766/// xmlDictPtr xmlDictCreate(void);
3767/// ```
3768#[no_mangle]
3769pub extern "C" fn xmlDictCreate() -> *mut c_void {
3770    unsafe { crate::xml::dictionary::dict_create() as *mut c_void }
3771}
3772
3773/// Create a sub-dictionary.
3774///
3775/// # UPSTREAM-PARITY
3776///
3777/// ```c
3778/// xmlDictPtr xmlDictCreateSub(xmlDictPtr sub);
3779/// ```
3780#[no_mangle]
3781pub extern "C" fn xmlDictCreateSub(sub: *mut c_void) -> *mut c_void {
3782    unsafe {
3783        crate::xml::dictionary::dict_create_sub(sub as *mut crate::xml::dictionary::Dict)
3784            as *mut c_void
3785    }
3786}
3787
3788/// Look up a string in the dictionary.
3789///
3790/// # UPSTREAM-PARITY
3791///
3792/// ```c
3793/// const xmlChar *xmlDictLookup(xmlDictPtr dict, const xmlChar *name, int len);
3794/// ```
3795///
3796/// Returns an interned string pointer (valid as long as the dictionary exists).
3797/// - If `len` < 0, `name` must be null-terminated.
3798/// - If `len` >= 0, exactly `len` bytes are used.
3799#[no_mangle]
3800pub unsafe extern "C" fn xmlDictLookup(
3801    dict: *mut c_void,
3802    name: *const xmlChar,
3803    len: c_int,
3804) -> *const xmlChar {
3805    unsafe {
3806        crate::xml::dictionary::dict_lookup(dict as *mut crate::xml::dictionary::Dict, name, len)
3807    }
3808}
3809
3810/// Check if a string exists in the dictionary.
3811///
3812/// # UPSTREAM-PARITY
3813///
3814/// ```c
3815/// const xmlChar *xmlDictExists(xmlDictPtr dict, const xmlChar *name, int len);
3816/// ```
3817#[no_mangle]
3818pub unsafe extern "C" fn xmlDictExists(
3819    dict: *mut c_void,
3820    name: *const xmlChar,
3821    len: c_int,
3822) -> *const xmlChar {
3823    unsafe {
3824        crate::xml::dictionary::dict_exists(dict as *mut crate::xml::dictionary::Dict, name, len)
3825    }
3826}
3827
3828/// Query dictionary size.
3829///
3830/// # UPSTREAM-PARITY
3831///
3832/// ```c
3833/// unsigned int xmlDictSize(const xmlDictPtr dict);
3834/// ```
3835#[no_mangle]
3836pub extern "C" fn xmlDictSize(dict: *const c_void) -> c_uint {
3837    unsafe {
3838        crate::xml::dictionary::dict_size(dict as *const crate::xml::dictionary::Dict) as c_uint
3839    }
3840}
3841
3842/// Free a dictionary.
3843///
3844/// # UPSTREAM-PARITY
3845///
3846/// ```c
3847/// void xmlDictFree(xmlDictPtr dict);
3848/// ```
3849#[no_mangle]
3850pub extern "C" fn xmlDictFree(dict: *mut c_void) {
3851    unsafe { crate::xml::dictionary::dict_free(dict as *mut crate::xml::dictionary::Dict) }
3852}
3853
3854/// Set the dictionary size limit.
3855///
3856/// # UPSTREAM-PARITY
3857///
3858/// ```c
3859/// unsigned int xmlDictSetLimit(xmlDictPtr dict, unsigned int limit);
3860/// ```
3861#[no_mangle]
3862pub extern "C" fn xmlDictSetLimit(dict: *mut c_void, limit: c_uint) -> c_uint {
3863    unsafe {
3864        crate::xml::dictionary::dict_set_limit(
3865            dict as *mut crate::xml::dictionary::Dict,
3866            limit as usize,
3867        ) as c_uint
3868    }
3869}
3870
3871/// Get current dictionary usage.
3872///
3873/// # UPSTREAM-PARITY
3874///
3875/// ```c
3876/// unsigned int xmlDictGetUsage(const xmlDictPtr dict);
3877/// ```
3878#[no_mangle]
3879pub extern "C" fn xmlDictGetUsage(dict: *const c_void) -> c_uint {
3880    unsafe {
3881        crate::xml::dictionary::dict_get_usage(dict as *mut crate::xml::dictionary::Dict) as c_uint
3882    }
3883}
3884
3885// ═══════════════════════════════════════════════════════════════════════════════
3886// 10. Hash Table
3887// ═══════════════════════════════════════════════════════════════════════════════
3888
3889/// Create a new hash table.
3890///
3891/// # UPSTREAM-PARITY
3892///
3893/// ```c
3894/// xmlHashTablePtr xmlHashCreate(int size);
3895/// ```
3896#[no_mangle]
3897pub extern "C" fn xmlHashCreate(size: c_int) -> *mut c_void {
3898    unsafe { crate::xml::hash::hash_create(size) as *mut c_void }
3899}
3900
3901/// Create a new hash table with a dictionary.
3902///
3903/// # UPSTREAM-PARITY
3904///
3905/// ```c
3906/// xmlHashTablePtr xmlHashCreateDict(int size, xmlDictPtr dict);
3907/// ```
3908#[no_mangle]
3909pub extern "C" fn xmlHashCreateDict(size: c_int, dict: *mut c_void) -> *mut c_void {
3910    unsafe { crate::xml::hash::hash_create_dict(size, dict) as *mut c_void }
3911}
3912
3913/// Free a hash table.
3914///
3915/// # UPSTREAM-PARITY
3916///
3917/// ```c
3918/// void xmlHashFree(xmlHashTablePtr table, xmlHashDeallocator f);
3919/// ```
3920#[no_mangle]
3921pub extern "C" fn xmlHashFree(
3922    table: *mut c_void,
3923    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
3924) {
3925    unsafe { crate::xml::hash::hash_free(table as *mut crate::xml::hash::HashTable, f) }
3926}
3927
3928/// Add an entry to a hash table.
3929///
3930/// # UPSTREAM-PARITY
3931///
3932/// ```c
3933/// int xmlHashAddEntry(xmlHashTablePtr table, const xmlChar *name, void *userdata);
3934/// ```
3935#[no_mangle]
3936pub unsafe extern "C" fn xmlHashAddEntry(
3937    table: *mut c_void,
3938    name: *const xmlChar,
3939    userdata: *mut c_void,
3940) -> c_int {
3941    unsafe {
3942        crate::xml::hash::hash_add_entry(table as *mut crate::xml::hash::HashTable, name, userdata)
3943    }
3944}
3945
3946/// Add a 2-key entry.
3947///
3948/// # UPSTREAM-PARITY
3949///
3950/// ```c
3951/// int xmlHashAddEntry2(xmlHashTablePtr table, const xmlChar *name,
3952///                      const xmlChar *name2, void *userdata);
3953/// ```
3954#[no_mangle]
3955pub unsafe extern "C" fn xmlHashAddEntry2(
3956    table: *mut c_void,
3957    name: *const xmlChar,
3958    name2: *const xmlChar,
3959    userdata: *mut c_void,
3960) -> c_int {
3961    unsafe {
3962        crate::xml::hash::hash_add_entry2(
3963            table as *mut crate::xml::hash::HashTable,
3964            name,
3965            name2,
3966            userdata,
3967        )
3968    }
3969}
3970
3971/// Add a 3-key entry.
3972///
3973/// # UPSTREAM-PARITY
3974///
3975/// ```c
3976/// int xmlHashAddEntry3(xmlHashTablePtr table, const xmlChar *name,
3977///                      const xmlChar *name2, const xmlChar *name3, void *userdata);
3978/// ```
3979#[no_mangle]
3980pub unsafe extern "C" fn xmlHashAddEntry3(
3981    table: *mut c_void,
3982    name: *const xmlChar,
3983    name2: *const xmlChar,
3984    name3: *const xmlChar,
3985    userdata: *mut c_void,
3986) -> c_int {
3987    unsafe {
3988        crate::xml::hash::hash_add_entry3(
3989            table as *mut crate::xml::hash::HashTable,
3990            name,
3991            name2,
3992            name3,
3993            userdata,
3994        )
3995    }
3996}
3997
3998/// Update or add an entry.
3999///
4000/// # UPSTREAM-PARITY
4001///
4002/// ```c
4003/// int xmlHashUpdateEntry(xmlHashTablePtr table, const xmlChar *name,
4004///                        void *userdata, xmlHashDeallocator f);
4005/// ```
4006#[no_mangle]
4007pub unsafe extern "C" fn xmlHashUpdateEntry(
4008    table: *mut c_void,
4009    name: *const xmlChar,
4010    userdata: *mut c_void,
4011    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4012) -> c_int {
4013    unsafe {
4014        crate::xml::hash::hash_update_entry(
4015            table as *mut crate::xml::hash::HashTable,
4016            name,
4017            userdata,
4018            f,
4019        )
4020    }
4021}
4022
4023/// Update or add a 2-key entry.
4024#[no_mangle]
4025pub unsafe extern "C" fn xmlHashUpdateEntry2(
4026    table: *mut c_void,
4027    name: *const xmlChar,
4028    name2: *const xmlChar,
4029    userdata: *mut c_void,
4030    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4031) -> c_int {
4032    unsafe {
4033        crate::xml::hash::hash_update_entry2(
4034            table as *mut crate::xml::hash::HashTable,
4035            name,
4036            name2,
4037            userdata,
4038            f,
4039        )
4040    }
4041}
4042
4043/// Update or add a 3-key entry.
4044#[no_mangle]
4045pub unsafe extern "C" fn xmlHashUpdateEntry3(
4046    table: *mut c_void,
4047    name: *const xmlChar,
4048    name2: *const xmlChar,
4049    name3: *const xmlChar,
4050    userdata: *mut c_void,
4051    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4052) -> c_int {
4053    unsafe {
4054        crate::xml::hash::hash_update_entry3(
4055            table as *mut crate::xml::hash::HashTable,
4056            name,
4057            name2,
4058            name3,
4059            userdata,
4060            f,
4061        )
4062    }
4063}
4064
4065/// Look up an entry.
4066///
4067/// # UPSTREAM-PARITY
4068///
4069/// ```c
4070/// void *xmlHashLookup(xmlHashTablePtr table, const xmlChar *name);
4071/// ```
4072#[no_mangle]
4073pub unsafe extern "C" fn xmlHashLookup(table: *mut c_void, name: *const xmlChar) -> *mut c_void {
4074    unsafe { crate::xml::hash::hash_lookup(table as *mut crate::xml::hash::HashTable, name) }
4075}
4076
4077/// Look up a 2-key entry.
4078#[no_mangle]
4079pub unsafe extern "C" fn xmlHashLookup2(
4080    table: *mut c_void,
4081    name: *const xmlChar,
4082    name2: *const xmlChar,
4083) -> *mut c_void {
4084    unsafe {
4085        crate::xml::hash::hash_lookup2(table as *mut crate::xml::hash::HashTable, name, name2)
4086    }
4087}
4088
4089/// Look up a 3-key entry.
4090#[no_mangle]
4091pub unsafe extern "C" fn xmlHashLookup3(
4092    table: *mut c_void,
4093    name: *const xmlChar,
4094    name2: *const xmlChar,
4095    name3: *const xmlChar,
4096) -> *mut c_void {
4097    unsafe {
4098        crate::xml::hash::hash_lookup3(
4099            table as *mut crate::xml::hash::HashTable,
4100            name,
4101            name2,
4102            name3,
4103        )
4104    }
4105}
4106
4107/// Get the size of a hash table.
4108///
4109/// # UPSTREAM-PARITY
4110///
4111/// ```c
4112/// int xmlHashSize(xmlHashTablePtr table);
4113/// ```
4114#[no_mangle]
4115pub extern "C" fn xmlHashSize(table: *mut c_void) -> c_int {
4116    unsafe { crate::xml::hash::hash_size(table as *mut crate::xml::hash::HashTable) }
4117}
4118
4119/// Remove an entry.
4120///
4121/// # UPSTREAM-PARITY
4122///
4123/// ```c
4124/// int xmlHashRemoveEntry(xmlHashTablePtr table, const xmlChar *name,
4125///                        xmlHashDeallocator f);
4126/// ```
4127#[no_mangle]
4128pub unsafe extern "C" fn xmlHashRemoveEntry(
4129    table: *mut c_void,
4130    name: *const xmlChar,
4131    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4132) -> c_int {
4133    unsafe {
4134        crate::xml::hash::hash_remove_entry(table as *mut crate::xml::hash::HashTable, name, f)
4135    }
4136}
4137
4138/// Remove a 2-key entry.
4139#[no_mangle]
4140pub unsafe extern "C" fn xmlHashRemoveEntry2(
4141    table: *mut c_void,
4142    name: *const xmlChar,
4143    name2: *const xmlChar,
4144    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4145) -> c_int {
4146    unsafe {
4147        crate::xml::hash::hash_remove_entry2(
4148            table as *mut crate::xml::hash::HashTable,
4149            name,
4150            name2,
4151            f,
4152        )
4153    }
4154}
4155
4156/// Remove a 3-key entry.
4157#[no_mangle]
4158pub unsafe extern "C" fn xmlHashRemoveEntry3(
4159    table: *mut c_void,
4160    name: *const xmlChar,
4161    name2: *const xmlChar,
4162    name3: *const xmlChar,
4163    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4164) -> c_int {
4165    unsafe {
4166        crate::xml::hash::hash_remove_entry3(
4167            table as *mut crate::xml::hash::HashTable,
4168            name,
4169            name2,
4170            name3,
4171            f,
4172        )
4173    }
4174}
4175
4176/// Scan a hash table with a scanner function.
4177///
4178/// # UPSTREAM-PARITY
4179///
4180/// ```c
4181/// void xmlHashScan(xmlHashTablePtr table, xmlHashScanner f, void *data);
4182/// ```
4183#[no_mangle]
4184pub extern "C" fn xmlHashScan(table: *mut c_void, f: Option<xmlHashScanner>, data: *mut c_void) {
4185    unsafe { crate::xml::hash::hash_scan(table as *mut crate::xml::hash::HashTable, f, data) }
4186}
4187
4188/// Scan a hash table with a full scanner function.
4189#[no_mangle]
4190pub extern "C" fn xmlHashScanFull(
4191    table: *mut c_void,
4192    f: Option<xmlHashScannerFull>,
4193    data: *mut c_void,
4194) {
4195    unsafe { crate::xml::hash::hash_scan_full(table as *mut crate::xml::hash::HashTable, f, data) }
4196}
4197
4198/// Copy a hash table.
4199///
4200/// # UPSTREAM-PARITY
4201///
4202/// ```c
4203/// xmlHashTablePtr xmlHashCopy(xmlHashTablePtr table, xmlHashCopier f);
4204/// ```
4205#[no_mangle]
4206pub extern "C" fn xmlHashCopy(
4207    table: *mut c_void,
4208    f: Option<unsafe extern "C" fn(*mut c_void, *const xmlChar) -> *mut c_void>,
4209) -> *mut c_void {
4210    unsafe {
4211        crate::xml::hash::hash_copy(table as *mut crate::xml::hash::HashTable, f) as *mut c_void
4212    }
4213}
4214
4215// ═══════════════════════════════════════════════════════════════════════════════
4216// 11. List
4217// ═══════════════════════════════════════════════════════════════════════════════
4218
4219/// Create a new list.
4220///
4221/// # UPSTREAM-PARITY
4222///
4223/// ```c
4224/// xmlListPtr xmlListCreate(xmlListDeallocator deallocator,
4225///                          xmlListDataCompare compare);
4226/// ```
4227#[no_mangle]
4228pub extern "C" fn xmlListCreate(
4229    deallocator: Option<unsafe extern "C" fn(*mut c_void)>,
4230    compare: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
4231) -> *mut c_void {
4232    unsafe { crate::xml::list::list_create(deallocator, compare) as *mut c_void }
4233}
4234
4235/// Delete a list.
4236///
4237/// # UPSTREAM-PARITY
4238///
4239/// ```c
4240/// void xmlListDelete(xmlListPtr list);
4241/// ```
4242#[no_mangle]
4243pub extern "C" fn xmlListDelete(list: *mut c_void) {
4244    unsafe { crate::xml::list::list_delete(list as *mut crate::xml::list::List) }
4245}
4246
4247/// Search a list.
4248///
4249/// # UPSTREAM-PARITY
4250///
4251/// ```c
4252/// void *xmlListSearch(xmlListPtr list, void *data);
4253/// ```
4254#[no_mangle]
4255pub extern "C" fn xmlListSearch(list: *mut c_void, data: *mut c_void) -> *mut c_void {
4256    unsafe { crate::xml::list::list_search(list as *mut crate::xml::list::List, data) }
4257}
4258
4259/// Walk a list.
4260///
4261/// # UPSTREAM-PARITY
4262///
4263/// ```c
4264/// void xmlListWalk(xmlListPtr list, xmlListWalker walker, void *data);
4265/// ```
4266#[no_mangle]
4267pub extern "C" fn xmlListWalk(
4268    list: *mut c_void,
4269    walker: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
4270    data: *mut c_void,
4271) {
4272    unsafe { crate::xml::list::list_walk(list as *mut crate::xml::list::List, walker, data) }
4273}
4274
4275/// Push to back.
4276///
4277/// # UPSTREAM-PARITY
4278///
4279/// ```c
4280/// int xmlListPushBack(xmlListPtr list, void *data);
4281/// ```
4282#[no_mangle]
4283pub extern "C" fn xmlListPushBack(list: *mut c_void, data: *mut c_void) -> c_int {
4284    unsafe { crate::xml::list::list_push_back(list as *mut crate::xml::list::List, data) }
4285}
4286
4287/// Push to front.
4288///
4289/// # UPSTREAM-PARITY
4290///
4291/// ```c
4292/// int xmlListPushFront(xmlListPtr list, void *data);
4293/// ```
4294#[no_mangle]
4295pub extern "C" fn xmlListPushFront(list: *mut c_void, data: *mut c_void) -> c_int {
4296    unsafe { crate::xml::list::list_push_front(list as *mut crate::xml::list::List, data) }
4297}
4298
4299/// Pop from back.
4300#[no_mangle]
4301pub extern "C" fn xmlListPopBack(list: *mut c_void) {
4302    unsafe { crate::xml::list::list_pop_back(list as *mut crate::xml::list::List) }
4303}
4304
4305/// Pop from front.
4306#[no_mangle]
4307pub extern "C" fn xmlListPopFront(list: *mut c_void) {
4308    unsafe { crate::xml::list::list_pop_front(list as *mut crate::xml::list::List) }
4309}
4310
4311/// Insert into sorted list.
4312///
4313/// # UPSTREAM-PARITY
4314///
4315/// ```c
4316/// int xmlListInsert(xmlListPtr list, void *data);
4317/// ```
4318#[no_mangle]
4319pub extern "C" fn xmlListInsert(list: *mut c_void, data: *mut c_void) -> c_int {
4320    unsafe { crate::xml::list::list_insert(list as *mut crate::xml::list::List, data) }
4321}
4322
4323/// Append to list.
4324#[no_mangle]
4325pub extern "C" fn xmlListAppend(list: *mut c_void, data: *mut c_void) -> c_int {
4326    unsafe { crate::xml::list::list_append(list as *mut crate::xml::list::List, data) }
4327}
4328
4329/// Remove first matching element.
4330#[no_mangle]
4331pub extern "C" fn xmlListRemoveFirst(list: *mut c_void, data: *mut c_void) -> c_int {
4332    unsafe { crate::xml::list::list_remove_first(list as *mut crate::xml::list::List, data) }
4333}
4334
4335/// Remove last matching element.
4336#[no_mangle]
4337pub extern "C" fn xmlListRemoveLast(list: *mut c_void, data: *mut c_void) -> c_int {
4338    unsafe { crate::xml::list::list_remove_last(list as *mut crate::xml::list::List, data) }
4339}
4340
4341/// Remove all matching elements.
4342#[no_mangle]
4343pub extern "C" fn xmlListRemoveAll(list: *mut c_void, data: *mut c_void) -> c_int {
4344    unsafe { crate::xml::list::list_remove_all(list as *mut crate::xml::list::List, data) }
4345}
4346
4347/// Clear a list.
4348#[no_mangle]
4349pub extern "C" fn xmlListClear(list: *mut c_void) {
4350    unsafe { crate::xml::list::list_clear(list as *mut crate::xml::list::List) }
4351}
4352
4353/// Check if list is empty.
4354///
4355/// # UPSTREAM-PARITY
4356///
4357/// ```c
4358/// int xmlListEmpty(xmlListPtr list);
4359/// ```
4360#[no_mangle]
4361pub extern "C" fn xmlListEmpty(list: *mut c_void) -> c_int {
4362    unsafe { crate::xml::list::list_empty(list as *mut crate::xml::list::List) }
4363}
4364
4365/// Get front element.
4366///
4367/// # UPSTREAM-PARITY
4368///
4369/// ```c
4370/// void *xmlListFront(xmlListPtr list);
4371/// ```
4372#[no_mangle]
4373pub extern "C" fn xmlListFront(list: *mut c_void) -> *mut c_void {
4374    unsafe { crate::xml::list::list_front(list as *mut crate::xml::list::List) }
4375}
4376
4377/// Get back element.
4378///
4379/// # UPSTREAM-PARITY
4380///
4381/// ```c
4382/// void *xmlListBack(xmlListPtr list);
4383/// ```
4384#[no_mangle]
4385pub extern "C" fn xmlListBack(list: *mut c_void) -> *mut c_void {
4386    unsafe { crate::xml::list::list_back(list as *mut crate::xml::list::List) }
4387}
4388
4389/// Get list size.
4390///
4391/// # UPSTREAM-PARITY
4392///
4393/// ```c
4394/// int xmlListSize(xmlListPtr list);
4395/// ```
4396#[no_mangle]
4397pub extern "C" fn xmlListSize(list: *mut c_void) -> c_int {
4398    unsafe { crate::xml::list::list_size(list as *mut crate::xml::list::List) }
4399}
4400
4401/// Sort a list.
4402#[no_mangle]
4403pub extern "C" fn xmlListSort(list: *mut c_void) {
4404    unsafe { crate::xml::list::list_sort(list as *mut crate::xml::list::List) }
4405}
4406
4407/// Reverse a list.
4408#[no_mangle]
4409pub extern "C" fn xmlListReverse(list: *mut c_void) {
4410    unsafe { crate::xml::list::list_reverse(list as *mut crate::xml::list::List) }
4411}
4412
4413/// Reverse a list in-place.
4414#[no_mangle]
4415pub extern "C" fn xmlListReverseSplice(list: *mut c_void, list2: *mut c_void) {
4416    unsafe {
4417        crate::xml::list::list_reverse_splice(
4418            list as *mut crate::xml::list::List,
4419            list2 as *mut crate::xml::list::List,
4420        )
4421    }
4422}
4423
4424/// Merge two sorted lists.
4425#[no_mangle]
4426pub extern "C" fn xmlListMerge(list: *mut c_void, list2: *mut c_void) {
4427    unsafe {
4428        crate::xml::list::list_merge(
4429            list as *mut crate::xml::list::List,
4430            list2 as *mut crate::xml::list::List,
4431        )
4432    }
4433}
4434/// Return the last element of a list (upstream list.h).
4435///
4436/// # UPSTREAM-PARITY
4437///
4438/// ```c
4439/// void *xmlListEnd(xmlListPtr l);
4440/// ```
4441#[no_mangle]
4442pub unsafe extern "C" fn xmlListEnd(l: *mut c_void) -> *mut c_void {
4443    crate::xml::list::list_end(l as *mut crate::xml::list::List)
4444}
4445
4446/// Reverse-search a list (upstream list.h).
4447///
4448/// # UPSTREAM-PARITY
4449///
4450/// ```c
4451/// void *xmlListReverseSearch(xmlListPtr l, void *data);
4452/// ```
4453#[no_mangle]
4454pub unsafe extern "C" fn xmlListReverseSearch(l: *mut c_void, data: *mut c_void) -> *mut c_void {
4455    crate::xml::list::list_reverse_search(l as *mut crate::xml::list::List, data)
4456}
4457
4458/// Walk a list in reverse (upstream list.h).
4459///
4460/// # UPSTREAM-PARITY
4461///
4462/// ```c
4463/// void xmlListReverseWalk(xmlListPtr l, xmlListWalker walker, void *data);
4464/// ```
4465#[no_mangle]
4466pub unsafe extern "C" fn xmlListReverseWalk(
4467    l: *mut c_void,
4468    walker: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
4469    data: *mut c_void,
4470) {
4471    crate::xml::list::list_reverse_walk(l as *mut crate::xml::list::List, walker, data)
4472}
4473
4474/// Duplicate a list (upstream list.h).
4475///
4476/// # UPSTREAM-PARITY
4477///
4478/// ```c
4479/// xmlListPtr xmlListDup(xmlListPtr l);
4480/// ```
4481#[no_mangle]
4482pub unsafe extern "C" fn xmlListDup(l: *mut c_void) -> *mut c_void {
4483    crate::xml::list::list_dup(l as *mut crate::xml::list::List) as *mut c_void
4484}
4485
4486/// Copy a list with a copier (upstream list.h).
4487///
4488/// # UPSTREAM-PARITY
4489///
4490/// ```c
4491/// int xmlListCopy(xmlListPtr l, xmlListCopier copier);
4492/// ```
4493#[no_mangle]
4494pub unsafe extern "C" fn xmlListCopy(
4495    l: *mut c_void,
4496    copier: Option<unsafe extern "C" fn(*mut c_void) -> *mut c_void>,
4497) -> c_int {
4498    crate::xml::list::list_copy(l as *mut crate::xml::list::List, copier)
4499}
4500
4501/// Return the data of a link (upstream list.h).
4502///
4503/// # UPSTREAM-PARITY
4504///
4505/// ```c
4506/// void *xmlLinkGetData(xmlLinkPtr lk);
4507/// ```
4508#[no_mangle]
4509pub unsafe extern "C" fn xmlLinkGetData(lk: *mut c_void) -> *mut c_void {
4510    crate::xml::list::link_get_data(lk)
4511}
4512
4513// ═══════════════════════════════════════════════════════════════════════════════
4514// 12. Buffer
4515// ═══════════════════════════════════════════════════════════════════════════════
4516
4517/// Create a new buffer.
4518///
4519/// # UPSTREAM-PARITY
4520///
4521/// ```c
4522/// xmlBufferPtr xmlBufferCreate(void);
4523/// ```
4524#[no_mangle]
4525pub extern "C" fn xmlBufferCreate() -> *mut _xmlBuffer {
4526    crate::xml::io::buf_create(-1)
4527}
4528
4529/// Create a new buffer of a given size.
4530///
4531/// # UPSTREAM-PARITY
4532///
4533/// ```c
4534/// xmlBufferPtr xmlBufferCreateSize(size_t size);
4535/// ```
4536#[no_mangle]
4537pub extern "C" fn xmlBufferCreateSize(size: usize) -> *mut _xmlBuffer {
4538    crate::xml::io::buf_create(size as c_int)
4539}
4540
4541/// Create a buffer from a static string.
4542///
4543/// # UPSTREAM-PARITY
4544///
4545/// ```c
4546/// xmlBufferPtr xmlBufferCreateStatic(void *mem, size_t size);
4547/// ```
4548#[no_mangle]
4549pub extern "C" fn xmlBufferCreateStatic(mem: *mut c_void, size: usize) -> *mut _xmlBuffer {
4550    if mem.is_null() || size == 0 {
4551        return ptr::null_mut();
4552    }
4553    crate::xml::io::buf_create_static(mem as *const xmlChar, size as c_int)
4554}
4555
4556/// Free a buffer.
4557///
4558/// # UPSTREAM-PARITY
4559///
4560/// ```c
4561/// void xmlBufferFree(xmlBufferPtr buf);
4562/// ```
4563#[no_mangle]
4564pub extern "C" fn xmlBufferFree(buf: *mut _xmlBuffer) {
4565    crate::xml::io::buf_free(buf)
4566}
4567
4568/// Empty a buffer.
4569///
4570/// # UPSTREAM-PARITY
4571///
4572/// ```c
4573/// void xmlBufferEmpty(xmlBufferPtr buf);
4574/// ```
4575#[no_mangle]
4576pub extern "C" fn xmlBufferEmpty(buf: *mut _xmlBuffer) {
4577    if buf.is_null() {
4578        return;
4579    }
4580    unsafe {
4581        if !(*buf).content.is_null() {
4582            *(*buf).content = 0;
4583        }
4584        (*buf).use_ = 0;
4585    }
4586}
4587
4588/// Get buffer content.
4589///
4590/// # UPSTREAM-PARITY
4591///
4592/// ```c
4593/// xmlChar *xmlBufferContent(const xmlBuffer *buf);
4594/// ```
4595#[no_mangle]
4596pub extern "C" fn xmlBufferContent(buf: *const _xmlBuffer) -> *mut xmlChar {
4597    crate::xml::io::buf_content(buf as *mut _xmlBuffer)
4598}
4599
4600/// Get buffer length.
4601///
4602/// # UPSTREAM-PARITY
4603///
4604/// ```c
4605/// int xmlBufferLength(const xmlBuffer *buf);
4606/// ```
4607#[no_mangle]
4608pub extern "C" fn xmlBufferLength(buf: *const _xmlBuffer) -> c_int {
4609    crate::xml::io::buf_length(buf as *mut _xmlBuffer)
4610}
4611
4612/// Write to a buffer.
4613///
4614/// # UPSTREAM-PARITY
4615///
4616/// ```c
4617/// int xmlBufferAdd(xmlBufferPtr buf, const xmlChar *str, int len);
4618/// ```
4619#[no_mangle]
4620pub unsafe extern "C" fn xmlBufferAdd(
4621    buf: *mut _xmlBuffer,
4622    str: *const xmlChar,
4623    len: c_int,
4624) -> c_int {
4625    crate::xml::io::buf_add(buf, str, len)
4626}
4627
4628/// Write to a buffer at a position.
4629///
4630/// # UPSTREAM-PARITY
4631///
4632/// ```c
4633/// int xmlBufferAddHead(xmlBufferPtr buf, const xmlChar *str, int len);
4634/// ```
4635#[no_mangle]
4636pub unsafe extern "C" fn xmlBufferAddHead(
4637    buf: *mut _xmlBuffer,
4638    str: *const xmlChar,
4639    len: c_int,
4640) -> c_int {
4641    crate::xml::io::buf_add_head(buf, str, len)
4642}
4643
4644/// Write a C string to a buffer.
4645///
4646/// # UPSTREAM-PARITY
4647///
4648/// ```c
4649/// int xmlBufferCat(xmlBufferPtr buf, const xmlChar *str);
4650/// ```
4651#[no_mangle]
4652pub unsafe extern "C" fn xmlBufferCat(buf: *mut _xmlBuffer, str: *const xmlChar) -> c_int {
4653    if str.is_null() {
4654        return -1;
4655    }
4656    let len = crate::xml::string::xml_strlen(str) as c_int;
4657    crate::xml::io::buf_add(buf, str, len)
4658}
4659
4660/// Set buffer allocation scheme.
4661///
4662/// # UPSTREAM-PARITY
4663///
4664/// ```c
4665/// void xmlBufferSetAllocationScheme(xmlBufferPtr buf,
4666///                                    xmlBufferAllocationScheme scheme);
4667/// ```
4668#[no_mangle]
4669pub extern "C" fn xmlBufferSetAllocationScheme(buf: *mut _xmlBuffer, scheme: c_int) {
4670    if buf.is_null() {
4671        return;
4672    }
4673    unsafe {
4674        (*buf).alloc = scheme;
4675    }
4676}
4677
4678/// Shrink buffer.
4679///
4680/// # UPSTREAM-PARITY
4681///
4682/// ```c
4683/// int xmlBufferShrink(xmlBufferPtr buf, int len);
4684/// ```
4685#[no_mangle]
4686pub extern "C" fn xmlBufferShrink(buf: *mut _xmlBuffer, len: c_int) -> c_int {
4687    if buf.is_null() || len <= 0 {
4688        return 0;
4689    }
4690    unsafe {
4691        let b = &mut *buf;
4692        let shrink_len = (len as c_uint).min(b.use_);
4693        if shrink_len > 0 {
4694            let remaining = b.use_ - shrink_len;
4695            if remaining > 0 {
4696                core::ptr::copy(
4697                    b.content.add(shrink_len as usize),
4698                    b.content,
4699                    remaining as usize,
4700                );
4701            }
4702            *b.content.add(remaining as usize) = 0;
4703            b.use_ = remaining;
4704        }
4705    }
4706    len
4707}
4708
4709/// Grow buffer.
4710///
4711/// # UPSTREAM-PARITY
4712///
4713/// ```c
4714/// int xmlBufferGrow(xmlBufferPtr buf, int len);
4715/// ```
4716#[no_mangle]
4717pub extern "C" fn xmlBufferGrow(buf: *mut _xmlBuffer, len: c_int) -> c_int {
4718    if buf.is_null() || len <= 0 {
4719        return 0;
4720    }
4721    let cur_use = unsafe { (*buf).use_ };
4722    let new_size = cur_use + len as c_uint + 1;
4723    crate::xml::io::buf_grow(buf, new_size)
4724}
4725
4726/// Reserve buffer space.
4727///
4728/// # UPSTREAM-PARITY
4729///
4730/// ```c
4731/// int xmlBufferReserve(xmlBufferPtr buf, int len);
4732/// ```
4733#[no_mangle]
4734pub extern "C" fn xmlBufferReserve(buf: *mut _xmlBuffer, len: c_int) -> c_int {
4735    xmlBufferGrow(buf, len)
4736}
4737
4738/// Detach buffer content.
4739///
4740/// # UPSTREAM-PARITY
4741///
4742/// ```c
4743/// xmlChar *xmlBufferDetach(xmlBufferPtr buf);
4744/// ```
4745#[no_mangle]
4746pub extern "C" fn xmlBufferDetach(buf: *mut _xmlBuffer) -> *mut xmlChar {
4747    if buf.is_null() {
4748        return ptr::null_mut();
4749    }
4750    unsafe {
4751        let content = (*buf).content;
4752        (*buf).content = ptr::null_mut();
4753        (*buf).use_ = 0;
4754        (*buf).size = 0;
4755        content
4756    }
4757}
4758
4759// ═══════════════════════════════════════════════════════════════════════════════
4760// 13. Encoding
4761// ═══════════════════════════════════════════════════════════════════════════════
4762
4763/// Get encoding from a name string.
4764///
4765/// # UPSTREAM-PARITY
4766///
4767/// ```c
4768/// xmlCharEncoding xmlGetCharEncoding(const char *name);
4769/// ```
4770#[no_mangle]
4771pub extern "C" fn xmlGetCharEncoding(name: *const c_char) -> c_int {
4772    if name.is_null() {
4773        return 0; // XML_CHAR_ENCODING_NONE
4774    }
4775    let name_bytes = unsafe {
4776        let len = libc::strlen(name);
4777        core::slice::from_raw_parts(name as *const u8, len)
4778    };
4779    crate::xml::encoding::encoding_from_name(name_bytes) as c_int
4780}
4781
4782/// Find an encoding handler.
4783///
4784/// # UPSTREAM-PARITY
4785///
4786/// ```c
4787/// xmlCharEncodingHandlerPtr xmlFindCharEncodingHandler(const char *name);
4788/// ```
4789#[no_mangle]
4790pub extern "C" fn xmlFindCharEncodingHandler(name: *const c_char) -> *mut c_void {
4791    if name.is_null() {
4792        return ptr::null_mut();
4793    }
4794    crate::xml::encoding::find_encoding_handler(name as *const xmlChar) as *mut c_void
4795}
4796
4797/// Close an encoding handler.
4798///
4799/// # UPSTREAM-PARITY
4800///
4801/// ```c
4802/// int xmlCharEncCloseFunc(xmlCharEncodingHandlerPtr handler);
4803/// ```
4804#[no_mangle]
4805pub extern "C" fn xmlCharEncCloseFunc(handler: *mut c_void) -> c_int {
4806    if handler.is_null() {
4807        return -1;
4808    }
4809    // Free the encoding handler
4810    unsafe {
4811        let h = handler as *mut crate::abi::structs::_xmlCharEncodingHandler;
4812        if !(*h).name.is_null() {
4813            crate::abi::allocator::xmlFree((*h).name as *mut c_void);
4814        }
4815        crate::abi::allocator::xmlFree(handler);
4816    }
4817    0
4818}
4819
4820/// Return the name of a character encoding (upstream encoding.h).
4821///
4822/// # UPSTREAM-PARITY
4823///
4824/// ```c
4825/// const char *xmlGetCharEncodingName(xmlCharEncoding enc);
4826/// ```
4827#[no_mangle]
4828pub extern "C" fn xmlGetCharEncodingName(enc: c_int) -> *const c_char {
4829    /* Values outside the local enum resolve against the upstream
4830     * defaultHandlers table (XML_CHAR_ENCODING_UTF16=23, HTML=24,
4831     * WINDOWS_1252=31); anything else is unknown (NULL). */
4832    if enc < -1 || enc > 22 {
4833        return match enc {
4834            23 => c"UTF-16".as_ptr(),
4835            24 => c"HTML".as_ptr(),
4836            31 => c"windows-1252".as_ptr(),
4837            _ => ptr::null(),
4838        };
4839    }
4840    let e: crate::abi::types::xmlCharEncoding = unsafe { core::mem::transmute(enc) };
4841    crate::xml::encoding::xmlGetCharEncodingName(e)
4842}
4843
4844/// Parse an encoding name into an xmlCharEncoding value (upstream encoding.h).
4845///
4846/// # UPSTREAM-PARITY
4847///
4848/// ```c
4849/// xmlCharEncoding xmlParseCharEncoding(const char *name);
4850/// ```
4851///
4852/// Returns the encoding value or XML_CHAR_ENCODING_ERROR (-1).
4853#[no_mangle]
4854pub extern "C" fn xmlParseCharEncoding(name: *const c_char) -> c_int {
4855    crate::xml::encoding::xmlParseCharEncoding(name)
4856}
4857
4858/// Add an encoding alias (upstream encoding.h).
4859///
4860/// # UPSTREAM-PARITY
4861///
4862/// ```c
4863/// int xmlAddEncodingAlias(const char *name, const char *alias);
4864/// ```
4865#[no_mangle]
4866pub extern "C" fn xmlAddEncodingAlias(name: *const c_char, alias: *const c_char) -> c_int {
4867    crate::xml::encoding::add_encoding_alias(name, alias)
4868}
4869
4870/// Delete an encoding alias (upstream encoding.h).
4871///
4872/// # UPSTREAM-PARITY
4873///
4874/// ```c
4875/// int xmlDelEncodingAlias(const char *alias);
4876/// ```
4877#[no_mangle]
4878pub extern "C" fn xmlDelEncodingAlias(alias: *const c_char) -> c_int {
4879    crate::xml::encoding::del_encoding_alias(alias)
4880}
4881
4882/// Look up an encoding alias (upstream encoding.h).
4883///
4884/// # UPSTREAM-PARITY
4885///
4886/// ```c
4887/// const char *xmlGetEncodingAlias(const char *alias);
4888/// ```
4889#[no_mangle]
4890pub extern "C" fn xmlGetEncodingAlias(alias: *const c_char) -> *const c_char {
4891    crate::xml::encoding::get_encoding_alias(alias)
4892}
4893
4894/// Clean up the encoding alias table (upstream encoding.h).
4895///
4896/// # UPSTREAM-PARITY
4897///
4898/// ```c
4899/// void xmlCleanupEncodingAliases(void);
4900/// ```
4901#[no_mangle]
4902pub extern "C" fn xmlCleanupEncodingAliases() {
4903    crate::xml::encoding::cleanup_encoding_aliases();
4904}
4905
4906/// Convert the input buffer using an encoding handler (upstream encoding.h).
4907///
4908/// # UPSTREAM-PARITY
4909///
4910/// ```c
4911/// int xmlCharEncInFunc(xmlCharEncodingHandler *handler,
4912///                      xmlBufferPtr out, xmlBufferPtr in);
4913/// ```
4914#[no_mangle]
4915pub extern "C" fn xmlCharEncInFunc(
4916    handler: *mut c_void,
4917    out: *mut c_void,
4918    in_: *mut c_void,
4919) -> c_int {
4920    crate::xml::encoding::xmlCharEncInFunc(
4921        handler as *mut crate::abi::structs::_xmlCharEncodingHandler,
4922        out as *mut crate::abi::structs::_xmlBuffer,
4923        in_ as *mut crate::abi::structs::_xmlBuffer,
4924    )
4925}
4926
4927/// Convert the output buffer using an encoding handler (upstream encoding.h).
4928///
4929/// # UPSTREAM-PARITY
4930///
4931/// ```c
4932/// int xmlCharEncOutFunc(xmlCharEncodingHandler *handler,
4933///                       xmlBufferPtr out, xmlBufferPtr in);
4934/// ```
4935#[no_mangle]
4936pub extern "C" fn xmlCharEncOutFunc(
4937    handler: *mut c_void,
4938    out: *mut c_void,
4939    in_: *mut c_void,
4940) -> c_int {
4941    crate::xml::encoding::xmlCharEncOutFunc(
4942        handler as *mut crate::abi::structs::_xmlCharEncodingHandler,
4943        out as *mut crate::abi::structs::_xmlBuffer,
4944        in_ as *mut crate::abi::structs::_xmlBuffer,
4945    )
4946}
4947
4948/// Create a new encoding handler (upstream encoding.h).
4949///
4950/// # UPSTREAM-PARITY
4951///
4952/// ```c
4953/// xmlCharEncodingHandlerPtr xmlNewCharEncodingHandler(
4954///     const char *name, xmlCharEncodingInputFunc input,
4955///     xmlCharEncodingOutputFunc output);
4956/// ```
4957#[no_mangle]
4958pub extern "C" fn xmlNewCharEncodingHandler(
4959    name: *const c_char,
4960    input: crate::abi::callbacks::xmlCharEncodingInputFunc,
4961    output: crate::abi::callbacks::xmlCharEncodingOutputFunc,
4962) -> *mut c_void {
4963    crate::xml::encoding::xmlNewCharEncodingHandler(name, input, output) as *mut c_void
4964}
4965
4966/// Initialize the built-in encoding handlers (upstream encoding.h).
4967///
4968/// # UPSTREAM-PARITY
4969///
4970/// ```c
4971/// void xmlInitCharEncodingHandlers(void);
4972/// ```
4973#[no_mangle]
4974pub extern "C" fn xmlInitCharEncodingHandlers() {
4975    crate::xml::encoding::xmlInitCharEncodingHandlers();
4976}
4977
4978/// Clean up the encoding handlers (upstream encoding.h).
4979///
4980/// # UPSTREAM-PARITY
4981///
4982/// ```c
4983/// void xmlCleanupCharEncodingHandlers(void);
4984/// ```
4985#[no_mangle]
4986pub extern "C" fn xmlCleanupCharEncodingHandlers() {
4987    crate::xml::encoding::xmlCleanupCharEncodingHandlers();
4988}
4989
4990/// Look up a built-in encoding handler by `xmlCharEncoding` value.
4991///
4992/// Returns an `xmlParserErrors` code; on success `*out` receives the static
4993/// handler (NULL for UTF-8, which needs no conversion).
4994///
4995/// # UPSTREAM-PARITY
4996///
4997/// ```c
4998/// xmlParserErrors xmlLookupCharEncodingHandler(xmlCharEncoding enc,
4999///                                              xmlCharEncodingHandler **out);
5000/// ```
5001#[no_mangle]
5002pub extern "C" fn xmlLookupCharEncodingHandler(enc: c_int, out: *mut *mut c_void) -> c_int {
5003    crate::xml::encoding::xmlLookupCharEncodingHandler(enc, out)
5004}
5005
5006/// Get the encoding handler for an `xmlCharEncoding` value (deprecated).
5007///
5008/// # UPSTREAM-PARITY
5009///
5010/// ```c
5011/// xmlCharEncodingHandler *xmlGetCharEncodingHandler(xmlCharEncoding enc);
5012/// ```
5013#[no_mangle]
5014pub extern "C" fn xmlGetCharEncodingHandler(enc: c_int) -> *mut c_void {
5015    crate::xml::encoding::xmlGetCharEncodingHandler(enc)
5016}
5017
5018/// Find or create an encoding handler by name for one conversion direction.
5019///
5020/// # UPSTREAM-PARITY
5021///
5022/// ```c
5023/// xmlParserErrors xmlOpenCharEncodingHandler(const char *name, int output,
5024///                                            xmlCharEncodingHandler **out);
5025/// ```
5026#[no_mangle]
5027pub extern "C" fn xmlOpenCharEncodingHandler(
5028    name: *const c_char,
5029    output: c_int,
5030    out: *mut *mut c_void,
5031) -> c_int {
5032    crate::xml::encoding::xmlOpenCharEncodingHandler(name, output, out)
5033}
5034
5035/// Find or create an encoding handler by name with flags and an optional
5036/// custom conversion implementation.
5037///
5038/// # UPSTREAM-PARITY
5039///
5040/// ```c
5041/// xmlParserErrors xmlCreateCharEncodingHandler(
5042///     const char *name, xmlCharEncFlags flags, xmlCharEncConvImpl impl,
5043///     void *implCtxt, xmlCharEncodingHandler **out);
5044/// ```
5045#[no_mangle]
5046pub extern "C" fn xmlCreateCharEncodingHandler(
5047    name: *const c_char,
5048    flags: c_int,
5049    impl_: Option<crate::abi::callbacks::xmlCharEncConvImpl>,
5050    implCtxt: *mut c_void,
5051    out: *mut *mut c_void,
5052) -> c_int {
5053    crate::xml::encoding::xmlCreateCharEncodingHandler(name, flags, impl_, implCtxt, out)
5054}
5055
5056/// Create an encoding handler backed by modern conversion callbacks.
5057///
5058/// # UPSTREAM-PARITY
5059///
5060/// ```c
5061/// xmlParserErrors xmlCharEncNewCustomHandler(
5062///     const char *name, xmlCharEncConvFunc input, xmlCharEncConvFunc output,
5063///     xmlCharEncConvCtxtDtor ctxtDtor, void *inputCtxt, void *outputCtxt,
5064///     xmlCharEncodingHandler **out);
5065/// ```
5066#[no_mangle]
5067pub extern "C" fn xmlCharEncNewCustomHandler(
5068    name: *const c_char,
5069    input: crate::abi::callbacks::xmlCharEncConvFunc,
5070    output: crate::abi::callbacks::xmlCharEncConvFunc,
5071    ctxtDtor: Option<crate::abi::callbacks::xmlCharEncConvCtxtDtor>,
5072    inputCtxt: *mut c_void,
5073    outputCtxt: *mut c_void,
5074    out: *mut *mut c_void,
5075) -> c_int {
5076    crate::xml::encoding::xmlCharEncNewCustomHandler(
5077        name, input, output, ctxtDtor, inputCtxt, outputCtxt, out,
5078    )
5079}
5080
5081/// Convert an input buffer's encoding.
5082///
5083/// # UPSTREAM-PARITY
5084///
5085/// ```c
5086/// int xmlCharEncInput(xmlParserInputBufferPtr input, int to);
5087/// ```
5088#[no_mangle]
5089pub unsafe extern "C" fn xmlCharEncInput(input: *mut _xmlParserInputBuffer, _to: c_int) -> c_int {
5090    if input.is_null() {
5091        return -1;
5092    }
5093    let handler = (*input).encoder as *mut crate::abi::structs::_xmlCharEncodingHandler;
5094    if handler.is_null() {
5095        return -1;
5096    }
5097    let raw = (*input).raw as *mut crate::abi::structs::_xmlBuffer;
5098    let buf = (*input).buffer as *mut crate::abi::structs::_xmlBuffer;
5099    if raw.is_null() || buf.is_null() {
5100        return -1;
5101    }
5102    crate::xml::encoding::char_enc_in(handler, buf, raw)
5103}
5104
5105/// Convert an output buffer's encoding.
5106///
5107/// # UPSTREAM-PARITY
5108///
5109/// ```c
5110/// int xmlCharEncOutput(xmlOutputBufferPtr output, int to);
5111/// ```
5112#[no_mangle]
5113pub unsafe extern "C" fn xmlCharEncOutput(output: *mut _xmlOutputBuffer, _to: c_int) -> c_int {
5114    if output.is_null() {
5115        return -1;
5116    }
5117    let handler = (*output).encoder as *mut crate::abi::structs::_xmlCharEncodingHandler;
5118    if handler.is_null() {
5119        return -1;
5120    }
5121    let buf = (*output).buffer as *mut crate::abi::structs::_xmlBuffer;
5122    let conv = (*output).conv as *mut crate::abi::structs::_xmlBuffer;
5123    if buf.is_null() || conv.is_null() {
5124        return -1;
5125    }
5126    crate::xml::encoding::char_enc_out(handler, conv, buf)
5127}
5128
5129// ═══════════════════════════════════════════════════════════════════════════════
5130// URI
5131// ═══════════════════════════════════════════════════════════════════════════════
5132
5133/// Parse a URI string.
5134///
5135/// # UPSTREAM-PARITY
5136///
5137/// ```c
5138/// xmlURIPtr xmlParseURI(const char *str);
5139/// ```
5140#[no_mangle]
5141pub unsafe extern "C" fn xmlParseURI(str: *const c_char) -> *mut c_void {
5142    crate::xml::uri::xmlParseURI(str)
5143}
5144
5145/// Parse a URI string (raw version).
5146///
5147/// # UPSTREAM-PARITY
5148///
5149/// ```c
5150/// xmlURIPtr xmlParseURIRaw(const char *str, int raw);
5151/// ```
5152#[no_mangle]
5153pub unsafe extern "C" fn xmlParseURIRaw(str: *const c_char, raw: c_int) -> *mut c_void {
5154    let _ = raw;
5155    crate::xml::uri::xmlParseURI(str)
5156}
5157
5158/// Free a URI structure.
5159///
5160/// # UPSTREAM-PARITY
5161///
5162/// ```c
5163/// void xmlFreeURI(xmlURIPtr uri);
5164/// ```
5165#[no_mangle]
5166pub unsafe extern "C" fn xmlFreeURI(uri: *mut c_void) {
5167    crate::xml::uri::xmlFreeURI(uri)
5168}
5169
5170/// Create an empty URI.
5171///
5172/// # UPSTREAM-PARITY
5173///
5174/// ```c
5175/// xmlURIPtr xmlCreateURI(void);
5176/// ```
5177#[no_mangle]
5178pub extern "C" fn xmlCreateURI() -> *mut c_void {
5179    crate::xml::uri::xmlCreateURI()
5180}
5181
5182/// Save a URI structure to a string.
5183///
5184/// # UPSTREAM-PARITY
5185///
5186/// ```c
5187/// xmlChar *xmlSaveUri(xmlURIPtr uri);
5188/// ```
5189#[no_mangle]
5190pub unsafe extern "C" fn xmlSaveUri(uri: *mut c_void) -> *mut xmlChar {
5191    crate::xml::uri::xmlSaveUri(uri)
5192}
5193
5194/// Parse a URI string into an existing URI structure (upstream uri.h).
5195///
5196/// # UPSTREAM-PARITY
5197///
5198/// ```c
5199/// int xmlParseURIReference(xmlURIPtr uri, const char *str);
5200/// ```
5201///
5202/// Returns 0 on success, -1 on failure (the URI structure is left
5203/// untouched on failure).
5204///
5205/// # Safety
5206///
5207/// - `uri` must be a valid pointer from `xmlParseURI`/`xmlCreateURI`.
5208/// - `str` must be a valid null-terminated C string.
5209#[no_mangle]
5210pub unsafe extern "C" fn xmlParseURIReference(uri: *mut c_void, str: *const c_char) -> c_int {
5211    crate::xml::uri::xmlParseURIReference(uri, str)
5212}
5213
5214/// Normalize a URI path in place (upstream uri.h).
5215///
5216/// # UPSTREAM-PARITY
5217///
5218/// ```c
5219/// int xmlNormalizeURIPath(char *path);
5220/// ```
5221///
5222/// Returns 0 on success, -1 if the path is NULL, not absolute, or contains
5223/// `..` segments that climb above the root.
5224///
5225/// # Safety
5226///
5227/// `path` must be a valid writable null-terminated C string buffer.
5228#[no_mangle]
5229pub unsafe extern "C" fn xmlNormalizeURIPath(path: *mut c_char) -> c_int {
5230    crate::xml::uri::xmlNormalizeURIPath(path)
5231}
5232
5233/// Escape a URI string.
5234///
5235/// # UPSTREAM-PARITY
5236///
5237/// ```c
5238/// xmlChar *xmlURIEscapeStr(const xmlChar *str, const xmlChar *list);
5239/// ```
5240#[no_mangle]
5241pub unsafe extern "C" fn xmlURIEscapeStr(
5242    str: *const xmlChar,
5243    list: *const xmlChar,
5244) -> *mut xmlChar {
5245    crate::xml::uri::xmlURIEscapeStr(str, list)
5246}
5247
5248/// Unescape a URI string.
5249///
5250/// # UPSTREAM-PARITY
5251///
5252/// ```c
5253/// char *xmlURIUnescapeString(const char *str, int len, char *target);
5254/// ```
5255#[no_mangle]
5256pub unsafe extern "C" fn xmlURIUnescapeString(
5257    str: *const c_char,
5258    len: c_int,
5259    target: *mut c_char,
5260) -> *mut c_char {
5261    crate::xml::uri::xmlURIUnescapeString(str, len, target)
5262}
5263
5264// ═══════════════════════════════════════════════════════════════════════════════
5265// 14. XPath
5266// ═══════════════════════════════════════════════════════════════════════════════
5267
5268// ── Helper functions ────────────────────────────────────────────────────
5269
5270/// Convert an internal `XPathValue` to a C ABI `_xmlXPathObject`.
5271///
5272/// The returned pointer is heap-allocated via `xmlMallocZero` and must be
5273/// freed with `xmlXPathFreeObject`.
5274///
5275/// # Safety
5276///
5277/// Must be called from a context where `xmlMalloc` is safe to call.
5278unsafe fn xpath_to_object(val: XPathValue) -> *mut _xmlXPathObject {
5279    let obj = xmlMallocZero(size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject;
5280    if obj.is_null() {
5281        return ptr::null_mut();
5282    }
5283    match val {
5284        XPathValue::NodeSet(ns) => {
5285            (*obj).type_ = xmlXPathObjectType::XPATH_NODESET as c_int;
5286            (*obj).nodesetval = ns.to_raw() as *mut c_void;
5287        }
5288        XPathValue::Boolean(b) => {
5289            (*obj).type_ = xmlXPathObjectType::XPATH_BOOLEAN as c_int;
5290            (*obj).boolval = if b { 1 } else { 0 };
5291        }
5292        XPathValue::Number(n) => {
5293            (*obj).type_ = xmlXPathObjectType::XPATH_NUMBER as c_int;
5294            (*obj).floatval = n;
5295        }
5296        XPathValue::String(s) => {
5297            (*obj).type_ = xmlXPathObjectType::XPATH_STRING as c_int;
5298            let bytes = s.as_bytes();
5299            let len = bytes.len();
5300            let buf = xmlMalloc(len + 1) as *mut xmlChar;
5301            if !buf.is_null() {
5302                ptr::copy_nonoverlapping(bytes.as_ptr(), buf, len);
5303                *buf.add(len) = 0; // null terminator
5304            }
5305            (*obj).stringval = buf;
5306        }
5307    }
5308    obj
5309}
5310
5311/// Extract an internal `XPathValue` from a C ABI `_xmlXPathObject`.
5312///
5313/// # Safety
5314///
5315/// `obj` must be a valid, non-null pointer to a properly initialised
5316/// `_xmlXPathObject`.
5317unsafe fn object_to_xpathvalue(obj: *mut _xmlXPathObject) -> XPathValue {
5318    let typ = (*obj).type_;
5319    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
5320        let ns_ptr = (*obj).nodesetval as *mut _xmlNodeSet;
5321        if ns_ptr.is_null() {
5322            return XPathValue::NodeSet(NodeSet::new());
5323        }
5324        let node_nr = (*ns_ptr).nodeNr;
5325        let node_tab = (*ns_ptr).nodeTab;
5326        let mut ns = NodeSet::new();
5327        if !node_tab.is_null() {
5328            for i in 0..node_nr as isize {
5329                let node = *node_tab.add(i as usize);
5330                ns.push(node);
5331            }
5332        }
5333        XPathValue::NodeSet(ns)
5334    } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
5335        XPathValue::Boolean((*obj).boolval != 0)
5336    } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
5337        XPathValue::Number((*obj).floatval)
5338    } else if typ == xmlXPathObjectType::XPATH_STRING as c_int {
5339        let s_ptr = (*obj).stringval;
5340        if s_ptr.is_null() {
5341            XPathValue::String(String::new())
5342        } else {
5343            let s = CStr::from_ptr(s_ptr as *const c_char)
5344                .to_string_lossy()
5345                .into_owned();
5346            XPathValue::String(s)
5347        }
5348    } else if typ == xmlXPathObjectType::XPATH_XSLT_TREE as c_int {
5349        // A result tree fragment: node-set containing the fragment's
5350        // document node (matching how global RTF variables are bound), so
5351        // local RTF variables stringify to their text and remain navigable
5352        // via exsl:node-set.
5353        let frag_doc = (*obj).nodesetval as *mut _xmlDoc;
5354        if frag_doc.is_null() {
5355            XPathValue::NodeSet(NodeSet::new())
5356        } else {
5357            let mut ns = NodeSet::new();
5358            ns.push(frag_doc as *mut _xmlNode);
5359            XPathValue::NodeSet(ns)
5360        }
5361    } else {
5362        // Undefined / unknown type — return boolean false as a safe default.
5363        XPathValue::Boolean(false)
5364    }
5365}
5366
5367/// Public wrapper for `xpath_to_object` (used by the XPath export bridge).
5368///
5369/// # Safety
5370///
5371/// - `val` is consumed and converted into a heap-allocated `_xmlXPathObject`.
5372pub unsafe fn xpath_to_object_pub(val: XPathValue) -> *mut _xmlXPathObject {
5373    xpath_to_object(val)
5374}
5375
5376/// Public wrapper for `object_to_xpathvalue` (used by the XSLT engine).
5377///
5378/// # Safety
5379///
5380/// `obj` must be a valid, non-null pointer to a properly initialised
5381/// `_xmlXPathObject`.
5382pub unsafe fn object_to_xpathvalue_pub(obj: *mut _xmlXPathObject) -> XPathValue {
5383    object_to_xpathvalue(obj)
5384}
5385
5386// ── Compiled expression registry ────────────────────────────────────────
5387//
5388// Compiled XPath expressions are opaque pointers returned by xmlXPathCompile.
5389// We store them in a global registry keyed by a monotonically increasing ID.
5390
5391static COMPILED_EXPRS: Lazy<Mutex<HashMap<u64, Box<CompiledExpr>>>> =
5392    Lazy::new(|| Mutex::new(HashMap::new()));
5393static NEXT_COMPILED_KEY: Lazy<Mutex<u64>> = Lazy::new(|| Mutex::new(1));
5394
5395/// Accessor for the compiled-expression registry (used by the XPath export
5396/// bridge for `xmlXPathCompiledEval` / `xmlXPathCompiledEvalToBoolean`).
5397pub(crate) fn xpath_compiled_registry() -> &'static Mutex<HashMap<u64, Box<CompiledExpr>>> {
5398    &COMPILED_EXPRS
5399}
5400
5401// ── C extension-function registry ──────────────────────────────────────
5402//
5403// C extension functions registered via xmlXPathRegisterFunc / RegisterFuncNS
5404// are stored here because the Rust XPathFunction signature is incompatible
5405// with the C xmlXPathFunction calling convention (the C function expects a
5406// parser context, not pre-evaluated argument slices). The registration is
5407// stored faithfully; invoking registered C functions from within the Rust
5408// evaluator requires a bridge that is not yet implemented.
5409
5410type CXPathFunc = unsafe extern "C" fn(*mut c_void, c_int);
5411
5412/// Wrapper around `*mut c_void` that implements `Send` + `Sync` so it can
5413/// be used as a key in a `Mutex`-protected global `HashMap`.
5414#[derive(Clone, Copy, PartialEq, Eq, Hash)]
5415struct SendSyncPtr(*mut c_void);
5416unsafe impl Send for SendSyncPtr {}
5417unsafe impl Sync for SendSyncPtr {}
5418
5419static C_FUNCTIONS: Lazy<Mutex<HashMap<(SendSyncPtr, String), CXPathFunc>>> =
5420    Lazy::new(|| Mutex::new(HashMap::new()));
5421
5422/// Look up a C-registered extension function for the context identified by
5423/// `extra` (the internal XPathContext pointer). Used by
5424/// `xmlXPathFunctionLookupNS`.
5425pub(crate) fn xpath_cfunc_lookup(extra: *mut c_void, qualified: &str) -> Option<CXPathFunc> {
5426    C_FUNCTIONS
5427        .lock()
5428        .get(&(SendSyncPtr(extra), qualified.to_string()))
5429        .copied()
5430}
5431
5432/// Drop every C extension-function registration belonging to the context
5433/// identified by `extra` (upstream `xmlXPathRegisteredFuncsCleanup`).
5434pub(crate) fn xpath_cfunc_cleanup(extra: *mut c_void) {
5435    C_FUNCTIONS.lock().retain(|(k, _), _| k.0 != extra);
5436}
5437
5438/// Rust-side wrapper that is registered in the internal XPathContext when a
5439/// C extension function is registered. It looks up the C function pointer and
5440/// attempts to call it, but the calling-convention mismatch means this is a
5441/// stub that returns an error for now.
5442fn c_func_stub(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
5443    Err(
5444        "C extension function cannot be called from Rust evaluator without a parser-context bridge"
5445            .to_string(),
5446    )
5447}
5448
5449// ── Public API ─────────────────────────────────────────────────────────
5450
5451/// Create a new XPath context.
5452///
5453/// Allocates a `_xmlXPathContext` and an internal `XPathContext`, storing
5454/// the latter's pointer in the `extra` field.
5455///
5456/// # UPSTREAM-PARITY
5457///
5458/// ```c
5459/// xmlXPathContextPtr xmlXPathNewContext(xmlDocPtr doc);
5460/// ```
5461#[no_mangle]
5462pub unsafe extern "C" fn xmlXPathNewContext(doc: *mut _xmlDoc) -> *mut _xmlXPathContext {
5463    let ctxt = xmlMallocZero(size_of::<_xmlXPathContext>()) as *mut _xmlXPathContext;
5464    if ctxt.is_null() {
5465        return ptr::null_mut();
5466    }
5467
5468    // Initialise the C ABI context fields.
5469    (*ctxt).doc = doc;
5470    (*ctxt).node = ptr::null_mut();
5471    (*ctxt).contextSize = 1;
5472    (*ctxt).proximityPosition = 1;
5473
5474    // Create the internal XPathContext and store it in `extra`.
5475    let mut internal = Box::new(XPathContext::new(doc));
5476    // UPSTREAM-PARITY: the standard function library is implicitly available
5477    // in every context (upstream compiles it in; xmlXPathRegisterAllFunctions
5478    // is a no-op since 2.14.0). Without this, core-function calls such as
5479    // count() would fail as unknown functions.
5480    for (name, func) in crate::xml::xpath::functions::core_functions() {
5481        internal.register_function(&name, func);
5482    }
5483    (*ctxt).extra = Box::into_raw(internal) as *mut c_void;
5484
5485    ctxt
5486}
5487
5488/// Free an XPath context.
5489///
5490/// # UPSTREAM-PARITY
5491///
5492/// ```c
5493/// void xmlXPathFreeContext(xmlXPathContextPtr ctxt);
5494/// ```
5495#[no_mangle]
5496pub unsafe extern "C" fn xmlXPathFreeContext(ctxt: *mut _xmlXPathContext) {
5497    if ctxt.is_null() {
5498        return;
5499    }
5500    // Drop the internal XPathContext.
5501    if !(*ctxt).extra.is_null() {
5502        let _ = Box::from_raw((*ctxt).extra as *mut XPathContext);
5503        (*ctxt).extra = ptr::null_mut();
5504    }
5505    // Drop the registered-namespace C-string hash (xmlXPathNsLookup pointers).
5506    if !(*ctxt).nsHash.is_null() {
5507        drop(Box::from_raw(
5508            (*ctxt).nsHash as *mut HashMap<String, CString>,
5509        ));
5510        (*ctxt).nsHash = ptr::null_mut();
5511    }
5512    // Free the C ABI context struct.
5513    xmlFree(ctxt as *mut c_void);
5514}
5515
5516/// Evaluate an XPath expression.
5517///
5518/// # UPSTREAM-PARITY
5519///
5520/// ```c
5521/// xmlXPathObjectPtr xmlXPathEvalExpression(const xmlChar *str,
5522///                                          xmlXPathContextPtr ctxt);
5523/// ```
5524#[no_mangle]
5525pub unsafe extern "C" fn xmlXPathEvalExpression(
5526    str_: *const xmlChar,
5527    ctxt: *mut _xmlXPathContext,
5528) -> *mut _xmlXPathObject {
5529    if str_.is_null() || ctxt.is_null() {
5530        return ptr::null_mut();
5531    }
5532    let expr_str = match CStr::from_ptr(str_ as *const c_char).to_str() {
5533        Ok(s) => s,
5534        Err(_) => return ptr::null_mut(),
5535    };
5536    let internal = (*ctxt).extra as *mut XPathContext;
5537    if internal.is_null() {
5538        return ptr::null_mut();
5539    }
5540    let internal = &mut *internal;
5541
5542    match crate::xml::xpath::evaluate_str(expr_str, internal) {
5543        Some(val) => xpath_to_object(val),
5544        None => {
5545            // UPSTREAM-PARITY: libxml2 reports a failed compile/eval with
5546            // "XPath error : Invalid expression" (xmlXPathErr,
5547            // XPATH_EXPR_ERROR). The precise per-expression diagnostics are
5548            // tracked as RESIDUAL R-XPATH-ERRMSG.
5549            if internal.error.is_none() {
5550                internal.set_error("Invalid expression");
5551            }
5552            ptr::null_mut()
5553        }
5554    }
5555}
5556
5557/// Evaluate an XPath expression (simplified alias).
5558///
5559/// # UPSTREAM-PARITY
5560///
5561/// ```c
5562/// xmlXPathObjectPtr xmlXPathEval(const xmlChar *str, xmlXPathContextPtr ctxt);
5563/// ```
5564#[no_mangle]
5565pub unsafe extern "C" fn xmlXPathEval(
5566    str_: *const xmlChar,
5567    ctxt: *mut _xmlXPathContext,
5568) -> *mut _xmlXPathObject {
5569    xmlXPathEvalExpression(str_, ctxt)
5570}
5571
5572/// Free an XPath object.
5573///
5574/// Releases the internal members (string buffer or node-set) and then frees
5575/// the object struct itself.
5576///
5577/// # UPSTREAM-PARITY
5578///
5579/// ```c
5580/// void xmlXPathFreeObject(xmlXPathObjectPtr obj);
5581/// ```
5582#[no_mangle]
5583pub unsafe extern "C" fn xmlXPathFreeObject(obj: *mut _xmlXPathObject) {
5584    if obj.is_null() {
5585        return;
5586    }
5587    let typ = (*obj).type_;
5588    // Free string storage.
5589    if typ == xmlXPathObjectType::XPATH_STRING as c_int {
5590        if !(*obj).stringval.is_null() {
5591            xmlFree((*obj).stringval as *mut c_void);
5592            (*obj).stringval = ptr::null_mut();
5593        }
5594    }
5595    // Free node-set storage.
5596    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
5597        let ns = (*obj).nodesetval as *mut _xmlNodeSet;
5598        if !ns.is_null() {
5599            if !(*ns).nodeTab.is_null() {
5600                xmlFree((*ns).nodeTab as *mut c_void);
5601            }
5602            xmlFree(ns as *mut c_void);
5603        }
5604        (*obj).nodesetval = ptr::null_mut();
5605    }
5606    xmlFree(obj as *mut c_void);
5607}
5608
5609/// Copy an XPath object (deep copy).
5610///
5611/// # UPSTREAM-PARITY
5612///
5613/// ```c
5614/// xmlXPathObjectPtr xmlXPathObjectCopy(xmlXPathObjectPtr val);
5615/// ```
5616///
5617/// Oracle behavior: returns a newly allocated object with the same type
5618/// and value. Node-sets are copied element-by-element; strings are
5619/// duplicated; numbers and booleans are copied by value.
5620#[no_mangle]
5621pub unsafe extern "C" fn xmlXPathObjectCopy(val: *mut _xmlXPathObject) -> *mut _xmlXPathObject {
5622    if val.is_null() {
5623        return ptr::null_mut();
5624    }
5625    let typ = (*val).type_;
5626    let obj = xmlMallocZero(size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject;
5627    if obj.is_null() {
5628        return ptr::null_mut();
5629    }
5630    (*obj).type_ = typ;
5631    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
5632        let src_ns = (*val).nodesetval as *mut _xmlNodeSet;
5633        if !src_ns.is_null() {
5634            let nr = (*src_ns).nodeNr;
5635            let ns = xmlMallocZero(size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
5636            if ns.is_null() {
5637                xmlFree(obj as *mut c_void);
5638                return ptr::null_mut();
5639            }
5640            (*ns).nodeNr = nr;
5641            (*ns).nodeMax = nr;
5642            if nr > 0 && !(*src_ns).nodeTab.is_null() {
5643                let tab = xmlMalloc((nr as usize) * core::mem::size_of::<*mut _xmlNode>())
5644                    as *mut *mut _xmlNode;
5645                if tab.is_null() {
5646                    xmlFree(ns as *mut c_void);
5647                    xmlFree(obj as *mut c_void);
5648                    return ptr::null_mut();
5649                }
5650                ptr::copy_nonoverlapping((*src_ns).nodeTab, tab, nr as usize);
5651                (*ns).nodeTab = tab;
5652            } else {
5653                (*ns).nodeTab = ptr::null_mut();
5654            }
5655            (*obj).nodesetval = ns as *mut c_void;
5656        }
5657    } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
5658        (*obj).boolval = (*val).boolval;
5659    } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
5660        (*obj).floatval = (*val).floatval;
5661    } else if typ == xmlXPathObjectType::XPATH_STRING as c_int {
5662        let src = (*val).stringval;
5663        if !src.is_null() {
5664            let len = libc::strlen(src as *const libc::c_char);
5665            let buf = xmlMalloc(len + 1) as *mut xmlChar;
5666            if !buf.is_null() {
5667                ptr::copy_nonoverlapping(src, buf, len);
5668                *buf.add(len) = 0;
5669            }
5670            (*obj).stringval = buf;
5671        }
5672    }
5673    obj
5674}
5675
5676/// Cast an XPath object to its string value.
5677///
5678/// Returns a newly allocated string (caller frees with `xmlFree`).
5679///
5680/// # UPSTREAM-PARITY
5681///
5682/// ```c
5683/// xmlChar *xmlXPathCastToString(xmlXPathObjectPtr val);
5684/// ```
5685#[no_mangle]
5686pub unsafe extern "C" fn xmlXPathCastToString(val: *mut _xmlXPathObject) -> *mut xmlChar {
5687    if val.is_null() {
5688        return ptr::null_mut();
5689    }
5690    let typ = (*val).type_;
5691    let mut result: Vec<u8> = Vec::new();
5692    if typ == xmlXPathObjectType::XPATH_STRING as c_int {
5693        if !(*val).stringval.is_null() {
5694            let len = libc::strlen((*val).stringval as *const libc::c_char);
5695            result.extend_from_slice(core::slice::from_raw_parts((*val).stringval, len));
5696        }
5697    } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
5698        // Number → string conversion per XPath 1.0 §4.2:
5699        // - NaN → "NaN"
5700        // - +0/-0 → "0"
5701        // - infinity → "Infinity" / "-Infinity"
5702        // - integer → decimal representation without exponent
5703        let n = (*val).floatval;
5704        result.extend_from_slice(xml_number_to_string(n).as_bytes());
5705    } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
5706        result.extend_from_slice(if (*val).boolval != 0 {
5707            b"true"
5708        } else {
5709            b"false"
5710        });
5711    } else if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
5712        // String value of a node-set is the string value of the first node
5713        // in document order (or empty if empty).
5714        let ns = (*val).nodesetval as *mut _xmlNodeSet;
5715        if !ns.is_null() && (*ns).nodeNr > 0 && !(*ns).nodeTab.is_null() {
5716            let node = *(*ns).nodeTab;
5717            if !node.is_null() {
5718                let content = crate::xml::tree::node_get_content(node);
5719                if !content.is_null() {
5720                    let len = libc::strlen(content as *const libc::c_char);
5721                    result.extend_from_slice(core::slice::from_raw_parts(content, len));
5722                    xmlFree(content as *mut c_void);
5723                }
5724            }
5725        }
5726    }
5727    // Allocate the C string.
5728    let buf = xmlMalloc(result.len() + 1) as *mut xmlChar;
5729    if buf.is_null() {
5730        return ptr::null_mut();
5731    }
5732    if !result.is_empty() {
5733        ptr::copy_nonoverlapping(result.as_ptr(), buf, result.len());
5734    }
5735    *buf.add(result.len()) = 0;
5736    buf
5737}
5738
5739/// Convert an XPath number to its string representation (XPath 1.0 §4.2).
5740///
5741/// Exposed as a helper; matches upstream `xmlXPathCastNumberToString`.
5742pub fn xml_number_to_string(n: f64) -> String {
5743    if n.is_nan() {
5744        return "NaN".to_string();
5745    }
5746    if n.is_infinite() {
5747        return if n > 0.0 {
5748            "Infinity".to_string()
5749        } else {
5750            "-Infinity".to_string()
5751        };
5752    }
5753    if n == 0.0 {
5754        // Both +0 and -0 serialize as "0" per XPath 1.0.
5755        return "0".to_string();
5756    }
5757    // Integer values serialize without a decimal point or exponent.
5758    if n.fract() == 0.0 && n.abs() < 1e15 {
5759        return format!("{:.0}", n);
5760    }
5761    // For other values, upstream uses %.15g-ish formatting with adjustments.
5762    // Try to find the shortest representation that round-trips (%.17g then
5763    // trim), which matches upstream's effective behavior for most inputs.
5764    let mut s = format!("{:.15}", n);
5765    // Trim trailing zeros and possible trailing dot.
5766    if s.contains('.') {
5767        while s.ends_with('0') {
5768            s.pop();
5769        }
5770        if s.ends_with('.') {
5771            s.pop();
5772        }
5773    }
5774    if s == "-0" {
5775        return "0".to_string();
5776    }
5777    s
5778}
5779
5780/// Cast a C string to a number per XPath 1.0 §4.2 conversion rules.
5781///
5782/// # UPSTREAM-PARITY
5783///
5784/// ```c
5785/// double xmlXPathCastStringToNumber(const xmlChar *val);
5786/// ```
5787#[no_mangle]
5788pub unsafe extern "C" fn xmlXPathCastStringToNumber(val: *const xmlChar) -> f64 {
5789    if val.is_null() {
5790        return f64::NAN;
5791    }
5792    let len = libc::strlen(val as *const libc::c_char);
5793    let bytes = core::slice::from_raw_parts(val, len);
5794    // Skip leading whitespace (XML whitespace per XPath 1.0).
5795    let mut i = 0;
5796    while i < bytes.len() && matches!(bytes[i], b' ' | b'\t' | b'\n' | b'\r') {
5797        i += 1;
5798    }
5799    let s = &bytes[i..];
5800    if s.is_empty() {
5801        return f64::NAN;
5802    }
5803    // Parse an optional sign.
5804    let (sign, rest) = match s[0] {
5805        b'+' => (1.0f64, &s[1..]),
5806        b'-' => (-1.0f64, &s[1..]),
5807        _ => (1.0f64, s),
5808    };
5809    if rest.is_empty() {
5810        return f64::NAN;
5811    }
5812    // Try full parse; if it fails (trailing junk), the value is NaN per spec.
5813    // XPath 1.0: a string that does not conform to the Number production is NaN.
5814    let num_str = core::str::from_utf8(rest);
5815    match num_str {
5816        Ok(s) => {
5817            // Accept only valid Number productions: digits with optional
5818            // fraction/exponent.
5819            let valid = is_xpath_number(s);
5820            if !valid {
5821                f64::NAN
5822            } else {
5823                s.trim()
5824                    .parse::<f64>()
5825                    .map(|v| v * sign)
5826                    .unwrap_or(f64::NAN)
5827            }
5828        }
5829        Err(_) => f64::NAN,
5830    }
5831}
5832
5833/// Check whether a string conforms to the XPath 1.0 Number production.
5834fn is_xpath_number(s: &str) -> bool {
5835    let b = s.as_bytes();
5836    if b.is_empty() {
5837        return false;
5838    }
5839    let mut i = 0;
5840    let mut saw_digit = false;
5841    while i < b.len() && b[i].is_ascii_digit() {
5842        saw_digit = true;
5843        i += 1;
5844    }
5845    if i < b.len() && b[i] == b'.' {
5846        i += 1;
5847        while i < b.len() && b[i].is_ascii_digit() {
5848            saw_digit = true;
5849            i += 1;
5850        }
5851    }
5852    if !saw_digit {
5853        return false;
5854    }
5855    if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
5856        i += 1;
5857        if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
5858            i += 1;
5859        }
5860        let mut saw_exp = false;
5861        while i < b.len() && b[i].is_ascii_digit() {
5862            saw_exp = true;
5863            i += 1;
5864        }
5865        if !saw_exp {
5866            return false;
5867        }
5868    }
5869    i == b.len()
5870}
5871
5872/// Compare two nodes in document order.
5873///
5874/// Returns negative if `node1` precedes `node2`, positive if it follows,
5875/// 0 if they are the same node.
5876///
5877/// # UPSTREAM-PARITY
5878///
5879/// ```c
5880/// int xmlXPathCmpNodes(xmlNodePtr node1, xmlNodePtr node2);
5881/// ```
5882///
5883/// Oracle behavior: uses ancestor comparison — if one node is an ancestor
5884/// of the other, the ancestor comes first; otherwise the nearest common
5885/// ancestor's child order determines the result.
5886#[no_mangle]
5887pub unsafe extern "C" fn xmlXPathCmpNodes(node1: *mut _xmlNode, node2: *mut _xmlNode) -> c_int {
5888    if node1.is_null() || node2.is_null() {
5889        return 0;
5890    }
5891    if node1 == node2 {
5892        return 0;
5893    }
5894    // Build ancestor chains.
5895    let mut chain1: Vec<*mut _xmlNode> = Vec::new();
5896    let mut chain2: Vec<*mut _xmlNode> = Vec::new();
5897    let mut n = node1;
5898    while !n.is_null() {
5899        chain1.push(n);
5900        n = (*n).parent as *mut _xmlNode;
5901    }
5902    let mut n = node2;
5903    while !n.is_null() {
5904        chain2.push(n);
5905        n = (*n).parent as *mut _xmlNode;
5906    }
5907    // Find the nearest common ancestor.
5908    let mut i = chain1.len();
5909    let mut j = chain2.len();
5910    while i > 0 && j > 0 && chain1[i - 1] == chain2[j - 1] {
5911        i -= 1;
5912        j -= 1;
5913    }
5914    if i == 0 && j == 0 {
5915        return 0; // Same node (already handled) or disjoint trees treated as equal
5916    }
5917    if i == 0 {
5918        return -1; // node1 is an ancestor of node2
5919    }
5920    if j == 0 {
5921        return 1; // node2 is an ancestor of node1
5922    }
5923    // Compare sibling order at the divergence point.
5924    let mut a = chain1[i - 1];
5925    let mut b = chain2[j - 1];
5926    // Climb to the same level.
5927    while !a.is_null() && !b.is_null() {
5928        let pa = (*a).parent as *mut _xmlNode;
5929        let pb = (*b).parent as *mut _xmlNode;
5930        if pa == pb {
5931            break;
5932        }
5933        a = pa;
5934        b = pb;
5935    }
5936    // Walk forward from the first child of the common parent.
5937    let parent = (*a).parent as *mut _xmlNode;
5938    let mut child = if parent.is_null() {
5939        ptr::null_mut()
5940    } else {
5941        (*parent).children
5942    };
5943    while !child.is_null() {
5944        if child == a {
5945            return -1;
5946        }
5947        if child == b {
5948            return 1;
5949        }
5950        child = (*child).next;
5951    }
5952    0
5953}
5954
5955/// Create a node-set from a range of an existing node-set.
5956///
5957/// # UPSTREAM-PARITY
5958///
5959/// ```c
5960/// xmlNodeSetPtr xmlXPathNodeSetCreate(xmlNodePtr val);
5961/// ```
5962///
5963/// With a null `val`, creates an empty node-set.
5964#[no_mangle]
5965pub unsafe extern "C" fn xmlXPathNodeSetCreate(val: *mut _xmlNode) -> *mut _xmlNodeSet {
5966    let ns = xmlMallocZero(size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
5967    if ns.is_null() {
5968        return ptr::null_mut();
5969    }
5970    if val.is_null() {
5971        return ns;
5972    }
5973    let tab = xmlMalloc(core::mem::size_of::<*mut _xmlNode>()) as *mut *mut _xmlNode;
5974    if tab.is_null() {
5975        xmlFree(ns as *mut c_void);
5976        return ptr::null_mut();
5977    }
5978    *tab = val;
5979    (*ns).nodeTab = tab;
5980    (*ns).nodeNr = 1;
5981    (*ns).nodeMax = 1;
5982    ns
5983}
5984
5985/// Free a node-set allocated by `xmlXPathNodeSetCreate` or a node-set
5986/// builder in this library.
5987///
5988/// Frees the node-set structure and its node table; the nodes themselves
5989/// are owned by their document and are not freed.
5990///
5991/// # UPSTREAM-PARITY
5992///
5993/// ```c
5994/// void xmlXPathFreeNodeSet(xmlNodeSetPtr ns);
5995/// ```
5996#[no_mangle]
5997pub unsafe extern "C" fn xmlXPathFreeNodeSet(ns: *mut _xmlNodeSet) {
5998    if ns.is_null() {
5999        return;
6000    }
6001    if !(*ns).nodeTab.is_null() {
6002        xmlFree((*ns).nodeTab as *mut c_void);
6003        (*ns).nodeTab = ptr::null_mut();
6004    }
6005    (*ns).nodeNr = 0;
6006    (*ns).nodeMax = 0;
6007    xmlFree(ns as *mut c_void);
6008}
6009
6010/// Compile an XPath expression.
6011///
6012/// Returns an opaque pointer that can be passed to `xmlXPathEvalExpression`
6013/// (via the compiled-expr infrastructure) or freed with `xmlXPathFreeCompExpr`.
6014///
6015/// # UPSTREAM-PARITY
6016///
6017/// ```c
6018/// xmlXPathCompExprPtr xmlXPathCompile(const xmlChar *str);
6019/// ```
6020#[no_mangle]
6021pub unsafe extern "C" fn xmlXPathCompile(str_: *const xmlChar) -> *mut c_void {
6022    if str_.is_null() {
6023        return ptr::null_mut();
6024    }
6025    let expr_str = match CStr::from_ptr(str_ as *const c_char).to_str() {
6026        Ok(s) => s,
6027        Err(_) => return ptr::null_mut(),
6028    };
6029
6030    match crate::xml::xpath::compile(expr_str) {
6031        Some(compiled) => {
6032            let mut map = COMPILED_EXPRS.lock();
6033            let mut counter = NEXT_COMPILED_KEY.lock();
6034            let key = *counter;
6035            *counter += 1;
6036            map.insert(key, Box::new(compiled));
6037            key as *mut c_void
6038        }
6039        None => ptr::null_mut(),
6040    }
6041}
6042
6043/// Free a compiled XPath expression.
6044///
6045/// # UPSTREAM-PARITY
6046///
6047/// ```c
6048/// void xmlXPathFreeCompExpr(xmlXPathCompExprPtr comp);
6049/// ```
6050#[no_mangle]
6051pub unsafe extern "C" fn xmlXPathFreeCompExpr(comp: *mut c_void) {
6052    if comp.is_null() {
6053        return;
6054    }
6055    let mut map = COMPILED_EXPRS.lock();
6056    map.remove(&(comp as u64));
6057}
6058
6059/// Register an XPath namespace.
6060///
6061/// # UPSTREAM-PARITY
6062///
6063/// ```c
6064/// int xmlXPathRegisterNs(xmlXPathContextPtr ctxt,
6065///                        const xmlChar *prefix, const xmlChar *ns_uri);
6066/// ```
6067#[no_mangle]
6068pub unsafe extern "C" fn xmlXPathRegisterNs(
6069    ctxt: *mut _xmlXPathContext,
6070    prefix: *const xmlChar,
6071    ns_uri: *const xmlChar,
6072) -> c_int {
6073    if ctxt.is_null() || prefix.is_null() || ns_uri.is_null() {
6074        return -1;
6075    }
6076    let internal = (*ctxt).extra as *mut XPathContext;
6077    if internal.is_null() {
6078        return -1;
6079    }
6080    let internal = &mut *internal;
6081
6082    let prefix_str = match CStr::from_ptr(prefix as *const c_char).to_str() {
6083        Ok(s) => s,
6084        Err(_) => return -1,
6085    };
6086    let uri_str = match CStr::from_ptr(ns_uri as *const c_char).to_str() {
6087        Ok(s) => s,
6088        Err(_) => return -1,
6089    };
6090
6091    internal.register_namespace(prefix_str, uri_str);
6092
6093    // Mirror the registration into the C context's nsHash (Box<HashMap<
6094    // String, CString>>): xmlXPathNsLookup hands out pointers into these
6095    // owned C strings, matching upstream ownership (strdup'd in nsHash,
6096    // freed by xmlXPathRegisteredNsCleanup / xmlXPathFreeContext).
6097    let map: &mut HashMap<String, CString> = if (*ctxt).nsHash.is_null() {
6098        let b: Box<HashMap<String, CString>> = Box::new(HashMap::new());
6099        (*ctxt).nsHash = Box::into_raw(b) as *mut c_void;
6100        &mut *((*ctxt).nsHash as *mut HashMap<String, CString>)
6101    } else {
6102        &mut *((*ctxt).nsHash as *mut HashMap<String, CString>)
6103    };
6104    map.insert(
6105        prefix_str.to_string(),
6106        CString::new(uri_str.as_bytes()).unwrap_or_default(),
6107    );
6108    0
6109}
6110
6111/// Register an XPath function.
6112///
6113/// The C function pointer is stored in a side table keyed by the context.
6114/// A Rust-side stub is registered in the internal context so that the Rust
6115/// evaluator is aware of the function; however, calling the C function
6116/// directly from the Rust evaluator is not yet supported.
6117///
6118/// # UPSTREAM-PARITY
6119///
6120/// ```c
6121/// int xmlXPathRegisterFunc(xmlXPathContextPtr ctxt,
6122///                          const xmlChar *name, xmlXPathFunction f);
6123/// ```
6124#[no_mangle]
6125pub unsafe extern "C" fn xmlXPathRegisterFunc(
6126    ctxt: *mut _xmlXPathContext,
6127    name: *const xmlChar,
6128    f: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
6129) -> c_int {
6130    if ctxt.is_null() || name.is_null() {
6131        return -1;
6132    }
6133    let internal = (*ctxt).extra as *mut XPathContext;
6134    if internal.is_null() {
6135        return -1;
6136    }
6137    let internal = &mut *internal;
6138
6139    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
6140        Ok(s) => s,
6141        Err(_) => return -1,
6142    };
6143
6144    if let Some(func) = f {
6145        // Store the C function pointer in the side table.
6146        let key = (SendSyncPtr((*ctxt).extra), name_str.to_string());
6147        C_FUNCTIONS.lock().insert(key, func);
6148        // Register a Rust stub so the evaluator knows the function exists.
6149        internal.register_function(name_str, c_func_stub);
6150    }
6151    0
6152}
6153
6154/// Register an XPath function with namespace.
6155///
6156/// # UPSTREAM-PARITY
6157///
6158/// ```c
6159/// int xmlXPathRegisterFuncNS(xmlXPathContextPtr ctxt,
6160///                            const xmlChar *name, const xmlChar *ns_uri,
6161///                            xmlXPathFunction f);
6162/// ```
6163#[no_mangle]
6164pub unsafe extern "C" fn xmlXPathRegisterFuncNS(
6165    ctxt: *mut _xmlXPathContext,
6166    name: *const xmlChar,
6167    ns_uri: *const xmlChar,
6168    f: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
6169) -> c_int {
6170    if ctxt.is_null() || name.is_null() {
6171        return -1;
6172    }
6173    let internal = (*ctxt).extra as *mut XPathContext;
6174    if internal.is_null() {
6175        return -1;
6176    }
6177    let internal = &mut *internal;
6178
6179    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
6180        Ok(s) => s,
6181        Err(_) => return -1,
6182    };
6183    let ns_str = if ns_uri.is_null() {
6184        String::new()
6185    } else {
6186        match CStr::from_ptr(ns_uri as *const c_char).to_str() {
6187            Ok(s) => s.to_string(),
6188            Err(_) => return -1,
6189        }
6190    };
6191
6192    // Use "{ns}:" prefix as part of the key to keep functions unique.
6193    let qualified = if ns_str.is_empty() {
6194        name_str.to_string()
6195    } else {
6196        format!("{{{}}}{}", ns_str, name_str)
6197    };
6198
6199    if let Some(func) = f {
6200        let key = (SendSyncPtr((*ctxt).extra), qualified.clone());
6201        C_FUNCTIONS.lock().insert(key, func);
6202        internal.register_function(&qualified, c_func_stub);
6203    }
6204    0
6205}
6206
6207/// Register an XPath variable.
6208///
6209/// # UPSTREAM-PARITY
6210///
6211/// ```c
6212/// int xmlXPathRegisterVariable(xmlXPathContextPtr ctxt,
6213///                              const xmlChar *name, xmlXPathObjectPtr value);
6214/// ```
6215#[no_mangle]
6216pub unsafe extern "C" fn xmlXPathRegisterVariable(
6217    ctxt: *mut _xmlXPathContext,
6218    name: *const xmlChar,
6219    value: *mut _xmlXPathObject,
6220) -> c_int {
6221    if ctxt.is_null() || name.is_null() || value.is_null() {
6222        return -1;
6223    }
6224    let internal = (*ctxt).extra as *mut XPathContext;
6225    if internal.is_null() {
6226        return -1;
6227    }
6228    let internal = &mut *internal;
6229
6230    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
6231        Ok(s) => s,
6232        Err(_) => return -1,
6233    };
6234
6235    let xpath_val = object_to_xpathvalue(value);
6236    internal.register_variable(name_str, xpath_val);
6237    0
6238}
6239
6240/// Create an XPath object wrapping a single node in a node-set.
6241///
6242/// # UPSTREAM-PARITY
6243///
6244/// ```c
6245/// xmlXPathObjectPtr xmlXPathNewNodeSet(xmlNodePtr val);
6246/// ```
6247#[no_mangle]
6248pub unsafe extern "C" fn xmlXPathNewNodeSet(val: *mut _xmlNode) -> *mut _xmlXPathObject {
6249    let ns = if val.is_null() {
6250        NodeSet::new()
6251    } else {
6252        NodeSet::singleton(val)
6253    };
6254    xpath_to_object(XPathValue::NodeSet(ns))
6255}
6256
6257/// Create an XPath object from a C string value.
6258///
6259/// # UPSTREAM-PARITY
6260///
6261/// ```c
6262/// xmlXPathObjectPtr xmlXPathNewCString(const xmlChar *val);
6263/// ```
6264#[no_mangle]
6265pub unsafe extern "C" fn xmlXPathNewCString(val: *const xmlChar) -> *mut _xmlXPathObject {
6266    if val.is_null() {
6267        return xpath_to_object(XPathValue::String(String::new()));
6268    }
6269    let s = match CStr::from_ptr(val as *const c_char).to_str() {
6270        Ok(s) => s.to_string(),
6271        Err(_) => return ptr::null_mut(),
6272    };
6273    xpath_to_object(XPathValue::String(s))
6274}
6275
6276/// Create an XPath number object.
6277///
6278/// # UPSTREAM-PARITY
6279///
6280/// ```c
6281/// xmlXPathObjectPtr xmlXPathNewFloat(double val);
6282/// ```
6283#[no_mangle]
6284pub extern "C" fn xmlXPathNewFloat(val: f64) -> *mut _xmlXPathObject {
6285    unsafe { xpath_to_object(XPathValue::Number(val)) }
6286}
6287
6288/// Create an XPath boolean object.
6289///
6290/// # UPSTREAM-PARITY
6291///
6292/// ```c
6293/// xmlXPathObjectPtr xmlXPathNewBoolean(int val);
6294/// ```
6295#[no_mangle]
6296pub extern "C" fn xmlXPathNewBoolean(val: c_int) -> *mut _xmlXPathObject {
6297    unsafe { xpath_to_object(XPathValue::Boolean(val != 0)) }
6298}
6299
6300// ═══════════════════════════════════════════════════════════════════════════════
6301// 14.5. XPointer
6302// ═══════════════════════════════════════════════════════════════════════════════
6303
6304/// Evaluate an XPointer expression.
6305///
6306/// Delegates to the xpointer module.
6307///
6308/// # UPSTREAM-PARITY
6309///
6310/// ```c
6311/// xmlNodePtr xmlXPtrEval(const xmlChar *expr, xmlDocPtr doc);
6312/// ```
6313#[no_mangle]
6314pub unsafe extern "C" fn xmlXPtrEval(expr: *const c_char, doc: *mut _xmlDoc) -> *mut _xmlNode {
6315    crate::xml::xpointer::xmlXPtrEval(expr, doc)
6316}
6317
6318// ═══════════════════════════════════════════════════════════════════════════════
6319// 15. XInclude
6320// ═══════════════════════════════════════════════════════════════════════════════
6321
6322/// Process XInclude nodes in a document.
6323///
6324/// # UPSTREAM-PARITY
6325///
6326/// ```c
6327/// int xmlXIncludeProcess(xmlDocPtr doc);
6328/// ```
6329#[no_mangle]
6330pub unsafe extern "C" fn xmlXIncludeProcess(doc: *mut _xmlDoc) -> c_int {
6331    crate::xml::xinclude::xinclude_process(doc)
6332}
6333
6334/// Process XInclude nodes with flags.
6335///
6336/// # UPSTREAM-PARITY
6337///
6338/// ```c
6339/// int xmlXIncludeProcessFlags(xmlDocPtr doc, int flags);
6340/// ```
6341#[no_mangle]
6342pub unsafe extern "C" fn xmlXIncludeProcessFlags(doc: *mut _xmlDoc, flags: c_int) -> c_int {
6343    crate::xml::xinclude::xinclude_process_flags(doc, flags)
6344}
6345
6346// ═══════════════════════════════════════════════════════════════════════════════
6347// 16. Catalog
6348// ═══════════════════════════════════════════════════════════════════════════════
6349
6350/// Load a catalog.
6351///
6352/// # UPSTREAM-PARITY
6353///
6354/// ```c
6355/// xmlCatalogPtr xmlCatalogLoad(const char *catalogs);
6356/// ```
6357#[no_mangle]
6358pub extern "C" fn xmlCatalogLoad(catalogs: *const c_char) -> *mut c_void {
6359    if catalogs.is_null() {
6360        return ptr::null_mut();
6361    }
6362    crate::xml::catalog::load_catalog(catalogs)
6363}
6364
6365/// Resolve a public ID.
6366///
6367/// # UPSTREAM-PARITY
6368///
6369/// ```c
6370/// xmlCharPtr xmlCatalogResolvePublic(const xmlChar *pubID);
6371/// ```
6372#[no_mangle]
6373pub unsafe extern "C" fn xmlCatalogResolvePublic(pubID: *const xmlChar) -> *mut xmlChar {
6374    if pubID.is_null() {
6375        return ptr::null_mut();
6376    }
6377    crate::xml::catalog::resolve_public(pubID)
6378}
6379
6380/// Resolve a system ID.
6381///
6382/// # UPSTREAM-PARITY
6383///
6384/// ```c
6385/// xmlCharPtr xmlCatalogResolveSystem(const xmlChar *sysID);
6386/// ```
6387#[no_mangle]
6388pub unsafe extern "C" fn xmlCatalogResolveSystem(sysID: *const xmlChar) -> *mut xmlChar {
6389    if sysID.is_null() {
6390        return ptr::null_mut();
6391    }
6392    crate::xml::catalog::resolve_system(sysID)
6393}
6394
6395/// Resolve a URI.
6396///
6397/// # UPSTREAM-PARITY
6398///
6399/// ```c
6400/// xmlCharPtr xmlCatalogResolveURI(const xmlChar *URI);
6401/// ```
6402#[no_mangle]
6403pub unsafe extern "C" fn xmlCatalogResolveURI(URI: *const xmlChar) -> *mut xmlChar {
6404    if URI.is_null() {
6405        return ptr::null_mut();
6406    }
6407    crate::xml::catalog::resolve_uri(URI)
6408}
6409
6410/// Set catalog defaults.
6411///
6412/// # UPSTREAM-PARITY
6413///
6414/// ```c
6415/// void xmlCatalogSetDefaults(xmlCatalogAllowValue allow);
6416/// ```
6417#[no_mangle]
6418pub extern "C" fn xmlCatalogSetDefaults(allow: c_int) {
6419    crate::xml::catalog::set_defaults(allow)
6420}
6421
6422/// Get catalog defaults.
6423///
6424/// # UPSTREAM-PARITY
6425///
6426/// ```c
6427/// xmlCatalogAllowValue xmlCatalogGetDefaults(void);
6428/// ```
6429#[no_mangle]
6430pub extern "C" fn xmlCatalogGetDefaults() -> c_int {
6431    crate::xml::catalog::get_defaults()
6432}
6433
6434/// Add a catalog.
6435///
6436/// # UPSTREAM-PARITY
6437///
6438/// ```c
6439/// int xmlCatalogAdd(const xmlChar *type, const xmlChar *orig, const xmlChar *replace);
6440/// ```
6441#[no_mangle]
6442pub unsafe extern "C" fn xmlCatalogAdd(
6443    type_: *const xmlChar,
6444    orig: *const xmlChar,
6445    replace: *const xmlChar,
6446) -> c_int {
6447    if type_.is_null() || orig.is_null() || replace.is_null() {
6448        return -1;
6449    }
6450    crate::xml::catalog::add(type_, orig, replace)
6451}
6452
6453/// Remove a catalog entry.
6454///
6455/// # UPSTREAM-PARITY
6456///
6457/// ```c
6458/// int xmlCatalogRemove(const xmlChar *value);
6459/// ```
6460#[no_mangle]
6461pub unsafe extern "C" fn xmlCatalogRemove(value: *const xmlChar) -> c_int {
6462    if value.is_null() {
6463        return 0;
6464    }
6465    crate::xml::catalog::remove(value)
6466}
6467
6468/// Dump the catalog in XML format to a FILE* (upstream `xmlCatalogDump`).
6469///
6470/// # UPSTREAM-PARITY
6471///
6472/// ```c
6473/// void xmlCatalogDump(FILE *out, xmlCatalogPtr catal);
6474/// ```
6475#[no_mangle]
6476pub unsafe extern "C" fn xmlCatalogDump(output: *mut c_void, _catal: *mut c_void) {
6477    if output.is_null() {
6478        return;
6479    }
6480    let doc = crate::xml::catalog::dump_doc();
6481    if doc.is_null() {
6482        return;
6483    }
6484    let mut mem: *mut xmlChar = ptr::null_mut();
6485    let mut size: c_int = 0;
6486    crate::xml::tree::xmlDocDumpFormatMemory(doc, &mut mem, &mut size, 1);
6487    if !mem.is_null() {
6488        libc::fwrite(
6489            mem as *const c_void,
6490            1,
6491            size as usize,
6492            output as *mut libc::FILE,
6493        );
6494        xmlFree(mem as *mut c_void);
6495    }
6496    crate::xml::tree::free_doc(doc);
6497}
6498
6499/// Save the catalog to a file (upstream `xmlCatalogSave`).
6500///
6501/// Returns 0 on success, -1 on failure.
6502///
6503/// # UPSTREAM-PARITY
6504///
6505/// ```c
6506/// int xmlCatalogSave(const char *filename);
6507/// ```
6508#[no_mangle]
6509pub unsafe extern "C" fn xmlCatalogSave(filename: *const c_char) -> c_int {
6510    if filename.is_null() {
6511        return -1;
6512    }
6513    let doc = crate::xml::catalog::dump_doc();
6514    if doc.is_null() {
6515        return -1;
6516    }
6517    let mut mem: *mut xmlChar = ptr::null_mut();
6518    let mut size: c_int = 0;
6519    crate::xml::tree::xmlDocDumpFormatMemory(doc, &mut mem, &mut size, 1);
6520    let mut ret: c_int = -1;
6521    if !mem.is_null() {
6522        let fp = libc::fopen(filename, b"w\0".as_ptr() as *const c_char);
6523        if !fp.is_null() {
6524            let written = libc::fwrite(mem as *const c_void, 1, size as usize, fp);
6525            ret = if written == size as usize { 0 } else { -1 };
6526            libc::fclose(fp);
6527        }
6528        xmlFree(mem as *mut c_void);
6529    }
6530    crate::xml::tree::free_doc(doc);
6531    ret
6532}
6533
6534/// Clean up the catalog subsystem.
6535///
6536/// # UPSTREAM-PARITY
6537///
6538/// ```c
6539/// void xmlCatalogCleanup(void);
6540/// ```
6541#[no_mangle]
6542pub extern "C" fn xmlCatalogCleanup() {
6543    crate::xml::catalog::cleanup();
6544}
6545
6546/// Convert an SGML catalog to XML.
6547///
6548/// # UPSTREAM-PARITY
6549///
6550/// ```c
6551/// xmlDocPtr xmlCatalogConvert(void);
6552/// ```
6553#[no_mangle]
6554pub extern "C" fn xmlCatalogConvert() -> *mut _xmlDoc {
6555    // SAFETY: catalog::convert() allocates and builds an XML document tree.
6556    unsafe { crate::xml::catalog::convert() }
6557}
6558
6559// ═══════════════════════════════════════════════════════════════════════════════
6560// 17. HTML
6561// ═══════════════════════════════════════════════════════════════════════════════
6562
6563/// Parse an HTML document from a file.
6564///
6565/// # UPSTREAM-PARITY
6566///
6567/// ```c
6568/// htmlDocPtr htmlParseFile(const char *filename, const char *encoding);
6569/// ```
6570#[no_mangle]
6571pub unsafe extern "C" fn htmlParseFile(
6572    _filename: *const c_char,
6573    _encoding: *const c_char,
6574) -> *mut _xmlDoc {
6575    // Phase 1: STUB
6576    ptr::null_mut()
6577}
6578
6579/// Parse an HTML document from memory.
6580///
6581/// # UPSTREAM-PARITY
6582///
6583/// ```c
6584/// htmlDocPtr htmlParseMemory(const char *buffer, int size);
6585/// ```
6586#[no_mangle]
6587pub unsafe extern "C" fn htmlParseMemory(_buffer: *const c_char, _size: c_int) -> *mut _xmlDoc {
6588    // Phase 1: STUB
6589    ptr::null_mut()
6590}
6591
6592/// Parse an HTML document from a document string.
6593///
6594/// # UPSTREAM-PARITY
6595///
6596/// ```c
6597/// htmlDocPtr htmlParseDoc(const xmlChar *cur, const char *encoding);
6598/// ```
6599#[no_mangle]
6600pub unsafe extern "C" fn htmlParseDoc(
6601    _cur: *const xmlChar,
6602    _encoding: *const c_char,
6603) -> *mut _xmlDoc {
6604    // Phase 1: STUB
6605    ptr::null_mut()
6606}
6607
6608/// Create an HTML parser context.
6609///
6610/// # UPSTREAM-PARITY
6611///
6612/// ```c
6613/// htmlParserCtxtPtr htmlCreateFileParserCtxt(const char *filename,
6614///                                            const char *encoding);
6615/// ```
6616#[no_mangle]
6617pub unsafe extern "C" fn htmlCreateFileParserCtxt(
6618    _filename: *const c_char,
6619    _encoding: *const c_char,
6620) -> *mut c_void {
6621    // Phase 1: STUB
6622    ptr::null_mut()
6623}
6624
6625/// Free an HTML parser context.
6626///
6627/// # UPSTREAM-PARITY
6628///
6629/// ```c
6630/// void htmlFreeParserCtxt(htmlParserCtxtPtr ctxt);
6631/// ```
6632#[no_mangle]
6633pub extern "C" fn htmlFreeParserCtxt(ctxt: *mut c_void) {
6634    unsafe { crate::xml::html::free_parser_ctxt(ctxt) }
6635}
6636
6637/// Initialize the HTML parser.
6638///
6639/// # UPSTREAM-PARITY
6640///
6641/// ```c
6642/// void htmlInitParser(void);
6643/// ```
6644#[no_mangle]
6645pub extern "C" fn htmlInitParser() {
6646    // Phase 1: STUB
6647}
6648
6649/// Clean up the HTML parser.
6650///
6651/// # UPSTREAM-PARITY
6652///
6653/// ```c
6654/// void htmlCleanupParser(void);
6655/// ```
6656#[no_mangle]
6657pub extern "C" fn htmlCleanupParser() {
6658    // Phase 1: STUB
6659}
6660
6661// ═══════════════════════════════════════════════════════════════════════════════
6662// 17.5. Validation (DTD)
6663// ═══════════════════════════════════════════════════════════════════════════════
6664
6665/// Create a new validation context.
6666///
6667/// # UPSTREAM-PARITY
6668///
6669/// ```c
6670/// xmlValidCtxtPtr xmlNewValidCtxt(void);
6671/// ```
6672#[no_mangle]
6673pub unsafe extern "C" fn xmlNewValidCtxt() -> *mut _xmlValidCtxt {
6674    crate::xml::validation::new_valid_ctxt()
6675}
6676
6677/// Free a validation context.
6678///
6679/// # UPSTREAM-PARITY
6680///
6681/// ```c
6682/// void xmlFreeValidCtxt(xmlValidCtxtPtr ctxt);
6683/// ```
6684#[no_mangle]
6685pub unsafe extern "C" fn xmlFreeValidCtxt(ctxt: *mut _xmlValidCtxt) {
6686    crate::xml::validation::free_valid_ctxt(ctxt);
6687}
6688
6689/// Set error and warning callbacks on a validation context.
6690///
6691/// # UPSTREAM-PARITY
6692///
6693/// ```c
6694/// void xmlSetValidErrors(xmlValidCtxtPtr ctxt,
6695///                        xmlGenericErrorFunc err,
6696///                        xmlGenericErrorFunc warn,
6697///                        void *data);
6698/// ```
6699#[no_mangle]
6700pub unsafe extern "C" fn xmlSetValidErrors(
6701    ctxt: *mut _xmlValidCtxt,
6702    err: Option<xmlGenericErrorFunc>,
6703    warn: Option<xmlGenericErrorFunc>,
6704    data: *mut c_void,
6705) {
6706    crate::xml::validation::set_valid_errors(ctxt, err, warn, data);
6707}
6708
6709/// Validate a document against its DTD.
6710///
6711/// # UPSTREAM-PARITY
6712///
6713/// ```c
6714/// int xmlValidateDocument(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
6715/// ```
6716#[no_mangle]
6717pub unsafe extern "C" fn xmlValidateDocument(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
6718    crate::xml::validation::validate_document(ctxt, doc)
6719}
6720
6721/// Final validation pass (check ID/IDREF consistency).
6722///
6723/// # UPSTREAM-PARITY
6724///
6725/// ```c
6726/// int xmlValidateDocumentFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
6727/// ```
6728#[no_mangle]
6729pub unsafe extern "C" fn xmlValidateDocumentFinal(
6730    ctxt: *mut _xmlValidCtxt,
6731    doc: *mut _xmlDoc,
6732) -> c_int {
6733    crate::xml::validation::validate_document_final(ctxt, doc)
6734}
6735
6736/// Validate an element node against its DTD declarations.
6737///
6738/// # UPSTREAM-PARITY
6739///
6740/// ```c
6741/// int xmlValidateElement(xmlValidCtxtPtr ctxt,
6742///                        xmlDocPtr doc,
6743///                        xmlNodePtr elem);
6744/// ```
6745#[no_mangle]
6746pub unsafe extern "C" fn xmlValidateElement(
6747    ctxt: *mut _xmlValidCtxt,
6748    doc: *mut _xmlDoc,
6749    elem: *mut _xmlNode,
6750) -> c_int {
6751    crate::xml::validation::validate_element(ctxt, doc, elem)
6752}
6753
6754/// Validate an attribute declaration.
6755///
6756/// # UPSTREAM-PARITY
6757///
6758/// ```c
6759/// int xmlValidateAttributeDecl(xmlValidCtxtPtr ctxt,
6760///                              xmlDocPtr doc,
6761///                              xmlNodePtr elem,
6762///                              xmlAttributePtr attr);
6763/// ```
6764#[no_mangle]
6765pub unsafe extern "C" fn xmlValidateAttributeDecl(
6766    ctxt: *mut _xmlValidCtxt,
6767    doc: *mut _xmlDoc,
6768    elem: *mut _xmlNode,
6769    attr: *mut _xmlAttribute,
6770) -> c_int {
6771    crate::xml::validation::validate_attribute_decl(ctxt, doc, elem, attr)
6772}
6773
6774/// Validate an attribute value against its declared type.
6775///
6776/// # UPSTREAM-PARITY
6777///
6778/// ```c
6779/// int xmlValidateAttributeValue(int type, const xmlChar *value);
6780/// ```
6781#[no_mangle]
6782pub unsafe extern "C" fn xmlValidateAttributeValue(atype: c_int, value: *const xmlChar) -> c_int {
6783    crate::xml::validation::validate_attribute_value(atype, value)
6784}
6785
6786/// Validate a NOTATION reference.
6787///
6788/// # UPSTREAM-PARITY
6789///
6790/// ```c
6791/// int xmlValidateNotationUse(xmlValidCtxtPtr ctxt,
6792///                            xmlDocPtr doc,
6793///                            const xmlChar *notationName);
6794/// ```
6795#[no_mangle]
6796pub unsafe extern "C" fn xmlValidateNotationUse(
6797    ctxt: *mut _xmlValidCtxt,
6798    doc: *mut _xmlDoc,
6799    notation_name: *const xmlChar,
6800) -> c_int {
6801    crate::xml::validation::validate_notation_use(ctxt, doc, notation_name)
6802}
6803
6804/// Validate an ID value (check uniqueness).
6805///
6806/// # UPSTREAM-PARITY
6807///
6808/// ```c
6809/// int xmlValidateID(xmlValidCtxtPtr ctxt,
6810///                   xmlDocPtr doc,
6811///                   xmlNodePtr node,
6812///                   const xmlChar *value);
6813/// ```
6814#[no_mangle]
6815pub unsafe extern "C" fn xmlValidateID(
6816    ctxt: *mut _xmlValidCtxt,
6817    doc: *mut _xmlDoc,
6818    node: *mut _xmlNode,
6819    value: *const xmlChar,
6820) -> c_int {
6821    crate::xml::validation::validate_id(ctxt, doc, node, value)
6822}
6823
6824/// Validate an IDREF value (check it references a known ID).
6825///
6826/// # UPSTREAM-PARITY
6827///
6828/// ```c
6829/// int xmlValidateIDRef(xmlValidCtxtPtr ctxt,
6830///                      xmlDocPtr doc,
6831///                      xmlNodePtr node,
6832///                      const xmlChar *value);
6833/// ```
6834#[no_mangle]
6835pub unsafe extern "C" fn xmlValidateIDRef(
6836    ctxt: *mut _xmlValidCtxt,
6837    doc: *mut _xmlDoc,
6838    node: *mut _xmlNode,
6839    value: *const xmlChar,
6840) -> c_int {
6841    crate::xml::validation::validate_id_ref(ctxt, doc, node, value)
6842}
6843
6844/// Validate IDREFS (whitespace-separated list of IDREFs).
6845///
6846/// # UPSTREAM-PARITY
6847///
6848/// ```c
6849/// int xmlValidateIDRefs(xmlValidCtxtPtr ctxt,
6850///                       xmlDocPtr doc,
6851///                       xmlNodePtr node,
6852///                       const xmlChar *value);
6853/// ```
6854#[no_mangle]
6855pub unsafe extern "C" fn xmlValidateIDRefs(
6856    ctxt: *mut _xmlValidCtxt,
6857    doc: *mut _xmlDoc,
6858    node: *mut _xmlNode,
6859    value: *const xmlChar,
6860) -> c_int {
6861    crate::xml::validation::validate_id_refs(ctxt, doc, node, value)
6862}
6863
6864/// Validate an NCName value (modern 2-arg form, upstream tree.c).
6865///
6866/// # UPSTREAM-PARITY
6867///
6868/// ```c
6869/// int xmlValidateNCName(const xmlChar *value, int space);
6870/// ```
6871///
6872/// Returns -1 on NULL, 0 if valid, 1 if invalid.
6873#[no_mangle]
6874pub unsafe extern "C" fn xmlValidateNCName(value: *const xmlChar, space: c_int) -> c_int {
6875    crate::xml::validation::validate_ncname(value, space)
6876}
6877
6878/// Validate a QName value (modern 2-arg form, upstream tree.c).
6879///
6880/// # UPSTREAM-PARITY
6881///
6882/// ```c
6883/// int xmlValidateQName(const xmlChar *value, int space);
6884/// ```
6885#[no_mangle]
6886pub unsafe extern "C" fn xmlValidateQName(value: *const xmlChar, space: c_int) -> c_int {
6887    crate::xml::validation::validate_qname(value, space)
6888}
6889
6890/// Validate an XML Name value (modern 2-arg form, upstream tree.c).
6891///
6892/// # UPSTREAM-PARITY / HISTORICAL
6893///
6894/// Since libxml2 2.12 the DSO symbol carries a second `int space` parameter
6895/// with inverted return semantics (0 valid / 1 invalid / -1 NULL); the
6896/// pre-2.12 1-arg form no longer exists in the DSO. The candidate matches
6897/// the current oracle. (The 1-arg semantics live on as xmlValidateNameValue.)
6898///
6899/// ```c
6900/// int xmlValidateName(const xmlChar *value, int space);
6901/// ```
6902#[no_mangle]
6903pub unsafe extern "C" fn xmlValidateName(value: *const xmlChar, space: c_int) -> c_int {
6904    crate::xml::validation::validate_name_space(value, space)
6905}
6906
6907/// Validate an NMToken value (modern 2-arg form, upstream tree.c).
6908///
6909/// # UPSTREAM-PARITY
6910///
6911/// ```c
6912/// int xmlValidateNMToken(const xmlChar *value, int space);
6913/// ```
6914#[no_mangle]
6915pub unsafe extern "C" fn xmlValidateNMToken(value: *const xmlChar, space: c_int) -> c_int {
6916    crate::xml::validation::validate_nmtoken_space(value, space)
6917}
6918
6919/// Validate a Name value (1-arg form, upstream valid.c).
6920///
6921/// # UPSTREAM-PARITY
6922///
6923/// ```c
6924/// int xmlValidateNameValue(const xmlChar *value);
6925/// ```
6926///
6927/// Returns 1 if valid, 0 if not (NULL included).
6928#[no_mangle]
6929pub unsafe extern "C" fn xmlValidateNameValue(value: *const xmlChar) -> c_int {
6930    crate::xml::validation::validate_name_value(value)
6931}
6932
6933/// Validate a whitespace-separated list of Names (separator is exactly
6934/// 0x20, upstream erratum E20).
6935///
6936/// # UPSTREAM-PARITY
6937///
6938/// ```c
6939/// int xmlValidateNamesValue(const xmlChar *value);
6940/// ```
6941#[no_mangle]
6942pub unsafe extern "C" fn xmlValidateNamesValue(value: *const xmlChar) -> c_int {
6943    crate::xml::validation::validate_names_value(value)
6944}
6945
6946/// Validate an Nmtoken value (1-arg form, upstream valid.c).
6947///
6948/// # UPSTREAM-PARITY
6949///
6950/// ```c
6951/// int xmlValidateNmtokenValue(const xmlChar *value);
6952/// ```
6953#[no_mangle]
6954pub unsafe extern "C" fn xmlValidateNmtokenValue(value: *const xmlChar) -> c_int {
6955    crate::xml::validation::validate_nmtoken_value(value)
6956}
6957
6958/// Validate a whitespace-separated list of Nmtokens.
6959///
6960/// # UPSTREAM-PARITY
6961///
6962/// ```c
6963/// int xmlValidateNmtokensValue(const xmlChar *value);
6964/// ```
6965#[no_mangle]
6966pub unsafe extern "C" fn xmlValidateNmtokensValue(value: *const xmlChar) -> c_int {
6967    crate::xml::validation::validate_nmtokens_value(value)
6968}
6969
6970/// Validate a single element declaration (VC: Unique Element Type
6971/// Declaration, VC: No Duplicate Types).
6972///
6973/// # UPSTREAM-PARITY
6974///
6975/// ```c
6976/// int xmlValidateElementDecl(xmlValidCtxtPtr ctxt,
6977///                            xmlDocPtr doc,
6978///                            xmlElementPtr elem);
6979/// ```
6980#[no_mangle]
6981pub unsafe extern "C" fn xmlValidateElementDecl(
6982    ctxt: *mut _xmlValidCtxt,
6983    doc: *mut _xmlDoc,
6984    elem: *mut _xmlElement,
6985) -> c_int {
6986    crate::xml::validation::validate_element_decl(ctxt, doc, elem)
6987}
6988
6989/// Validate a notation declaration.
6990///
6991/// # UPSTREAM-PARITY
6992///
6993/// Modern libxml2 has no validity constraint on notation declarations; the
6994/// oracle returns 1 unconditionally (verified by DSO disassembly).
6995///
6996/// ```c
6997/// int xmlValidateNotationDecl(xmlValidCtxtPtr ctxt,
6998///                             xmlDocPtr doc,
6999///                             xmlNotationPtr nota);
7000/// ```
7001#[no_mangle]
7002pub unsafe extern "C" fn xmlValidateNotationDecl(
7003    ctxt: *mut _xmlValidCtxt,
7004    doc: *mut _xmlDoc,
7005    nota: *mut _xmlNotation,
7006) -> c_int {
7007    crate::xml::validation::validate_notation_decl(ctxt, doc, nota)
7008}
7009
7010/// Validate a single attribute against its declaration.
7011///
7012/// # UPSTREAM-PARITY
7013///
7014/// ```c
7015/// int xmlValidateOneAttribute(xmlValidCtxtPtr ctxt,
7016///                             xmlDocPtr doc,
7017///                             xmlNodePtr elem,
7018///                             xmlAttrPtr attr,
7019///                             const xmlChar *value);
7020/// ```
7021#[no_mangle]
7022pub unsafe extern "C" fn xmlValidateOneAttribute(
7023    ctxt: *mut _xmlValidCtxt,
7024    doc: *mut _xmlDoc,
7025    elem: *mut _xmlNode,
7026    attr: *mut _xmlAttr,
7027    value: *const xmlChar,
7028) -> c_int {
7029    crate::xml::validation::validate_one_attribute(ctxt, doc, elem, attr, value)
7030}
7031
7032/// Validate a single element against its declaration (without recursing).
7033///
7034/// # UPSTREAM-PARITY
7035///
7036/// ```c
7037/// int xmlValidateOneElement(xmlValidCtxtPtr ctxt,
7038///                           xmlDocPtr doc,
7039///                           xmlNodePtr elem);
7040/// ```
7041#[no_mangle]
7042pub unsafe extern "C" fn xmlValidateOneElement(
7043    ctxt: *mut _xmlValidCtxt,
7044    doc: *mut _xmlDoc,
7045    elem: *mut _xmlNode,
7046) -> c_int {
7047    crate::xml::validation::validate_one_element(ctxt, doc, elem)
7048}
7049
7050/// Validate a namespace declaration attribute.
7051///
7052/// # UPSTREAM-PARITY
7053///
7054/// ```c
7055/// int xmlValidateOneNamespace(xmlValidCtxtPtr ctxt,
7056///                             xmlDocPtr doc,
7057///                             xmlNodePtr elem,
7058///                             const xmlChar *prefix,
7059///                             xmlNsPtr ns,
7060///                             const xmlChar *value);
7061/// ```
7062#[no_mangle]
7063pub unsafe extern "C" fn xmlValidateOneNamespace(
7064    ctxt: *mut _xmlValidCtxt,
7065    doc: *mut _xmlDoc,
7066    elem: *mut _xmlNode,
7067    prefix: *const xmlChar,
7068    ns: *mut _xmlNs,
7069    value: *const xmlChar,
7070) -> c_int {
7071    crate::xml::validation::validate_one_namespace(ctxt, doc, elem, prefix, ns, value)
7072}
7073
7074/// Push a new element start onto the validation stack (streaming DTD
7075/// validation).
7076///
7077/// # UPSTREAM-PARITY
7078///
7079/// ```c
7080/// int xmlValidatePushElement(xmlValidCtxtPtr ctxt,
7081///                            xmlDocPtr doc,
7082///                            xmlNodePtr elem,
7083///                            const xmlChar *qname);
7084/// ```
7085#[no_mangle]
7086pub unsafe extern "C" fn xmlValidatePushElement(
7087    ctxt: *mut _xmlValidCtxt,
7088    doc: *mut _xmlDoc,
7089    elem: *mut _xmlNode,
7090    qname: *const xmlChar,
7091) -> c_int {
7092    crate::xml::validation::validate_push_element(ctxt, doc, elem, qname)
7093}
7094
7095/// Push character data onto the validation stack.
7096///
7097/// # UPSTREAM-PARITY
7098///
7099/// ```c
7100/// int xmlValidatePushCData(xmlValidCtxtPtr ctxt,
7101///                          const xmlChar *data,
7102///                          int len);
7103/// ```
7104#[no_mangle]
7105pub unsafe extern "C" fn xmlValidatePushCData(
7106    ctxt: *mut _xmlValidCtxt,
7107    data: *const xmlChar,
7108    len: c_int,
7109) -> c_int {
7110    crate::xml::validation::validate_push_cdata(ctxt, data, len)
7111}
7112
7113/// Pop an element end from the validation stack.
7114///
7115/// # UPSTREAM-PARITY
7116///
7117/// ```c
7118/// int xmlValidatePopElement(xmlValidCtxtPtr ctxt,
7119///                           xmlDocPtr doc,
7120///                           xmlNodePtr elem,
7121///                           const xmlChar *qname);
7122/// ```
7123#[no_mangle]
7124pub unsafe extern "C" fn xmlValidatePopElement(
7125    ctxt: *mut _xmlValidCtxt,
7126    doc: *mut _xmlDoc,
7127    elem: *mut _xmlNode,
7128    qname: *const xmlChar,
7129) -> c_int {
7130    crate::xml::validation::validate_pop_element(ctxt, doc, elem, qname)
7131}
7132
7133/// Build the content-model automaton for an element declaration.
7134///
7135/// # UPSTREAM-PARITY
7136///
7137/// ```c
7138/// int xmlValidBuildContentModel(xmlValidCtxtPtr ctxt,
7139///                               xmlElementPtr elem);
7140/// ```
7141#[no_mangle]
7142pub unsafe extern "C" fn xmlValidBuildContentModel(
7143    ctxt: *mut _xmlValidCtxt,
7144    elem: *mut _xmlElement,
7145) -> c_int {
7146    crate::xml::validation::validate_build_content_model(ctxt, elem)
7147}
7148
7149/// Add an attribute to the document's ID table.
7150///
7151/// # UPSTREAM-PARITY
7152///
7153/// ```c
7154/// xmlIDPtr xmlAddID(xmlValidCtxtPtr ctxt,
7155///                   xmlDocPtr doc,
7156///                   const xmlChar *value,
7157///                   xmlAttrPtr attr);
7158/// ```
7159#[no_mangle]
7160pub unsafe extern "C" fn xmlAddID(
7161    ctxt: *mut _xmlValidCtxt,
7162    doc: *mut _xmlDoc,
7163    value: *const xmlChar,
7164    attr: *mut _xmlAttr,
7165) -> *mut _xmlID {
7166    crate::xml::validation::add_id(ctxt, doc, value, attr)
7167}
7168
7169/// Remove an attribute from the document's ID table.
7170///
7171/// # UPSTREAM-PARITY
7172///
7173/// ```c
7174/// int xmlRemoveID(xmlDocPtr doc, xmlAttrPtr attr);
7175/// ```
7176#[no_mangle]
7177pub unsafe extern "C" fn xmlRemoveID(doc: *mut _xmlDoc, attr: *mut _xmlAttr) -> c_int {
7178    crate::xml::validation::remove_id(doc, attr)
7179}
7180
7181/// Register an IDREF in the document's ref table.
7182///
7183/// # UPSTREAM-PARITY
7184///
7185/// ```c
7186/// xmlRefPtr xmlAddRef(xmlValidCtxtPtr ctxt,
7187///                     xmlDocPtr doc,
7188///                     const xmlChar *value,
7189///                     xmlAttrPtr attr);
7190/// ```
7191#[no_mangle]
7192pub unsafe extern "C" fn xmlAddRef(
7193    ctxt: *mut _xmlValidCtxt,
7194    doc: *mut _xmlDoc,
7195    value: *const xmlChar,
7196    attr: *mut _xmlAttr,
7197) -> *mut _xmlRef {
7198    crate::xml::validation::add_ref(ctxt, doc, value, attr)
7199}
7200
7201/// Remove an attribute's IDREF entries.
7202///
7203/// # UPSTREAM-PARITY
7204///
7205/// ```c
7206/// int xmlRemoveRef(xmlDocPtr doc, xmlAttrPtr attr);
7207/// ```
7208#[no_mangle]
7209pub unsafe extern "C" fn xmlRemoveRef(doc: *mut _xmlDoc, attr: *mut _xmlAttr) -> c_int {
7210    crate::xml::validation::remove_ref(doc, attr)
7211}
7212
7213/// Add an ID without a validation context (2.13+).
7214///
7215/// # UPSTREAM-PARITY
7216///
7217/// ```c
7218/// int xmlAddIDSafe(xmlAttrPtr attr, const xmlChar *value);
7219/// ```
7220#[no_mangle]
7221pub unsafe extern "C" fn xmlAddIDSafe(attr: *mut _xmlAttr, value: *const xmlChar) -> c_int {
7222    crate::xml::validation::add_id_safe(attr, value)
7223}
7224
7225/// Free an ID hash table.
7226///
7227/// # UPSTREAM-PARITY
7228///
7229/// ```c
7230/// void xmlFreeIDTable(xmlIDTablePtr table);
7231/// ```
7232#[no_mangle]
7233pub unsafe extern "C" fn xmlFreeIDTable(table: *mut c_void) {
7234    crate::xml::validation::free_id_table(table as *mut crate::xml::hash::HashTable);
7235}
7236
7237/// Free an IDREF hash table.
7238///
7239/// # UPSTREAM-PARITY
7240///
7241/// ```c
7242/// void xmlFreeRefTable(xmlRefTablePtr table);
7243/// ```
7244#[no_mangle]
7245pub unsafe extern "C" fn xmlFreeRefTable(table: *mut c_void) {
7246    crate::xml::validation::free_ref_table(table as *mut crate::xml::hash::HashTable);
7247}
7248
7249/// Look up the attribute holding an ID.
7250///
7251/// # UPSTREAM-PARITY
7252///
7253/// ```c
7254/// xmlAttrPtr xmlGetID(xmlDocPtr doc, const xmlChar *ID);
7255/// ```
7256#[no_mangle]
7257pub unsafe extern "C" fn xmlGetID(doc: *mut _xmlDoc, id: *const xmlChar) -> *mut _xmlAttr {
7258    crate::xml::validation::get_id(doc, id)
7259}
7260
7261/// Look up the list of references for an ID.
7262///
7263/// # UPSTREAM-PARITY
7264///
7265/// ```c
7266/// xmlListPtr xmlGetRefs(xmlDocPtr doc, const xmlChar *ID);
7267/// ```
7268#[no_mangle]
7269pub unsafe extern "C" fn xmlGetRefs(doc: *mut _xmlDoc, id: *const xmlChar) -> *mut c_void {
7270    crate::xml::validation::get_refs(doc, id) as *mut c_void
7271}
7272
7273/// Is this attribute an ID?
7274///
7275/// # UPSTREAM-PARITY
7276///
7277/// ```c
7278/// int xmlIsID(xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr);
7279/// ```
7280#[no_mangle]
7281pub unsafe extern "C" fn xmlIsID(
7282    doc: *mut _xmlDoc,
7283    elem: *mut _xmlNode,
7284    attr: *mut _xmlAttr,
7285) -> c_int {
7286    crate::xml::validation::is_id(doc, elem, attr)
7287}
7288
7289/// Is this attribute an IDREF?
7290///
7291/// # UPSTREAM-PARITY
7292///
7293/// ```c
7294/// int xmlIsRef(xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr);
7295/// ```
7296#[no_mangle]
7297pub unsafe extern "C" fn xmlIsRef(
7298    doc: *mut _xmlDoc,
7299    elem: *mut _xmlNode,
7300    attr: *mut _xmlAttr,
7301) -> c_int {
7302    crate::xml::validation::is_ref(doc, elem, attr)
7303}
7304
7305/// Search a DTD for an element declaration (with QName splitting).
7306///
7307/// # UPSTREAM-PARITY
7308///
7309/// ```c
7310/// xmlElementPtr xmlGetDtdElementDesc(xmlDtdPtr dtd, const xmlChar *name);
7311/// ```
7312#[no_mangle]
7313pub unsafe extern "C" fn xmlGetDtdElementDesc(
7314    dtd: *mut _xmlDtd,
7315    name: *const xmlChar,
7316) -> *mut _xmlElement {
7317    crate::xml::validation::get_dtd_element_desc(dtd, name)
7318}
7319
7320/// Search a DTD for an attribute declaration (with QName splitting).
7321///
7322/// # UPSTREAM-PARITY
7323///
7324/// ```c
7325/// xmlAttributePtr xmlGetDtdAttrDesc(xmlDtdPtr dtd,
7326///                                   const xmlChar *elem,
7327///                                   const xmlChar *name);
7328/// ```
7329#[no_mangle]
7330pub unsafe extern "C" fn xmlGetDtdAttrDesc(
7331    dtd: *mut _xmlDtd,
7332    elem: *const xmlChar,
7333    name: *const xmlChar,
7334) -> *mut _xmlAttribute {
7335    crate::xml::validation::get_dtd_attr_desc(dtd, elem, name)
7336}
7337
7338/// Search a DTD for a qualified element declaration.
7339///
7340/// # UPSTREAM-PARITY
7341///
7342/// ```c
7343/// xmlElementPtr xmlGetDtdQElementDesc(xmlDtdPtr dtd,
7344///                                     const xmlChar *name,
7345///                                     const xmlChar *prefix);
7346/// ```
7347#[no_mangle]
7348pub unsafe extern "C" fn xmlGetDtdQElementDesc(
7349    dtd: *mut _xmlDtd,
7350    name: *const xmlChar,
7351    prefix: *const xmlChar,
7352) -> *mut _xmlElement {
7353    crate::xml::validation::get_dtd_qelement_desc(dtd, name, prefix)
7354}
7355
7356/// Search a DTD for a qualified attribute declaration.
7357///
7358/// # UPSTREAM-PARITY
7359///
7360/// ```c
7361/// xmlAttributePtr xmlGetDtdQAttrDesc(xmlDtdPtr dtd,
7362///                                    const xmlChar *elem,
7363///                                    const xmlChar *name,
7364///                                    const xmlChar *prefix);
7365/// ```
7366#[no_mangle]
7367pub unsafe extern "C" fn xmlGetDtdQAttrDesc(
7368    dtd: *mut _xmlDtd,
7369    elem: *const xmlChar,
7370    name: *const xmlChar,
7371    prefix: *const xmlChar,
7372) -> *mut _xmlAttribute {
7373    crate::xml::validation::get_dtd_qattr_desc(dtd, elem, name, prefix)
7374}
7375
7376/// Search a DTD for a notation declaration.
7377///
7378/// # UPSTREAM-PARITY
7379///
7380/// ```c
7381/// xmlNotationPtr xmlGetDtdNotationDesc(xmlDtdPtr dtd, const xmlChar *name);
7382/// ```
7383#[no_mangle]
7384pub unsafe extern "C" fn xmlGetDtdNotationDesc(
7385    dtd: *mut _xmlDtd,
7386    name: *const xmlChar,
7387) -> *mut _xmlNotation {
7388    crate::xml::validation::get_dtd_notation_desc(dtd, name)
7389}
7390
7391/// Validate the root element of a document.
7392///
7393/// # UPSTREAM-PARITY
7394///
7395/// ```c
7396/// int xmlValidateRoot(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
7397/// ```
7398#[no_mangle]
7399pub unsafe extern "C" fn xmlValidateRoot(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
7400    crate::xml::validation::validate_root(ctxt, doc)
7401}
7402
7403/// Validate element content against its content model.
7404///
7405/// # UPSTREAM-PARITY
7406///
7407/// ```c
7408/// int xmlValidateContent(xmlValidCtxtPtr ctxt,
7409///                        xmlNodePtr node,
7410///                        xmlDocPtr doc);
7411/// ```
7412#[no_mangle]
7413pub unsafe extern "C" fn xmlValidateContent(
7414    ctxt: *mut _xmlValidCtxt,
7415    node: *mut _xmlNode,
7416    doc: *mut _xmlDoc,
7417) -> c_int {
7418    crate::xml::validation::validate_content(ctxt, node, doc)
7419}
7420
7421/// Check if an element is declared as mixed content.
7422///
7423/// # UPSTREAM-PARITY
7424///
7425/// ```c
7426/// int xmlIsMixedElement(xmlDocPtr doc, const xmlChar *name);
7427/// ```
7428#[no_mangle]
7429pub unsafe extern "C" fn xmlIsMixedElement(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
7430    crate::xml::validation::is_mixed_element(doc, name)
7431}
7432
7433/// Check if an element is declared as EMPTY.
7434///
7435/// # UPSTREAM-PARITY
7436///
7437/// ```c
7438/// int xmlIsEmptyElement(xmlDocPtr doc, const xmlChar *name);
7439/// ```
7440#[no_mangle]
7441pub unsafe extern "C" fn xmlIsEmptyElement(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
7442    crate::xml::validation::is_empty_element(doc, name)
7443}
7444
7445/// Validate a DTD's declarations.
7446///
7447/// # UPSTREAM-PARITY
7448///
7449/// ```c
7450/// int xmlValidateDtd(xmlValidCtxtPtr ctxt,
7451///                    xmlDocPtr doc,
7452///                    xmlDtdPtr dtd);
7453/// ```
7454#[no_mangle]
7455pub unsafe extern "C" fn xmlValidateDtd(
7456    ctxt: *mut _xmlValidCtxt,
7457    doc: *mut _xmlDoc,
7458    dtd: *mut _xmlDtd,
7459) -> c_int {
7460    crate::xml::validation::validate_dtd(ctxt, doc, dtd)
7461}
7462
7463/// Final DTD validation (ID/IDREF consistency).
7464///
7465/// # UPSTREAM-PARITY
7466///
7467/// ```c
7468/// int xmlValidateDtdFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
7469/// ```
7470#[no_mangle]
7471pub unsafe extern "C" fn xmlValidateDtdFinal(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
7472    crate::xml::validation::validate_dtd_final(ctxt, doc)
7473}
7474
7475/// Validate that a value is in an enumeration.
7476///
7477/// # UPSTREAM-PARITY
7478///
7479/// ```c
7480/// int xmlValidateEnumeration(xmlValidCtxtPtr ctxt,
7481///                            const xmlChar *value,
7482///                            xmlEnumerationPtr tree);
7483/// ```
7484#[no_mangle]
7485pub unsafe extern "C" fn xmlValidateEnumeration(
7486    ctxt: *mut _xmlValidCtxt,
7487    value: *const xmlChar,
7488    tree: *mut _xmlEnumeration,
7489) -> c_int {
7490    crate::xml::validation::validate_enumeration(ctxt, value, tree)
7491}
7492
7493// ═══════════════════════════════════════════════════════════════════════════════
7494// 18. Debug / Miscellaneous
7495// ═══════════════════════════════════════════════════════════════════════════════
7496
7497/// Dump a document to a file for debugging.
7498
7499/// Get the path to the current executable.
7500///
7501/// # UPSTREAM-PARITY
7502///
7503/// ```c
7504/// char *xmlGetBinaryPath(void);
7505/// ```
7506#[no_mangle]
7507pub extern "C" fn xmlGetBinaryPath() -> *mut c_char {
7508    // Phase 1: STUB
7509    ptr::null_mut()
7510}
7511
7512/// Get the path to the current executable's home directory.
7513///
7514/// # UPSTREAM-PARITY
7515///
7516/// ```c
7517/// char *xmlGetHomeOfBinary(void);
7518/// ```
7519#[no_mangle]
7520pub extern "C" fn xmlGetHomeOfBinary() -> *mut c_char {
7521    // Phase 1: STUB
7522    ptr::null_mut()
7523}
7524
7525// ═══════════════════════════════════════════════════════════════════════════════
7526// SAX2 default callback entry points (upstream SAX2.c)
7527// ═══════════════════════════════════════════════════════════════════════════════
7528//
7529// These are the public `xmlSAX2*` callback functions that downstream code
7530// installs into `xmlSAXHandler` structures. They are the same implementations
7531// the candidate's default SAX handler uses; exporting them under the
7532// upstream names is required for ABI parity (R-000136 closure).
7533
7534/// Upstream SAX2.c `xmlSAX2StartDocument` — public entry point of the default handler.
7535#[no_mangle]
7536pub unsafe extern "C" fn xmlSAX2StartDocument(ctx: *mut c_void) {
7537    crate::xml::sax::default::default_sax_handler::startDocument(ctx)
7538}
7539
7540/// Upstream SAX2.c `xmlSAX2EndDocument` — public entry point of the default handler.
7541#[no_mangle]
7542pub unsafe extern "C" fn xmlSAX2EndDocument(ctx: *mut c_void) {
7543    crate::xml::sax::default::default_sax_handler::endDocument(ctx)
7544}
7545
7546/// Upstream SAX2.c `xmlSAX2StartElementNs` — public entry point of the default handler.
7547#[no_mangle]
7548pub unsafe extern "C" fn xmlSAX2StartElementNs(
7549    ctx: *mut c_void,
7550    localname: *const xmlChar,
7551    prefix: *const xmlChar,
7552    URI: *const xmlChar,
7553    nb_namespaces: c_int,
7554    namespaces: *mut *const xmlChar,
7555    nb_attributes: c_int,
7556    nb_defaulted: c_int,
7557    attributes: *mut *const xmlChar,
7558) {
7559    crate::xml::sax::default::default_sax_handler::startElementNs(
7560        ctx,
7561        localname,
7562        prefix,
7563        URI,
7564        nb_namespaces,
7565        namespaces,
7566        nb_attributes,
7567        nb_defaulted,
7568        attributes,
7569    )
7570}
7571
7572/// Upstream SAX2.c `xmlSAX2EndElementNs` — public entry point of the default handler.
7573#[no_mangle]
7574pub unsafe extern "C" fn xmlSAX2EndElementNs(
7575    ctx: *mut c_void,
7576    localname: *const xmlChar,
7577    prefix: *const xmlChar,
7578    URI: *const xmlChar,
7579) {
7580    crate::xml::sax::default::default_sax_handler::endElementNs(ctx, localname, prefix, URI)
7581}
7582
7583/// Upstream SAX2.c `xmlSAX2Characters` — public entry point of the default handler.
7584#[no_mangle]
7585pub unsafe extern "C" fn xmlSAX2Characters(ctx: *mut c_void, ch: *const xmlChar, len: c_int) {
7586    crate::xml::sax::default::default_sax_handler::characters(ctx, ch, len)
7587}
7588
7589/// Upstream SAX2.c `xmlSAX2IgnorableWhitespace` — public entry point of the default handler.
7590#[no_mangle]
7591pub unsafe extern "C" fn xmlSAX2IgnorableWhitespace(
7592    ctx: *mut c_void,
7593    ch: *const xmlChar,
7594    len: c_int,
7595) {
7596    crate::xml::sax::default::default_sax_handler::ignorableWhitespace(ctx, ch, len)
7597}
7598
7599/// Upstream SAX2.c `xmlSAX2Comment` — public entry point of the default handler.
7600#[no_mangle]
7601pub unsafe extern "C" fn xmlSAX2Comment(ctx: *mut c_void, value: *const xmlChar) {
7602    crate::xml::sax::default::default_sax_handler::comment(ctx, value)
7603}
7604
7605/// Upstream SAX2.c `xmlSAX2ProcessingInstruction` — public entry point of the default handler.
7606#[no_mangle]
7607pub unsafe extern "C" fn xmlSAX2ProcessingInstruction(
7608    ctx: *mut c_void,
7609    target: *const xmlChar,
7610    data: *const xmlChar,
7611) {
7612    crate::xml::sax::default::default_sax_handler::processingInstruction(ctx, target, data)
7613}
7614
7615/// Upstream SAX2.c `xmlSAX2CDataBlock` — public entry point of the default handler.
7616#[no_mangle]
7617pub unsafe extern "C" fn xmlSAX2CDataBlock(ctx: *mut c_void, value: *const xmlChar, len: c_int) {
7618    crate::xml::sax::default::default_sax_handler::cdataBlock(ctx, value, len)
7619}
7620
7621/// Upstream SAX2.c `xmlSAX2InternalSubset` — public entry point of the default handler.
7622#[no_mangle]
7623pub unsafe extern "C" fn xmlSAX2InternalSubset(
7624    ctx: *mut c_void,
7625    name: *const xmlChar,
7626    ExternalID: *const xmlChar,
7627    SystemID: *const xmlChar,
7628) {
7629    crate::xml::sax::default::default_sax_handler::internalSubset(ctx, name, ExternalID, SystemID)
7630}
7631
7632/// Upstream SAX2.c `xmlSAX2ExternalSubset` — public entry point of the default handler.
7633#[no_mangle]
7634pub unsafe extern "C" fn xmlSAX2ExternalSubset(
7635    ctx: *mut c_void,
7636    name: *const xmlChar,
7637    ExternalID: *const xmlChar,
7638    SystemID: *const xmlChar,
7639) {
7640    crate::xml::sax::default::default_sax_handler::externalSubset(ctx, name, ExternalID, SystemID)
7641}
7642
7643/// Upstream SAX2.c `xmlSAX2EntityDecl` — public entry point of the default handler.
7644#[no_mangle]
7645pub unsafe extern "C" fn xmlSAX2EntityDecl(
7646    ctx: *mut c_void,
7647    name: *const xmlChar,
7648    type_: c_int,
7649    publicId: *const xmlChar,
7650    systemId: *const xmlChar,
7651    content: *mut xmlChar,
7652) {
7653    crate::xml::sax::default::default_sax_handler::entityDecl(
7654        ctx, name, type_, publicId, systemId, content,
7655    )
7656}
7657
7658/// Upstream SAX2.c `xmlSAX2AttributeDecl` — public entry point of the default handler.
7659#[no_mangle]
7660pub unsafe extern "C" fn xmlSAX2AttributeDecl(
7661    ctx: *mut c_void,
7662    elem: *const xmlChar,
7663    fullname: *const xmlChar,
7664    type_: c_int,
7665    def: c_int,
7666    defaultValue: *const xmlChar,
7667    tree: *mut crate::abi::structs::_xmlEnumeration,
7668) {
7669    crate::xml::sax::default::default_sax_handler::attributeDecl(
7670        ctx,
7671        elem,
7672        fullname,
7673        type_,
7674        def,
7675        defaultValue,
7676        tree,
7677    )
7678}
7679
7680/// Upstream SAX2.c `xmlSAX2ElementDecl` — public entry point of the default handler.
7681#[no_mangle]
7682pub unsafe extern "C" fn xmlSAX2ElementDecl(
7683    ctx: *mut c_void,
7684    name: *const xmlChar,
7685    type_: c_int,
7686    content: *mut crate::abi::structs::_xmlElementContent,
7687) {
7688    crate::xml::sax::default::default_sax_handler::elementDecl(ctx, name, type_, content)
7689}
7690
7691/// Upstream SAX2.c `xmlSAX2NotationDecl` — public entry point of the default handler.
7692#[no_mangle]
7693pub unsafe extern "C" fn xmlSAX2NotationDecl(
7694    ctx: *mut c_void,
7695    name: *const xmlChar,
7696    publicId: *const xmlChar,
7697    systemId: *const xmlChar,
7698) {
7699    crate::xml::sax::default::default_sax_handler::notationDecl(ctx, name, publicId, systemId)
7700}
7701
7702/// Upstream SAX2.c `xmlSAX2UnparsedEntityDecl` — public entry point of the default handler.
7703#[no_mangle]
7704pub unsafe extern "C" fn xmlSAX2UnparsedEntityDecl(
7705    ctx: *mut c_void,
7706    name: *const xmlChar,
7707    publicId: *const xmlChar,
7708    systemId: *const xmlChar,
7709    notationName: *const xmlChar,
7710) {
7711    crate::xml::sax::default::default_sax_handler::unparsedEntityDecl(
7712        ctx,
7713        name,
7714        publicId,
7715        systemId,
7716        notationName,
7717    )
7718}
7719
7720/// Upstream SAX2.c `xmlSAX2ResolveEntity` — public entry point of the default handler.
7721#[no_mangle]
7722pub unsafe extern "C" fn xmlSAX2ResolveEntity(
7723    ctx: *mut c_void,
7724    publicId: *const xmlChar,
7725    systemId: *const xmlChar,
7726) -> *mut crate::abi::structs::_xmlParserInput {
7727    crate::xml::sax::default::default_sax_handler::resolveEntity(ctx, publicId, systemId)
7728}
7729
7730/// Upstream SAX2.c `xmlSAX2IsStandalone` — public entry point of the default handler.
7731#[no_mangle]
7732pub unsafe extern "C" fn xmlSAX2IsStandalone(ctx: *mut c_void) -> c_int {
7733    crate::xml::sax::default::default_sax_handler::isStandalone(ctx)
7734}
7735
7736/// Upstream SAX2.c `xmlSAX2HasInternalSubset` — public entry point of the default handler.
7737#[no_mangle]
7738pub unsafe extern "C" fn xmlSAX2HasInternalSubset(ctx: *mut c_void) -> c_int {
7739    crate::xml::sax::default::default_sax_handler::hasInternalSubset(ctx)
7740}
7741
7742/// Upstream SAX2.c `xmlSAX2HasExternalSubset` — public entry point of the default handler.
7743#[no_mangle]
7744pub unsafe extern "C" fn xmlSAX2HasExternalSubset(ctx: *mut c_void) -> c_int {
7745    crate::xml::sax::default::default_sax_handler::hasExternalSubset(ctx)
7746}
7747
7748/// Upstream SAX2.c `xmlSAX2GetEntity` — public entry point of the default handler.
7749#[no_mangle]
7750pub unsafe extern "C" fn xmlSAX2GetEntity(
7751    ctx: *mut c_void,
7752    name: *const xmlChar,
7753) -> *mut crate::abi::structs::_xmlEntity {
7754    crate::xml::sax::default::default_sax_handler::getEntity(ctx, name)
7755}
7756
7757/// Upstream SAX2.c `xmlSAX2GetParameterEntity` — public entry point of the default handler.
7758#[no_mangle]
7759pub unsafe extern "C" fn xmlSAX2GetParameterEntity(
7760    ctx: *mut c_void,
7761    name: *const xmlChar,
7762) -> *mut crate::abi::structs::_xmlEntity {
7763    crate::xml::sax::default::default_sax_handler::getParameterEntity(ctx, name)
7764}
7765
7766/// Upstream SAX2.c `xmlSAX2GetLineNumber` — public entry point of the
7767/// default handler (SAX locator callback).
7768#[no_mangle]
7769pub unsafe extern "C" fn xmlSAX2GetLineNumber(ctx: *mut c_void) -> c_int {
7770    crate::xml::sax::default::default_sax_handler::getLineNumber(ctx)
7771}
7772
7773/// Upstream SAX2.c `xmlSAX2GetColumnNumber`.
7774#[no_mangle]
7775pub unsafe extern "C" fn xmlSAX2GetColumnNumber(ctx: *mut c_void) -> c_int {
7776    crate::xml::sax::default::default_sax_handler::getColumnNumber(ctx)
7777}
7778
7779/// Upstream SAX2.c `xmlSAX2GetPublicId`.
7780#[no_mangle]
7781pub unsafe extern "C" fn xmlSAX2GetPublicId(ctx: *mut c_void) -> *const xmlChar {
7782    crate::xml::sax::default::default_sax_handler::getPublicId(ctx)
7783}
7784
7785/// Upstream SAX2.c `xmlSAX2GetSystemId`.
7786#[no_mangle]
7787pub unsafe extern "C" fn xmlSAX2GetSystemId(ctx: *mut c_void) -> *const xmlChar {
7788    crate::xml::sax::default::default_sax_handler::getSystemId(ctx)
7789}
7790
7791/// Upstream SAX2.c `xmlSAX2StartElement` — SAX1 start-element entry point.
7792/// The candidate parser dispatches through the SAX2 (namespaced) callbacks;
7793/// this wrapper maps to the SAX1 handler when installed.
7794#[no_mangle]
7795pub unsafe extern "C" fn xmlSAX2StartElement(
7796    ctx: *mut c_void,
7797    name: *const xmlChar,
7798    atts: *mut *const xmlChar,
7799) {
7800    // The parser core invokes startElementNs; the SAX1 shim is provided by
7801    // the dispatch layer. When this entry point is installed directly on a
7802    // handler, route through the internal SAX1 path.
7803    crate::xml::sax::dispatch::SaxDispatcher::sax1_start_element(ctx, name, atts);
7804}
7805
7806/// Upstream SAX2.c `xmlSAX2EndElement` — SAX1 end-element entry point.
7807#[no_mangle]
7808pub unsafe extern "C" fn xmlSAX2EndElement(ctx: *mut c_void, name: *const xmlChar) {
7809    crate::xml::sax::dispatch::SaxDispatcher::sax1_end_element(ctx, name);
7810}
7811
7812/// Upstream SAX2.c `xmlSAX2SetDocumentLocator` — public entry point of the default handler.
7813#[no_mangle]
7814pub unsafe extern "C" fn xmlSAX2SetDocumentLocator(
7815    ctx: *mut c_void,
7816    loc: *mut crate::abi::callbacks::_xmlSAXLocator,
7817) {
7818    crate::xml::sax::default::default_sax_handler::setDocumentLocator(ctx, loc)
7819}
7820
7821/// Upstream SAX2.c `xmlSAX2Reference` — public entry point of the default handler.
7822#[no_mangle]
7823pub unsafe extern "C" fn xmlSAX2Reference(ctx: *mut c_void, name: *const xmlChar) {
7824    crate::xml::sax::default::default_sax_handler::reference(ctx, name)
7825}