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//! # Upstream contract
37//!
38//! The parity target is the complete libxml2.so.2 export surface of the oracle
39//! DSO (libxml2 2.15.3): `globals.c`, `parser.c`, `threads.c`, `encoding.c`,
40//! `xmlmemory.c` and `xmlstring.c` entry points with upstream header
41//! signatures. Residuals R-000116, R-000117, R-000132, R-000133, R-000135,
42//! R-000136, R-000138, R-000157, R-000161, R-000162, R-000163, R-000164 and
43//! R-000165 all touch this module.
44//!
45//! # Conceptual behavior
46//!
47//! This module implements the core libxml2 ABI: init/cleanup, version, memory,
48//! error handling, string utilities, tree/document construction, parser entry
49//! points, I/O, dict/hash/list, buffer, encoding, XPath and catalog — grouped
50//! by subsystem in upstream header order. Functions needing the engine call
51//! into `src/xml/*`; the rest are faithful ports.
52//!
53//! # Ownership & safety invariants
54//!
55//! Ownership follows OWNERSHIP_ATLAS: docs/nodes/strings returned to C are
56//! caller-owned (freed with the documented xmlFree-family); `xmlReadMemory`/
57//! `xmlCtxtRead*` propagate the URL into the owned input filename (R-000161);
58//! the error channel routes through the exported handler slots
59//! (R-000161/R-000163). The deprecated init/cleanup no-ops are deliberate:
60//! upstream bodies are empty (R-000138).
61//!
62//! # Historical quirks & epochs
63//!
64//! QUIRK-0001: 2.9.0 default parser limits (commit `52d8ade7`); E-002/E-005:
65//! parse-error diagnostics and exit codes across 2.9.10-2.13.0; R-000138: the
66//! deprecated no-op entry points dispositioned as the oracles own behavior;
67//! R-000161: the five wrong default values fixed (e.g. `xmlParserVersion` =
68//! `21503-GITv2.15.3`); R-000162: allocator entry points exported as DATA;
69//! R-000157: iconv-only encodings report XML_ERR_UNSUPPORTED_ENCODING (no
70//! iconv backend — OPEN residual, UNRESOLVED since 11.1-Z.1: the executed
71//! Iconv+ICU-enabled oracle serves those encodings, so closing requires an
72//! iconv/ICU backend rather than a waiver).
73//!
74//! # Deliberate oddities
75//!
76//! The no-op init/cleanup exports (R-000138), the `xmlGenericError`/
77//! `xsltGenericError` variadic asm stderr printers (R-000161), and the
78//! XML_ERR_UNSUPPORTED_ENCODING divergence for iconv/ICU-only encodings
79//! (R-000157, OPEN/UNRESOLVED) are the deliberate oddities of this module.
80//!
81//! # Proving courts
82//!
83//! ABI-DATA, ALLOCATOR, GLOBAL-STATE, PARSER and THREADING court families;
84//! the data-ABI probes (CALLBACK-001, ERROR-001, TREE-001, ENCODING-001, ...)
85//! require byte-identical output vs the oracle DSO; DSO-LOADER and
86//! HEADER-COMPILE close the surface.
87//!
88//! # Tempting simplifications that would break parity
89//!
90//! A tempting simplification is to delete the deprecated no-op exports as dead
91//! code — R-000138 records they ARE the upstream observable behavior and
92//! downstream linking depends on them. Another shortcut, defaulting
93//! `xmlGenericError` to NULL instead of the variadic stderr printer, is the
94//! pre-R-000161 state that broke counting handlers (err-count 1 vs oracle 6).
95//! Both must not be simplified.
96
97#![allow(non_snake_case)]
98#![allow(unused_variables)]
99#![allow(clippy::missing_safety_doc)]
100#![allow(clippy::not_unsafe_ptr_arg_deref)]
101
102// SAFETY-SCOPE: EXPORT-XML2-MECHANICAL-001
103// (11.1-Z.3 proof scope, classified-generated) — this module is the
104// mechanical extern-"C" export surface: every `unsafe` block in it is
105// the documented indirection/registry-access pattern whose validity
106// rests on the upstream C contract, and the exported signatures are
107// machine-measured by the ABI-FUNCTION-SIGNATURE and DSO-LOADER
108// courts and the C-API differential probes. The safety contract of
109// each export is stated in its own doc comment; this scope covers the
110// mechanical wrappers' unsafe blocks.
111
112use core::ffi::c_void;
113use core::ptr;
114use once_cell::sync::Lazy;
115use parking_lot::Mutex;
116use std::collections::HashMap;
117use std::ffi::{CStr, CString};
118use std::mem::size_of;
119use std::os::raw::{c_char, c_int, c_long, c_uint, c_ulong};
120
121use crate::xml::xpath::ast::CompiledExpr;
122use crate::xml::xpath::context::{BoxedXPathFunction, XPathContext};
123use crate::xml::xpath::types::{NodeSet, XPathValue};
124
125use crate::abi::allocator::*;
126use crate::abi::callbacks::*;
127use crate::abi::structs::*;
128use crate::abi::types::*;
129
130// ═══════════════════════════════════════════════════════════════════════════════
131// 1. Initialization / Cleanup
132// ═══════════════════════════════════════════════════════════════════════════════
133
134/// Initialize the parser library.
135///
136/// Must be called before any other libxml2 functions.
137/// Safe to call multiple times (reference-counted in modern libxml2).
138///
139/// # UPSTREAM-PARITY
140///
141/// ```c
142/// void xmlInitParser(void);
143/// ```
144#[no_mangle]
145pub unsafe extern "C" fn xmlInitParser() {
146    crate::internal::globals::init_parser();
147}
148
149/// Initialize the global variables module (upstream globals.h).
150///
151/// # UPSTREAM-PARITY
152///
153/// ```c
154/// void xmlInitGlobals(void);
155/// ```
156///
157/// Upstream `xmlInitGlobals` (globals.c) is called once to initialize the
158/// global variable defaults. The candidate's globals are initialized
159/// statically/on first use, so this is a no-op that exists for ABI
160/// compatibility.
161#[no_mangle]
162pub const unsafe extern "C" fn xmlInitGlobals() {
163    // Globals are statically initialized in the candidate.
164}
165
166/// Upstream `xmlInitializeGlobalState` (globals.c) — initializes a
167/// `xmlGlobalState` struct; the candidate keeps no global-state struct, so
168/// this is a no-op for ABI compatibility.
169///
170/// # UPSTREAM-PARITY
171///
172/// ```c
173/// void xmlInitializeGlobalState(xmlGlobalStatePtr gs);
174/// ```
175#[no_mangle]
176pub const unsafe extern "C" fn xmlInitializeGlobalState(_gs: *mut c_void) {
177    // No-op: the candidate's globals are statically initialized.
178    // R-000138: upstream globals.c body is empty (lazy init); the no-op
179    // IS the oracle behavior, so this must never become a real initializer.
180}
181
182/// Upstream `xmlInitializeDict` (dict.c) — ensures the dictionary
183/// subsystem is initialized; no-op in the candidate (lazy init).
184///
185/// # UPSTREAM-PARITY
186///
187/// ```c
188/// int xmlInitializeDict(void);
189/// ```
190#[no_mangle]
191pub const extern "C" fn xmlInitializeDict() -> c_int {
192    // R-000138: upstream dict.c xmlInitializeDict is an empty body after lazy
193    // init; returning 0 is the oracle observable behavior.
194    0
195}
196
197/// Upstream `xmlInitializePredefinedEntities` (entities.c) — the
198/// predefined entities (& < > " ') are built lazily by
199/// the candidate; no-op.
200///
201/// # UPSTREAM-PARITY
202///
203/// ```c
204/// void xmlInitializePredefinedEntities(void);
205/// ```
206#[no_mangle]
207pub const extern "C" fn xmlInitializePredefinedEntities() {
208    // No-op: predefined entities are resolved on demand.
209}
210
211/// Upstream `xmlCleanupPredefinedEntities` (entities.c) — no-op in the
212/// candidate (no global entity table to release).
213///
214/// # UPSTREAM-PARITY
215///
216/// ```c
217/// void xmlCleanupPredefinedEntities(void);
218/// ```
219#[no_mangle]
220pub const extern "C" fn xmlCleanupPredefinedEntities() {
221    // No-op.
222}
223
224/// Upstream `xmlDefaultSAXHandlerInit` (SAX2.c) — fills the
225/// `xmlDefaultSAXHandler` global. The candidate's default handler is built
226/// on demand; this initializes the exported default-handler global when it
227/// is added (currently tracked in R-000135). No-op for now.
228///
229/// # UPSTREAM-PARITY
230///
231/// ```c
232/// void xmlDefaultSAXHandlerInit(void);
233/// ```
234#[no_mangle]
235pub const extern "C" fn xmlDefaultSAXHandlerInit() {
236    // The candidate builds default handlers on demand; the exported
237    // xmlDefaultSAXHandler global is part of the R-000135 data closure.
238}
239
240/// The current default SAX version (2), stored as an atomic so callers can
241/// query it without taking a lock.
242static SAX2_DEFAULT_VERSION: core::sync::atomic::AtomicI32 = core::sync::atomic::AtomicI32::new(2);
243/// Set the default SAX version (upstream SAX2.c `xmlSAXDefaultVersion`):
244/// returns the previous default; -1 when the version is not 1 or 2.
245///
246/// # UPSTREAM-PARITY
247///
248/// ```c
249/// int xmlSAXDefaultVersion(int version);
250/// ```
251#[no_mangle]
252pub extern "C" fn xmlSAXDefaultVersion(version: c_int) -> c_int {
253    use core::sync::atomic::Ordering;
254    let ret = SAX2_DEFAULT_VERSION.load(Ordering::Relaxed);
255    if version != 1 && version != 2 {
256        return -1;
257    }
258    SAX2_DEFAULT_VERSION.store(version, Ordering::Relaxed);
259    ret
260}
261
262/// Initialize a SAX handler for a given SAX version (upstream SAX2.c
263/// `xmlSAXVersion`): fills the handler with the default callbacks and sets
264/// `initialized` (XML_SAX2_MAGIC for version 2, 1 for version 1).
265///
266/// # UPSTREAM-PARITY
267///
268/// ```c
269/// int xmlSAXVersion(xmlSAXHandler *hdlr, int version);
270/// ```
271#[no_mangle]
272pub unsafe extern "C" fn xmlSAXVersion(
273    hdlr: *mut crate::abi::structs::_xmlSAXHandler,
274    version: c_int,
275) -> c_int {
276    if hdlr.is_null() {
277        return -1;
278    }
279    if version != 1 && version != 2 {
280        return -1;
281    }
282    // SAFETY: hdlr is non-NULL and writable.
283    unsafe {
284        crate::xml::sax::dispatch::xmlSAX2InitDefaultSAXHandler(hdlr);
285        let h = &mut *hdlr;
286        if version == 2 {
287            h.initialized = crate::abi::constants::XML_SAX2_MAGIC as c_uint;
288        } else {
289            h.initialized = 1;
290        }
291    }
292    0
293}
294
295/// Upstream `xmlHasFeature` (parser.c): returns 1 when the library was
296/// compiled with the requested feature. The candidate enables the full
297/// feature set (see include/libxml/xmlversion.h), so every known feature
298/// reports 1; unknown features report 0.
299///
300/// # UPSTREAM-PARITY
301///
302/// ```c
303/// int xmlHasFeature(xmlFeature feature);
304/// ```
305#[no_mangle]
306pub extern "C" fn xmlHasFeature(feature: c_int) -> c_int {
307    // xmlFeature enum values (upstream xmlversion.h): XML_WITH_* run 1..24
308    // (XML_WITH_THREAD=1 ... XML_WITH_MODULES=24).
309    if (1..=24).contains(&feature) {
310        1
311    } else {
312        0
313    }
314}
315
316/// Clean up the global variables module (upstream globals.h).
317///
318/// # UPSTREAM-PARITY
319///
320/// ```c
321/// void xmlCleanupGlobals(void);
322/// ```
323///
324/// Upstream `xmlCleanupGlobals` frees the global defaults. The candidate
325/// keeps globals alive for the process lifetime (repeated init/cleanup is
326/// reference-counted); no-op for ABI compatibility.
327#[no_mangle]
328pub const unsafe extern "C" fn xmlCleanupGlobals() {
329    // The candidate's globals are process-lifetime statics.
330}
331
332/// Clean up the parser library.
333///
334/// Should be called when the library is no longer needed.
335///
336/// # UPSTREAM-PARITY
337///
338/// ```c
339/// void xmlCleanupParser(void);
340/// ```
341#[no_mangle]
342pub unsafe extern "C" fn xmlCleanupParser() {
343    crate::internal::globals::cleanup_parser();
344}
345
346/// Create a simple mutex (upstream threads.h).
347///
348/// # UPSTREAM-PARITY
349///
350/// ```c
351/// xmlMutexPtr xmlNewMutex(void);
352/// ```
353#[no_mangle]
354pub extern "C" fn xmlNewMutex() -> *mut c_void {
355    crate::xml::threads::new_mutex()
356}
357
358/// Free a simple mutex (upstream threads.h).
359///
360/// # UPSTREAM-PARITY
361///
362/// ```c
363/// void xmlFreeMutex(xmlMutexPtr tok);
364/// ```
365#[no_mangle]
366pub unsafe extern "C" fn xmlFreeMutex(tok: *mut c_void) {
367    crate::xml::threads::free_mutex(tok);
368}
369
370/// Lock a simple mutex (upstream threads.h).
371///
372/// # UPSTREAM-PARITY
373///
374/// ```c
375/// void xmlMutexLock(xmlMutexPtr tok);
376/// ```
377#[no_mangle]
378pub unsafe extern "C" fn xmlMutexLock(tok: *mut c_void) {
379    crate::xml::threads::mutex_lock(tok);
380}
381
382/// Unlock a simple mutex (upstream threads.h).
383///
384/// # UPSTREAM-PARITY
385///
386/// ```c
387/// void xmlMutexUnlock(xmlMutexPtr tok);
388/// ```
389#[no_mangle]
390pub unsafe extern "C" fn xmlMutexUnlock(tok: *mut c_void) {
391    crate::xml::threads::mutex_unlock(tok);
392}
393
394/// Create a recursive mutex (upstream threads.h).
395///
396/// # UPSTREAM-PARITY
397///
398/// ```c
399/// xmlRMutexPtr xmlNewRMutex(void);
400/// ```
401#[no_mangle]
402pub extern "C" fn xmlNewRMutex() -> *mut c_void {
403    crate::xml::threads::new_rmutex()
404}
405
406/// Free a recursive mutex (upstream threads.h).
407///
408/// # UPSTREAM-PARITY
409///
410/// ```c
411/// void xmlFreeRMutex(xmlRMutexPtr tok);
412/// ```
413#[no_mangle]
414pub unsafe extern "C" fn xmlFreeRMutex(tok: *mut c_void) {
415    crate::xml::threads::free_rmutex(tok);
416}
417
418/// Lock a recursive mutex (upstream threads.h).
419///
420/// # UPSTREAM-PARITY
421///
422/// ```c
423/// void xmlRMutexLock(xmlRMutexPtr tok);
424/// ```
425#[no_mangle]
426pub unsafe extern "C" fn xmlRMutexLock(tok: *mut c_void) {
427    crate::xml::threads::rmutex_lock(tok);
428}
429
430/// Unlock a recursive mutex (upstream threads.h).
431///
432/// # UPSTREAM-PARITY
433///
434/// ```c
435/// void xmlRMutexUnlock(xmlRMutexPtr tok);
436/// ```
437#[no_mangle]
438pub unsafe extern "C" fn xmlRMutexUnlock(tok: *mut c_void) {
439    crate::xml::threads::rmutex_unlock(tok);
440}
441
442/// Check the thread-local storage (upstream threads.h `xmlCheckThreadLocalStorage`):
443/// returns 0 when TLS is functional, -1 otherwise. The candidate uses Rust
444/// thread-locals which are always functional.
445///
446/// # UPSTREAM-PARITY
447///
448/// ```c
449/// int xmlCheckThreadLocalStorage(void);
450/// ```
451#[no_mangle]
452pub const extern "C" fn xmlCheckThreadLocalStorage() -> c_int {
453    // R-000138: upstream threads.c body is empty (TLS always works); 0 is the
454    // oracle observable behavior, not a stub.
455    0
456}
457
458/// Initialize threading support.
459///
460/// # UPSTREAM-PARITY
461///
462/// ```c
463/// void xmlInitThreads(void);
464/// ```
465///
466/// Upstream threads.h declares `void xmlInitThreads(void)` (11.1-Z.3
467/// signature court: the pre-Z.3 candidate returned `int`).
468#[no_mangle]
469pub unsafe extern "C" fn xmlInitThreads() {
470    let _ = unsafe { crate::internal::globals::init_threads() };
471}
472
473/// Clean up threading support.
474///
475/// # UPSTREAM-PARITY
476///
477/// ```c
478/// void xmlCleanupThreads(void);
479/// ```
480#[no_mangle]
481pub unsafe extern "C" fn xmlCleanupThreads() {
482    crate::xml::threads::cleanup_threads();
483}
484
485/// Check whether the library has been initialized.
486///
487/// # UPSTREAM-PARITY
488///
489/// ```c
490/// int xmlIsInitialized(void);
491/// ```
492#[no_mangle]
493pub extern "C" fn xmlIsInitialized() -> c_int {
494    if crate::abi::versioning::is_initialized() {
495        1
496    } else {
497        0
498    }
499}
500
501/// Initialize a set of threads (libxml2 compat).
502///
503/// # UPSTREAM-PARITY
504///
505/// ```c
506/// int xmlInitThreads(void);
507/// ```
508/// This is an alias.
509#[no_mangle]
510pub const unsafe extern "C" fn xmlLockLibrary() {
511    crate::xml::threads::lock_library();
512}
513
514/// Unlock the library (libxml2 compat).
515///
516/// # UPSTREAM-PARITY
517///
518/// ```c
519/// void xmlUnlockLibrary(void);
520/// ```
521#[no_mangle]
522pub const unsafe extern "C" fn xmlUnlockLibrary() {
523    crate::xml::threads::unlock_library();
524}
525
526// ═══════════════════════════════════════════════════════════════════════════════
527// 4. Error Handling
528// ═══════════════════════════════════════════════════════════════════════════════
529
530/// Set the generic error handler.
531///
532/// # UPSTREAM-PARITY
533///
534/// ```c
535/// void xmlSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler);
536/// ```
537///
538/// # SAFETY
539///
540/// - `handler` must be a valid function pointer or NULL (to reset to default).
541/// - If non-NULL, the handler may be called at any time with `ctx`.
542#[no_mangle]
543pub unsafe extern "C" fn xmlSetGenericErrorFunc(
544    ctx: *mut c_void,
545    handler: Option<crate::abi::callbacks::xmlGenericErrorFunc>,
546) {
547    // SAFETY: Delegates to xml::errors with same safety contract.
548    unsafe { crate::xml::errors::set_generic_error_func(ctx, handler) };
549}
550
551/// Set the structured error handler.
552///
553/// # UPSTREAM-PARITY
554///
555/// ```c
556/// void xmlSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler);
557/// ```
558///
559/// # SAFETY
560///
561/// - `handler` must be a valid function pointer or NULL.
562#[no_mangle]
563pub unsafe extern "C" fn xmlSetStructuredErrorFunc(
564    ctx: *mut c_void,
565    handler: Option<xmlStructuredErrorFunc>,
566) {
567    // SAFETY: Delegates to xml::errors with same safety contract.
568    unsafe { crate::xml::errors::set_structured_error_func(ctx, handler) };
569}
570
571/// Get the last error for the current thread.
572///
573/// # UPSTREAM-PARITY
574///
575/// ```c
576/// xmlErrorPtr xmlGetLastError(void);
577/// ```
578///
579/// Returns a pointer to the last error, or NULL if no error occurred.
580/// The returned pointer is valid until the next libxml2 call in this thread.
581#[no_mangle]
582pub extern "C" fn xmlGetLastError() -> *mut _xmlError {
583    crate::xml::errors::get_last_error()
584}
585
586/// Get a copy of the last error for the current thread.
587///
588/// # UPSTREAM-PARITY
589///
590/// ```c
591/// xmlErrorPtr xmlCopyError(xmlErrorPtr from, xmlErrorPtr to);
592/// ```
593///
594/// Copies `from` into `to`. Returns 0 on success, -1 on error.
595///
596/// # SAFETY
597///
598/// - `from` and `to` must be valid pointers to `_xmlError` structs, or NULL.
599#[no_mangle]
600pub unsafe extern "C" fn xmlCopyError(from: *const _xmlError, to: *mut _xmlError) -> c_int {
601    // SAFETY: Delegates to xml::errors with same safety contract.
602    unsafe { crate::xml::errors::copy_error(from, to) }
603}
604
605/// Reset an error structure.
606///
607/// # UPSTREAM-PARITY
608///
609/// ```c
610/// void xmlResetError(xmlErrorPtr err);
611/// ```
612///
613/// # SAFETY
614///
615/// - `err` must be a valid pointer to `_xmlError`, or NULL.
616#[no_mangle]
617pub const unsafe extern "C" fn xmlResetError(err: *mut _xmlError) {
618    // SAFETY: Delegates to xml::errors with same safety contract.
619    unsafe { crate::xml::errors::reset_error(err) };
620}
621
622/// Raise a structured error.
623///
624/// This is called internally when an error occurs. It updates the last error
625/// and invokes the structured error handler if one is set.
626///
627/// # SAFETY
628///
629/// - `ctxt` may be NULL (context of the error).
630/// - `domain`, `code`, `level`: valid error codes.
631/// - `msg` must be a valid C string or NULL.
632/// - `file` must be a valid C string or NULL.
633/// - `str1`, `str2`, `str3`: error-related strings (may be NULL).
634#[no_mangle]
635pub unsafe extern "C" fn xmlRaiseError(
636    ctxt: *mut c_void,
637    ctxt2: *mut c_void,
638    ctxt3: *mut c_void,
639    ctxt4: *mut c_void,
640    ctxt5: *mut c_void,
641    domain: c_int,
642    code: c_int,
643    level: c_int,
644    file: *const c_char,
645    line: c_int,
646    str1: *const c_char,
647    str2: *const c_char,
648    str3: *const c_char,
649    int1: c_int,
650    int2: c_int,
651    msg: *const c_char,
652) {
653    // SAFETY: Delegates to xml::errors with same safety contract.
654    unsafe {
655        crate::xml::errors::raise_error(
656            ctxt, ctxt2, ctxt3, ctxt4, ctxt5, domain, code, level, file, line, str1, str2, str3,
657            int1, int2, msg,
658        );
659    }
660}
661
662/// Remove any error from the last error stack.
663///
664/// # UPSTREAM-PARITY
665///
666/// ```c
667/// void xmlResetLastError(void);
668/// ```
669#[no_mangle]
670pub extern "C" fn xmlResetLastError() {
671    crate::xml::errors::reset_last_error();
672}
673
674// ═══════════════════════════════════════════════════════════════════════════════
675// 5. String Utilities
676// ═══════════════════════════════════════════════════════════════════════════════
677
678/// Duplicate a string using xmlChar.
679///
680/// # UPSTREAM-PARITY
681///
682/// ```c
683/// xmlChar *xmlStrdup(const xmlChar *cur);
684/// ```
685///
686/// # SAFETY
687///
688/// - `cur` must be a valid null-terminated xmlChar string or NULL.
689#[no_mangle]
690pub unsafe extern "C" fn xmlStrdup(cur: *const xmlChar) -> *mut xmlChar {
691    if cur.is_null() {
692        return ptr::null_mut();
693    }
694    let len = unsafe { xmlStrlen(cur) };
695    let size = len + 1;
696    let new_ptr = unsafe { xmlMallocImpl(size as usize) };
697    if new_ptr.is_null() {
698        return ptr::null_mut();
699    }
700    unsafe {
701        ptr::copy_nonoverlapping(cur, new_ptr as *mut u8, size as usize);
702    }
703    new_ptr as *mut xmlChar
704}
705
706/// Duplicate a substring.
707///
708/// # UPSTREAM-PARITY
709///
710/// ```c
711/// xmlChar *xmlStrndup(const xmlChar *cur, int len);
712/// ```
713///
714/// # SAFETY
715///
716/// - `cur` must be a valid pointer or NULL.
717#[no_mangle]
718pub unsafe extern "C" fn xmlStrndup(cur: *const xmlChar, len: c_int) -> *mut xmlChar {
719    // UPSTREAM-PARITY (xmlstring.c xmlStrndup): a NEGATIVE length means
720    // strlen; length 0 still allocates a 1-byte NUL string (never NULL) —
721    // xmlNewTextLen("", 0) depends on it so an empty text node keeps its
722    // content and survives xmlAddChild (php textContent = NULL writes an
723    // empty text child; serialization then prints <e></e>, not <e/>).
724    if cur.is_null() || len < 0 {
725        return ptr::null_mut();
726    }
727    let size = len as usize + 1;
728    let new_ptr = unsafe { xmlMallocImpl(size) };
729    if new_ptr.is_null() {
730        return ptr::null_mut();
731    }
732    unsafe {
733        ptr::copy_nonoverlapping(cur, new_ptr as *mut u8, len as usize);
734        *(new_ptr.add(len as usize) as *mut u8) = 0;
735    }
736    new_ptr as *mut xmlChar
737}
738
739/// Get the length of an xmlChar string.
740///
741/// # UPSTREAM-PARITY
742///
743/// ```c
744/// int xmlStrlen(const xmlChar *str);
745/// ```
746///
747/// # SAFETY
748///
749/// - `str` must be a valid null-terminated string or NULL (returns 0).
750#[no_mangle]
751pub unsafe extern "C" fn xmlStrlen(str: *const xmlChar) -> c_int {
752    if str.is_null() {
753        return 0;
754    }
755    unsafe { libc::strlen(str as *const c_char) as c_int }
756}
757
758/// Find the first occurrence of a character in a string (upstream tree.c
759/// `xmlStrchr`): returns a pointer to the first occurrence or NULL.
760///
761/// # UPSTREAM-PARITY
762///
763/// ```c
764/// const xmlChar *xmlStrchr(const xmlChar *str, xmlChar val);
765/// ```
766///
767/// # SAFETY
768///
769/// - `str` must be a valid null-terminated string or NULL.
770#[no_mangle]
771pub const unsafe extern "C" fn xmlStrchr(str: *const xmlChar, val: xmlChar) -> *const xmlChar {
772    if str.is_null() {
773        return ptr::null();
774    }
775    unsafe {
776        let mut cur = str;
777        while *cur != 0 {
778            if *cur == val {
779                return cur;
780            }
781            cur = cur.add(1);
782        }
783        ptr::null()
784    }
785}
786
787/// Compare two xmlChar strings.
788///
789/// # UPSTREAM-PARITY
790///
791/// ```c
792/// int xmlStrcmp(const xmlChar *str1, const xmlChar *str2);
793/// ```
794///
795/// Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2.
796/// NULL-safe: NULL sorts before any non-NULL string.
797#[no_mangle]
798pub unsafe extern "C" fn xmlStrcmp(str1: *const xmlChar, str2: *const xmlChar) -> c_int {
799    if str1.is_null() && str2.is_null() {
800        return 0;
801    }
802    if str1.is_null() {
803        return -1;
804    }
805    if str2.is_null() {
806        return 1;
807    }
808    unsafe { libc::strcmp(str1 as *const c_char, str2 as *const c_char) as c_int }
809}
810
811/// Compare two xmlChar strings up to a given length.
812///
813/// # UPSTREAM-PARITY
814///
815/// ```c
816/// int xmlStrncmp(const xmlChar *str1, const xmlChar *str2, int len);
817/// ```
818#[no_mangle]
819pub unsafe extern "C" fn xmlStrncmp(
820    str1: *const xmlChar,
821    str2: *const xmlChar,
822    len: c_int,
823) -> c_int {
824    if len <= 0 {
825        return 0;
826    }
827    if str1.is_null() && str2.is_null() {
828        return 0;
829    }
830    if str1.is_null() {
831        return -1;
832    }
833    if str2.is_null() {
834        return 1;
835    }
836    unsafe { libc::strncmp(str1 as *const c_char, str2 as *const c_char, len as usize) as c_int }
837}
838
839/// Case-insensitive comparison of two xmlChar strings.
840///
841/// # UPSTREAM-PARITY
842///
843/// ```c
844/// int xmlStrcasecmp(const xmlChar *str1, const xmlChar *str2);
845/// ```
846#[no_mangle]
847pub unsafe extern "C" fn xmlStrcasecmp(str1: *const xmlChar, str2: *const xmlChar) -> c_int {
848    if str1.is_null() && str2.is_null() {
849        return 0;
850    }
851    if str1.is_null() {
852        return -1;
853    }
854    if str2.is_null() {
855        return 1;
856    }
857    unsafe { libc::strcasecmp(str1 as *const c_char, str2 as *const c_char) as c_int }
858}
859
860/// Case-insensitive comparison with length limit.
861///
862/// # UPSTREAM-PARITY
863///
864/// ```c
865/// int xmlStrncasecmp(const xmlChar *str1, const xmlChar *str2, int len);
866/// ```
867#[no_mangle]
868pub unsafe extern "C" fn xmlStrncasecmp(
869    str1: *const xmlChar,
870    str2: *const xmlChar,
871    len: c_int,
872) -> c_int {
873    if len <= 0 {
874        return 0;
875    }
876    if str1.is_null() && str2.is_null() {
877        return 0;
878    }
879    if str1.is_null() {
880        return -1;
881    }
882    if str2.is_null() {
883        return 1;
884    }
885    unsafe {
886        libc::strncasecmp(str1 as *const c_char, str2 as *const c_char, len as usize) as c_int
887    }
888}
889
890/// Check if two xmlChar strings are equal.
891///
892/// # UPSTREAM-PARITY
893///
894/// ```c
895/// int xmlStrEqual(const xmlChar *str1, const xmlChar *str2);
896/// ```
897///
898/// Returns 1 if equal, 0 if not. NULL-safe.
899#[no_mangle]
900pub unsafe extern "C" fn xmlStrEqual(str1: *const xmlChar, str2: *const xmlChar) -> c_int {
901    if str1.is_null() && str2.is_null() {
902        return 1;
903    }
904    if str1.is_null() || str2.is_null() {
905        return 0;
906    }
907    unsafe { (libc::strcmp(str1 as *const c_char, str2 as *const c_char) == 0) as c_int }
908}
909
910/// Build a QName (upstream tree.h).
911///
912/// # UPSTREAM-PARITY
913///
914/// ```c
915/// xmlChar *xmlBuildQName(const xmlChar *ncname, const xmlChar *prefix,
916///                        xmlChar *memory, int len);
917/// ```
918#[no_mangle]
919pub unsafe extern "C" fn xmlBuildQName(
920    ncname: *const xmlChar,
921    prefix: *const xmlChar,
922    memory: *mut xmlChar,
923    len: c_int,
924) -> *mut xmlChar {
925    crate::xml::string::build_qname(ncname, prefix, memory, len)
926}
927
928/// Split a QName into prefix + local part (upstream tree.h).
929///
930/// # UPSTREAM-PARITY
931///
932/// ```c
933/// xmlChar *xmlSplitQName2(const xmlChar *name, xmlChar **prefix);
934/// ```
935#[no_mangle]
936pub unsafe extern "C" fn xmlSplitQName2(
937    name: *const xmlChar,
938    prefix: *mut *mut xmlChar,
939) -> *mut xmlChar {
940    crate::xml::string::split_qname2(name, prefix)
941}
942
943/// Return a pointer to the local part of a QName, filling `*len` with the
944/// prefix length (upstream tree.h — R-000176, the candidate previously
945/// returned the prefix length as an int).
946///
947/// # UPSTREAM-PARITY
948///
949/// ```c
950/// const xmlChar *xmlSplitQName3(const xmlChar *name, int *len);
951/// ```
952#[no_mangle]
953pub unsafe extern "C" fn xmlSplitQName3(name: *const xmlChar, len: *mut c_int) -> *mut xmlChar {
954    crate::xml::string::split_qname3(name, len)
955}
956
957/// Split a QName into prefix + local part (upstream parserInternals.h
958/// `xmlSplitQName(ctxt, name, prefix)` — the `ctxt` first argument is part
959/// of the ABI; R-000176, the candidate previously exported the 2-argument
960/// tree.h `xmlSplitQName2` form under this name).
961///
962/// # UPSTREAM-PARITY
963///
964/// ```c
965/// xmlChar *xmlSplitQName(xmlParserCtxt *ctxt, const xmlChar *name,
966///                        xmlChar **prefix);
967/// ```
968///
969/// `ctxt` is accepted for ABI parity; upstream uses it only for the name-
970/// length limit and error reporting (candidate: parser-side error model).
971#[no_mangle]
972pub unsafe extern "C" fn xmlSplitQName(
973    _ctxt: *mut _xmlParserCtxt,
974    name: *const xmlChar,
975    prefix: *mut *mut xmlChar,
976) -> *mut xmlChar {
977    crate::xml::string::split_qname2(name, prefix)
978}
979
980/// Count UTF-8 characters (upstream xmlstring.h).
981///
982/// # UPSTREAM-PARITY
983///
984/// ```c
985/// int xmlUTF8Strlen(const xmlChar *utf);
986/// ```
987#[no_mangle]
988pub const unsafe extern "C" fn xmlUTF8Strlen(utf: *const xmlChar) -> c_int {
989    crate::xml::string::utf8_strlen(utf)
990}
991
992/// Size in bytes of a UTF-8 sequence (upstream xmlstring.h).
993///
994/// # UPSTREAM-PARITY
995///
996/// ```c
997/// int xmlUTF8Size(const xmlChar *utf);
998/// ```
999#[no_mangle]
1000pub const unsafe extern "C" fn xmlUTF8Size(utf: *const xmlChar) -> c_int {
1001    crate::xml::string::utf8_size(utf)
1002}
1003
1004/// Check UTF-8 validity (upstream xmlstring.h).
1005///
1006/// # UPSTREAM-PARITY
1007///
1008/// ```c
1009/// int xmlCheckUTF8(const unsigned char *utf);
1010/// ```
1011#[no_mangle]
1012pub const unsafe extern "C" fn xmlCheckUTF8(utf: *const xmlChar) -> c_int {
1013    crate::xml::string::check_utf8(utf)
1014}
1015
1016/// Check if an xmlChar string equals a qualified name.
1017///
1018/// # UPSTREAM-PARITY
1019///
1020/// ```c
1021/// int xmlStrQEqual(const xmlChar *pref, const xmlChar *name, const xmlChar *str);
1022/// ```
1023///
1024/// Returns 1 if `pref:name` equals `str`, 0 otherwise.
1025/// `pref` may be NULL (compares only name).
1026#[no_mangle]
1027pub unsafe extern "C" fn xmlStrQEqual(
1028    pref: *const xmlChar,
1029    name: *const xmlChar,
1030    str: *const xmlChar,
1031) -> c_int {
1032    if name.is_null() || str.is_null() {
1033        return 0;
1034    }
1035    if pref.is_null() {
1036        return unsafe { xmlStrEqual(name, str) };
1037    }
1038    // Compare "pref:name" with str
1039    let pref_len = unsafe { xmlStrlen(pref) };
1040    let name_len = unsafe { xmlStrlen(name) };
1041    let total_len = pref_len + 1 + name_len;
1042    let str_len = unsafe { xmlStrlen(str) };
1043    if total_len != str_len {
1044        return 0;
1045    }
1046    // Compare prefix part
1047    if unsafe {
1048        libc::strncmp(
1049            pref as *const c_char,
1050            str as *const c_char,
1051            pref_len as usize,
1052        )
1053    } != 0
1054    {
1055        return 0;
1056    }
1057    // Check colon
1058    if unsafe { *str.add(pref_len as usize) } != b':' as xmlChar {
1059        return 0;
1060    }
1061    // Compare name part
1062    (unsafe {
1063        libc::strncmp(
1064            name as *const c_char,
1065            str.add((pref_len + 1) as usize) as *const c_char,
1066            name_len as usize,
1067        ) == 0
1068    }) as c_int
1069}
1070
1071/// Concatenate two strings.
1072///
1073/// # UPSTREAM-PARITY
1074///
1075/// ```c
1076/// xmlChar *xmlStrcat(xmlChar *cur, const xmlChar *add);
1077/// ```
1078///
1079/// # SAFETY
1080///
1081/// - `cur` must be a valid xmlMalloc'd string or NULL.
1082/// - `add` must be a valid string or NULL.
1083/// - If `cur` is NULL, behaves like xmlStrdup(add).
1084#[no_mangle]
1085pub unsafe extern "C" fn xmlStrcat(cur: *mut xmlChar, add: *const xmlChar) -> *mut xmlChar {
1086    if add.is_null() {
1087        return cur;
1088    }
1089    if cur.is_null() {
1090        return unsafe { xmlStrdup(add) };
1091    }
1092    let cur_len = unsafe { xmlStrlen(cur) } as usize;
1093    let add_len = unsafe { xmlStrlen(add) } as usize;
1094    let new_size = cur_len + add_len + 1;
1095    let new_ptr = unsafe { xmlReallocImpl(cur as *mut c_void, new_size) };
1096    if new_ptr.is_null() {
1097        // UPSTREAM-PARITY (xmlstring.c xmlStrcat -> xmlStrncat): on realloc
1098        // failure upstream frees `cur` and returns NULL — the caller must
1099        // not touch `cur` afterwards (HOSTILE-ALLOCATOR H4).
1100        unsafe { xmlFreeImpl(cur as *mut c_void) };
1101        return ptr::null_mut();
1102    }
1103    unsafe {
1104        ptr::copy_nonoverlapping(add, (new_ptr as *mut u8).add(cur_len), add_len);
1105        *((new_ptr as *mut u8).add(cur_len + add_len)) = 0;
1106    }
1107    new_ptr as *mut xmlChar
1108}
1109
1110/// Concatenate up to `len` characters.
1111///
1112/// # UPSTREAM-PARITY
1113///
1114/// ```c
1115/// xmlChar *xmlStrncat(xmlChar *cur, const xmlChar *add, int len);
1116/// ```
1117///
1118/// # SAFETY
1119///
1120/// Same as xmlStrcat, but only copies up to `len` characters from `add`.
1121#[no_mangle]
1122pub unsafe extern "C" fn xmlStrncat(
1123    cur: *mut xmlChar,
1124    add: *const xmlChar,
1125    len: c_int,
1126) -> *mut xmlChar {
1127    if add.is_null() || len <= 0 {
1128        return cur;
1129    }
1130    let len = len as usize;
1131    if cur.is_null() {
1132        return unsafe { xmlStrndup(add, len as c_int) };
1133    }
1134    let cur_len = unsafe { xmlStrlen(cur) } as usize;
1135    let new_size = cur_len + len + 1;
1136    let new_ptr = unsafe { xmlReallocImpl(cur as *mut c_void, new_size) };
1137    if new_ptr.is_null() {
1138        // UPSTREAM-PARITY (xmlstring.c xmlStrncat): on realloc failure
1139        // upstream frees `cur` and returns NULL — the caller must not touch
1140        // `cur` afterwards (HOSTILE-ALLOCATOR H4).
1141        unsafe { xmlFreeImpl(cur as *mut c_void) };
1142        return ptr::null_mut();
1143    }
1144    unsafe {
1145        ptr::copy_nonoverlapping(add, (new_ptr as *mut u8).add(cur_len), len);
1146        *((new_ptr as *mut u8).add(cur_len + len)) = 0;
1147    }
1148    new_ptr as *mut xmlChar
1149}
1150
1151/// Create a new string by concatenating up to `len` characters.
1152///
1153/// # UPSTREAM-PARITY
1154///
1155/// ```c
1156/// xmlChar *xmlStrncatNew(const xmlChar *str1, const xmlChar *str2, int len);
1157/// ```
1158#[no_mangle]
1159pub unsafe extern "C" fn xmlStrncatNew(
1160    str1: *const xmlChar,
1161    str2: *const xmlChar,
1162    len: c_int,
1163) -> *mut xmlChar {
1164    let mut result: *mut xmlChar = ptr::null_mut();
1165    if !str1.is_null() {
1166        result = unsafe { xmlStrdup(str1) };
1167    }
1168    if !str2.is_null() && len > 0 {
1169        result = unsafe { xmlStrncat(result, str2, len) };
1170    }
1171    result
1172}
1173
1174/// Copy a string.
1175///
1176/// # UPSTREAM-PARITY
1177///
1178/// ```c
1179/// xmlChar *xmlStrcpy(xmlChar *dst, const xmlChar *src);
1180/// ```
1181///
1182/// # SAFETY
1183///
1184/// - `dst` must be a valid xmlMalloc'd buffer large enough to hold `src`.
1185/// - `src` must be a valid string.
1186#[no_mangle]
1187pub unsafe extern "C" fn xmlStrcpy(dst: *mut xmlChar, src: *const xmlChar) -> *mut xmlChar {
1188    if dst.is_null() || src.is_null() {
1189        return dst;
1190    }
1191    let len = unsafe { xmlStrlen(src) } as usize + 1;
1192    unsafe {
1193        ptr::copy_nonoverlapping(src, dst, len);
1194    }
1195    dst
1196}
1197
1198/// Copy up to `len` characters.
1199///
1200/// # UPSTREAM-PARITY
1201///
1202/// ```c
1203/// xmlChar *xmlStrncpy(xmlChar *dst, const xmlChar *src, int len);
1204/// ```
1205#[no_mangle]
1206pub unsafe extern "C" fn xmlStrncpy(
1207    dst: *mut xmlChar,
1208    src: *const xmlChar,
1209    len: c_int,
1210) -> *mut xmlChar {
1211    if dst.is_null() || src.is_null() || len <= 0 {
1212        return dst;
1213    }
1214    let len = len as usize;
1215    let src_len = unsafe { xmlStrlen(src) } as usize;
1216    let copy_len = if src_len < len { src_len } else { len - 1 };
1217    unsafe {
1218        ptr::copy_nonoverlapping(src, dst, copy_len);
1219        *dst.add(copy_len) = 0;
1220    }
1221    dst
1222}
1223
1224/// Extract a substring.
1225///
1226/// # UPSTREAM-PARITY
1227///
1228/// ```c
1229/// xmlChar *xmlStrsub(const xmlChar *str, int start, int len);
1230/// ```
1231///
1232/// Returns a newly allocated substring, or NULL on error.
1233#[no_mangle]
1234pub unsafe extern "C" fn xmlStrsub(str: *const xmlChar, start: c_int, len: c_int) -> *mut xmlChar {
1235    if str.is_null() || start < 0 || len < 0 {
1236        return ptr::null_mut();
1237    }
1238    let str_len = unsafe { xmlStrlen(str) };
1239    if start >= str_len {
1240        return unsafe { xmlStrdup(b"\0" as *const u8 as *const xmlChar) };
1241    }
1242    let actual_len = if start + len > str_len {
1243        str_len - start
1244    } else {
1245        len
1246    };
1247    unsafe { xmlStrndup(str.add(start as usize), actual_len) }
1248}
1249
1250// ═══════════════════════════════════════════════════════════════════════════════
1251// 6. Tree — Document, Node, Attribute, Namespace, DTD, Entity
1252// ═══════════════════════════════════════════════════════════════════════════════
1253
1254/// Create a new document.
1255///
1256/// # UPSTREAM-PARITY
1257///
1258/// ```c
1259/// xmlDocPtr xmlNewDoc(const xmlChar *version);
1260/// ```
1261///
1262/// # SAFETY
1263///
1264/// - `version` must be a valid string or NULL (defaults to "1.0").
1265/// - Returns a newly allocated document. Caller must free with `xmlFreeDoc`.
1266#[no_mangle]
1267pub unsafe extern "C" fn xmlNewDoc(version: *const xmlChar) -> *mut _xmlDoc {
1268    crate::xml::tree::new_doc(version)
1269}
1270
1271/// Free a document.
1272///
1273/// # UPSTREAM-PARITY
1274///
1275/// ```c
1276/// void xmlFreeDoc(xmlDocPtr doc);
1277/// ```
1278///
1279/// # SAFETY
1280///
1281/// - `doc` must be a valid document pointer or NULL.
1282#[no_mangle]
1283pub unsafe extern "C" fn xmlFreeDoc(doc: *mut _xmlDoc) {
1284    crate::xml::tree::free_doc(doc);
1285}
1286
1287/// Get the compression mode of a document (upstream tree.h).
1288///
1289/// # UPSTREAM-PARITY
1290///
1291/// ```c
1292/// int xmlGetDocCompressMode(const xmlDoc *doc);
1293/// ```
1294///
1295/// Returns the compression level (0-9) or -1 if `doc` is NULL.
1296#[no_mangle]
1297pub unsafe extern "C" fn xmlGetDocCompressMode(doc: *mut _xmlDoc) -> c_int {
1298    crate::xml::tree::xmlGetDocCompressMode(doc)
1299}
1300
1301/// Set the compression mode of a document (upstream tree.h).
1302///
1303/// # UPSTREAM-PARITY
1304///
1305/// ```c
1306/// void xmlSetDocCompressMode(xmlDocPtr doc, int mode);
1307/// ```
1308#[no_mangle]
1309pub unsafe extern "C" fn xmlSetDocCompressMode(doc: *mut _xmlDoc, mode: c_int) {
1310    crate::xml::tree::xmlSetDocCompressMode(doc, mode);
1311}
1312
1313/// Create a new node.
1314///
1315/// # UPSTREAM-PARITY
1316///
1317/// ```c
1318/// xmlNodePtr xmlNewNode(xmlNsPtr ns, const xmlChar *name);
1319/// ```
1320///
1321/// # SAFETY
1322///
1323/// - `ns` may be NULL.
1324/// - `name` must be a valid string.
1325/// - Returns a newly allocated node. Caller must free with `xmlFreeNode`.
1326#[no_mangle]
1327pub unsafe extern "C" fn xmlNewNode(ns: *mut _xmlNs, name: *const xmlChar) -> *mut _xmlNode {
1328    crate::xml::tree::new_node(ns, name)
1329}
1330
1331/// Free a node.
1332///
1333/// # UPSTREAM-PARITY
1334///
1335/// ```c
1336/// void xmlFreeNode(xmlNodePtr node);
1337/// ```
1338///
1339/// # SAFETY
1340///
1341/// - `node` must be a valid node pointer or NULL.
1342/// - The node must NOT be part of a document tree (must be unlinked first).
1343#[no_mangle]
1344pub unsafe extern "C" fn xmlFreeNode(node: *mut _xmlNode) {
1345    crate::xml::tree::free_node(node);
1346}
1347
1348/// Free a linked list of nodes (upstream tree.h).
1349///
1350/// # UPSTREAM-PARITY
1351///
1352/// ```c
1353/// void xmlFreeNodeList(xmlNodePtr node);
1354/// ```
1355///
1356/// Frees the node and all its siblings (following `next` pointers),
1357/// recursively freeing children. Matches upstream `xmlFreeNodeList`
1358/// (tree.c): a NULL argument is a no-op.
1359///
1360/// # SAFETY
1361///
1362/// - `node` must be a valid node pointer or NULL.
1363/// - The list must NOT be part of a document tree (must be unlinked first).
1364#[no_mangle]
1365pub unsafe extern "C" fn xmlFreeNodeList(node: *mut _xmlNode) {
1366    crate::xml::tree::free_node_list(node);
1367}
1368
1369/// Unlink a node from its tree.
1370///
1371/// # UPSTREAM-PARITY
1372///
1373/// ```c
1374/// void xmlUnlinkNode(xmlNodePtr node);
1375/// ```
1376///
1377/// # SAFETY
1378///
1379/// - `node` must be a valid node pointer or NULL.
1380#[no_mangle]
1381pub unsafe extern "C" fn xmlUnlinkNode(node: *mut _xmlNode) {
1382    crate::xml::tree::unlink_node(node);
1383}
1384
1385/// Initialize a SAX handler with the default SAX2 callbacks (upstream SAX2.h).
1386///
1387/// # UPSTREAM-PARITY
1388///
1389/// ```c
1390/// void xmlSAX2InitDefaultSAXHandler(xmlSAXHandler *hdlr, int warning);
1391/// ```
1392///
1393/// The `warning` parameter controls whether the warning callback is set in
1394/// upstream; the candidate always sets it (the parser dispatches warnings
1395/// identically) — a documented safe divergence tracked in the parity ledger.
1396///
1397/// # SAFETY
1398///
1399/// - `handler` must be a valid writable `_xmlSAXHandler` or NULL.
1400#[no_mangle]
1401pub unsafe extern "C" fn xmlSAX2InitDefaultSAXHandler(
1402    handler: *mut crate::abi::structs::_xmlSAXHandler,
1403    _warning: c_int,
1404) {
1405    crate::xml::sax::dispatch::xmlSAX2InitDefaultSAXHandler(handler);
1406}
1407
1408/// Initialize a SAX handler with the default HTML callbacks (upstream SAX2.h).
1409///
1410/// # UPSTREAM-PARITY
1411///
1412/// ```c
1413/// void xmlSAX2InitHtmlDefaultSAXHandler(xmlSAXHandler *hdlr);
1414/// ```
1415///
1416/// Upstream (SAX2.c `xmlSAX2InitHtmlDefaultSAXHandler`) fills the handler
1417/// with the SAX2 defaults minus the DTD-declaration callbacks
1418/// (resolveEntity/getParameterEntity/entityDecl/attributeDecl/elementDecl/
1419/// notationDecl/unparsedEntityDecl/reference/externalSubset are NULL) and
1420/// sets `initialized = 1` (not XML_SAX2_MAGIC). The candidate mirrors that
1421/// exactly.
1422///
1423/// # SAFETY
1424///
1425/// - `handler` must be a valid writable `_xmlSAXHandler` or NULL.
1426#[no_mangle]
1427pub unsafe extern "C" fn xmlSAX2InitHtmlDefaultSAXHandler(
1428    handler: *mut crate::abi::structs::_xmlSAXHandler,
1429) {
1430    if handler.is_null() {
1431        return;
1432    }
1433    // SAFETY: handler is non-NULL and writable.
1434    unsafe {
1435        // The DTD-ish callbacks are not part of the HTML default set.
1436        if (*handler).initialized != 0 {
1437            return;
1438        }
1439        crate::xml::sax::dispatch::xmlSAX2InitDefaultSAXHandler(handler);
1440        let h = &mut *handler;
1441        h.resolveEntity = None;
1442        h.getParameterEntity = None;
1443        h.entityDecl = None;
1444        h.attributeDecl = None;
1445        h.elementDecl = None;
1446        h.notationDecl = None;
1447        h.unparsedEntityDecl = None;
1448        h.reference = None;
1449        h.externalSubset = None;
1450        h.initialized = 1;
1451    }
1452}
1453
1454/// Add a child node.
1455///
1456/// # UPSTREAM-PARITY
1457///
1458/// ```c
1459/// xmlNodePtr xmlAddChild(xmlNodePtr parent, xmlNodePtr cur);
1460/// ```
1461///
1462/// # SAFETY
1463///
1464/// - `parent` must be a valid node.
1465/// - `cur` must be a valid node (ownership transfers to parent).
1466/// - Returns pointer to the added child (borrowed).
1467#[no_mangle]
1468pub unsafe extern "C" fn xmlAddChild(parent: *mut _xmlNode, cur: *mut _xmlNode) -> *mut _xmlNode {
1469    crate::xml::tree::add_child(parent, cur)
1470}
1471
1472/// Add a sibling node.
1473///
1474/// # UPSTREAM-PARITY
1475///
1476/// ```c
1477/// xmlNodePtr xmlAddSibling(xmlNodePtr cur, xmlNodePtr sibling);
1478/// ```
1479///
1480/// # SAFETY
1481///
1482/// Same as xmlAddChild, but adds after `cur` instead of as a child.
1483#[no_mangle]
1484pub unsafe extern "C" fn xmlAddSibling(
1485    cur: *mut _xmlNode,
1486    sibling: *mut _xmlNode,
1487) -> *mut _xmlNode {
1488    crate::xml::tree::add_sibling(cur, sibling)
1489}
1490
1491/// Create a new child element.
1492///
1493/// # UPSTREAM-PARITY
1494///
1495/// ```c
1496/// xmlNodePtr xmlNewChild(xmlNodePtr parent, xmlNsPtr ns,
1497///                        const xmlChar *name, const xmlChar *content);
1498/// ```
1499///
1500/// Creates a new element node, adds it as a child of `parent`, and
1501/// sets its content if `content` is non-NULL.
1502///
1503/// # SAFETY
1504///
1505/// - `parent` must be a valid node (may be NULL).
1506/// - `ns` may be NULL.
1507/// - `name` must be a valid string.
1508/// - Returns a newly allocated node (owned by parent).
1509#[no_mangle]
1510pub unsafe extern "C" fn xmlNewChild(
1511    parent: *mut _xmlNode,
1512    ns: *mut _xmlNs,
1513    name: *const xmlChar,
1514    content: *const xmlChar,
1515) -> *mut _xmlNode {
1516    // UPSTREAM-PARITY (tree.c 2.15 xmlNewChild -> xmlNewDocNode -> xmlNewElem):
1517    // the content is parsed as an ATTRIBUTE VALUE (xmlNodeParseAttValue) —
1518    // character references are decoded (`a &#38; b` becomes `a & b`),
1519    // declared general entities become entity-ref children, and an EMPTY
1520    // content adds NO text child (SimpleXML addChild: bug44478 decode,
1521    // bug76712 `<bar/>` for addChild('bar','')). The old raw `new_text`
1522    // storage kept the reference text verbatim and appended an empty text
1523    // node for "".
1524    if parent.is_null() || name.is_null() {
1525        return ptr::null_mut();
1526    }
1527    let ptype = unsafe { (*parent).type_ };
1528    use crate::abi::types::xmlElementType::*;
1529    if ptype != XML_DOCUMENT_NODE as c_int
1530        && ptype != XML_HTML_DOCUMENT_NODE as c_int
1531        && ptype != XML_DOCUMENT_FRAG_NODE as c_int
1532        && ptype != XML_ELEMENT_NODE as c_int
1533    {
1534        return ptr::null_mut();
1535    }
1536    let mut ns = ns;
1537    if ptype == XML_ELEMENT_NODE as c_int && ns.is_null() {
1538        ns = unsafe { (*parent).ns };
1539    }
1540    let node = crate::abi::exports_tree::xmlNewDocNode(unsafe { (*parent).doc }, ns, name, content);
1541    if node.is_null() {
1542        return ptr::null_mut();
1543    }
1544    // Add the new element at the end of the parent's children (upstream
1545    // xmlNewChild links it directly after xmlNewDocNode).
1546    unsafe {
1547        (*node).parent = parent;
1548        if (*parent).children.is_null() {
1549            (*parent).children = node;
1550            (*parent).last = node;
1551        } else {
1552            let prev = (*parent).last;
1553            (*prev).next = node;
1554            (*node).prev = prev;
1555            (*parent).last = node;
1556        }
1557    }
1558    node
1559}
1560
1561/// Set the root element of a document.
1562///
1563/// # UPSTREAM-PARITY
1564///
1565/// ```c
1566/// xmlNodePtr xmlDocSetRootElement(xmlDocPtr doc, xmlNodePtr root);
1567/// ```
1568///
1569/// Returns the old root element (if any), which the caller must free.
1570///
1571/// # SAFETY
1572///
1573/// - `doc` must be a valid document.
1574/// - `root` must be a valid node (ownership transfers to doc).
1575#[no_mangle]
1576pub unsafe extern "C" fn xmlDocSetRootElement(
1577    doc: *mut _xmlDoc,
1578    root: *mut _xmlNode,
1579) -> *mut _xmlNode {
1580    crate::xml::tree::doc_set_root_element(doc, root)
1581}
1582
1583/// Get the root element of a document.
1584///
1585/// # UPSTREAM-PARITY
1586///
1587/// ```c
1588/// xmlNodePtr xmlDocGetRootElement(const xmlDoc *doc);
1589/// ```
1590///
1591/// Returns a borrowed pointer (do not free).
1592#[no_mangle]
1593pub extern "C" fn xmlDocGetRootElement(doc: *const _xmlDoc) -> *mut _xmlNode {
1594    crate::xml::tree::doc_get_root_element(doc as *mut _xmlDoc)
1595}
1596
1597/// Copy a node.
1598///
1599/// # UPSTREAM-PARITY
1600///
1601/// ```c
1602/// xmlNodePtr xmlCopyNode(const xmlNodePtr node, int extended);
1603/// ```
1604///
1605/// If `extended` is 1, copies recursively (deep copy).
1606/// If `extended` is 0, copies only the node itself (shallow copy).
1607///
1608/// Returns a newly allocated copy. Caller must free with `xmlFreeNode`.
1609#[no_mangle]
1610pub unsafe extern "C" fn xmlCopyNode(node: *const _xmlNode, extended: c_int) -> *mut _xmlNode {
1611    crate::xml::tree::copy_node(node, extended)
1612}
1613
1614/// Copy a document.
1615///
1616/// # UPSTREAM-PARITY
1617///
1618/// ```c
1619/// xmlDocPtr xmlCopyDoc(const xmlDocPtr doc, int recursive);
1620/// ```
1621///
1622/// Returns a newly allocated copy. Caller must free with `xmlFreeDoc`.
1623#[no_mangle]
1624pub unsafe extern "C" fn xmlCopyDoc(doc: *const _xmlDoc, recursive: c_int) -> *mut _xmlDoc {
1625    crate::xml::tree::copy_doc(doc, recursive)
1626}
1627
1628/// Create a text node.
1629///
1630/// # UPSTREAM-PARITY
1631///
1632/// ```c
1633/// xmlNodePtr xmlNewText(const xmlChar *content);
1634/// ```
1635///
1636/// Creates a new text node with the given content.
1637/// If `content` is NULL, creates an empty text node.
1638#[no_mangle]
1639pub unsafe extern "C" fn xmlNewText(content: *const xmlChar) -> *mut _xmlNode {
1640    crate::xml::tree::new_text(content)
1641}
1642
1643/// Create a new comment node.
1644///
1645/// # UPSTREAM-PARITY
1646///
1647/// ```c
1648/// xmlNodePtr xmlNewComment(const xmlChar *content);
1649/// ```
1650#[no_mangle]
1651pub unsafe extern "C" fn xmlNewComment(content: *const xmlChar) -> *mut _xmlNode {
1652    crate::xml::tree::new_comment(content)
1653}
1654
1655/// Create a new PI node.
1656///
1657/// # UPSTREAM-PARITY
1658///
1659/// ```c
1660/// xmlNodePtr xmlNewPI(const xmlChar *name, const xmlChar *content);
1661/// ```
1662#[no_mangle]
1663pub unsafe extern "C" fn xmlNewPI(name: *const xmlChar, content: *const xmlChar) -> *mut _xmlNode {
1664    crate::xml::tree::new_pi(name, content)
1665}
1666
1667/// Create a new CDATA node.
1668///
1669/// # UPSTREAM-PARITY
1670///
1671/// ```c
1672/// xmlNodePtr xmlNewCDataBlock(xmlDocPtr doc, const xmlChar *content, int len);
1673/// ```
1674#[no_mangle]
1675pub unsafe extern "C" fn xmlNewCDataBlock(
1676    doc: *mut _xmlDoc,
1677    content: *const xmlChar,
1678    len: c_int,
1679) -> *mut _xmlNode {
1680    crate::xml::tree::new_cdata_block(doc, content, len)
1681}
1682
1683/// Create a new namespace definition.
1684///
1685/// # UPSTREAM-PARITY
1686///
1687/// ```c
1688/// xmlNsPtr xmlNewNs(xmlNodePtr node, const xmlChar *href, const xmlChar *prefix);
1689/// ```
1690///
1691/// # SAFETY
1692///
1693/// - `node` may be NULL.
1694/// - `href` and `prefix` are copied.
1695/// - Returns a borrowed pointer (namespace is owned by the node).
1696#[no_mangle]
1697pub unsafe extern "C" fn xmlNewNs(
1698    node: *mut _xmlNode,
1699    href: *const xmlChar,
1700    prefix: *const xmlChar,
1701) -> *mut _xmlNs {
1702    crate::xml::tree::new_ns(node, href, prefix)
1703}
1704
1705/// Set the namespace of a node.
1706///
1707/// # UPSTREAM-PARITY
1708///
1709/// ```c
1710/// void xmlSetNs(xmlNodePtr node, xmlNsPtr ns);
1711/// ```
1712#[no_mangle]
1713pub unsafe extern "C" fn xmlSetNs(node: *mut _xmlNode, ns: *mut _xmlNs) {
1714    crate::xml::tree::set_ns(node, ns);
1715}
1716
1717/// Get the namespace of a node.
1718///
1719/// # UPSTREAM-PARITY
1720///
1721/// ```c
1722/// xmlNsPtr xmlGetNsList(xmlDocPtr doc, const xmlNode *node);
1723/// ```
1724#[no_mangle]
1725pub unsafe extern "C" fn xmlGetNsList(
1726    doc: *mut _xmlDoc,
1727    node: *const _xmlNode,
1728) -> *mut *mut _xmlNs {
1729    crate::xml::tree::get_ns_list(doc, node as *mut _xmlNode)
1730}
1731
1732/// Search for a namespace by href.
1733///
1734/// # UPSTREAM-PARITY
1735///
1736/// ```c
1737/// xmlNsPtr xmlSearchNs(xmlDocPtr doc, xmlNodePtr node, const xmlChar *nameSpace);
1738/// ```
1739#[no_mangle]
1740pub unsafe extern "C" fn xmlSearchNs(
1741    doc: *mut _xmlDoc,
1742    node: *mut _xmlNode,
1743    nameSpace: *const xmlChar,
1744) -> *mut _xmlNs {
1745    crate::xml::tree::search_ns(doc, node, nameSpace)
1746}
1747
1748/// Search for a namespace by href, using the full in-scope chain.
1749///
1750/// # UPSTREAM-PARITY
1751///
1752/// ```c
1753/// xmlNsPtr xmlSearchNsByHref(xmlDocPtr doc, xmlNodePtr node, const xmlChar *href);
1754/// ```
1755#[no_mangle]
1756pub unsafe extern "C" fn xmlSearchNsByHref(
1757    doc: *mut _xmlDoc,
1758    node: *mut _xmlNode,
1759    href: *const xmlChar,
1760) -> *mut _xmlNs {
1761    crate::xml::tree::search_ns_by_href(doc, node, href)
1762}
1763
1764/// Set a property (attribute) on a node.
1765///
1766/// # UPSTREAM-PARITY
1767///
1768/// ```c
1769/// xmlAttrPtr xmlSetProp(xmlNodePtr node, const xmlChar *name, const xmlChar *value);
1770/// ```
1771///
1772/// If the attribute already exists, its value is updated.
1773/// Returns a borrowed pointer to the attribute.
1774///
1775/// # SAFETY
1776///
1777/// - `node` must be a valid element node.
1778/// - `name` must be a valid string.
1779/// - `value` may be NULL.
1780#[no_mangle]
1781pub unsafe extern "C" fn xmlSetProp(
1782    node: *mut _xmlNode,
1783    name: *const xmlChar,
1784    value: *const xmlChar,
1785) -> *mut _xmlAttr {
1786    crate::xml::tree::set_prop(node, name, value)
1787}
1788
1789/// Get a property value by name.
1790///
1791/// # UPSTREAM-PARITY
1792///
1793/// ```c
1794/// xmlChar *xmlGetProp(const xmlNode *node, const xmlChar *name);
1795/// ```
1796///
1797/// Returns a newly allocated string. Caller must free with `xmlFree`.
1798#[no_mangle]
1799pub unsafe extern "C" fn xmlGetProp(node: *const _xmlNode, name: *const xmlChar) -> *mut xmlChar {
1800    crate::xml::tree::get_prop(node as *mut _xmlNode, name)
1801}
1802
1803/// Get a namespaced property value.
1804///
1805/// # UPSTREAM-PARITY
1806///
1807/// ```c
1808/// xmlChar *xmlGetNsProp(const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace);
1809/// ```
1810#[no_mangle]
1811pub unsafe extern "C" fn xmlGetNsProp(
1812    node: *const _xmlNode,
1813    name: *const xmlChar,
1814    nameSpace: *const xmlChar,
1815) -> *mut xmlChar {
1816    crate::xml::tree::get_ns_prop(node as *mut _xmlNode, name, nameSpace)
1817}
1818
1819/// Set a namespaced property.
1820///
1821/// # UPSTREAM-PARITY
1822///
1823/// ```c
1824/// xmlAttrPtr xmlSetNsProp(xmlNodePtr node, xmlNsPtr ns,
1825///                         const xmlChar *name, const xmlChar *value);
1826/// ```
1827#[no_mangle]
1828pub unsafe extern "C" fn xmlSetNsProp(
1829    node: *mut _xmlNode,
1830    ns: *mut _xmlNs,
1831    name: *const xmlChar,
1832    value: *const xmlChar,
1833) -> *mut _xmlAttr {
1834    crate::xml::tree::set_ns_prop(node, ns, name, value)
1835}
1836
1837/// Remove a property by name.
1838///
1839/// # UPSTREAM-PARITY
1840///
1841/// ```c
1842/// int xmlRemoveProp(xmlAttrPtr attr);
1843/// ```
1844///
1845/// Returns 0 on success, -1 on error.
1846#[no_mangle]
1847pub unsafe extern "C" fn xmlRemoveProp(attr: *mut _xmlAttr) -> c_int {
1848    crate::xml::tree::remove_prop(attr)
1849}
1850
1851/// Check whether a node has a property (upstream tree.h).
1852///
1853/// # UPSTREAM-PARITY
1854///
1855/// ```c
1856/// xmlAttrPtr xmlHasProp(const xmlNode *node, const xmlChar *name);
1857/// ```
1858///
1859/// Returns the attribute pointer or NULL.
1860#[no_mangle]
1861pub unsafe extern "C" fn xmlHasProp(node: *const _xmlNode, name: *const xmlChar) -> *mut _xmlAttr {
1862    crate::xml::tree::has_prop(node as *mut _xmlNode, name)
1863}
1864
1865/// Check whether a node has a namespaced property (upstream tree.h).
1866///
1867/// # UPSTREAM-PARITY
1868///
1869/// ```c
1870/// xmlAttrPtr xmlHasNsProp(const xmlNode *node, const xmlChar *name,
1871///                         const xmlChar *nameSpace);
1872/// ```
1873#[no_mangle]
1874pub unsafe extern "C" fn xmlHasNsProp(
1875    node: *const _xmlNode,
1876    name: *const xmlChar,
1877    nameSpace: *const xmlChar,
1878) -> *mut _xmlAttr {
1879    crate::xml::tree::has_ns_prop(node as *mut _xmlNode, name, nameSpace)
1880}
1881
1882/// Remove a property by name (upstream tree.h).
1883///
1884/// # UPSTREAM-PARITY
1885///
1886/// ```c
1887/// int xmlUnsetProp(xmlNodePtr node, const xmlChar *name);
1888/// ```
1889///
1890/// Returns 0 on success, -1 if not found.
1891#[no_mangle]
1892pub unsafe extern "C" fn xmlUnsetProp(node: *mut _xmlNode, name: *const xmlChar) -> c_int {
1893    crate::xml::tree::unset_prop(node, name)
1894}
1895
1896/// Remove a namespaced property by name (upstream tree.h).
1897///
1898/// # UPSTREAM-PARITY
1899///
1900/// ```c
1901/// int xmlUnsetNsProp(xmlNodePtr node, const xmlChar *name,
1902///                    const xmlChar *nameSpace);
1903/// ```
1904#[no_mangle]
1905pub unsafe extern "C" fn xmlUnsetNsProp(
1906    node: *mut _xmlNode,
1907    name: *const xmlChar,
1908    nameSpace: *const xmlChar,
1909) -> c_int {
1910    crate::xml::tree::unset_ns_prop(node, name, nameSpace)
1911}
1912
1913/// Return the first child element (upstream tree.h).
1914///
1915/// # UPSTREAM-PARITY
1916///
1917/// ```c
1918/// xmlNodePtr xmlFirstElementChild(xmlNodePtr parent);
1919/// ```
1920#[no_mangle]
1921pub unsafe extern "C" fn xmlFirstElementChild(parent: *mut _xmlNode) -> *mut _xmlNode {
1922    crate::xml::tree::first_element_child(parent)
1923}
1924
1925/// Return the last child element (upstream tree.h).
1926#[no_mangle]
1927pub unsafe extern "C" fn xmlLastElementChild(parent: *mut _xmlNode) -> *mut _xmlNode {
1928    crate::xml::tree::last_element_child(parent)
1929}
1930
1931/// Return the next element sibling (upstream tree.h).
1932#[no_mangle]
1933pub unsafe extern "C" fn xmlNextElementSibling(node: *mut _xmlNode) -> *mut _xmlNode {
1934    crate::xml::tree::next_element_sibling(node)
1935}
1936
1937/// Return the previous element sibling (upstream tree.h).
1938#[no_mangle]
1939pub unsafe extern "C" fn xmlPreviousElementSibling(node: *mut _xmlNode) -> *mut _xmlNode {
1940    crate::xml::tree::previous_element_sibling(node)
1941}
1942
1943/// Count the child elements (upstream tree.h).
1944///
1945/// # UPSTREAM-PARITY
1946///
1947/// ```c
1948/// unsigned long xmlChildElementCount(xmlNodePtr parent);
1949/// ```
1950#[no_mangle]
1951pub unsafe extern "C" fn xmlChildElementCount(parent: *mut _xmlNode) -> c_ulong {
1952    crate::xml::tree::child_element_count(parent)
1953}
1954
1955/// Concatenate text to a node (upstream tree.h).
1956///
1957/// # UPSTREAM-PARITY
1958///
1959/// ```c
1960/// int xmlTextConcat(xmlNodePtr node, const xmlChar *content, int len);
1961/// ```
1962#[no_mangle]
1963pub unsafe extern "C" fn xmlTextConcat(
1964    node: *mut _xmlNode,
1965    content: *const xmlChar,
1966    len: c_int,
1967) -> c_int {
1968    crate::xml::tree::text_concat(node, content, len)
1969}
1970
1971/// Merge two text nodes (upstream tree.h).
1972///
1973/// # UPSTREAM-PARITY
1974///
1975/// ```c
1976/// xmlNodePtr xmlTextMerge(xmlNodePtr first, xmlNodePtr second);
1977/// ```
1978#[no_mangle]
1979pub unsafe extern "C" fn xmlTextMerge(
1980    first: *mut _xmlNode,
1981    second: *mut _xmlNode,
1982) -> *mut _xmlNode {
1983    crate::xml::tree::text_merge(first, second)
1984}
1985
1986/// Get a DTD from a document, creating one if needed.
1987///
1988/// # UPSTREAM-PARITY
1989///
1990/// ```c
1991/// xmlDtdPtr xmlGetIntSubset(const xmlDoc *doc);
1992/// ```
1993#[no_mangle]
1994pub const extern "C" fn xmlGetIntSubset(doc: *const _xmlDoc) -> *mut _xmlDtd {
1995    crate::xml::tree::get_int_subset(doc)
1996}
1997
1998/// Create a new DTD.
1999///
2000/// # UPSTREAM-PARITY
2001///
2002/// ```c
2003/// xmlDtdPtr xmlNewDtd(xmlDocPtr doc, const xmlChar *name,
2004///                     const xmlChar *ExternalID, const xmlChar *SystemID);
2005/// ```
2006#[no_mangle]
2007pub unsafe extern "C" fn xmlNewDtd(
2008    doc: *mut _xmlDoc,
2009    name: *const xmlChar,
2010    ExternalID: *const xmlChar,
2011    SystemID: *const xmlChar,
2012) -> *mut _xmlDtd {
2013    crate::xml::tree::new_dtd(doc, name, ExternalID, SystemID)
2014}
2015
2016/// Create a new entity.
2017///
2018/// # UPSTREAM-PARITY
2019///
2020/// ```c
2021/// xmlEntityPtr xmlNewEntity(xmlDocPtr doc, const xmlChar *name, int type,
2022///                           const xmlChar *ExternalID, const xmlChar *SystemID,
2023///                           const xmlChar *content);
2024/// ```
2025#[no_mangle]
2026pub unsafe extern "C" fn xmlNewEntity(
2027    doc: *mut _xmlDoc,
2028    name: *const xmlChar,
2029    type_: c_int,
2030    ExternalID: *const xmlChar,
2031    SystemID: *const xmlChar,
2032    content: *const xmlChar,
2033) -> *mut _xmlEntity {
2034    crate::xml::tree::new_entity(doc, name, type_, ExternalID, SystemID, content)
2035}
2036
2037/// Get an entity by name.
2038///
2039/// # UPSTREAM-PARITY
2040///
2041/// ```c
2042/// xmlEntityPtr xmlGetDocEntity(const xmlDoc *doc, const xmlChar *name);
2043/// ```
2044#[no_mangle]
2045pub unsafe extern "C" fn xmlGetDocEntity(
2046    doc: *const _xmlDoc,
2047    name: *const xmlChar,
2048) -> *mut _xmlEntity {
2049    crate::xml::tree::get_doc_entity(doc, name)
2050}
2051
2052/// Get a parameter entity by name.
2053///
2054/// # UPSTREAM-PARITY
2055///
2056/// ```c
2057/// xmlEntityPtr xmlGetParameterEntity(const xmlDoc *doc, const xmlChar *name);
2058/// ```
2059#[no_mangle]
2060pub unsafe extern "C" fn xmlGetParameterEntity(
2061    doc: *const _xmlDoc,
2062    name: *const xmlChar,
2063) -> *mut _xmlEntity {
2064    crate::xml::tree::get_parameter_entity(doc, name)
2065}
2066
2067// ── DTD Declaration Exports ────────────────────────────────────────────
2068
2069/// Create an internal subset (DTD).
2070///
2071/// # UPSTREAM-PARITY
2072///
2073/// ```c
2074/// xmlDtdPtr xmlCreateIntSubset(xmlDocPtr doc, const xmlChar *name,
2075///                              const xmlChar *ExternalID, const xmlChar *SystemID);
2076/// ```
2077#[no_mangle]
2078pub unsafe extern "C" fn xmlCreateIntSubset(
2079    doc: *mut _xmlDoc,
2080    name: *const xmlChar,
2081    ExternalID: *const xmlChar,
2082    SystemID: *const xmlChar,
2083) -> *mut _xmlDtd {
2084    crate::xml::dtd::create_int_subset(doc, name, ExternalID, SystemID)
2085}
2086
2087/// Free a DTD.
2088///
2089/// # UPSTREAM-PARITY
2090///
2091/// ```c
2092/// void xmlFreeDtd(xmlDtdPtr dtd);
2093/// ```
2094#[no_mangle]
2095pub unsafe extern "C" fn xmlFreeDtd(dtd: *mut _xmlDtd) {
2096    crate::xml::dtd::free_dtd(dtd);
2097}
2098
2099/// Add a notation declaration (upstream valid.h 2.15: the `ctxt` first
2100/// argument is part of the ABI; R-000176).
2101///
2102/// # UPSTREAM-PARITY
2103///
2104/// ```c
2105/// xmlNotationPtr xmlAddNotationDecl(xmlValidCtxt *ctxt, xmlDtd *dtd,
2106///                                   const xmlChar *name,
2107///                                   const xmlChar *publicId,
2108///                                   const xmlChar *systemId);
2109/// ```
2110///
2111/// `ctxt` is accepted for ABI parity; upstream uses it only for validation
2112/// error reporting, which the candidate performs in `xml/validation` (the
2113/// parser-side error model), so the argument is currently unused.
2114#[no_mangle]
2115pub unsafe extern "C" fn xmlAddNotationDecl(
2116    _ctxt: *mut _xmlValidCtxt,
2117    dtd: *mut _xmlDtd,
2118    name: *const xmlChar,
2119    PublicID: *const xmlChar,
2120    SystemID: *const xmlChar,
2121) -> *mut _xmlNotation {
2122    crate::xml::dtd::add_notation_decl(dtd, name, PublicID, SystemID)
2123}
2124
2125/// Look up a notation declaration.
2126///
2127/// # UPSTREAM-PARITY
2128///
2129/// ```c
2130/// xmlNotationPtr xmlGetNotationDecl(xmlDtdPtr dtd, const xmlChar *name);
2131/// ```
2132#[no_mangle]
2133pub unsafe extern "C" fn xmlGetNotationDecl(
2134    dtd: *mut _xmlDtd,
2135    name: *const xmlChar,
2136) -> *mut _xmlNotation {
2137    crate::xml::dtd::get_notation_decl(dtd, name)
2138}
2139
2140/// Copy a notation declaration.
2141///
2142/// # UPSTREAM-PARITY
2143///
2144/// ```c
2145/// xmlNotationPtr xmlCopyNotation(xmlNotationPtr notation);
2146/// ```
2147#[no_mangle]
2148pub unsafe extern "C" fn xmlCopyNotation(notation: *mut _xmlNotation) -> *mut _xmlNotation {
2149    crate::xml::dtd::copy_notation(notation)
2150}
2151
2152/// Free a notation declaration.
2153///
2154/// # UPSTREAM-PARITY
2155///
2156/// ```c
2157/// void xmlFreeNotation(xmlNotationPtr notation);
2158/// ```
2159#[no_mangle]
2160pub unsafe extern "C" fn xmlFreeNotation(notation: *mut _xmlNotation) {
2161    crate::xml::dtd::free_notation(notation);
2162}
2163
2164/// Add an element declaration (upstream valid.h 2.15: `ctxt` first arg;
2165/// R-000176).
2166///
2167/// # UPSTREAM-PARITY
2168///
2169/// ```c
2170/// xmlElementPtr xmlAddElementDecl(xmlValidCtxt *ctxt, xmlDtd *dtd,
2171///                                 const xmlChar *name, xmlElementTypeVal type,
2172///                                 xmlElementContent *content);
2173/// ```
2174///
2175/// `ctxt` is accepted for ABI parity; upstream uses it only for validation
2176/// error reporting (candidate: parser-side error model in `xml/validation`).
2177#[no_mangle]
2178pub unsafe extern "C" fn xmlAddElementDecl(
2179    _ctxt: *mut _xmlValidCtxt,
2180    dtd: *mut _xmlDtd,
2181    name: *const xmlChar,
2182    type_: c_int,
2183    content: *mut _xmlElementContent,
2184) -> *mut _xmlElement {
2185    crate::xml::dtd::add_element_decl(dtd, name, type_, content)
2186}
2187
2188/// Look up an element declaration.
2189///
2190/// # UPSTREAM-PARITY
2191///
2192/// ```c
2193/// xmlElementPtr xmlGetElementDecl(xmlDtdPtr dtd, const xmlChar *name);
2194/// ```
2195#[no_mangle]
2196pub unsafe extern "C" fn xmlGetElementDecl(
2197    dtd: *mut _xmlDtd,
2198    name: *const xmlChar,
2199) -> *mut _xmlElement {
2200    crate::xml::dtd::get_element_decl(dtd, name)
2201}
2202
2203/// Copy an element declaration.
2204///
2205/// # UPSTREAM-PARITY
2206///
2207/// ```c
2208/// xmlElementPtr xmlCopyElement(xmlElementPtr elem);
2209/// ```
2210#[no_mangle]
2211pub unsafe extern "C" fn xmlCopyElement(elem: *mut _xmlElement) -> *mut _xmlElement {
2212    crate::xml::dtd::copy_element(elem)
2213}
2214
2215/// Free an element declaration.
2216///
2217/// # UPSTREAM-PARITY
2218///
2219/// ```c
2220/// void xmlFreeElement(xmlElementPtr elem);
2221/// ```
2222#[no_mangle]
2223pub unsafe extern "C" fn xmlFreeElement(elem: *mut _xmlElement) {
2224    crate::xml::dtd::free_element(elem);
2225}
2226
2227/// Add an attribute declaration (upstream valid.h 2.15: 9-arg contract with
2228/// `ctxt` and the namespace key; R-000176).
2229///
2230/// # UPSTREAM-PARITY
2231///
2232/// ```c
2233/// xmlAttributePtr xmlAddAttributeDecl(xmlValidCtxt *ctxt, xmlDtd *dtd,
2234///                                     const xmlChar *elem, const xmlChar *name,
2235///                                     const xmlChar *ns, xmlAttributeType type,
2236///                                     xmlAttributeDefault def,
2237///                                     const xmlChar *defaultValue,
2238///                                     xmlEnumeration *tree);
2239/// ```
2240///
2241/// `ctxt` is accepted for ABI parity; upstream uses it only for validation
2242/// error reporting (candidate: parser-side error model in `xml/validation`).
2243/// The `ns` namespace is threaded into the DTD attribute table as the
2244/// middle hash key and into `attr->prefix`, exactly as upstream valid.c.
2245#[no_mangle]
2246pub unsafe extern "C" fn xmlAddAttributeDecl(
2247    _ctxt: *mut _xmlValidCtxt,
2248    dtd: *mut _xmlDtd,
2249    elem: *mut _xmlElement,
2250    name: *const xmlChar,
2251    ns: *const xmlChar,
2252    type_: c_int,
2253    def: c_int,
2254    defaultValue: *const xmlChar,
2255    tree: *mut _xmlEnumeration,
2256) -> *mut _xmlAttribute {
2257    crate::xml::dtd::add_attribute_decl(dtd, elem, name, ns, type_, def, defaultValue, tree)
2258}
2259
2260/// Look up an attribute declaration.
2261///
2262/// # UPSTREAM-PARITY
2263///
2264/// ```c
2265/// xmlAttributePtr xmlGetAttributeDecl(xmlDtdPtr dtd, xmlElementPtr elem,
2266///                                     const xmlChar *name, int namePrefix);
2267/// ```
2268#[no_mangle]
2269pub unsafe extern "C" fn xmlGetAttributeDecl(
2270    dtd: *mut _xmlDtd,
2271    elem: *mut _xmlElement,
2272    name: *const xmlChar,
2273    namePrefix: c_int,
2274) -> *mut _xmlAttribute {
2275    crate::xml::dtd::get_attribute_decl(dtd, elem, name, namePrefix)
2276}
2277
2278/// Copy an attribute declaration.
2279///
2280/// # UPSTREAM-PARITY
2281///
2282/// ```c
2283/// xmlAttributePtr xmlCopyAttribute(xmlAttributePtr attr);
2284/// ```
2285#[no_mangle]
2286pub unsafe extern "C" fn xmlCopyAttribute(attr: *mut _xmlAttribute) -> *mut _xmlAttribute {
2287    crate::xml::dtd::copy_attribute_decl(attr)
2288}
2289
2290/// Free an attribute declaration.
2291///
2292/// # UPSTREAM-PARITY
2293///
2294/// ```c
2295/// void xmlFreeAttribute(xmlAttributePtr attr);
2296/// ```
2297#[no_mangle]
2298pub unsafe extern "C" fn xmlFreeAttribute(attr: *mut _xmlAttribute) {
2299    crate::xml::dtd::free_attribute(attr);
2300}
2301
2302/// Create a new element content model.
2303///
2304/// # UPSTREAM-PARITY
2305///
2306/// ```c
2307/// xmlElementContentPtr xmlNewElementContent(const xmlChar *name, int type);
2308/// ```
2309#[no_mangle]
2310pub unsafe extern "C" fn xmlNewElementContent(
2311    name: *const xmlChar,
2312    type_: c_int,
2313) -> *mut _xmlElementContent {
2314    crate::xml::dtd::create_content_model(name, type_)
2315}
2316
2317/// Copy an element content model.
2318///
2319/// # UPSTREAM-PARITY
2320///
2321/// ```c
2322/// xmlElementContentPtr xmlCopyElementContent(xmlElementContentPtr content);
2323/// ```
2324#[no_mangle]
2325pub unsafe extern "C" fn xmlCopyElementContent(
2326    content: *mut _xmlElementContent,
2327) -> *mut _xmlElementContent {
2328    crate::xml::dtd::copy_content_model(content)
2329}
2330
2331/// Free an element content model.
2332///
2333/// # UPSTREAM-PARITY
2334///
2335/// ```c
2336/// void xmlFreeElementContent(xmlElementContentPtr cur);
2337/// ```
2338#[no_mangle]
2339pub unsafe extern "C" fn xmlFreeElementContent(cur: *mut _xmlElementContent) {
2340    crate::xml::dtd::free_content_model(cur);
2341}
2342
2343// ── Entity Exports ─────────────────────────────────────────────────────
2344
2345/// Add an entity declaration to a document's DTD (upstream entities.h 2.15:
2346/// entities.c `xmlAddEntity` — a full int/error-code contract, R-000176).
2347///
2348/// # UPSTREAM-PARITY
2349///
2350/// ```c
2351/// int xmlAddEntity(xmlDoc *doc, int extSubset, const xmlChar *name, int type,
2352///                  const xmlChar *publicId, const xmlChar *systemId,
2353///                  const xmlChar *content, xmlEntity **out);
2354/// ```
2355///
2356/// Returns 0 on success (with the new entity in `*out`), `XML_ERR_ARGUMENT`
2357/// for NULL doc/name or an unknown type, `XML_DTD_NO_DTD` when the selected
2358/// subset does not exist, `XML_ERR_REDECL_PREDEF_ENTITY` for an invalid
2359/// predefined-entity redeclaration, `XML_ERR_NO_MEMORY` on allocation
2360/// failure and `XML_WAR_ENTITY_REDEFINED` when the name already exists.
2361/// `*out` is set to NULL on entry and on every failure.
2362#[no_mangle]
2363pub unsafe extern "C" fn xmlAddEntity(
2364    doc: *mut _xmlDoc,
2365    extSubset: c_int,
2366    name: *const xmlChar,
2367    type_: c_int,
2368    publicId: *const xmlChar,
2369    systemId: *const xmlChar,
2370    content: *const xmlChar,
2371    out: *mut *mut _xmlEntity,
2372) -> c_int {
2373    crate::xml::entities::add_entity_doc(
2374        doc, extSubset, name, type_, publicId, systemId, content, out,
2375    )
2376}
2377
2378/// Add an entity declaration to a document's internal subset (upstream
2379/// entities.c `xmlAddDocEntity`): if the document has no internal subset
2380/// one is created.
2381///
2382/// # UPSTREAM-PARITY
2383///
2384/// ```c
2385/// xmlEntityPtr xmlAddDocEntity(xmlDocPtr doc, const xmlChar *name, int type,
2386///                              const xmlChar *ExternalID, const xmlChar *SystemID,
2387///                              const xmlChar *content);
2388/// ```
2389#[no_mangle]
2390pub unsafe extern "C" fn xmlAddDocEntity(
2391    doc: *mut _xmlDoc,
2392    name: *const xmlChar,
2393    type_: c_int,
2394    ExternalID: *const xmlChar,
2395    SystemID: *const xmlChar,
2396    content: *const xmlChar,
2397) -> *mut _xmlEntity {
2398    crate::xml::tree::add_doc_entity(doc, name, type_, ExternalID, SystemID, content)
2399}
2400
2401/// Add an entity declaration to a document's external subset (upstream
2402/// entities.c `xmlAddDtdEntity`).
2403///
2404/// # UPSTREAM-PARITY
2405///
2406/// ```c
2407/// xmlEntityPtr xmlAddDtdEntity(xmlDocPtr doc, const xmlChar *name, int type,
2408///                              const xmlChar *ExternalID, const xmlChar *SystemID,
2409///                              const xmlChar *content);
2410/// ```
2411#[no_mangle]
2412pub unsafe extern "C" fn xmlAddDtdEntity(
2413    doc: *mut _xmlDoc,
2414    name: *const xmlChar,
2415    type_: c_int,
2416    ExternalID: *const xmlChar,
2417    SystemID: *const xmlChar,
2418    content: *const xmlChar,
2419) -> *mut _xmlEntity {
2420    crate::xml::tree::add_dtd_entity(doc, name, type_, ExternalID, SystemID, content)
2421}
2422
2423/// Get an entity declaration from a DTD (upstream entities.c
2424/// `xmlGetDtdEntity`): searches the internal then external subset.
2425///
2426/// # UPSTREAM-PARITY
2427///
2428/// ```c
2429/// xmlEntityPtr xmlGetDtdEntity(xmlDocPtr doc, const xmlChar *name);
2430/// ```
2431#[no_mangle]
2432pub unsafe extern "C" fn xmlGetDtdEntity(
2433    doc: *mut _xmlDoc,
2434    name: *const xmlChar,
2435) -> *mut _xmlEntity {
2436    crate::xml::tree::get_dtd_entity(doc, name)
2437}
2438
2439/// Get an entity by name.
2440///
2441/// # UPSTREAM-PARITY
2442///
2443/// ```c
2444/// xmlEntityPtr xmlGetEntity(xmlDocPtr doc, const xmlChar *name);
2445/// ```
2446#[no_mangle]
2447pub unsafe extern "C" fn xmlGetEntity(doc: *mut _xmlDoc, name: *const xmlChar) -> *mut _xmlEntity {
2448    crate::xml::entities::get_entity(doc, name)
2449}
2450
2451/// Copy an entity.
2452///
2453/// # UPSTREAM-PARITY
2454///
2455/// ```c
2456/// xmlEntityPtr xmlCopyEntity(xmlEntityPtr entity);
2457/// ```
2458#[no_mangle]
2459pub unsafe extern "C" fn xmlCopyEntity(entity: *mut _xmlEntity) -> *mut _xmlEntity {
2460    crate::xml::entities::copy_entity(entity)
2461}
2462
2463/// Free an entity.
2464///
2465/// # UPSTREAM-PARITY
2466///
2467/// ```c
2468/// void xmlFreeEntity(xmlEntityPtr entity);
2469/// ```
2470#[no_mangle]
2471pub unsafe extern "C" fn xmlFreeEntity(entity: *mut _xmlEntity) {
2472    crate::xml::entities::free_entity(entity);
2473}
2474
2475/// Encode entities for reentrant output.
2476///
2477/// # UPSTREAM-PARITY
2478///
2479/// ```c
2480/// xmlChar *xmlEncodeEntitiesReentrant(xmlDocPtr doc, const xmlChar *input);
2481/// ```
2482#[no_mangle]
2483pub unsafe extern "C" fn xmlEncodeEntitiesReentrant(
2484    doc: *mut _xmlDoc,
2485    input: *const xmlChar,
2486) -> *mut xmlChar {
2487    crate::xml::entities::encode_entities_reentrant(doc, input)
2488}
2489
2490/// Encode special characters in a string (upstream entities.c
2491/// `xmlEncodeSpecialChars`): escapes `<`, `>`, `&`, `"` and `\r`.
2492///
2493/// # UPSTREAM-PARITY
2494///
2495/// ```c
2496/// xmlChar *xmlEncodeSpecialChars(const xmlDoc *doc, const xmlChar *input);
2497/// ```
2498///
2499/// Returns a newly allocated string (free with `xmlFree`) or NULL.
2500#[no_mangle]
2501pub unsafe extern "C" fn xmlEncodeSpecialChars(
2502    _doc: *const _xmlDoc,
2503    input: *const xmlChar,
2504) -> *mut xmlChar {
2505    if input.is_null() {
2506        return ptr::null_mut();
2507    }
2508    unsafe {
2509        let len = crate::xml::string::xml_strlen(input);
2510        // Worst case: every byte becomes a 6-byte entity (&#13; is 5; &quot;
2511        // is 6).
2512        let cap = len * 6 + 1;
2513        let out = crate::abi::allocator::xmlMallocImpl(cap) as *mut xmlChar;
2514        if out.is_null() {
2515            return ptr::null_mut();
2516        }
2517        let mut o = 0usize;
2518        let mut i = 0usize;
2519        while i < len {
2520            let c = *input.add(i);
2521            let rep: &[u8] = match c {
2522                b'<' => b"&lt;",
2523                b'>' => b"&gt;",
2524                b'&' => b"&amp;",
2525                b'"' => b"&quot;",
2526                b'\r' => b"&#13;",
2527                _ => {
2528                    *out.add(o) = c;
2529                    o += 1;
2530                    i += 1;
2531                    continue;
2532                }
2533            };
2534            core::ptr::copy_nonoverlapping(rep.as_ptr(), out.add(o), rep.len());
2535            o += rep.len();
2536            i += 1;
2537        }
2538        *out.add(o) = 0;
2539        out
2540    }
2541}
2542
2543/// Deprecated entity encoder (upstream 2.15 `xmlEncodeEntities`): the
2544/// symbol still exists for ABI compatibility but emits a one-time
2545/// deprecation warning and returns NULL (verified against the oracle DSO
2546/// disassembly — the 2.15 implementation returns NULL after warning).
2547///
2548/// # UPSTREAM-PARITY
2549///
2550/// ```c
2551/// xmlChar *xmlEncodeEntities(xmlDocPtr doc, const xmlChar *input);
2552/// ```
2553#[no_mangle]
2554pub unsafe extern "C" fn xmlEncodeEntities(
2555    _doc: *mut _xmlDoc,
2556    _input: *const xmlChar,
2557) -> *mut xmlChar {
2558    use core::sync::atomic::{AtomicBool, Ordering};
2559    static WARNED: AtomicBool = AtomicBool::new(false);
2560    if !WARNED.swap(true, Ordering::Relaxed) {
2561        // Match the oracle: one-time "deprecated" diagnostic on stderr.
2562        let msg = b"xmlEncodeEntities is deprecated, use xmlEncodeSpecialChars or xmlEncodeEntitiesReentrant\n";
2563        unsafe {
2564            libc::fwrite(
2565                msg.as_ptr() as *const c_void,
2566                1,
2567                msg.len(),
2568                libc::fdopen(2, b"w\0" as *const u8 as *const c_char),
2569            );
2570        }
2571    }
2572    ptr::null_mut()
2573}
2574
2575/// Get the line number of a node.
2576///
2577/// # UPSTREAM-PARITY
2578///
2579/// ```c
2580/// long xmlGetLineNo(const xmlNode *node);
2581/// ```
2582#[no_mangle]
2583pub extern "C" fn xmlGetLineNo(node: *const _xmlNode) -> c_long {
2584    crate::xml::tree::get_line_no(node)
2585}
2586
2587// ═══════════════════════════════════════════════════════════════════════════════
2588// Serialization — xmlNodeDump, xmlDocDump, xmlSaveFile, etc.
2589// ═══════════════════════════════════════════════════════════════════════════════
2590
2591/// Dump a node to a buffer.
2592///
2593/// # UPSTREAM-PARITY
2594///
2595/// ```c
2596/// int xmlNodeDump(xmlBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format);
2597/// ```
2598#[no_mangle]
2599pub unsafe extern "C" fn xmlNodeDump(
2600    buf: *mut _xmlBuffer,
2601    doc: *mut _xmlDoc,
2602    cur: *mut _xmlNode,
2603    level: c_int,
2604    format: c_int,
2605) -> c_int {
2606    if buf.is_null() || cur.is_null() {
2607        return -1;
2608    }
2609    crate::xml::tree::xmlNodeDump(buf, doc, cur, level, format)
2610}
2611
2612/// Dump a document to a file pointer.
2613///
2614/// # UPSTREAM-PARITY
2615///
2616/// ```c
2617/// int xmlDocDump(FILE *f, xmlDocPtr doc);
2618/// ```
2619#[no_mangle]
2620pub unsafe extern "C" fn xmlDocDump(fp: *mut c_void, doc: *mut _xmlDoc) -> c_int {
2621    if fp.is_null() || doc.is_null() {
2622        return -1;
2623    }
2624    crate::xml::tree::xmlDocDump(fp, doc)
2625}
2626
2627/// Dump a document to memory with format.
2628///
2629/// # UPSTREAM-PARITY
2630///
2631/// ```c
2632/// void xmlDocDumpFormatMemory(xmlDocPtr doc, xmlChar **mem, int *size, int format);
2633/// ```
2634#[no_mangle]
2635pub unsafe extern "C" fn xmlDocDumpFormatMemory(
2636    doc: *mut _xmlDoc,
2637    mem: *mut *mut xmlChar,
2638    size: *mut c_int,
2639    format: c_int,
2640) {
2641    if doc.is_null() || mem.is_null() {
2642        return;
2643    }
2644    crate::xml::tree::xmlDocDumpFormatMemory(doc, mem, size, format)
2645}
2646
2647/// Dump a document to memory (unformatted).
2648///
2649/// # UPSTREAM-PARITY
2650///
2651/// ```c
2652/// void xmlDocDumpMemory(xmlDocPtr doc, xmlChar **mem, int *size);
2653/// ```
2654#[no_mangle]
2655pub unsafe extern "C" fn xmlDocDumpMemory(
2656    doc: *mut _xmlDoc,
2657    mem: *mut *mut xmlChar,
2658    size: *mut c_int,
2659) {
2660    if doc.is_null() || mem.is_null() {
2661        return;
2662    }
2663    crate::xml::tree::xmlDocDumpMemory(doc, mem, size)
2664}
2665
2666/// Save a document to a file.
2667///
2668/// # UPSTREAM-PARITY
2669///
2670/// ```c
2671/// int xmlSaveFile(const char *filename, xmlDocPtr cur);
2672/// ```
2673#[no_mangle]
2674pub unsafe extern "C" fn xmlSaveFile(filename: *const c_char, cur: *mut _xmlDoc) -> c_int {
2675    if filename.is_null() || cur.is_null() {
2676        return -1;
2677    }
2678    crate::xml::tree::xmlSaveFile(filename, cur)
2679}
2680
2681/// Save a document to a file with encoding.
2682///
2683/// # UPSTREAM-PARITY
2684///
2685/// ```c
2686/// int xmlSaveFileEnc(const char *filename, xmlDocPtr cur, const char *encoding);
2687/// ```
2688#[no_mangle]
2689pub unsafe extern "C" fn xmlSaveFileEnc(
2690    filename: *const c_char,
2691    cur: *mut _xmlDoc,
2692    encoding: *const c_char,
2693) -> c_int {
2694    if filename.is_null() || cur.is_null() {
2695        return -1;
2696    }
2697    crate::xml::tree::xmlSaveFileEnc(filename, cur, encoding)
2698}
2699
2700/// Save a document to a file with format.
2701///
2702/// # UPSTREAM-PARITY
2703///
2704/// ```c
2705/// int xmlSaveFormatFile(const char *filename, xmlDocPtr cur, int format);
2706/// ```
2707#[no_mangle]
2708pub unsafe extern "C" fn xmlSaveFormatFile(
2709    filename: *const c_char,
2710    cur: *mut _xmlDoc,
2711    format: c_int,
2712) -> c_int {
2713    if filename.is_null() || cur.is_null() {
2714        return -1;
2715    }
2716    crate::xml::tree::xmlSaveFormatFile(filename, cur, format)
2717}
2718
2719/// Save a document to a file with encoding and format.
2720///
2721/// # UPSTREAM-PARITY
2722///
2723/// ```c
2724/// int xmlSaveFormatFileEnc(const char *filename, xmlDocPtr cur, const char *encoding, int format);
2725/// ```
2726#[no_mangle]
2727pub unsafe extern "C" fn xmlSaveFormatFileEnc(
2728    filename: *const c_char,
2729    cur: *mut _xmlDoc,
2730    encoding: *const c_char,
2731    format: c_int,
2732) -> c_int {
2733    if filename.is_null() || cur.is_null() {
2734        return -1;
2735    }
2736    crate::xml::tree::xmlSaveFormatFileEnc(filename, cur, encoding, format)
2737}
2738
2739// ═══════════════════════════════════════════════════════════════════════════════
2740// 7. Parser — SAX, DOM, Push, Reader
2741// ═══════════════════════════════════════════════════════════════════════════════
2742
2743/// Read an XML document from a string.
2744///
2745/// # UPSTREAM-PARITY
2746///
2747/// ```c
2748/// xmlDocPtr xmlReadDoc(const xmlChar *cur, const char *URL,
2749///                      const char *encoding, int options);
2750/// ```
2751///
2752/// Returns a parsed document. Caller must free with `xmlFreeDoc`.
2753#[no_mangle]
2754pub unsafe extern "C" fn xmlReadDoc(
2755    cur: *const xmlChar,
2756    URL: *const c_char,
2757    encoding: *const c_char,
2758    options: c_int,
2759) -> *mut _xmlDoc {
2760    // SAFETY: cur must be a valid null-terminated xmlChar string if non-null.
2761    if cur.is_null() {
2762        return ptr::null_mut();
2763    }
2764    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2765    if ctxt.is_null() {
2766        return ptr::null_mut();
2767    }
2768    let len = crate::xml::string::xml_strlen(cur);
2769    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
2770    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2771    (*ctxt).options = options;
2772    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2773        let doc = (*ctxt).myDoc;
2774        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2775        return doc;
2776    }
2777    let doc = (*ctxt).myDoc;
2778    if !doc.is_null() {
2779        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
2780    }
2781    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2782    doc
2783}
2784
2785/// Read an XML document from a file.
2786///
2787/// # UPSTREAM-PARITY
2788///
2789/// ```c
2790/// xmlDocPtr xmlReadFile(const char *URL, const char *encoding, int options);
2791/// ```
2792#[no_mangle]
2793pub unsafe extern "C" fn xmlReadFile(
2794    URL: *const c_char,
2795    encoding: *const c_char,
2796    options: c_int,
2797) -> *mut _xmlDoc {
2798    // SAFETY: URL must be a valid C string or NULL.
2799    if URL.is_null() {
2800        return ptr::null_mut();
2801    }
2802    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2803    if ctxt.is_null() {
2804        return ptr::null_mut();
2805    }
2806    // UPSTREAM-PARITY (parser.c xmlReadFile -> xmlCtxtReadFile): options are
2807    // applied before the input open (xmlCtxtUseOptions -> xmlCtxtNewInputFromUrl
2808    // -> xmlLoadResource), so a registered external entity loader observes
2809    // them; below it the xmlParserInputBufferCreateFilenameDefault (php
2810    // streams loader) is consulted — a NULL result raises xmlCtxtErrIO — "I/O
2811    // warning : failed to load \"%s\": %s\n" — and the load fails.
2812    (*ctxt).options = options;
2813    // UPSTREAM-PARITY (xmlCtxtUseOptions): replaceEntities is derived from
2814    // the options argument — a deprecated-global seed (create_parser_ctxt
2815    // snapshots xmlSubstituteEntitiesDefault, which PHP's ext/xsl sets at
2816    // request init) must not leak into a read whose options lack NOENT.
2817    (*ctxt).replaceEntities = (options & crate::abi::types::XML_PARSE_NOENT != 0) as c_int;
2818    let input = match crate::abi::exports_parser::open_filename_routed(URL, ctxt) {
2819        crate::abi::exports_parser::RoutedFileOpen::Loaded(i) => i,
2820        crate::abi::exports_parser::RoutedFileOpen::Failed => {
2821            crate::abi::exports_parser::emit_io_warning(
2822                ctxt,
2823                crate::abi::exports_parser::io_load_failure_message(URL),
2824            );
2825            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2826            return ptr::null_mut();
2827        }
2828        crate::abi::exports_parser::RoutedFileOpen::EntityLoaderFailed => {
2829            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2830            return ptr::null_mut();
2831        }
2832        crate::abi::exports_parser::RoutedFileOpen::Builtin => {
2833            match crate::xml::parser::helpers::input_from_file(URL) {
2834                Ok(input) => input,
2835                Err(_) => {
2836                    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2837                    return ptr::null_mut();
2838                }
2839            }
2840        }
2841    };
2842    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2843    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2844        let doc = (*ctxt).myDoc;
2845        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2846        // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
2847        // partially built document is discarded and NULL is returned; with
2848        // XML_PARSE_RECOVER the partial tree is kept.
2849        if options & 1 << 0 != 0 {
2850            return doc;
2851        }
2852        if !doc.is_null() {
2853            crate::xml::tree::free_doc(doc);
2854        }
2855        return ptr::null_mut();
2856    }
2857    let doc = (*ctxt).myDoc;
2858    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2859    doc
2860}
2861
2862/// Recover-parse a document from a string (upstream parser.h): same as
2863/// `xmlReadDoc` with XML_PARSE_RECOVER forced.
2864///
2865/// # UPSTREAM-PARITY
2866///
2867/// ```c
2868/// xmlDocPtr xmlRecoverDoc(const xmlChar *cur);
2869/// ```
2870#[no_mangle]
2871pub unsafe extern "C" fn xmlRecoverDoc(cur: *const xmlChar) -> *mut _xmlDoc {
2872    unsafe { xmlReadDoc(cur, ptr::null(), ptr::null(), 1 << 0) }
2873}
2874
2875/// Recover-parse a document from a file (upstream parser.h).
2876///
2877/// # UPSTREAM-PARITY
2878///
2879/// ```c
2880/// xmlDocPtr xmlRecoverFile(const char *filename);
2881/// ```
2882#[no_mangle]
2883pub unsafe extern "C" fn xmlRecoverFile(filename: *const c_char) -> *mut _xmlDoc {
2884    unsafe { xmlReadFile(filename, ptr::null(), 1 << 0) }
2885}
2886
2887/// Recover-parse a document from memory (upstream parser.h).
2888///
2889/// # UPSTREAM-PARITY
2890///
2891/// ```c
2892/// xmlDocPtr xmlRecoverMemory(const char *buffer, int size);
2893/// ```
2894#[no_mangle]
2895pub unsafe extern "C" fn xmlRecoverMemory(buffer: *const c_char, size: c_int) -> *mut _xmlDoc {
2896    unsafe { xmlReadMemory(buffer, size, ptr::null(), ptr::null(), 1 << 0) }
2897}
2898
2899/// Read an XML document from a file (upstream parser.h).
2900/// Canonically record an explicit input `encoding` on `doc->encoding` when
2901/// the caller supplied one and the document has no encoding of its own.
2902///
2903/// Mirrors upstream: the encoding name is canonicalized via the encoding
2904/// handler table (so `utf-8`/`UTF8` become `UTF-8`, `latin1` becomes
2905/// `ISO-8859-1`, …) rather than stored verbatim.
2906///
2907/// # SAFETY
2908///
2909/// - `doc` must be a valid `_xmlDoc` with a NULL `encoding` field.
2910/// - `encoding` must be a valid NUL-terminated C string.
2911unsafe fn canonical_doc_encoding(doc: *mut _xmlDoc, encoding: *const c_char) {
2912    let handler = crate::xml::encoding::xmlFindCharEncodingHandler(encoding);
2913    if handler.is_null() {
2914        return;
2915    }
2916    // SAFETY: handler is non-NULL; name is a NUL-terminated owned buffer.
2917    let name = unsafe { (*handler).name }; // *mut c_char
2918    if name.is_null() {
2919        return;
2920    }
2921    // SAFETY: name is a valid NUL-terminated string; caller frees via xmlFree.
2922    unsafe {
2923        (*doc).encoding = crate::xml::string::xml_strdup(name as *const xmlChar);
2924    }
2925}
2926
2927/// Parse an XML document from a C memory buffer.
2928///
2929/// # UPSTREAM-PARITY
2930///
2931/// ```c
2932/// xmlDocPtr xmlReadMemory(const char *buffer, int size,
2933///                         const char *URL, const char *encoding, int options);
2934/// ```
2935#[no_mangle]
2936pub unsafe extern "C" fn xmlReadMemory(
2937    buffer: *const c_char,
2938    size: c_int,
2939    URL: *const c_char,
2940    encoding: *const c_char,
2941    options: c_int,
2942) -> *mut _xmlDoc {
2943    // SAFETY: buffer must be a valid pointer with at least `size` readable
2944    // bytes. An empty input (size 0) is still parsed — upstream reports
2945    // "Document is empty".
2946    if buffer.is_null() || size < 0 {
2947        return ptr::null_mut();
2948    }
2949    // UPSTREAM-PARITY + HOSTILE-ABI hardening (parser.c 2.15 xmlReadMemory):
2950    // upstream only rejects `size < 0` and then streams from the caller's
2951    // buffer, so a size at or beyond INT_MAX turns into an unsized wild read
2952    // (the oracle's own outcome for xmlReadMemory("<a/>", INT_MAX, ...) is a
2953    // NULL document — or a crash of the oracle itself depending on the heap
2954    // layout). The candidate rejects such sizes up front instead of copying
2955    // ~2 GiB from the caller's buffer; the observable result matches the
2956    // oracle's deterministic probe outcome (HOSTILE-ABI D1).
2957    if size == c_int::MAX {
2958        return ptr::null_mut();
2959    }
2960    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2961    if ctxt.is_null() {
2962        return ptr::null_mut();
2963    }
2964    // UPSTREAM-PARITY: the URL becomes the input's filename (feeds the
2965    // `file:line:` error prefix and doc->URL).
2966    let input = crate::xml::parser::helpers::input_from_memory_named(buffer, size, URL);
2967    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2968    // UPSTREAM-PARITY (xmlReadMemory -> xmlCtxtReadMemory): the parse
2969    // options are mirrored into the context members (dictNames, keepBlanks,
2970    // recovery, ...) before parsing starts.
2971    crate::abi::exports_parser::apply_options(ctxt, options);
2972    let parsed = crate::xml::parser::helpers::parse_document(ctxt);
2973    let doc = (*ctxt).myDoc;
2974    // UPSTREAM-PARITY: the URL is attached to the document on success AND on
2975    // the recovery path (the partial tree keeps the document identity).
2976    if !doc.is_null() && !URL.is_null() && (*doc).URL.is_null() {
2977        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
2978    }
2979    // UPSTREAM-PARITY (xmlCtxtReadMemory): an explicit `encoding` argument
2980    // is recorded on the document when the document carries no encoding
2981    // declaration of its own, so `doc->encoding` (nokogiri Document#encoding)
2982    // reflects what the caller requested.
2983    if !doc.is_null() && (*doc).encoding.is_null() && !encoding.is_null() {
2984        canonical_doc_encoding(doc, encoding);
2985    }
2986    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2987    if parsed != 0 {
2988        // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
2989        // partially built document is discarded and NULL is returned; with
2990        // XML_PARSE_RECOVER the partial tree is kept.
2991        if options & 1 << 0 != 0 {
2992            return doc;
2993        }
2994        if !doc.is_null() {
2995            crate::xml::tree::free_doc(doc);
2996        }
2997        return ptr::null_mut();
2998    }
2999    doc
3000}
3001
3002/// Load a list of catalogs (upstream `xmlLoadCatalogs`).
3003///
3004/// # SAFETY
3005///
3006/// - `catalogs` must be a valid NUL-terminated string or NULL.
3007#[no_mangle]
3008pub unsafe extern "C" fn xmlLoadCatalogs(catalogs: *const c_char) {
3009    if !catalogs.is_null() {
3010        crate::xml::catalog::load_catalog(catalogs);
3011    }
3012}
3013
3014/// Load a single catalog (upstream `xmlLoadCatalog`).
3015///
3016/// # SAFETY
3017///
3018/// - `catalogs` must be a valid NUL-terminated string or NULL.
3019#[no_mangle]
3020pub unsafe extern "C" fn xmlLoadCatalog(catalogs: *const c_char) -> c_int {
3021    // UPSTREAM-PARITY (catalog.c xmlLoadCatalog): returns 0 on success,
3022    // 1 on error (unlike xmlCatalogLoad which returns the catalog handle).
3023    let handle = crate::xml::catalog::load_catalog(catalogs);
3024    if handle.is_null() {
3025        1
3026    } else {
3027        0
3028    }
3029}
3030
3031/// Read an XML document from a file descriptor.
3032///
3033/// # UPSTREAM-PARITY
3034///
3035/// ```c
3036/// xmlDocPtr xmlReadFd(int fd, const char *URL, const char *encoding, int options);
3037/// ```
3038#[no_mangle]
3039pub unsafe extern "C" fn xmlReadFd(
3040    fd: c_int,
3041    URL: *const c_char,
3042    encoding: *const c_char,
3043    options: c_int,
3044) -> *mut _xmlDoc {
3045    // SAFETY: fd must be a valid open file descriptor.
3046    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3047    if ctxt.is_null() {
3048        return ptr::null_mut();
3049    }
3050    // Read all data from the fd
3051    let mut buf = Vec::new();
3052    let mut tmp = [0u8; 4096];
3053    loop {
3054        let n = libc::read(fd, tmp.as_mut_ptr() as *mut c_void, tmp.len());
3055        if n <= 0 {
3056            break;
3057        }
3058        buf.extend_from_slice(&tmp[..n as usize]);
3059    }
3060    let input = crate::xml::parser::helpers::input_from_memory(
3061        buf.as_ptr() as *const c_char,
3062        buf.len() as c_int,
3063    );
3064    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3065    (*ctxt).options = options;
3066    if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
3067        let doc = (*ctxt).myDoc;
3068        crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3069        return doc;
3070    }
3071    let doc = (*ctxt).myDoc;
3072    if !doc.is_null() && !URL.is_null() {
3073        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
3074    }
3075    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3076    doc
3077}
3078
3079/// Read an XML document from I/O callbacks.
3080///
3081/// # UPSTREAM-PARITY
3082///
3083/// ```c
3084/// xmlDocPtr xmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
3085///                     void *ioctx, const char *URL, const char *encoding, int options);
3086/// ```
3087#[no_mangle]
3088pub unsafe extern "C" fn xmlReadIO(
3089    ioread: Option<xmlInputReadCallback>,
3090    ioclose: Option<xmlInputCloseCallback>,
3091    ioctx: *mut c_void,
3092    URL: *const c_char,
3093    encoding: *const c_char,
3094    options: c_int,
3095) -> *mut _xmlDoc {
3096    // SAFETY: callbacks must be valid function pointers if non-NULL.
3097    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3098    if ctxt.is_null() {
3099        return ptr::null_mut();
3100    }
3101    let input = crate::xml::parser::helpers::input_from_io(ioread, ioclose, ioctx);
3102    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3103    (*ctxt).options = options;
3104    let parsed = crate::xml::parser::helpers::parse_document(ctxt);
3105    let doc = (*ctxt).myDoc;
3106    // UPSTREAM-PARITY (xmlReadIO -> xmlCtxtReadIO): the URL is attached to the
3107    // document on success AND on the recovery path (the partial tree keeps the
3108    // document identity).
3109    if !doc.is_null() && !URL.is_null() && (*doc).URL.is_null() {
3110        (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
3111    }
3112    if !doc.is_null() && (*doc).encoding.is_null() && !encoding.is_null() {
3113        canonical_doc_encoding(doc, encoding);
3114    }
3115    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3116    if parsed != 0 {
3117        // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
3118        // partially built document is discarded and NULL is returned; only with
3119        // XML_PARSE_RECOVER is the partial tree kept. nokogiri's read_io/strict
3120        // path relies on NULL here to raise a SyntaxError.
3121        if options & 1 << 0 != 0 {
3122            return doc;
3123        }
3124        if !doc.is_null() {
3125            crate::xml::tree::free_doc(doc);
3126        }
3127        return ptr::null_mut();
3128    }
3129    doc
3130}
3131
3132/// Parse an XML document (SAX1).
3133///
3134/// # UPSTREAM-PARITY
3135///
3136/// ```c
3137/// xmlDocPtr xmlSAXParseDoc(xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery);
3138/// ```
3139#[no_mangle]
3140pub unsafe extern "C" fn xmlSAXParseDoc(
3141    sax: *mut _xmlSAXHandler,
3142    cur: *const xmlChar,
3143    recovery: c_int,
3144) -> *mut _xmlDoc {
3145    // SAFETY: cur must be a valid null-terminated xmlChar string.
3146    if cur.is_null() {
3147        return ptr::null_mut();
3148    }
3149    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3150    if ctxt.is_null() {
3151        return ptr::null_mut();
3152    }
3153    if !sax.is_null() {
3154        (*ctxt).sax = sax;
3155        (*ctxt).userData = (*ctxt).sax as *mut c_void;
3156    }
3157    if recovery != 0 {
3158        (*ctxt).recovery = 1;
3159        (*ctxt).options |= 1; // XML_PARSE_RECOVER
3160    }
3161    let len = crate::xml::string::xml_strlen(cur);
3162    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
3163    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3164    crate::xml::parser::helpers::parse_document(ctxt);
3165    let doc = (*ctxt).myDoc;
3166    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3167    doc
3168}
3169
3170/// Parse an XML document (SAX1) with user data (upstream parser.h
3171/// `xmlSAXParseDocWithData`): `user_data` is passed to the SAX callbacks.
3172///
3173/// # UPSTREAM-PARITY
3174///
3175/// ```c
3176/// xmlDocPtr xmlSAXParseDocWithData(xmlSAXHandlerPtr sax, const xmlChar *cur,
3177///                                  int recovery, void *data);
3178/// ```
3179#[no_mangle]
3180pub unsafe extern "C" fn xmlSAXParseDocWithData(
3181    sax: *mut _xmlSAXHandler,
3182    cur: *const xmlChar,
3183    recovery: c_int,
3184    data: *mut c_void,
3185) -> *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    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3191    if ctxt.is_null() {
3192        return ptr::null_mut();
3193    }
3194    if !sax.is_null() {
3195        (*ctxt).sax = sax;
3196    }
3197    (*ctxt).userData = data;
3198    if recovery != 0 {
3199        (*ctxt).recovery = 1;
3200        (*ctxt).options |= 1; // XML_PARSE_RECOVER
3201    }
3202    let len = crate::xml::string::xml_strlen(cur);
3203    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
3204    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3205    crate::xml::parser::helpers::parse_document(ctxt);
3206    let doc = (*ctxt).myDoc;
3207    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3208    doc
3209}
3210
3211/// Parse an XML file (SAX1) with user data (upstream parser.h
3212/// `xmlSAXParseFileWithData`).
3213///
3214/// # UPSTREAM-PARITY
3215///
3216/// ```c
3217/// xmlDocPtr xmlSAXParseFileWithData(xmlSAXHandlerPtr sax, const char *filename,
3218///                                   int recovery, void *data);
3219/// ```
3220#[no_mangle]
3221pub unsafe extern "C" fn xmlSAXParseFileWithData(
3222    sax: *mut _xmlSAXHandler,
3223    filename: *const c_char,
3224    recovery: c_int,
3225    data: *mut c_void,
3226) -> *mut _xmlDoc {
3227    // SAFETY: filename must be a valid C string or NULL.
3228    if filename.is_null() {
3229        return ptr::null_mut();
3230    }
3231    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3232    if ctxt.is_null() {
3233        return ptr::null_mut();
3234    }
3235    if !sax.is_null() {
3236        (*ctxt).sax = sax;
3237    }
3238    (*ctxt).userData = data;
3239    if recovery != 0 {
3240        (*ctxt).recovery = 1;
3241        (*ctxt).options |= 1; // XML_PARSE_RECOVER
3242    }
3243    let input = match crate::abi::exports_parser::open_filename_routed(filename, ctxt) {
3244        crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3245        crate::abi::exports_parser::RoutedFileOpen::Failed => {
3246            crate::abi::exports_parser::emit_io_warning(
3247                ctxt,
3248                crate::abi::exports_parser::io_load_failure_message(filename),
3249            );
3250            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3251            return ptr::null_mut();
3252        }
3253        crate::abi::exports_parser::RoutedFileOpen::EntityLoaderFailed => {
3254            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3255            return ptr::null_mut();
3256        }
3257        crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3258            match crate::xml::parser::helpers::input_from_file(filename) {
3259                Ok(input) => input,
3260                Err(_) => {
3261                    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3262                    return ptr::null_mut();
3263                }
3264            }
3265        }
3266    };
3267    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3268    crate::xml::parser::helpers::parse_document(ctxt);
3269    let doc = (*ctxt).myDoc;
3270    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3271    doc
3272}
3273
3274/// Parse an XML document (SAX1) with user data from memory (upstream
3275/// parser.h `xmlSAXParseMemoryWithData`).
3276///
3277/// # UPSTREAM-PARITY
3278///
3279/// ```c
3280/// xmlDocPtr xmlSAXParseMemoryWithData(xmlSAXHandlerPtr sax, const char *buffer,
3281///                                     int size, int recovery, void *data);
3282/// ```
3283#[no_mangle]
3284pub unsafe extern "C" fn xmlSAXParseMemoryWithData(
3285    sax: *mut _xmlSAXHandler,
3286    buffer: *const c_char,
3287    size: c_int,
3288    recovery: c_int,
3289    data: *mut c_void,
3290) -> *mut _xmlDoc {
3291    // SAFETY: buffer must be a valid pointer with `size` readable bytes.
3292    if buffer.is_null() || size <= 0 {
3293        return ptr::null_mut();
3294    }
3295    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3296    if ctxt.is_null() {
3297        return ptr::null_mut();
3298    }
3299    if !sax.is_null() {
3300        (*ctxt).sax = sax;
3301    }
3302    (*ctxt).userData = data;
3303    if recovery != 0 {
3304        (*ctxt).recovery = 1;
3305        (*ctxt).options |= 1; // XML_PARSE_RECOVER
3306    }
3307    let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3308    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3309    crate::xml::parser::helpers::parse_document(ctxt);
3310    let doc = (*ctxt).myDoc;
3311    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3312    doc
3313}
3314
3315/// Parse an XML file (SAX1).
3316///
3317/// # UPSTREAM-PARITY
3318///
3319/// ```c
3320/// xmlDocPtr xmlSAXParseFile(xmlSAXHandlerPtr sax, const char *filename, int recovery);
3321/// ```
3322#[no_mangle]
3323pub unsafe extern "C" fn xmlSAXParseFile(
3324    sax: *mut _xmlSAXHandler,
3325    filename: *const c_char,
3326    recovery: c_int,
3327) -> *mut _xmlDoc {
3328    // SAFETY: filename must be a valid C string.
3329    if filename.is_null() {
3330        return ptr::null_mut();
3331    }
3332    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3333    if ctxt.is_null() {
3334        return ptr::null_mut();
3335    }
3336    if !sax.is_null() {
3337        (*ctxt).sax = sax;
3338        (*ctxt).userData = (*ctxt).sax as *mut c_void;
3339    }
3340    if recovery != 0 {
3341        (*ctxt).recovery = 1;
3342        (*ctxt).options |= 1;
3343    }
3344    let input = match crate::abi::exports_parser::open_filename_routed(filename, ctxt) {
3345        crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3346        crate::abi::exports_parser::RoutedFileOpen::Failed => {
3347            crate::abi::exports_parser::emit_io_warning(
3348                ctxt,
3349                crate::abi::exports_parser::io_load_failure_message(filename),
3350            );
3351            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3352            return ptr::null_mut();
3353        }
3354        crate::abi::exports_parser::RoutedFileOpen::EntityLoaderFailed => {
3355            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3356            return ptr::null_mut();
3357        }
3358        crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3359            match crate::xml::parser::helpers::input_from_file(filename) {
3360                Ok(input) => input,
3361                Err(_) => {
3362                    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3363                    return ptr::null_mut();
3364                }
3365            }
3366        }
3367    };
3368    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3369    crate::xml::parser::helpers::parse_document(ctxt);
3370    let doc = (*ctxt).myDoc;
3371    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3372    doc
3373}
3374
3375/// Parse an XML document from memory (SAX1).
3376///
3377/// # UPSTREAM-PARITY
3378///
3379/// ```c
3380/// xmlDocPtr xmlSAXParseMemory(xmlSAXHandlerPtr sax,
3381///                             const char *buffer, int size, int recovery);
3382/// ```
3383#[no_mangle]
3384pub unsafe extern "C" fn xmlSAXParseMemory(
3385    sax: *mut _xmlSAXHandler,
3386    buffer: *const c_char,
3387    size: c_int,
3388    recovery: c_int,
3389) -> *mut _xmlDoc {
3390    // SAFETY: buffer must be valid with at least `size` bytes.
3391    if buffer.is_null() || size <= 0 {
3392        return ptr::null_mut();
3393    }
3394    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3395    if ctxt.is_null() {
3396        return ptr::null_mut();
3397    }
3398    if !sax.is_null() {
3399        (*ctxt).sax = sax;
3400        (*ctxt).userData = (*ctxt).sax as *mut c_void;
3401    }
3402    if recovery != 0 {
3403        (*ctxt).recovery = 1;
3404        (*ctxt).options |= 1;
3405    }
3406    let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3407    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3408    crate::xml::parser::helpers::parse_document(ctxt);
3409    let doc = (*ctxt).myDoc;
3410    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3411    doc
3412}
3413
3414/// SAX user parse file.
3415///
3416/// # UPSTREAM-PARITY
3417///
3418/// ```c
3419/// int xmlSAXUserParseFile(xmlSAXHandlerPtr sax, void *user_data,
3420///                         const char *filename);
3421/// ```
3422#[no_mangle]
3423pub unsafe extern "C" fn xmlSAXUserParseFile(
3424    sax: *mut _xmlSAXHandler,
3425    user_data: *mut c_void,
3426    filename: *const c_char,
3427) -> c_int {
3428    // SAFETY: filename must be a valid C string. sax and user_data may be NULL.
3429    if filename.is_null() {
3430        return -1;
3431    }
3432    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3433    if ctxt.is_null() {
3434        return -1;
3435    }
3436    if !sax.is_null() {
3437        // UPSTREAM-PARITY (parser.c xmlSAXUserParseFile): same copy-into-
3438        //-own-storage contract as xmlSAXUserParseMemory (HOSTILE-CALLBACKS
3439        // C10 class).
3440        if unsafe { (*sax).initialized } == XML_SAX2_MAGIC as c_uint {
3441            unsafe {
3442                ptr::copy_nonoverlapping(sax as *const _xmlSAXHandler, (*ctxt).sax, 1);
3443            }
3444        } else {
3445            unsafe {
3446                ptr::copy_nonoverlapping(
3447                    sax as *const u8,
3448                    (*ctxt).sax as *mut u8,
3449                    size_of::<crate::abi::structs::_xmlSAXHandlerV1>(),
3450                );
3451            }
3452        }
3453    }
3454    (*ctxt).userData = if !user_data.is_null() {
3455        user_data
3456    } else {
3457        ctxt as *mut c_void
3458    };
3459    let input = match crate::abi::exports_parser::open_filename_routed(filename, ctxt) {
3460        crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3461        crate::abi::exports_parser::RoutedFileOpen::Failed => {
3462            crate::abi::exports_parser::emit_io_warning(
3463                ctxt,
3464                crate::abi::exports_parser::io_load_failure_message(filename),
3465            );
3466            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3467            return -1;
3468        }
3469        crate::abi::exports_parser::RoutedFileOpen::EntityLoaderFailed => {
3470            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3471            return -1;
3472        }
3473        crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3474            match crate::xml::parser::helpers::input_from_file(filename) {
3475                Ok(input) => input,
3476                Err(_) => {
3477                    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3478                    return -1;
3479                }
3480            }
3481        }
3482    };
3483    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3484    let ret = crate::xml::parser::helpers::parse_document(ctxt);
3485    // UPSTREAM-PARITY (parser.c xmlSAXUserParseFile): 0 when well-formed,
3486    // otherwise the recorded errNo (or -1).
3487    let ret = if ret == 0 {
3488        0
3489    } else {
3490        let err = unsafe { (*ctxt).errNo };
3491        if err != crate::abi::types::XML_ERR_OK {
3492            err
3493        } else {
3494            -1
3495        }
3496    };
3497    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3498    ret
3499}
3500
3501/// SAX user parse memory.
3502///
3503/// # UPSTREAM-PARITY
3504///
3505/// ```c
3506/// int xmlSAXUserParseMemory(xmlSAXHandlerPtr sax, void *user_data,
3507///                           const char *buffer, int size);
3508/// ```
3509#[no_mangle]
3510pub unsafe extern "C" fn xmlSAXUserParseMemory(
3511    sax: *mut _xmlSAXHandler,
3512    user_data: *mut c_void,
3513    buffer: *const c_char,
3514    size: c_int,
3515) -> c_int {
3516    // SAFETY: buffer must be valid with at least `size` bytes.
3517    if buffer.is_null() || size <= 0 {
3518        return -1;
3519    }
3520    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3521    if ctxt.is_null() {
3522        return -1;
3523    }
3524    if !sax.is_null() {
3525        // UPSTREAM-PARITY (parser.c xmlSAXUserParseMemory): the caller's
3526        // handler is COPIED into the context's own SAX struct — never
3527        // borrowed — so xmlFreeParserCtxt frees only the copy. SAX2-magic
3528        // handlers are copied in full; legacy handlers expose only the V1
3529        // prefix (HOSTILE-CALLBACKS C10: borrowing the caller's struct made
3530        // xmlFreeParserCtxt free a stack object).
3531        if unsafe { (*sax).initialized } == XML_SAX2_MAGIC as c_uint {
3532            unsafe {
3533                ptr::copy_nonoverlapping(sax as *const _xmlSAXHandler, (*ctxt).sax, 1);
3534            }
3535        } else {
3536            unsafe {
3537                ptr::copy_nonoverlapping(
3538                    sax as *const u8,
3539                    (*ctxt).sax as *mut u8,
3540                    size_of::<crate::abi::structs::_xmlSAXHandlerV1>(),
3541                );
3542            }
3543        }
3544    }
3545    (*ctxt).userData = if !user_data.is_null() {
3546        user_data
3547    } else {
3548        ctxt as *mut c_void
3549    };
3550    let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3551    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3552    let ret = crate::xml::parser::helpers::parse_document(ctxt);
3553    // UPSTREAM-PARITY (parser.c xmlSAXUserParseMemory): the return value is
3554    // 0 when well-formed, otherwise the recorded errNo (or -1).
3555    let ret = if ret == 0 {
3556        0
3557    } else {
3558        let err = unsafe { (*ctxt).errNo };
3559        if err != crate::abi::types::XML_ERR_OK {
3560            err
3561        } else {
3562            -1
3563        }
3564    };
3565    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3566    ret
3567}
3568
3569/// Parse an XML document from a string (DOM).
3570///
3571/// # UPSTREAM-PARITY
3572///
3573/// ```c
3574/// xmlDocPtr xmlParseDoc(const xmlChar *cur);
3575/// ```
3576#[no_mangle]
3577pub unsafe extern "C" fn xmlParseDoc(cur: *const xmlChar) -> *mut _xmlDoc {
3578    // SAFETY: cur must be a valid null-terminated xmlChar string.
3579    if cur.is_null() {
3580        return ptr::null_mut();
3581    }
3582    xmlReadDoc(cur, ptr::null(), ptr::null(), 0)
3583}
3584
3585/// Parse an XML file (DOM).
3586///
3587/// # UPSTREAM-PARITY
3588///
3589/// ```c
3590/// xmlDocPtr xmlParseFile(const char *filename);
3591/// ```
3592#[no_mangle]
3593pub unsafe extern "C" fn xmlParseFile(filename: *const c_char) -> *mut _xmlDoc {
3594    // SAFETY: filename must be a valid C string.
3595    if filename.is_null() {
3596        return ptr::null_mut();
3597    }
3598    xmlReadFile(filename, ptr::null(), 0)
3599}
3600
3601/// Parse an XML document from memory (DOM).
3602///
3603/// # UPSTREAM-PARITY
3604///
3605/// ```c
3606/// xmlDocPtr xmlParseMemory(const char *buffer, int size);
3607/// ```
3608#[no_mangle]
3609pub unsafe extern "C" fn xmlParseMemory(buffer: *const c_char, size: c_int) -> *mut _xmlDoc {
3610    // SAFETY: buffer must be valid with at least `size` bytes.
3611    if buffer.is_null() || size <= 0 {
3612        return ptr::null_mut();
3613    }
3614    xmlReadMemory(buffer, size, ptr::null(), ptr::null(), 0)
3615}
3616
3617/// Create a file parser context.
3618///
3619/// # UPSTREAM-PARITY
3620///
3621/// ```c
3622/// xmlParserCtxtPtr xmlCreateFileParserCtxt(const char *filename);
3623/// ```
3624#[no_mangle]
3625pub unsafe extern "C" fn xmlCreateFileParserCtxt(filename: *const c_char) -> *mut _xmlParserCtxt {
3626    // SAFETY: filename must be a valid C string.
3627    if filename.is_null() {
3628        return ptr::null_mut();
3629    }
3630    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3631    if ctxt.is_null() {
3632        return ptr::null_mut();
3633    }
3634    let input = match crate::abi::exports_parser::open_filename_routed(filename, ctxt) {
3635        crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3636        crate::abi::exports_parser::RoutedFileOpen::Failed => {
3637            // UPSTREAM-PARITY (parser.c xmlCreateFileParserCtxt ->
3638            // xmlNewInputFromFile): a failed open raises the xmlCtxtErrIO
3639            // warning through the context channel.
3640            crate::abi::exports_parser::emit_io_warning(
3641                ctxt,
3642                crate::abi::exports_parser::io_load_failure_message(filename),
3643            );
3644            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3645            return ptr::null_mut();
3646        }
3647        crate::abi::exports_parser::RoutedFileOpen::EntityLoaderFailed => {
3648            crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3649            return ptr::null_mut();
3650        }
3651        crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3652            match crate::xml::parser::helpers::input_from_file(filename) {
3653                Ok(input) => input,
3654                Err(_) => {
3655                    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3656                    return ptr::null_mut();
3657                }
3658            }
3659        }
3660    };
3661    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3662    ctxt
3663}
3664
3665/// Create a document parser context.
3666///
3667/// # UPSTREAM-PARITY
3668///
3669/// ```c
3670/// xmlParserCtxtPtr xmlCreateDocParserCtxt(const xmlChar *cur);
3671/// ```
3672#[no_mangle]
3673pub unsafe extern "C" fn xmlCreateDocParserCtxt(cur: *const xmlChar) -> *mut _xmlParserCtxt {
3674    // SAFETY: cur must be a valid null-terminated xmlChar string.
3675    if cur.is_null() {
3676        return ptr::null_mut();
3677    }
3678    let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3679    if ctxt.is_null() {
3680        return ptr::null_mut();
3681    }
3682    let len = crate::xml::string::xml_strlen(cur);
3683    let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
3684    crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3685    ctxt
3686}
3687
3688/// Parse a document using an existing parser context.
3689///
3690/// # UPSTREAM-PARITY
3691///
3692/// ```c
3693/// int xmlParseDocument(xmlParserCtxtPtr ctxt);
3694/// ```
3695#[no_mangle]
3696pub unsafe extern "C" fn xmlParseDocument(ctxt: *mut _xmlParserCtxt) -> c_int {
3697    // SAFETY: ctxt must be a valid parser context.
3698    if ctxt.is_null() {
3699        return -1;
3700    }
3701    crate::xml::parser::helpers::parse_document(ctxt)
3702}
3703
3704/// Free a parser context.
3705///
3706/// # UPSTREAM-PARITY
3707///
3708/// ```c
3709/// void xmlFreeParserCtxt(xmlParserCtxtPtr ctxt);
3710/// ```
3711#[no_mangle]
3712pub unsafe extern "C" fn xmlFreeParserCtxt(ctxt: *mut _xmlParserCtxt) {
3713    if ctxt.is_null() {
3714        return;
3715    }
3716    crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3717}
3718
3719/// Set parser options.
3720///
3721/// # UPSTREAM-PARITY
3722///
3723/// ```c
3724/// int xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options);
3725/// ```
3726#[no_mangle]
3727pub unsafe extern "C" fn xmlCtxtUseOptions(ctxt: *mut _xmlParserCtxt, options: c_int) -> c_int {
3728    if ctxt.is_null() {
3729        return -1;
3730    }
3731    // UPSTREAM-PARITY (parser.c 2.15 xmlCtxtUseOptions ->
3732    // xmlCtxtSetOptionsInternal): options in the keep mask can only ever be
3733    // enabled (historic never-clear bits); the remaining handled bits are
3734    // taken from the caller's `options`. The historical struct members
3735    // (recovery / replaceEntities / loadsubset / validate / pedantic /
3736    // keepBlanks / dictNames) are derived from the option bits exactly like
3737    // upstream, because deprecated APIs and consumers (e.g. PHP's expat
3738    // compat layer, which sanitizes then calls xmlCtxtUseOptions with
3739    // XML_PARSE_OLDSAX | XML_PARSE_NOENT) read those members directly.
3740    const KEEP_MASK: c_int = XML_PARSE_NOERROR
3741        | XML_PARSE_NOWARNING
3742        | XML_PARSE_NONET
3743        | XML_PARSE_NSCLEAN
3744        | XML_PARSE_NOCDATA
3745        | XML_PARSE_COMPACT
3746        | XML_PARSE_OLD10
3747        | XML_PARSE_HUGE
3748        | XML_PARSE_OLDSAX
3749        | XML_PARSE_IGNORE_ENC
3750        | XML_PARSE_BIG_LINES;
3751    const ALL_MASK: c_int = XML_PARSE_RECOVER
3752        | XML_PARSE_NOENT
3753        | XML_PARSE_DTDLOAD
3754        | XML_PARSE_DTDATTR
3755        | XML_PARSE_DTDVALID
3756        | XML_PARSE_NOERROR
3757        | XML_PARSE_NOWARNING
3758        | XML_PARSE_PEDANTIC
3759        | XML_PARSE_NOBLANKS
3760        | XML_PARSE_SAX1
3761        | XML_PARSE_NONET
3762        | XML_PARSE_NODICT
3763        | XML_PARSE_NSCLEAN
3764        | XML_PARSE_NOCDATA
3765        | XML_PARSE_COMPACT
3766        | XML_PARSE_OLD10
3767        | XML_PARSE_HUGE
3768        | XML_PARSE_OLDSAX
3769        | XML_PARSE_IGNORE_ENC
3770        | XML_PARSE_BIG_LINES
3771        | XML_PARSE_NO_XXE;
3772    unsafe {
3773        let merged = ((*ctxt).options & KEEP_MASK) | (options & ALL_MASK);
3774        crate::abi::exports_parser::apply_options(ctxt, merged);
3775    }
3776    options & !ALL_MASK
3777}
3778
3779/// Parse a well-balanced chunk (for push parsing).
3780///
3781/// # UPSTREAM-PARITY
3782///
3783/// ```c
3784/// xmlParserErrors xmlParseChunk(xmlParserCtxtPtr ctxt,
3785///                               const char *chunk, int size, int terminate);
3786/// ```
3787#[no_mangle]
3788pub unsafe extern "C" fn xmlParseChunk(
3789    ctxt: *mut _xmlParserCtxt,
3790    chunk: *const c_char,
3791    size: c_int,
3792    terminate: c_int,
3793) -> c_int {
3794    // SAFETY: ctxt must be a valid parser context.
3795    // chunk may be NULL if terminate is set (finalize without data).
3796    //
3797    // UPSTREAM-PARITY (parser.c 2.15 xmlParseChunk): NULL context, negative
3798    // sizes and NULL chunk with positive size all return XML_ERR_ARGUMENT
3799    // (115), never -1 — HOSTILE-ABI B10/B13/D2.
3800    if ctxt.is_null() || size < 0 || (chunk.is_null() && size > 0) {
3801        return XML_ERR_ARGUMENT;
3802    }
3803    crate::xml::parser::helpers::parse_chunk(ctxt, chunk, size, terminate)
3804}
3805
3806/// Create a memory parser input buffer.
3807///
3808/// # UPSTREAM-PARITY
3809///
3810/// ```c
3811/// xmlParserInputBufferPtr xmlParserInputBufferCreateMem(const char *buffer, int size, int enc);
3812/// ```
3813#[no_mangle]
3814pub unsafe extern "C" fn xmlParserInputBufferCreateMem(
3815    buffer: *const c_char,
3816    size: c_int,
3817    enc: c_int,
3818) -> *mut _xmlParserInputBuffer {
3819    // SAFETY: buffer must be valid with at least `size` bytes.
3820    if buffer.is_null() || size <= 0 {
3821        return ptr::null_mut();
3822    }
3823    // UPSTREAM-PARITY (xmlIO.c xmlParserInputBufferCreateMem): the content
3824    // is copied into the buffer (readcallback stays NULL — PHP's
3825    // XMLReader::XML()/fromString() parse from the buffer's own bytes).
3826    // The enc argument selects an input converter upstream; the candidate
3827    // parser handles declared encodings itself, so it is not stored.
3828    let _ = enc;
3829    crate::xml::parser::helpers::alloc_parser_input_buffer_with_mem(buffer, size)
3830}
3831
3832/// Create a file parser input buffer.
3833///
3834/// # UPSTREAM-PARITY
3835///
3836/// ```c
3837/// xmlParserInputBufferPtr xmlParserInputBufferCreateFilename(const char *URI, int enc);
3838/// ```
3839#[no_mangle]
3840pub unsafe extern "C" fn xmlParserInputBufferCreateFilename(
3841    URI: *const c_char,
3842    enc: c_int,
3843) -> *mut _xmlParserInputBuffer {
3844    // SAFETY: URI must be a valid C string or NULL.
3845    if URI.is_null() {
3846        return ptr::null_mut();
3847    }
3848    crate::xml::parser::helpers::alloc_parser_input_buffer()
3849}
3850
3851/// Create an I/O parser input buffer.
3852///
3853/// # UPSTREAM-PARITY
3854///
3855/// ```c
3856/// xmlParserInputBufferPtr xmlParserInputBufferCreateIO(
3857///     xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
3858///     void *ioctx, int enc);
3859/// ```
3860#[no_mangle]
3861pub unsafe extern "C" fn xmlParserInputBufferCreateIO(
3862    ioread: Option<xmlInputReadCallback>,
3863    ioclose: Option<xmlInputCloseCallback>,
3864    ioctx: *mut c_void,
3865    enc: c_int,
3866) -> *mut _xmlParserInputBuffer {
3867    // SAFETY: ioread must be a valid callback if Some. ioctx may be NULL.
3868    let buf = crate::xml::parser::helpers::alloc_parser_input_buffer();
3869    if !buf.is_null() {
3870        (*buf).readcallback = ioread;
3871        (*buf).closecallback = ioclose;
3872        (*buf).context = ioctx;
3873    }
3874    buf
3875}
3876
3877/// Free a parser input buffer.
3878///
3879/// # UPSTREAM-PARITY
3880///
3881/// ```c
3882/// void xmlFreeParserInputBuffer(xmlParserInputBufferPtr buf);
3883/// ```
3884#[no_mangle]
3885pub unsafe extern "C" fn xmlFreeParserInputBuffer(buf: *mut _xmlParserInputBuffer) {
3886    if buf.is_null() {
3887        return;
3888    }
3889    crate::xml::parser::helpers::free_parser_input_buffer(buf);
3890}
3891
3892/// Create a new parser input.
3893///
3894/// # UPSTREAM-PARITY
3895///
3896/// ```c
3897/// xmlParserInputPtr xmlNewInputFromFile(xmlParserCtxtPtr ctxt, const char *filename);
3898/// ```
3899#[no_mangle]
3900pub unsafe extern "C" fn xmlNewInputFromFile(
3901    ctxt: *mut _xmlParserCtxt,
3902    filename: *const c_char,
3903) -> *mut _xmlParserInput {
3904    // SAFETY: filename must be a valid C string. ctxt may be NULL.
3905    // This function allocates a _xmlParserInput. The caller owns it.
3906    // Note: The InputBuffer backing data is NOT leaked here (no ctxt._private
3907    // to store it). Use xmlCreateFileParserCtxt + xmlParseDocument instead.
3908    if filename.is_null() {
3909        return ptr::null_mut();
3910    }
3911    crate::xml::parser::helpers::alloc_parser_input_buffer() as *mut _xmlParserInput
3912}
3913
3914/// Free a parser input.
3915///
3916/// # UPSTREAM-PARITY
3917///
3918/// ```c
3919/// void xmlFreeInputStream(xmlParserInputPtr input);
3920/// ```
3921#[no_mangle]
3922pub unsafe extern "C" fn xmlFreeInputStream(input: *mut _xmlParserInput) {
3923    if input.is_null() {
3924        return;
3925    }
3926    crate::xml::parser::helpers::free_parser_input(input);
3927}
3928
3929// ═══════════════════════════════════════════════════════════════════════════════
3930// 8. I/O
3931// ═══════════════════════════════════════════════════════════════════════════════
3932
3933/// Create an output buffer for a file.
3934///
3935/// # UPSTREAM-PARITY
3936///
3937/// ```c
3938/// xmlOutputBufferPtr xmlOutputBufferCreateFilename(const char *URI,
3939///                                                  xmlCharEncodingHandlerPtr encoder,
3940///                                                  int compression);
3941/// ```
3942#[no_mangle]
3943pub unsafe extern "C" fn xmlOutputBufferCreateFilename(
3944    URI: *const c_char,
3945    encoder: *mut c_void,
3946    compression: c_int,
3947) -> *mut _xmlOutputBuffer {
3948    if URI.is_null() {
3949        return ptr::null_mut();
3950    }
3951    // UPSTREAM-PARITY (xmlIO.c xmlOutputBufferCreateFilename): a default
3952    // create-filename callback registered via xmlOutputBufferCreateFilenameDefault
3953    // is consulted first (PHP installs php_libxml_output_buffer_create_filename at
3954    // request init, so every filename open routes through the PHP streams layer);
3955    // otherwise the builtin file open runs.
3956    crate::xml::io::output_buffer_create_filename_routed(
3957        URI,
3958        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3959        compression,
3960    )
3961}
3962
3963/// Create an output buffer for a file descriptor.
3964///
3965/// # UPSTREAM-PARITY
3966///
3967/// ```c
3968/// xmlOutputBufferPtr xmlOutputBufferCreateFd(int fd,
3969///                                            xmlCharEncodingHandlerPtr encoder);
3970/// ```
3971#[no_mangle]
3972pub unsafe extern "C" fn xmlOutputBufferCreateFd(
3973    fd: c_int,
3974    encoder: *mut c_void,
3975) -> *mut _xmlOutputBuffer {
3976    if fd < 0 {
3977        return ptr::null_mut();
3978    }
3979    crate::xml::io::output_buffer_create_fd(
3980        fd,
3981        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3982    )
3983}
3984
3985/// Create an output buffer from I/O callbacks.
3986///
3987/// # UPSTREAM-PARITY
3988///
3989/// ```c
3990/// xmlOutputBufferPtr xmlOutputBufferCreateIO(
3991///     xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose,
3992///     void *ioctx, xmlCharEncodingHandlerPtr encoder);
3993/// ```
3994#[no_mangle]
3995pub unsafe extern "C" fn xmlOutputBufferCreateIO(
3996    iowrite: Option<xmlOutputWriteCallback>,
3997    ioclose: Option<xmlOutputCloseCallback>,
3998    ioctx: *mut c_void,
3999    encoder: *mut c_void,
4000) -> *mut _xmlOutputBuffer {
4001    crate::xml::io::output_buffer_create_io(
4002        iowrite,
4003        ioclose,
4004        ioctx,
4005        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
4006    )
4007}
4008
4009/// Free an output buffer.
4010///
4011/// # UPSTREAM-PARITY
4012///
4013/// ```c
4014/// void xmlOutputBufferClose(xmlOutputBufferPtr out);
4015/// ```
4016#[no_mangle]
4017pub unsafe extern "C" fn xmlOutputBufferClose(out: *mut _xmlOutputBuffer) -> c_int {
4018    if out.is_null() {
4019        return -1;
4020    }
4021    crate::xml::io::output_buffer_close(out)
4022}
4023
4024/// Flush an output buffer.
4025///
4026/// # UPSTREAM-PARITY
4027///
4028/// ```c
4029/// int xmlOutputBufferFlush(xmlOutputBufferPtr out);
4030/// ```
4031#[no_mangle]
4032pub unsafe extern "C" fn xmlOutputBufferFlush(out: *mut _xmlOutputBuffer) -> c_int {
4033    if out.is_null() {
4034        return -1;
4035    }
4036    crate::xml::io::output_buffer_flush(out)
4037}
4038
4039/// Write to an output buffer.
4040///
4041/// # UPSTREAM-PARITY
4042///
4043/// ```c
4044/// int xmlOutputBufferWrite(xmlOutputBufferPtr out, int len, const char *data);
4045/// ```
4046#[no_mangle]
4047pub unsafe extern "C" fn xmlOutputBufferWrite(
4048    out: *mut _xmlOutputBuffer,
4049    len: c_int,
4050    data: *const c_char,
4051) -> c_int {
4052    // UPSTREAM-PARITY (xmlIO.c xmlOutputBufferWrite): a zero-length write
4053    // is a legal no-op returning 0 — PHP's W3C DOM-Parsing serializer
4054    // (ext/dom xml_serializer.c dom_xml_common_text_serialization) issues
4055    // xmlOutputBufferWrite(out, 0, p) when a text/attribute run starts with
4056    // a character that needs escaping; -1 there aborts the whole save with
4057    // "Could not save document".
4058    if out.is_null() || data.is_null() || len < 0 {
4059        return -1;
4060    }
4061    if len == 0 {
4062        return 0;
4063    }
4064    crate::xml::io::output_buffer_write(out, len, data)
4065}
4066
4067/// Write a string to an output buffer.
4068///
4069/// # UPSTREAM-PARITY
4070///
4071/// ```c
4072/// int xmlOutputBufferWriteString(xmlOutputBufferPtr out, const char *str);
4073/// ```
4074#[no_mangle]
4075pub unsafe extern "C" fn xmlOutputBufferWriteString(
4076    out: *mut _xmlOutputBuffer,
4077    str: *const c_char,
4078) -> c_int {
4079    if str.is_null() {
4080        return 0;
4081    }
4082    unsafe { xmlOutputBufferWrite(out, xmlStrlen(str as *const xmlChar), str) }
4083}
4084
4085/// Allocate an output buffer with no I/O target (upstream xmlAllocOutputBuffer).
4086///
4087/// # UPSTREAM-PARITY
4088///
4089/// ```c
4090/// xmlOutputBufferPtr xmlAllocOutputBuffer(xmlCharEncodingHandlerPtr encoder);
4091/// ```
4092#[no_mangle]
4093pub unsafe extern "C" fn xmlAllocOutputBuffer(encoder: *mut c_void) -> *mut _xmlOutputBuffer {
4094    crate::xml::io::output_buffer_create(
4095        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
4096    )
4097}
4098
4099/// Create an output buffer that writes into a `_xmlBuffer` (upstream
4100/// xmlOutputBufferCreateBuffer).
4101///
4102/// # UPSTREAM-PARITY
4103///
4104/// ```c
4105/// xmlOutputBufferPtr xmlOutputBufferCreateBuffer(xmlBufferPtr buffer,
4106///                                                xmlCharEncodingHandlerPtr encoder);
4107/// ```
4108///
4109/// # SAFETY
4110///
4111/// - `buffer` must be a valid `_xmlBuffer`.
4112#[no_mangle]
4113pub unsafe extern "C" fn xmlOutputBufferCreateBuffer(
4114    buffer: *mut crate::abi::structs::_xmlBuffer,
4115    encoder: *mut c_void,
4116) -> *mut _xmlOutputBuffer {
4117    crate::xml::io::output_buffer_create_buffer(
4118        buffer,
4119        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
4120    )
4121}
4122
4123/// Create an output buffer writing to a `FILE *` (upstream
4124/// xmlOutputBufferCreateFile): the FILE is the I/O context with a
4125/// write callback wrapping `fwrite` and a close callback wrapping `fflush`.
4126///
4127/// # SAFETY
4128///
4129/// - `file` must be a valid `FILE *` or NULL.
4130#[no_mangle]
4131pub unsafe extern "C" fn xmlOutputBufferCreateFile(
4132    file: *mut libc::FILE,
4133    encoder: *mut c_void,
4134) -> *mut _xmlOutputBuffer {
4135    crate::xml::io::output_buffer_create_file(
4136        file,
4137        encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
4138    )
4139}
4140
4141/// Get the current content of an output buffer (upstream xmlOutputBufferGetContent).
4142///
4143/// # SAFETY
4144///
4145/// - `out` must be a valid output buffer.
4146#[no_mangle]
4147pub unsafe extern "C" fn xmlOutputBufferGetContent(out: *mut _xmlOutputBuffer) -> *const c_char {
4148    crate::xml::io::output_buffer_get_content(out) as *const c_char
4149}
4150
4151/// Get the number of bytes currently in the output buffer (upstream
4152/// xmlOutputBufferGetSize: `size_t`, 0 on NULL/error — 11.1-Z.3 signature
4153/// court: the pre-Z.3 candidate returned `int` with -1 on error).
4154///
4155/// # SAFETY
4156///
4157/// - `out` must be a valid output buffer.
4158#[no_mangle]
4159pub unsafe extern "C" fn xmlOutputBufferGetSize(out: *mut _xmlOutputBuffer) -> usize {
4160    crate::xml::io::output_buffer_get_size(out)
4161}
4162
4163/// Write to an output buffer, escaping special characters with the given
4164/// escape function (upstream xmlOutputBufferWriteEscape).
4165///
4166/// # SAFETY
4167///
4168/// - `out` must be a valid output buffer; `str` a NUL-terminated string;
4169///   `escaping` a valid escape callback or NULL.
4170#[no_mangle]
4171pub unsafe extern "C" fn xmlOutputBufferWriteEscape(
4172    out: *mut _xmlOutputBuffer,
4173    str: *const xmlChar,
4174    escaping: Option<xmlCharEncodingOutputFunc>,
4175) -> c_int {
4176    if out.is_null() || str.is_null() {
4177        return -1;
4178    }
4179    crate::xml::io::output_buffer_write_escape(out, str, escaping)
4180}
4181
4182/// Set/query the default output-buffer filename callback
4183/// (upstream xmlOutputBufferCreateFilenameDefault).
4184///
4185/// Stored per-thread in the same cell the I/O layer consults
4186/// (`xml::globals::OUTPUT_CREATE_FILENAME`, upstream's
4187/// `xmlOutputBufferCreateFilenameValue`); the deprecated plain-global
4188/// accessor `__xmlOutputBufferCreateFilename` returns a pointer to it.
4189///
4190/// # SAFETY
4191///
4192/// - `func` must be a valid function pointer or NULL.
4193/// - The previous value (NULL when none was registered) is returned.
4194#[no_mangle]
4195pub unsafe extern "C" fn xmlOutputBufferCreateFilenameDefault(
4196    func: Option<
4197        unsafe extern "C" fn(
4198            *const c_char,
4199            *mut crate::abi::structs::_xmlCharEncodingHandler,
4200            c_int,
4201        ) -> *mut _xmlOutputBuffer,
4202    >,
4203) -> Option<
4204    unsafe extern "C" fn(
4205        *const c_char,
4206        *mut crate::abi::structs::_xmlCharEncodingHandler,
4207        c_int,
4208    ) -> *mut _xmlOutputBuffer,
4209> {
4210    // UPSTREAM-PARITY (xmlIO.c): set only when func is non-NULL, return the
4211    // previously registered value (NULL when none). Same per-thread slot the
4212    // thrDef variant and the I/O routing consult.
4213    let old = crate::xml::globals::get_output_buffer_create_filename_value();
4214    if func.is_some() {
4215        crate::xml::globals::set_output_buffer_create_filename_value(func);
4216    }
4217    old
4218}
4219
4220/// `__xmlOutputBufferCreateFilename` — accessor returning a pointer to the
4221/// default callback (upstream xmlIO.c).
4222#[no_mangle]
4223pub unsafe extern "C" fn __xmlOutputBufferCreateFilename() -> *mut Option<
4224    unsafe extern "C" fn(
4225        *const c_char,
4226        *mut crate::abi::structs::_xmlCharEncodingHandler,
4227        c_int,
4228    ) -> *mut _xmlOutputBuffer,
4229> {
4230    crate::xml::globals::output_create_filename_ptr()
4231}
4232
4233// ═══════════════════════════════════════════════════════════════════════════════
4234// 9. Dictionary
4235// ═══════════════════════════════════════════════════════════════════════════════
4236
4237/// Create a new dictionary.
4238///
4239/// # UPSTREAM-PARITY
4240///
4241/// ```c
4242/// xmlDictPtr xmlDictCreate(void);
4243/// ```
4244#[no_mangle]
4245pub extern "C" fn xmlDictCreate() -> *mut c_void {
4246    // The creator holds the base reference (Dict.ref_count = 1, upstream
4247    // ref_counter); xmlDictReference adds to it and xmlDictFree decrements,
4248    // freeing the dictionary when it reaches zero. The count lives in the
4249    // shared dict memory (R-000177: cross-DSO coherent).
4250    crate::xml::dictionary::dict_create() as *mut c_void
4251}
4252
4253/// Create a sub-dictionary.
4254///
4255/// # UPSTREAM-PARITY
4256///
4257/// ```c
4258/// xmlDictPtr xmlDictCreateSub(xmlDictPtr sub);
4259/// ```
4260#[no_mangle]
4261pub extern "C" fn xmlDictCreateSub(sub: *mut c_void) -> *mut c_void {
4262    // Base reference lives in the shared dict memory (Dict.ref_count).
4263    unsafe {
4264        crate::xml::dictionary::dict_create_sub(sub as *mut crate::xml::dictionary::Dict)
4265            as *mut c_void
4266    }
4267}
4268
4269/// Look up a string in the dictionary.
4270///
4271/// # UPSTREAM-PARITY
4272///
4273/// ```c
4274/// const xmlChar *xmlDictLookup(xmlDictPtr dict, const xmlChar *name, int len);
4275/// ```
4276///
4277/// Returns an interned string pointer (valid as long as the dictionary exists).
4278/// - If `len` < 0, `name` must be null-terminated.
4279/// - If `len` >= 0, exactly `len` bytes are used.
4280#[no_mangle]
4281pub unsafe extern "C" fn xmlDictLookup(
4282    dict: *mut c_void,
4283    name: *const xmlChar,
4284    len: c_int,
4285) -> *const xmlChar {
4286    unsafe {
4287        crate::xml::dictionary::dict_lookup(dict as *mut crate::xml::dictionary::Dict, name, len)
4288    }
4289}
4290
4291/// Check if a string exists in the dictionary.
4292///
4293/// # UPSTREAM-PARITY
4294///
4295/// ```c
4296/// const xmlChar *xmlDictExists(xmlDictPtr dict, const xmlChar *name, int len);
4297/// ```
4298#[no_mangle]
4299pub unsafe extern "C" fn xmlDictExists(
4300    dict: *mut c_void,
4301    name: *const xmlChar,
4302    len: c_int,
4303) -> *const xmlChar {
4304    unsafe {
4305        crate::xml::dictionary::dict_exists(dict as *mut crate::xml::dictionary::Dict, name, len)
4306    }
4307}
4308
4309/// Query dictionary size.
4310///
4311/// # UPSTREAM-PARITY
4312///
4313/// ```c
4314/// int xmlDictSize(const xmlDictPtr dict);
4315/// ```
4316#[no_mangle]
4317pub const extern "C" fn xmlDictSize(dict: *const c_void) -> c_int {
4318    {
4319        crate::xml::dictionary::dict_size(dict as *const crate::xml::dictionary::Dict)
4320    }
4321}
4322
4323/// Free a dictionary.
4324///
4325/// # UPSTREAM-PARITY
4326///
4327/// ```c
4328/// void xmlDictFree(xmlDictPtr dict);
4329/// ```
4330///
4331/// The reference counter added by `xmlDictReference` is honored: the
4332/// underlying dictionary is destroyed only when the last reference is
4333/// released (the base owner counts as one implicit reference).
4334#[no_mangle]
4335pub extern "C" fn xmlDictFree(dict: *mut c_void) {
4336    if dict.is_null() {
4337        return;
4338    }
4339    // The reference count lives IN the shared dict memory (R-000177): a
4340    // decrement through one DSO observes references made through every
4341    // other DSO, so a dict created by libxml2.so.16 is never freed early by
4342    // libxslt.so.1's teardown. The pre-fix per-DSO side table partitioned
4343    // the count and unconditionally freed unknown dicts.
4344    let d = dict as *mut crate::xml::dictionary::Dict;
4345    let prev = unsafe {
4346        (*d).ref_count
4347            .fetch_sub(1, core::sync::atomic::Ordering::Relaxed)
4348    };
4349    if prev == 1 {
4350        unsafe { crate::xml::dictionary::dict_free(dict as *mut crate::xml::dictionary::Dict) };
4351    }
4352}
4353
4354/// Set the dictionary size limit.
4355///
4356/// # UPSTREAM-PARITY
4357///
4358/// ```c
4359/// size_t xmlDictSetLimit(xmlDictPtr dict, size_t limit);
4360/// ```
4361#[no_mangle]
4362pub extern "C" fn xmlDictSetLimit(dict: *mut c_void, limit: usize) -> usize {
4363    {
4364        crate::xml::dictionary::dict_set_limit(dict as *mut crate::xml::dictionary::Dict, limit)
4365    }
4366}
4367
4368/// Get current dictionary usage.
4369///
4370/// # UPSTREAM-PARITY
4371///
4372/// ```c
4373/// size_t xmlDictGetUsage(const xmlDictPtr dict);
4374/// ```
4375#[no_mangle]
4376pub extern "C" fn xmlDictGetUsage(dict: *const c_void) -> usize {
4377    {
4378        crate::xml::dictionary::dict_get_usage(dict as *mut crate::xml::dictionary::Dict)
4379    }
4380}
4381
4382// ═══════════════════════════════════════════════════════════════════════════════
4383// 10. Hash Table
4384// ═══════════════════════════════════════════════════════════════════════════════
4385
4386/// Create a new hash table.
4387///
4388/// # UPSTREAM-PARITY
4389///
4390/// ```c
4391/// xmlHashTablePtr xmlHashCreate(int size);
4392/// ```
4393#[no_mangle]
4394pub extern "C" fn xmlHashCreate(size: c_int) -> *mut c_void {
4395    crate::xml::hash::hash_create(size) as *mut c_void
4396}
4397
4398/// Create a new hash table with a dictionary.
4399///
4400/// # UPSTREAM-PARITY
4401///
4402/// ```c
4403/// xmlHashTablePtr xmlHashCreateDict(int size, xmlDictPtr dict);
4404/// ```
4405#[no_mangle]
4406pub extern "C" fn xmlHashCreateDict(size: c_int, dict: *mut c_void) -> *mut c_void {
4407    crate::xml::hash::hash_create_dict(size, dict) as *mut c_void
4408}
4409
4410/// Free a hash table.
4411///
4412/// # UPSTREAM-PARITY
4413///
4414/// ```c
4415/// void xmlHashFree(xmlHashTablePtr table, xmlHashDeallocator f);
4416/// ```
4417#[no_mangle]
4418pub extern "C" fn xmlHashFree(
4419    table: *mut c_void,
4420    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4421) {
4422    unsafe { crate::xml::hash::hash_free(table as *mut crate::xml::hash::HashTable, f) }
4423}
4424
4425/// Add an entry to a hash table.
4426///
4427/// # UPSTREAM-PARITY
4428///
4429/// ```c
4430/// int xmlHashAddEntry(xmlHashTablePtr table, const xmlChar *name, void *userdata);
4431/// ```
4432#[no_mangle]
4433pub unsafe extern "C" fn xmlHashAddEntry(
4434    table: *mut c_void,
4435    name: *const xmlChar,
4436    userdata: *mut c_void,
4437) -> c_int {
4438    unsafe {
4439        crate::xml::hash::hash_add_entry(table as *mut crate::xml::hash::HashTable, name, userdata)
4440    }
4441}
4442
4443/// Add a 2-key entry.
4444///
4445/// # UPSTREAM-PARITY
4446///
4447/// ```c
4448/// int xmlHashAddEntry2(xmlHashTablePtr table, const xmlChar *name,
4449///                      const xmlChar *name2, void *userdata);
4450/// ```
4451#[no_mangle]
4452pub unsafe extern "C" fn xmlHashAddEntry2(
4453    table: *mut c_void,
4454    name: *const xmlChar,
4455    name2: *const xmlChar,
4456    userdata: *mut c_void,
4457) -> c_int {
4458    unsafe {
4459        crate::xml::hash::hash_add_entry2(
4460            table as *mut crate::xml::hash::HashTable,
4461            name,
4462            name2,
4463            userdata,
4464        )
4465    }
4466}
4467
4468/// Add a 3-key entry.
4469///
4470/// # UPSTREAM-PARITY
4471///
4472/// ```c
4473/// int xmlHashAddEntry3(xmlHashTablePtr table, const xmlChar *name,
4474///                      const xmlChar *name2, const xmlChar *name3, void *userdata);
4475/// ```
4476#[no_mangle]
4477pub unsafe extern "C" fn xmlHashAddEntry3(
4478    table: *mut c_void,
4479    name: *const xmlChar,
4480    name2: *const xmlChar,
4481    name3: *const xmlChar,
4482    userdata: *mut c_void,
4483) -> c_int {
4484    unsafe {
4485        crate::xml::hash::hash_add_entry3(
4486            table as *mut crate::xml::hash::HashTable,
4487            name,
4488            name2,
4489            name3,
4490            userdata,
4491        )
4492    }
4493}
4494
4495/// Update or add an entry.
4496///
4497/// # UPSTREAM-PARITY
4498///
4499/// ```c
4500/// int xmlHashUpdateEntry(xmlHashTablePtr table, const xmlChar *name,
4501///                        void *userdata, xmlHashDeallocator f);
4502/// ```
4503#[no_mangle]
4504pub unsafe extern "C" fn xmlHashUpdateEntry(
4505    table: *mut c_void,
4506    name: *const xmlChar,
4507    userdata: *mut c_void,
4508    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4509) -> c_int {
4510    unsafe {
4511        crate::xml::hash::hash_update_entry(
4512            table as *mut crate::xml::hash::HashTable,
4513            name,
4514            userdata,
4515            f,
4516        )
4517    }
4518}
4519
4520/// Update or add a 2-key entry.
4521#[no_mangle]
4522pub unsafe extern "C" fn xmlHashUpdateEntry2(
4523    table: *mut c_void,
4524    name: *const xmlChar,
4525    name2: *const xmlChar,
4526    userdata: *mut c_void,
4527    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4528) -> c_int {
4529    unsafe {
4530        crate::xml::hash::hash_update_entry2(
4531            table as *mut crate::xml::hash::HashTable,
4532            name,
4533            name2,
4534            userdata,
4535            f,
4536        )
4537    }
4538}
4539
4540/// Update or add a 3-key entry.
4541#[no_mangle]
4542pub unsafe extern "C" fn xmlHashUpdateEntry3(
4543    table: *mut c_void,
4544    name: *const xmlChar,
4545    name2: *const xmlChar,
4546    name3: *const xmlChar,
4547    userdata: *mut c_void,
4548    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4549) -> c_int {
4550    unsafe {
4551        crate::xml::hash::hash_update_entry3(
4552            table as *mut crate::xml::hash::HashTable,
4553            name,
4554            name2,
4555            name3,
4556            userdata,
4557            f,
4558        )
4559    }
4560}
4561
4562/// Look up an entry.
4563///
4564/// # UPSTREAM-PARITY
4565///
4566/// ```c
4567/// void *xmlHashLookup(xmlHashTablePtr table, const xmlChar *name);
4568/// ```
4569#[no_mangle]
4570pub unsafe extern "C" fn xmlHashLookup(table: *mut c_void, name: *const xmlChar) -> *mut c_void {
4571    unsafe { crate::xml::hash::hash_lookup(table as *mut crate::xml::hash::HashTable, name) }
4572}
4573
4574/// Look up a 2-key entry.
4575#[no_mangle]
4576pub unsafe extern "C" fn xmlHashLookup2(
4577    table: *mut c_void,
4578    name: *const xmlChar,
4579    name2: *const xmlChar,
4580) -> *mut c_void {
4581    unsafe {
4582        crate::xml::hash::hash_lookup2(table as *mut crate::xml::hash::HashTable, name, name2)
4583    }
4584}
4585
4586/// Look up a 3-key entry.
4587#[no_mangle]
4588pub unsafe extern "C" fn xmlHashLookup3(
4589    table: *mut c_void,
4590    name: *const xmlChar,
4591    name2: *const xmlChar,
4592    name3: *const xmlChar,
4593) -> *mut c_void {
4594    unsafe {
4595        crate::xml::hash::hash_lookup3(
4596            table as *mut crate::xml::hash::HashTable,
4597            name,
4598            name2,
4599            name3,
4600        )
4601    }
4602}
4603
4604/// Get the size of a hash table.
4605///
4606/// # UPSTREAM-PARITY
4607///
4608/// ```c
4609/// int xmlHashSize(xmlHashTablePtr table);
4610/// ```
4611#[no_mangle]
4612pub extern "C" fn xmlHashSize(table: *mut c_void) -> c_int {
4613    crate::xml::hash::hash_size(table as *mut crate::xml::hash::HashTable)
4614}
4615
4616/// Remove an entry.
4617///
4618/// # UPSTREAM-PARITY
4619///
4620/// ```c
4621/// int xmlHashRemoveEntry(xmlHashTablePtr table, const xmlChar *name,
4622///                        xmlHashDeallocator f);
4623/// ```
4624#[no_mangle]
4625pub unsafe extern "C" fn xmlHashRemoveEntry(
4626    table: *mut c_void,
4627    name: *const xmlChar,
4628    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4629) -> c_int {
4630    unsafe {
4631        crate::xml::hash::hash_remove_entry(table as *mut crate::xml::hash::HashTable, name, f)
4632    }
4633}
4634
4635/// Remove a 2-key entry.
4636#[no_mangle]
4637pub unsafe extern "C" fn xmlHashRemoveEntry2(
4638    table: *mut c_void,
4639    name: *const xmlChar,
4640    name2: *const xmlChar,
4641    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4642) -> c_int {
4643    unsafe {
4644        crate::xml::hash::hash_remove_entry2(
4645            table as *mut crate::xml::hash::HashTable,
4646            name,
4647            name2,
4648            f,
4649        )
4650    }
4651}
4652
4653/// Remove a 3-key entry.
4654#[no_mangle]
4655pub unsafe extern "C" fn xmlHashRemoveEntry3(
4656    table: *mut c_void,
4657    name: *const xmlChar,
4658    name2: *const xmlChar,
4659    name3: *const xmlChar,
4660    f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4661) -> c_int {
4662    unsafe {
4663        crate::xml::hash::hash_remove_entry3(
4664            table as *mut crate::xml::hash::HashTable,
4665            name,
4666            name2,
4667            name3,
4668            f,
4669        )
4670    }
4671}
4672
4673/// Scan a hash table with a scanner function.
4674///
4675/// # UPSTREAM-PARITY
4676///
4677/// ```c
4678/// void xmlHashScan(xmlHashTablePtr table, xmlHashScanner f, void *data);
4679/// ```
4680#[no_mangle]
4681pub extern "C" fn xmlHashScan(table: *mut c_void, f: Option<xmlHashScanner>, data: *mut c_void) {
4682    unsafe { crate::xml::hash::hash_scan(table as *mut crate::xml::hash::HashTable, f, data) }
4683}
4684
4685/// Scan a hash table with a full scanner function.
4686#[no_mangle]
4687pub extern "C" fn xmlHashScanFull(
4688    table: *mut c_void,
4689    f: Option<xmlHashScannerFull>,
4690    data: *mut c_void,
4691) {
4692    unsafe { crate::xml::hash::hash_scan_full(table as *mut crate::xml::hash::HashTable, f, data) }
4693}
4694
4695/// Copy a hash table.
4696///
4697/// # UPSTREAM-PARITY
4698///
4699/// ```c
4700/// xmlHashTablePtr xmlHashCopy(xmlHashTablePtr table, xmlHashCopier f);
4701/// ```
4702#[no_mangle]
4703pub extern "C" fn xmlHashCopy(
4704    table: *mut c_void,
4705    f: Option<unsafe extern "C" fn(*mut c_void, *const xmlChar) -> *mut c_void>,
4706) -> *mut c_void {
4707    unsafe {
4708        crate::xml::hash::hash_copy(table as *mut crate::xml::hash::HashTable, f) as *mut c_void
4709    }
4710}
4711
4712// ═══════════════════════════════════════════════════════════════════════════════
4713// 11. List
4714// ═══════════════════════════════════════════════════════════════════════════════
4715
4716/// Create a new list.
4717///
4718/// # UPSTREAM-PARITY
4719///
4720/// ```c
4721/// xmlListPtr xmlListCreate(xmlListDeallocator deallocator,
4722///                          xmlListDataCompare compare);
4723/// ```
4724#[no_mangle]
4725pub extern "C" fn xmlListCreate(
4726    deallocator: Option<unsafe extern "C" fn(*mut c_void)>,
4727    compare: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
4728) -> *mut c_void {
4729    crate::xml::list::list_create(deallocator, compare) as *mut c_void
4730}
4731
4732/// Delete a list.
4733///
4734/// # UPSTREAM-PARITY
4735///
4736/// ```c
4737/// void xmlListDelete(xmlListPtr list);
4738/// ```
4739#[no_mangle]
4740pub extern "C" fn xmlListDelete(list: *mut c_void) {
4741    unsafe { crate::xml::list::list_delete(list as *mut crate::xml::list::List) }
4742}
4743
4744/// Search a list.
4745///
4746/// # UPSTREAM-PARITY
4747///
4748/// ```c
4749/// void *xmlListSearch(xmlListPtr list, void *data);
4750/// ```
4751#[no_mangle]
4752pub extern "C" fn xmlListSearch(list: *mut c_void, data: *mut c_void) -> *mut c_void {
4753    unsafe { crate::xml::list::list_search(list as *mut crate::xml::list::List, data) }
4754}
4755
4756/// Walk a list.
4757///
4758/// # UPSTREAM-PARITY
4759///
4760/// ```c
4761/// void xmlListWalk(xmlListPtr list, xmlListWalker walker, void *data);
4762/// ```
4763#[no_mangle]
4764pub extern "C" fn xmlListWalk(
4765    list: *mut c_void,
4766    walker: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
4767    data: *mut c_void,
4768) {
4769    unsafe { crate::xml::list::list_walk(list as *mut crate::xml::list::List, walker, data) }
4770}
4771
4772/// Push to back.
4773///
4774/// # UPSTREAM-PARITY
4775///
4776/// ```c
4777/// int xmlListPushBack(xmlListPtr list, void *data);
4778/// ```
4779#[no_mangle]
4780pub extern "C" fn xmlListPushBack(list: *mut c_void, data: *mut c_void) -> c_int {
4781    unsafe { crate::xml::list::list_push_back(list as *mut crate::xml::list::List, data) }
4782}
4783
4784/// Push to front.
4785///
4786/// # UPSTREAM-PARITY
4787///
4788/// ```c
4789/// int xmlListPushFront(xmlListPtr list, void *data);
4790/// ```
4791#[no_mangle]
4792pub extern "C" fn xmlListPushFront(list: *mut c_void, data: *mut c_void) -> c_int {
4793    unsafe { crate::xml::list::list_push_front(list as *mut crate::xml::list::List, data) }
4794}
4795
4796/// Pop from back.
4797#[no_mangle]
4798pub extern "C" fn xmlListPopBack(list: *mut c_void) {
4799    unsafe { crate::xml::list::list_pop_back(list as *mut crate::xml::list::List) }
4800}
4801
4802/// Pop from front.
4803#[no_mangle]
4804pub extern "C" fn xmlListPopFront(list: *mut c_void) {
4805    unsafe { crate::xml::list::list_pop_front(list as *mut crate::xml::list::List) }
4806}
4807
4808/// Insert into sorted list.
4809///
4810/// # UPSTREAM-PARITY
4811///
4812/// ```c
4813/// int xmlListInsert(xmlListPtr list, void *data);
4814/// ```
4815#[no_mangle]
4816pub extern "C" fn xmlListInsert(list: *mut c_void, data: *mut c_void) -> c_int {
4817    unsafe { crate::xml::list::list_insert(list as *mut crate::xml::list::List, data) }
4818}
4819
4820/// Append to list.
4821#[no_mangle]
4822pub extern "C" fn xmlListAppend(list: *mut c_void, data: *mut c_void) -> c_int {
4823    unsafe { crate::xml::list::list_append(list as *mut crate::xml::list::List, data) }
4824}
4825
4826/// Remove first matching element.
4827#[no_mangle]
4828pub extern "C" fn xmlListRemoveFirst(list: *mut c_void, data: *mut c_void) -> c_int {
4829    unsafe { crate::xml::list::list_remove_first(list as *mut crate::xml::list::List, data) }
4830}
4831
4832/// Remove last matching element.
4833#[no_mangle]
4834pub extern "C" fn xmlListRemoveLast(list: *mut c_void, data: *mut c_void) -> c_int {
4835    unsafe { crate::xml::list::list_remove_last(list as *mut crate::xml::list::List, data) }
4836}
4837
4838/// Remove all matching elements.
4839#[no_mangle]
4840pub extern "C" fn xmlListRemoveAll(list: *mut c_void, data: *mut c_void) -> c_int {
4841    unsafe { crate::xml::list::list_remove_all(list as *mut crate::xml::list::List, data) }
4842}
4843
4844/// Clear a list.
4845#[no_mangle]
4846pub extern "C" fn xmlListClear(list: *mut c_void) {
4847    unsafe { crate::xml::list::list_clear(list as *mut crate::xml::list::List) }
4848}
4849
4850/// Check if list is empty.
4851///
4852/// # UPSTREAM-PARITY
4853///
4854/// ```c
4855/// int xmlListEmpty(xmlListPtr list);
4856/// ```
4857#[no_mangle]
4858pub extern "C" fn xmlListEmpty(list: *mut c_void) -> c_int {
4859    crate::xml::list::list_empty(list as *mut crate::xml::list::List)
4860}
4861
4862/// Get front element.
4863///
4864/// # UPSTREAM-PARITY
4865///
4866/// ```c
4867/// void *xmlListFront(xmlListPtr list);
4868/// ```
4869#[no_mangle]
4870pub extern "C" fn xmlListFront(list: *mut c_void) -> *mut c_void {
4871    crate::xml::list::list_front(list as *mut crate::xml::list::List)
4872}
4873
4874/// Get back element.
4875///
4876/// # UPSTREAM-PARITY
4877///
4878/// ```c
4879/// void *xmlListBack(xmlListPtr list);
4880/// ```
4881#[no_mangle]
4882pub extern "C" fn xmlListBack(list: *mut c_void) -> *mut c_void {
4883    crate::xml::list::list_back(list as *mut crate::xml::list::List)
4884}
4885
4886/// Get list size.
4887///
4888/// # UPSTREAM-PARITY
4889///
4890/// ```c
4891/// int xmlListSize(xmlListPtr list);
4892/// ```
4893#[no_mangle]
4894pub extern "C" fn xmlListSize(list: *mut c_void) -> c_int {
4895    crate::xml::list::list_size(list as *mut crate::xml::list::List)
4896}
4897
4898/// Sort a list.
4899#[no_mangle]
4900pub extern "C" fn xmlListSort(list: *mut c_void) {
4901    unsafe { crate::xml::list::list_sort(list as *mut crate::xml::list::List) }
4902}
4903
4904/// Reverse a list.
4905#[no_mangle]
4906pub extern "C" fn xmlListReverse(list: *mut c_void) {
4907    unsafe { crate::xml::list::list_reverse(list as *mut crate::xml::list::List) }
4908}
4909
4910/// Reverse a list in-place.
4911#[no_mangle]
4912pub extern "C" fn xmlListReverseSplice(list: *mut c_void, list2: *mut c_void) {
4913    unsafe {
4914        crate::xml::list::list_reverse_splice(
4915            list as *mut crate::xml::list::List,
4916            list2 as *mut crate::xml::list::List,
4917        )
4918    }
4919}
4920
4921/// Merge two sorted lists.
4922#[no_mangle]
4923pub extern "C" fn xmlListMerge(list: *mut c_void, list2: *mut c_void) {
4924    unsafe {
4925        crate::xml::list::list_merge(
4926            list as *mut crate::xml::list::List,
4927            list2 as *mut crate::xml::list::List,
4928        )
4929    }
4930}
4931/// Return the last element of a list (upstream list.h).
4932///
4933/// # UPSTREAM-PARITY
4934///
4935/// ```c
4936/// void *xmlListEnd(xmlListPtr l);
4937/// ```
4938#[no_mangle]
4939pub unsafe extern "C" fn xmlListEnd(l: *mut c_void) -> *mut c_void {
4940    crate::xml::list::list_end(l as *mut crate::xml::list::List)
4941}
4942
4943/// Reverse-search a list (upstream list.h).
4944///
4945/// # UPSTREAM-PARITY
4946///
4947/// ```c
4948/// void *xmlListReverseSearch(xmlListPtr l, void *data);
4949/// ```
4950#[no_mangle]
4951pub unsafe extern "C" fn xmlListReverseSearch(l: *mut c_void, data: *mut c_void) -> *mut c_void {
4952    crate::xml::list::list_reverse_search(l as *mut crate::xml::list::List, data)
4953}
4954
4955/// Walk a list in reverse (upstream list.h).
4956///
4957/// # UPSTREAM-PARITY
4958///
4959/// ```c
4960/// void xmlListReverseWalk(xmlListPtr l, xmlListWalker walker, void *data);
4961/// ```
4962#[no_mangle]
4963pub unsafe extern "C" fn xmlListReverseWalk(
4964    l: *mut c_void,
4965    walker: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
4966    data: *mut c_void,
4967) {
4968    crate::xml::list::list_reverse_walk(l as *mut crate::xml::list::List, walker, data)
4969}
4970
4971/// Duplicate a list (upstream list.h).
4972///
4973/// # UPSTREAM-PARITY
4974///
4975/// ```c
4976/// xmlListPtr xmlListDup(xmlListPtr l);
4977/// ```
4978#[no_mangle]
4979pub unsafe extern "C" fn xmlListDup(l: *mut c_void) -> *mut c_void {
4980    crate::xml::list::list_dup(l as *mut crate::xml::list::List) as *mut c_void
4981}
4982
4983/// Copy the contents of `old` into the existing list `cur` (upstream
4984/// list.h — R-000176, the candidate previously passed a copier callback).
4985///
4986/// # UPSTREAM-PARITY
4987///
4988/// ```c
4989/// int xmlListCopy(xmlListPtr cur, const xmlListPtr old);
4990/// ```
4991///
4992/// Returns 0 on success, 1 on error (upstream list.c).
4993#[no_mangle]
4994pub unsafe extern "C" fn xmlListCopy(cur: *mut c_void, old: *mut c_void) -> c_int {
4995    crate::xml::list::list_copy(
4996        cur as *mut crate::xml::list::List,
4997        old as *mut crate::xml::list::List,
4998    )
4999}
5000
5001/// Return the data of a link (upstream list.h).
5002///
5003/// # UPSTREAM-PARITY
5004///
5005/// ```c
5006/// void *xmlLinkGetData(xmlLinkPtr lk);
5007/// ```
5008#[no_mangle]
5009pub unsafe extern "C" fn xmlLinkGetData(lk: *mut c_void) -> *mut c_void {
5010    crate::xml::list::link_get_data(lk)
5011}
5012
5013// ═══════════════════════════════════════════════════════════════════════════════
5014// 12. Buffer
5015// ═══════════════════════════════════════════════════════════════════════════════
5016
5017/// Create a new buffer.
5018///
5019/// # UPSTREAM-PARITY
5020///
5021/// ```c
5022/// xmlBufferPtr xmlBufferCreate(void);
5023/// ```
5024#[no_mangle]
5025pub extern "C" fn xmlBufferCreate() -> *mut _xmlBuffer {
5026    // UPSTREAM-PARITY (buf.c 2.15): xmlBufferCreate = size 256, alloc scheme
5027    // XML_BUFFER_ALLOC_IO, content[0] = 0. (The pre-Phase-13 path used the
5028    // internal default-size DOUBLEIT helper, which diverged from the oracle
5029    // for negative/huge CreateSize arguments — HOSTILE-ABI finding.)
5030    unsafe { xml_buffer_create_upstream(256) }
5031}
5032
5033/// Create a new buffer of a given size.
5034///
5035/// # UPSTREAM-PARITY
5036///
5037/// ```c
5038/// xmlBufferPtr xmlBufferCreateSize(size_t size);
5039/// ```
5040///
5041/// Upstream buf.c 2.15: `size >= INT_MAX` returns NULL; `size == 0` returns
5042/// a buffer with a NULL content; otherwise the content is `size + 1` bytes
5043/// (the extra byte is the NUL terminator). The alloc scheme is
5044/// XML_BUFFER_ALLOC_IO.
5045#[no_mangle]
5046pub extern "C" fn xmlBufferCreateSize(size: usize) -> *mut _xmlBuffer {
5047    // UPSTREAM-PARITY (buf.c 2.15 xmlBufferCreateSize): sizes at or beyond
5048    // INT_MAX are rejected up front — a C caller passing -1 (huge size_t)
5049    // gets NULL exactly like the oracle (HOSTILE-ABI finding).
5050    if size >= c_int::MAX as usize {
5051        return ptr::null_mut();
5052    }
5053    unsafe { xml_buffer_create_upstream(size) }
5054}
5055
5056/// Upstream `xmlBufferCreateSize` body (buf.c 2.15): allocate the struct,
5057/// then `size + 1` content bytes when size != 0 (zero-size buffers have a
5058/// NULL content), alloc scheme XML_BUFFER_ALLOC_IO, content[0] = 0.
5059///
5060/// # Safety
5061///
5062/// - No caller-provided pointers; every allocation is checked for NULL and
5063///   the struct is freed on content-allocation failure.
5064unsafe fn xml_buffer_create_upstream(size: usize) -> *mut _xmlBuffer {
5065    let ret = unsafe { xmlMallocImpl(size_of::<_xmlBuffer>()) as *mut _xmlBuffer };
5066    if ret.is_null() {
5067        return ptr::null_mut();
5068    }
5069    let sz = if size != 0 { size + 1 } else { 0 };
5070    unsafe {
5071        if sz != 0 {
5072            let content = xmlMallocImpl(sz) as *mut xmlChar;
5073            if content.is_null() {
5074                xmlFreeImpl(ret as *mut c_void);
5075                return ptr::null_mut();
5076            }
5077            *content = 0;
5078            (*ret).content = content;
5079            (*ret).contentIO = content;
5080        } else {
5081            (*ret).content = ptr::null_mut();
5082            (*ret).contentIO = ptr::null_mut();
5083        }
5084        (*ret).use_ = 0;
5085        (*ret).size = sz as c_uint;
5086        (*ret).alloc = crate::abi::types::xmlBufferAllocationScheme::XML_BUFFER_ALLOC_IO as c_int;
5087    }
5088    ret
5089}
5090
5091/// Create a buffer from a static string.
5092///
5093/// # UPSTREAM-PARITY
5094///
5095/// ```c
5096/// xmlBufferPtr xmlBufferCreateStatic(void *mem, size_t size);
5097/// ```
5098#[no_mangle]
5099pub extern "C" fn xmlBufferCreateStatic(mem: *mut c_void, size: usize) -> *mut _xmlBuffer {
5100    if mem.is_null() || size == 0 {
5101        return ptr::null_mut();
5102    }
5103    crate::xml::io::buf_create_static(mem as *const xmlChar, size as c_int)
5104}
5105
5106/// Free a buffer.
5107///
5108/// # UPSTREAM-PARITY
5109///
5110/// ```c
5111/// void xmlBufferFree(xmlBufferPtr buf);
5112/// ```
5113#[no_mangle]
5114pub extern "C" fn xmlBufferFree(buf: *mut _xmlBuffer) {
5115    crate::xml::io::buf_free(buf)
5116}
5117
5118/// Empty a buffer.
5119///
5120/// # UPSTREAM-PARITY
5121///
5122/// ```c
5123/// void xmlBufferEmpty(xmlBufferPtr buf);
5124/// ```
5125#[no_mangle]
5126pub extern "C" fn xmlBufferEmpty(buf: *mut _xmlBuffer) {
5127    if buf.is_null() {
5128        return;
5129    }
5130    unsafe {
5131        if !(*buf).content.is_null() {
5132            *(*buf).content = 0;
5133        }
5134        (*buf).use_ = 0;
5135    }
5136}
5137
5138/// Get buffer content.
5139///
5140/// # UPSTREAM-PARITY
5141///
5142/// ```c
5143/// xmlChar *xmlBufferContent(const xmlBuffer *buf);
5144/// ```
5145#[no_mangle]
5146pub extern "C" fn xmlBufferContent(buf: *const _xmlBuffer) -> *mut xmlChar {
5147    crate::xml::io::buf_content(buf as *mut _xmlBuffer)
5148}
5149
5150/// Get buffer length.
5151///
5152/// # UPSTREAM-PARITY
5153///
5154/// ```c
5155/// int xmlBufferLength(const xmlBuffer *buf);
5156/// ```
5157#[no_mangle]
5158pub extern "C" fn xmlBufferLength(buf: *const _xmlBuffer) -> c_int {
5159    crate::xml::io::buf_length(buf as *mut _xmlBuffer)
5160}
5161
5162/// Write to a buffer.
5163///
5164/// # UPSTREAM-PARITY
5165///
5166/// ```c
5167/// int xmlBufferAdd(xmlBufferPtr buf, const xmlChar *str, int len);
5168/// ```
5169#[no_mangle]
5170pub unsafe extern "C" fn xmlBufferAdd(
5171    buf: *mut _xmlBuffer,
5172    str: *const xmlChar,
5173    len: c_int,
5174) -> c_int {
5175    crate::xml::io::buf_add(buf, str, len)
5176}
5177
5178/// Write to a buffer at a position.
5179///
5180/// # UPSTREAM-PARITY
5181///
5182/// ```c
5183/// int xmlBufferAddHead(xmlBufferPtr buf, const xmlChar *str, int len);
5184/// ```
5185#[no_mangle]
5186pub unsafe extern "C" fn xmlBufferAddHead(
5187    buf: *mut _xmlBuffer,
5188    str: *const xmlChar,
5189    len: c_int,
5190) -> c_int {
5191    crate::xml::io::buf_add_head(buf, str, len)
5192}
5193
5194/// Write a C string to a buffer.
5195///
5196/// # UPSTREAM-PARITY
5197///
5198/// ```c
5199/// int xmlBufferCat(xmlBufferPtr buf, const xmlChar *str);
5200/// ```
5201#[no_mangle]
5202pub unsafe extern "C" fn xmlBufferCat(buf: *mut _xmlBuffer, str: *const xmlChar) -> c_int {
5203    if str.is_null() {
5204        return -1;
5205    }
5206    let len = crate::xml::string::xml_strlen(str) as c_int;
5207    crate::xml::io::buf_add(buf, str, len)
5208}
5209
5210/// Set buffer allocation scheme.
5211///
5212/// # UPSTREAM-PARITY
5213///
5214/// ```c
5215/// void xmlBufferSetAllocationScheme(xmlBufferPtr buf,
5216///                                    xmlBufferAllocationScheme scheme);
5217/// ```
5218#[no_mangle]
5219pub extern "C" fn xmlBufferSetAllocationScheme(buf: *mut _xmlBuffer, scheme: c_int) {
5220    if buf.is_null() {
5221        return;
5222    }
5223    unsafe {
5224        (*buf).alloc = scheme;
5225    }
5226}
5227
5228/// Shrink buffer.
5229///
5230/// # UPSTREAM-PARITY
5231///
5232/// ```c
5233/// int xmlBufferShrink(xmlBufferPtr buf, unsigned int len);
5234/// ```
5235///
5236/// Oracle buf.c semantics (11.1-Z.3 alignment): -1 on NULL or `len` larger
5237/// than the buffer content, 0 for `len == 0`, else the removed byte count.
5238#[no_mangle]
5239pub extern "C" fn xmlBufferShrink(buf: *mut _xmlBuffer, len: c_uint) -> c_int {
5240    if buf.is_null() {
5241        return -1;
5242    }
5243    if len == 0 {
5244        return 0;
5245    }
5246    unsafe {
5247        let b = &mut *buf;
5248        if len > b.use_ {
5249            return -1;
5250        }
5251        let remaining = b.use_ - len;
5252        if remaining > 0 {
5253            core::ptr::copy(b.content.add(len as usize), b.content, remaining as usize);
5254        }
5255        *b.content.add(remaining as usize) = 0;
5256        b.use_ = remaining;
5257    }
5258    len as c_int
5259}
5260
5261/// Grow buffer.
5262///
5263/// # UPSTREAM-PARITY
5264///
5265/// ```c
5266/// int xmlBufferGrow(xmlBufferPtr buf, unsigned int len);
5267/// ```
5268#[no_mangle]
5269pub extern "C" fn xmlBufferGrow(buf: *mut _xmlBuffer, len: c_uint) -> c_int {
5270    if buf.is_null() || len == 0 {
5271        return 0;
5272    }
5273    let cur_use = unsafe { (*buf).use_ };
5274    let new_size = cur_use + len + 1;
5275    crate::xml::io::buf_grow(buf, new_size)
5276}
5277
5278/// Reserve buffer space.
5279///
5280/// # UPSTREAM-PARITY
5281///
5282/// ```c
5283/// int xmlBufferReserve(xmlBufferPtr buf, int len);
5284/// ```
5285#[no_mangle]
5286pub extern "C" fn xmlBufferReserve(buf: *mut _xmlBuffer, len: c_int) -> c_int {
5287    xmlBufferGrow(buf, len as c_uint)
5288}
5289
5290/// Detach buffer content.
5291///
5292/// # UPSTREAM-PARITY
5293///
5294/// ```c
5295/// xmlChar *xmlBufferDetach(xmlBufferPtr buf);
5296/// ```
5297#[no_mangle]
5298pub extern "C" fn xmlBufferDetach(buf: *mut _xmlBuffer) -> *mut xmlChar {
5299    if buf.is_null() {
5300        return ptr::null_mut();
5301    }
5302    unsafe {
5303        let content = (*buf).content;
5304        (*buf).content = ptr::null_mut();
5305        (*buf).use_ = 0;
5306        (*buf).size = 0;
5307        content
5308    }
5309}
5310
5311// ═══════════════════════════════════════════════════════════════════════════════
5312// 13. Encoding
5313// ═══════════════════════════════════════════════════════════════════════════════
5314
5315/// Get encoding from a name string.
5316///
5317/// # UPSTREAM-PARITY
5318///
5319/// ```c
5320/// xmlCharEncoding xmlGetCharEncoding(const char *name);
5321/// ```
5322#[no_mangle]
5323pub extern "C" fn xmlGetCharEncoding(name: *const c_char) -> c_int {
5324    if name.is_null() {
5325        return 0; // XML_CHAR_ENCODING_NONE
5326    }
5327    let name_bytes = unsafe {
5328        let len = libc::strlen(name);
5329        core::slice::from_raw_parts(name as *const u8, len)
5330    };
5331    crate::xml::encoding::encoding_from_name(name_bytes) as c_int
5332}
5333
5334/// Find an encoding handler.
5335///
5336/// # UPSTREAM-PARITY
5337///
5338/// ```c
5339/// xmlCharEncodingHandlerPtr xmlFindCharEncodingHandler(const char *name);
5340/// ```
5341#[no_mangle]
5342pub extern "C" fn xmlFindCharEncodingHandler(name: *const c_char) -> *mut c_void {
5343    if name.is_null() {
5344        return ptr::null_mut();
5345    }
5346    // Upstream hands the caller an OWNED handler it must release with
5347    // xmlCharEncCloseFunc (PHP's dom_document_encoding_write closes it after
5348    // every $dom->encoding= write) — except UTF-8, where the handler is static
5349    // and close is a no-op. Returning the persistent registry pointer directly
5350    // would let a non-UTF-8 caller's close free a still-registered handler (the
5351    // use-after-free behind DOMDocument::$encoding='UTF-16' crashing the next
5352    // registry lookup). See xmlFindCharEncodingHandler_owned.
5353    crate::xml::encoding::xmlFindCharEncodingHandler_owned(
5354        name as *const crate::abi::types::xmlChar,
5355    ) as *mut c_void
5356}
5357
5358/// Close an encoding handler.
5359///
5360/// # UPSTREAM-PARITY
5361///
5362/// ```c
5363/// int xmlCharEncCloseFunc(xmlCharEncodingHandlerPtr handler);
5364/// ```
5365#[no_mangle]
5366pub extern "C" fn xmlCharEncCloseFunc(handler: *mut c_void) -> c_int {
5367    if handler.is_null() {
5368        return -1;
5369    }
5370    // Upstream xmlCharEncCloseFunc (encoding.c): a handler flagged
5371    // XML_HANDLER_STATIC (UTF-8's default handler, or any static table
5372    // handler) is not owned by the caller and must not be released.
5373    unsafe {
5374        let h = handler as *mut crate::abi::structs::_xmlCharEncodingHandler;
5375        if (*h).flags & crate::xml::encoding::XML_HANDLER_STATIC != 0 {
5376            return 0;
5377        }
5378        if !(*h).name.is_null() {
5379            crate::abi::allocator::xmlFreeImpl((*h).name as *mut c_void);
5380        }
5381        // Run any conversion-context destructor before freeing the struct,
5382        // matching upstream's ordering (name, then ctxtDtor, then struct).
5383        if let Some(dtor) = (*h).ctxtDtor {
5384            if !(*h).inputCtxt.is_null() {
5385                dtor((*h).inputCtxt);
5386            }
5387            if !(*h).outputCtxt.is_null() {
5388                dtor((*h).outputCtxt);
5389            }
5390        }
5391        crate::abi::allocator::xmlFreeImpl(handler);
5392    }
5393    0
5394}
5395
5396/// Convert a block of ISO-8859-1 bytes to UTF-8 (upstream encoding.c
5397/// `xmlIsolat1ToUTF8`; R-000165 closure).
5398///
5399/// `*outlen`/`*inlen` are updated with the bytes produced/consumed; returns
5400/// the number of bytes written or an xmlCharEncError code.
5401///
5402/// # SAFETY
5403///
5404/// `out`/`in` must be valid buffers for `*outlen`/`*inlen` bytes.
5405#[no_mangle]
5406pub unsafe extern "C" fn xmlIsolat1ToUTF8(
5407    out: *mut u8,
5408    outlen: *mut c_int,
5409    input: *const u8,
5410    inlen: *mut c_int,
5411) -> c_int {
5412    // xmlCharEncError (encoding.h): SUCCESS 0, INTERNAL -1, SPACE -2.
5413    const XML_ENC_ERR_SPACE: c_int = -2;
5414    const XML_ENC_ERR_INTERNAL: c_int = -1;
5415    unsafe {
5416        if out.is_null() || input.is_null() || outlen.is_null() || inlen.is_null() {
5417            return XML_ENC_ERR_INTERNAL;
5418        }
5419        let outstart = out;
5420        let instart = input;
5421        let outend = out.add(*outlen as usize);
5422        let inend = input.add(*inlen as usize);
5423        let mut cur = input;
5424        let mut o = out;
5425        while cur < inend {
5426            let c = *cur;
5427            if c < 0x80 {
5428                if o >= outend {
5429                    break;
5430                }
5431                *o = c;
5432                o = o.add(1);
5433            } else {
5434                if (outend as usize) - (o as usize) < 2 {
5435                    break;
5436                }
5437                *o = (c >> 6) | 0xC0;
5438                *o.add(1) = (c & 0x3F) | 0x80;
5439                o = o.add(2);
5440            }
5441            cur = cur.add(1);
5442        }
5443        let mut ret = XML_ENC_ERR_SPACE;
5444        if cur == inend {
5445            ret = (o as usize - outstart as usize) as c_int;
5446        }
5447        *outlen = (o as usize - outstart as usize) as c_int;
5448        *inlen = (cur as usize - instart as usize) as c_int;
5449        ret
5450    }
5451}
5452
5453/// Convert a block of UTF-8 to ISO-8859-1 (upstream encoding.c
5454/// `xmlUTF8ToIsolat1`; R-000165 closure).
5455///
5456/// # SAFETY
5457///
5458/// `out`/`in` must be valid buffers for `*outlen`/`*inlen` bytes.
5459#[no_mangle]
5460pub unsafe extern "C" fn xmlUTF8ToIsolat1(
5461    out: *mut u8,
5462    outlen: *mut c_int,
5463    input: *const u8,
5464    inlen: *mut c_int,
5465) -> c_int {
5466    const XML_ENC_ERR_SPACE: c_int = -2;
5467    const XML_ENC_ERR_INTERNAL: c_int = -1;
5468    const XML_ENC_ERR_INPUT: c_int = -3;
5469    const XML_ENC_ERR_SUCCESS: c_int = 0;
5470    unsafe {
5471        if out.is_null() || outlen.is_null() || inlen.is_null() {
5472            return XML_ENC_ERR_INTERNAL;
5473        }
5474        if input.is_null() {
5475            *inlen = 0;
5476            *outlen = 0;
5477            return XML_ENC_ERR_SUCCESS;
5478        }
5479        let outstart = out;
5480        let instart = input;
5481        let outend = out.add(*outlen as usize);
5482        let inend = input.add(*inlen as usize);
5483        let mut cur = input;
5484        let mut o = out;
5485        let mut ret = XML_ENC_ERR_SPACE;
5486        while cur < inend {
5487            if o >= outend {
5488                break;
5489            }
5490            let c = *cur;
5491            if c < 0x80 {
5492                *o = c;
5493                o = o.add(1);
5494            } else if (0xC2..=0xC3).contains(&c) {
5495                if (inend as usize) - (cur as usize) < 2 {
5496                    break;
5497                }
5498                cur = cur.add(1);
5499                *o = (c << 6) | (*cur & 0x3F);
5500                o = o.add(1);
5501            } else {
5502                ret = XML_ENC_ERR_INPUT;
5503                break;
5504            }
5505            cur = cur.add(1);
5506        }
5507        if ret != XML_ENC_ERR_INPUT {
5508            ret = (o as usize - outstart as usize) as c_int;
5509        }
5510        *outlen = (o as usize - outstart as usize) as c_int;
5511        *inlen = (cur as usize - instart as usize) as c_int;
5512        ret
5513    }
5514}
5515
5516/// Return the name of a character encoding (upstream encoding.h).
5517///
5518/// # UPSTREAM-PARITY
5519///
5520/// ```c
5521/// const char *xmlGetCharEncodingName(xmlCharEncoding enc);
5522/// ```
5523#[no_mangle]
5524pub extern "C" fn xmlGetCharEncodingName(enc: c_int) -> *const c_char {
5525    /* Values outside the local enum resolve against the upstream
5526     * defaultHandlers table (XML_CHAR_ENCODING_UTF16=23, HTML=24,
5527     * WINDOWS_1252=31); anything else is unknown (NULL). */
5528    if !(-1..=22).contains(&enc) {
5529        return match enc {
5530            23 => c"UTF-16".as_ptr(),
5531            24 => c"HTML".as_ptr(),
5532            31 => c"windows-1252".as_ptr(),
5533            _ => ptr::null(),
5534        };
5535    }
5536    let e: crate::abi::types::xmlCharEncoding = unsafe { core::mem::transmute(enc) };
5537    crate::xml::encoding::xmlGetCharEncodingName(e)
5538}
5539
5540/// Parse an encoding name into an xmlCharEncoding value (upstream encoding.h).
5541///
5542/// # UPSTREAM-PARITY
5543///
5544/// ```c
5545/// xmlCharEncoding xmlParseCharEncoding(const char *name);
5546/// ```
5547///
5548/// Returns the encoding value or XML_CHAR_ENCODING_ERROR (-1).
5549#[no_mangle]
5550pub extern "C" fn xmlParseCharEncoding(name: *const c_char) -> c_int {
5551    crate::xml::encoding::xmlParseCharEncoding(name)
5552}
5553
5554/// Add an encoding alias (upstream encoding.h).
5555///
5556/// # UPSTREAM-PARITY
5557///
5558/// ```c
5559/// int xmlAddEncodingAlias(const char *name, const char *alias);
5560/// ```
5561#[no_mangle]
5562pub extern "C" fn xmlAddEncodingAlias(name: *const c_char, alias: *const c_char) -> c_int {
5563    crate::xml::encoding::add_encoding_alias(name, alias)
5564}
5565
5566/// Delete an encoding alias (upstream encoding.h).
5567///
5568/// # UPSTREAM-PARITY
5569///
5570/// ```c
5571/// int xmlDelEncodingAlias(const char *alias);
5572/// ```
5573#[no_mangle]
5574pub extern "C" fn xmlDelEncodingAlias(alias: *const c_char) -> c_int {
5575    crate::xml::encoding::del_encoding_alias(alias)
5576}
5577
5578/// Look up an encoding alias (upstream encoding.h).
5579///
5580/// # UPSTREAM-PARITY
5581///
5582/// ```c
5583/// const char *xmlGetEncodingAlias(const char *alias);
5584/// ```
5585#[no_mangle]
5586pub extern "C" fn xmlGetEncodingAlias(alias: *const c_char) -> *const c_char {
5587    crate::xml::encoding::get_encoding_alias(alias)
5588}
5589
5590/// Clean up the encoding alias table (upstream encoding.h).
5591///
5592/// # UPSTREAM-PARITY
5593///
5594/// ```c
5595/// void xmlCleanupEncodingAliases(void);
5596/// ```
5597#[no_mangle]
5598pub extern "C" fn xmlCleanupEncodingAliases() {
5599    crate::xml::encoding::cleanup_encoding_aliases();
5600}
5601
5602/// Convert the input buffer using an encoding handler (upstream encoding.h).
5603///
5604/// # UPSTREAM-PARITY
5605///
5606/// ```c
5607/// int xmlCharEncInFunc(xmlCharEncodingHandler *handler,
5608///                      xmlBufferPtr out, xmlBufferPtr in);
5609/// ```
5610#[no_mangle]
5611pub extern "C" fn xmlCharEncInFunc(
5612    handler: *mut c_void,
5613    out: *mut c_void,
5614    in_: *mut c_void,
5615) -> c_int {
5616    crate::xml::encoding::xmlCharEncInFunc(
5617        handler as *mut crate::abi::structs::_xmlCharEncodingHandler,
5618        out as *mut crate::abi::structs::_xmlBuffer,
5619        in_ as *mut crate::abi::structs::_xmlBuffer,
5620    )
5621}
5622
5623/// Convert the output buffer using an encoding handler (upstream encoding.h).
5624///
5625/// # UPSTREAM-PARITY
5626///
5627/// ```c
5628/// int xmlCharEncOutFunc(xmlCharEncodingHandler *handler,
5629///                       xmlBufferPtr out, xmlBufferPtr in);
5630/// ```
5631#[no_mangle]
5632pub extern "C" fn xmlCharEncOutFunc(
5633    handler: *mut c_void,
5634    out: *mut c_void,
5635    in_: *mut c_void,
5636) -> c_int {
5637    crate::xml::encoding::xmlCharEncOutFunc(
5638        handler as *mut crate::abi::structs::_xmlCharEncodingHandler,
5639        out as *mut crate::abi::structs::_xmlBuffer,
5640        in_ as *mut crate::abi::structs::_xmlBuffer,
5641    )
5642}
5643
5644/// Create a new encoding handler (upstream encoding.h).
5645///
5646/// # UPSTREAM-PARITY
5647///
5648/// ```c
5649/// xmlCharEncodingHandlerPtr xmlNewCharEncodingHandler(
5650///     const char *name, xmlCharEncodingInputFunc input,
5651///     xmlCharEncodingOutputFunc output);
5652/// ```
5653#[no_mangle]
5654pub extern "C" fn xmlNewCharEncodingHandler(
5655    name: *const c_char,
5656    input: crate::abi::callbacks::xmlCharEncodingInputFunc,
5657    output: crate::abi::callbacks::xmlCharEncodingOutputFunc,
5658) -> *mut c_void {
5659    crate::xml::encoding::xmlNewCharEncodingHandler(name, input, output) as *mut c_void
5660}
5661
5662/// Initialize the built-in encoding handlers (upstream encoding.h).
5663///
5664/// # UPSTREAM-PARITY
5665///
5666/// ```c
5667/// void xmlInitCharEncodingHandlers(void);
5668/// ```
5669#[no_mangle]
5670pub extern "C" fn xmlInitCharEncodingHandlers() {
5671    crate::xml::encoding::xmlInitCharEncodingHandlers();
5672}
5673
5674/// Clean up the encoding handlers (upstream encoding.h).
5675///
5676/// # UPSTREAM-PARITY
5677///
5678/// ```c
5679/// void xmlCleanupCharEncodingHandlers(void);
5680/// ```
5681#[no_mangle]
5682pub extern "C" fn xmlCleanupCharEncodingHandlers() {
5683    crate::xml::encoding::xmlCleanupCharEncodingHandlers();
5684}
5685
5686/// Look up a built-in encoding handler by `xmlCharEncoding` value.
5687///
5688/// Returns an `xmlParserErrors` code; on success `*out` receives the static
5689/// handler (NULL for UTF-8, which needs no conversion).
5690///
5691/// # UPSTREAM-PARITY
5692///
5693/// ```c
5694/// xmlParserErrors xmlLookupCharEncodingHandler(xmlCharEncoding enc,
5695///                                              xmlCharEncodingHandler **out);
5696/// ```
5697#[no_mangle]
5698pub extern "C" fn xmlLookupCharEncodingHandler(enc: c_int, out: *mut *mut c_void) -> c_int {
5699    crate::xml::encoding::xmlLookupCharEncodingHandler(enc, out)
5700}
5701
5702/// Get the encoding handler for an `xmlCharEncoding` value (deprecated).
5703///
5704/// # UPSTREAM-PARITY
5705///
5706/// ```c
5707/// xmlCharEncodingHandler *xmlGetCharEncodingHandler(xmlCharEncoding enc);
5708/// ```
5709#[no_mangle]
5710pub extern "C" fn xmlGetCharEncodingHandler(enc: c_int) -> *mut c_void {
5711    crate::xml::encoding::xmlGetCharEncodingHandler(enc)
5712}
5713
5714/// Find or create an encoding handler by name for one conversion direction.
5715///
5716/// # UPSTREAM-PARITY
5717///
5718/// ```c
5719/// xmlParserErrors xmlOpenCharEncodingHandler(const char *name, int output,
5720///                                            xmlCharEncodingHandler **out);
5721/// ```
5722#[no_mangle]
5723pub extern "C" fn xmlOpenCharEncodingHandler(
5724    name: *const c_char,
5725    output: c_int,
5726    out: *mut *mut c_void,
5727) -> c_int {
5728    crate::xml::encoding::xmlOpenCharEncodingHandler(name, output, out)
5729}
5730
5731/// Find or create an encoding handler by name with flags and an optional
5732/// custom conversion implementation.
5733///
5734/// # UPSTREAM-PARITY
5735///
5736/// ```c
5737/// xmlParserErrors xmlCreateCharEncodingHandler(
5738///     const char *name, xmlCharEncFlags flags, xmlCharEncConvImpl impl,
5739///     void *implCtxt, xmlCharEncodingHandler **out);
5740/// ```
5741#[no_mangle]
5742pub extern "C" fn xmlCreateCharEncodingHandler(
5743    name: *const c_char,
5744    flags: c_int,
5745    impl_: Option<crate::abi::callbacks::xmlCharEncConvImpl>,
5746    implCtxt: *mut c_void,
5747    out: *mut *mut c_void,
5748) -> c_int {
5749    crate::xml::encoding::xmlCreateCharEncodingHandler(name, flags, impl_, implCtxt, out)
5750}
5751
5752/// Create an encoding handler backed by modern conversion callbacks.
5753///
5754/// # UPSTREAM-PARITY
5755///
5756/// ```c
5757/// xmlParserErrors xmlCharEncNewCustomHandler(
5758///     const char *name, xmlCharEncConvFunc input, xmlCharEncConvFunc output,
5759///     xmlCharEncConvCtxtDtor ctxtDtor, void *inputCtxt, void *outputCtxt,
5760///     xmlCharEncodingHandler **out);
5761/// ```
5762#[no_mangle]
5763pub extern "C" fn xmlCharEncNewCustomHandler(
5764    name: *const c_char,
5765    input: crate::abi::callbacks::xmlCharEncConvFunc,
5766    output: crate::abi::callbacks::xmlCharEncConvFunc,
5767    ctxtDtor: Option<crate::abi::callbacks::xmlCharEncConvCtxtDtor>,
5768    inputCtxt: *mut c_void,
5769    outputCtxt: *mut c_void,
5770    out: *mut *mut c_void,
5771) -> c_int {
5772    crate::xml::encoding::xmlCharEncNewCustomHandler(
5773        name, input, output, ctxtDtor, inputCtxt, outputCtxt, out,
5774    )
5775}
5776
5777/// Convert an input buffer's encoding.
5778///
5779/// # UPSTREAM-PARITY
5780///
5781/// ```c
5782/// int xmlCharEncInput(xmlParserInputBufferPtr input, int to);
5783/// ```
5784#[no_mangle]
5785pub unsafe extern "C" fn xmlCharEncInput(input: *mut _xmlParserInputBuffer, _to: c_int) -> c_int {
5786    if input.is_null() {
5787        return -1;
5788    }
5789    let handler = (*input).encoder as *mut crate::abi::structs::_xmlCharEncodingHandler;
5790    if handler.is_null() {
5791        return -1;
5792    }
5793    let raw = (*input).raw as *mut crate::abi::structs::_xmlBuffer;
5794    let buf = (*input).buffer as *mut crate::abi::structs::_xmlBuffer;
5795    if raw.is_null() || buf.is_null() {
5796        return -1;
5797    }
5798    crate::xml::encoding::char_enc_in(handler, buf, raw)
5799}
5800
5801/// Convert an output buffer's encoding.
5802///
5803/// # UPSTREAM-PARITY
5804///
5805/// ```c
5806/// int xmlCharEncOutput(xmlOutputBufferPtr output, int to);
5807/// ```
5808#[no_mangle]
5809pub unsafe extern "C" fn xmlCharEncOutput(output: *mut _xmlOutputBuffer, _to: c_int) -> c_int {
5810    if output.is_null() {
5811        return -1;
5812    }
5813    let handler = (*output).encoder as *mut crate::abi::structs::_xmlCharEncodingHandler;
5814    if handler.is_null() {
5815        return -1;
5816    }
5817    let buf = (*output).buffer as *mut crate::abi::structs::_xmlBuffer;
5818    let conv = (*output).conv as *mut crate::abi::structs::_xmlBuffer;
5819    if buf.is_null() || conv.is_null() {
5820        return -1;
5821    }
5822    crate::xml::encoding::char_enc_out(handler, conv, buf)
5823}
5824
5825// ═══════════════════════════════════════════════════════════════════════════════
5826// URI
5827// ═══════════════════════════════════════════════════════════════════════════════
5828
5829/// Parse a URI string.
5830///
5831/// # UPSTREAM-PARITY
5832///
5833/// ```c
5834/// xmlURIPtr xmlParseURI(const char *str);
5835/// ```
5836#[no_mangle]
5837pub unsafe extern "C" fn xmlParseURI(str: *const c_char) -> *mut c_void {
5838    crate::xml::uri::xmlParseURI(str)
5839}
5840
5841/// Parse a URI string (raw version).
5842///
5843/// # UPSTREAM-PARITY
5844///
5845/// ```c
5846/// xmlURIPtr xmlParseURIRaw(const char *str, int raw);
5847/// ```
5848#[no_mangle]
5849pub unsafe extern "C" fn xmlParseURIRaw(str: *const c_char, raw: c_int) -> *mut c_void {
5850    let _ = raw;
5851    crate::xml::uri::xmlParseURI(str)
5852}
5853
5854/// Free a URI structure.
5855///
5856/// # UPSTREAM-PARITY
5857///
5858/// ```c
5859/// void xmlFreeURI(xmlURIPtr uri);
5860/// ```
5861#[no_mangle]
5862pub unsafe extern "C" fn xmlFreeURI(uri: *mut c_void) {
5863    crate::xml::uri::xmlFreeURI(uri)
5864}
5865
5866/// Create an empty URI.
5867///
5868/// # UPSTREAM-PARITY
5869///
5870/// ```c
5871/// xmlURIPtr xmlCreateURI(void);
5872/// ```
5873#[no_mangle]
5874pub extern "C" fn xmlCreateURI() -> *mut c_void {
5875    crate::xml::uri::xmlCreateURI()
5876}
5877
5878/// Save a URI structure to a string.
5879///
5880/// # UPSTREAM-PARITY
5881///
5882/// ```c
5883/// xmlChar *xmlSaveUri(xmlURIPtr uri);
5884/// ```
5885#[no_mangle]
5886pub unsafe extern "C" fn xmlSaveUri(uri: *mut c_void) -> *mut xmlChar {
5887    crate::xml::uri::xmlSaveUri(uri)
5888}
5889
5890/// Parse a URI string into an existing URI structure (upstream uri.h).
5891///
5892/// # UPSTREAM-PARITY
5893///
5894/// ```c
5895/// int xmlParseURIReference(xmlURIPtr uri, const char *str);
5896/// ```
5897///
5898/// Returns 0 on success, -1 on failure (the URI structure is left
5899/// untouched on failure).
5900///
5901/// # Safety
5902///
5903/// - `uri` must be a valid pointer from `xmlParseURI`/`xmlCreateURI`.
5904/// - `str` must be a valid null-terminated C string.
5905#[no_mangle]
5906pub unsafe extern "C" fn xmlParseURIReference(uri: *mut c_void, str: *const c_char) -> c_int {
5907    crate::xml::uri::xmlParseURIReference(uri, str)
5908}
5909
5910/// Normalize a URI path in place (upstream uri.h).
5911///
5912/// # UPSTREAM-PARITY
5913///
5914/// ```c
5915/// int xmlNormalizeURIPath(char *path);
5916/// ```
5917///
5918/// Returns 0 on success, -1 if the path is NULL, not absolute, or contains
5919/// `..` segments that climb above the root.
5920///
5921/// # Safety
5922///
5923/// `path` must be a valid writable null-terminated C string buffer.
5924#[no_mangle]
5925pub unsafe extern "C" fn xmlNormalizeURIPath(path: *mut c_char) -> c_int {
5926    crate::xml::uri::xmlNormalizeURIPath(path)
5927}
5928
5929/// Escape a URI string.
5930///
5931/// # UPSTREAM-PARITY
5932///
5933/// ```c
5934/// xmlChar *xmlURIEscapeStr(const xmlChar *str, const xmlChar *list);
5935/// ```
5936#[no_mangle]
5937pub unsafe extern "C" fn xmlURIEscapeStr(
5938    str: *const xmlChar,
5939    list: *const xmlChar,
5940) -> *mut xmlChar {
5941    crate::xml::uri::xmlURIEscapeStr(str, list)
5942}
5943
5944/// Unescape a URI string.
5945///
5946/// # UPSTREAM-PARITY
5947///
5948/// ```c
5949/// char *xmlURIUnescapeString(const char *str, int len, char *target);
5950/// ```
5951#[no_mangle]
5952pub unsafe extern "C" fn xmlURIUnescapeString(
5953    str: *const c_char,
5954    len: c_int,
5955    target: *mut c_char,
5956) -> *mut c_char {
5957    crate::xml::uri::xmlURIUnescapeString(str, len, target)
5958}
5959
5960// ═══════════════════════════════════════════════════════════════════════════════
5961// 14. XPath
5962// ═══════════════════════════════════════════════════════════════════════════════
5963
5964// ── Helper functions ────────────────────────────────────────────────────
5965
5966/// Convert an internal `XPathValue` to a C ABI `_xmlXPathObject`.
5967///
5968/// The returned pointer is heap-allocated via `xmlMallocZero` and must be
5969/// freed with `xmlXPathFreeObject`.
5970///
5971/// # Safety
5972///
5973/// Must be called from a context where `xmlMalloc` is safe to call.
5974unsafe fn xpath_to_object(val: XPathValue) -> *mut _xmlXPathObject {
5975    let obj = xmlMallocZero(size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject;
5976    if obj.is_null() {
5977        return ptr::null_mut();
5978    }
5979    match val {
5980        XPathValue::NodeSet(ns) => {
5981            (*obj).type_ = xmlXPathObjectType::XPATH_NODESET as c_int;
5982            (*obj).nodesetval = ns.to_raw() as *mut c_void;
5983        }
5984        XPathValue::Boolean(b) => {
5985            (*obj).type_ = xmlXPathObjectType::XPATH_BOOLEAN as c_int;
5986            (*obj).boolval = if b { 1 } else { 0 };
5987        }
5988        XPathValue::Number(n) => {
5989            (*obj).type_ = xmlXPathObjectType::XPATH_NUMBER as c_int;
5990            (*obj).floatval = n;
5991        }
5992        XPathValue::String(s) => {
5993            (*obj).type_ = xmlXPathObjectType::XPATH_STRING as c_int;
5994            let bytes = s.as_bytes();
5995            let len = bytes.len();
5996            let buf = xmlMallocImpl(len + 1) as *mut xmlChar;
5997            if !buf.is_null() {
5998                ptr::copy_nonoverlapping(bytes.as_ptr(), buf, len);
5999                *buf.add(len) = 0; // null terminator
6000            }
6001            (*obj).stringval = buf;
6002        }
6003    }
6004    obj
6005}
6006
6007/// Extract an internal `XPathValue` from a C ABI `_xmlXPathObject`.
6008///
6009/// # Safety
6010///
6011/// `obj` must be a valid, non-null pointer to a properly initialised
6012/// `_xmlXPathObject`.
6013unsafe fn object_to_xpathvalue(obj: *mut _xmlXPathObject) -> XPathValue {
6014    let typ = (*obj).type_;
6015    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
6016        let ns_ptr = (*obj).nodesetval as *mut _xmlNodeSet;
6017        if ns_ptr.is_null() {
6018            return XPathValue::NodeSet(NodeSet::new());
6019        }
6020        let node_nr = (*ns_ptr).nodeNr;
6021        let node_tab = (*ns_ptr).nodeTab;
6022        let mut ns = NodeSet::new();
6023        if !node_tab.is_null() {
6024            for i in 0..node_nr as isize {
6025                let node = *node_tab.add(i as usize);
6026                ns.push(node);
6027            }
6028        }
6029        XPathValue::NodeSet(ns)
6030    } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
6031        XPathValue::Boolean((*obj).boolval != 0)
6032    } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
6033        XPathValue::Number((*obj).floatval)
6034    } else if typ == xmlXPathObjectType::XPATH_STRING as c_int {
6035        let s_ptr = (*obj).stringval;
6036        if s_ptr.is_null() {
6037            XPathValue::String(String::new())
6038        } else {
6039            let s = CStr::from_ptr(s_ptr as *const c_char)
6040                .to_string_lossy()
6041                .into_owned();
6042            XPathValue::String(s)
6043        }
6044    } else if typ == xmlXPathObjectType::XPATH_XSLT_TREE as c_int {
6045        // A result tree fragment: node-set containing the fragment's
6046        // document node (matching how global RTF variables are bound), so
6047        // local RTF variables stringify to their text and remain navigable
6048        // via exsl:node-set.
6049        let frag_doc = (*obj).nodesetval as *mut _xmlDoc;
6050        if frag_doc.is_null() {
6051            XPathValue::NodeSet(NodeSet::new())
6052        } else {
6053            let mut ns = NodeSet::new();
6054            ns.push(frag_doc as *mut _xmlNode);
6055            XPathValue::NodeSet(ns)
6056        }
6057    } else {
6058        // Undefined / unknown type — return boolean false as a safe default.
6059        XPathValue::Boolean(false)
6060    }
6061}
6062
6063/// Public wrapper for `xpath_to_object` (used by the XPath export bridge).
6064///
6065/// # Safety
6066///
6067/// - `val` is consumed and converted into a heap-allocated `_xmlXPathObject`.
6068pub unsafe fn xpath_to_object_pub(val: XPathValue) -> *mut _xmlXPathObject {
6069    xpath_to_object(val)
6070}
6071
6072/// Public wrapper for `object_to_xpathvalue` (used by the XSLT engine).
6073///
6074/// # Safety
6075///
6076/// `obj` must be a valid, non-null pointer to a properly initialised
6077/// `_xmlXPathObject`.
6078pub unsafe fn object_to_xpathvalue_pub(obj: *mut _xmlXPathObject) -> XPathValue {
6079    object_to_xpathvalue(obj)
6080}
6081
6082// ── Compiled expression registry ────────────────────────────────────────
6083//
6084// Compiled XPath expressions are opaque pointers returned by xmlXPathCompile.
6085// We store them in a global registry keyed by a monotonically increasing ID.
6086
6087static COMPILED_EXPRS: Lazy<Mutex<HashMap<u64, Box<CompiledExpr>>>> =
6088    Lazy::new(|| Mutex::new(HashMap::new()));
6089static NEXT_COMPILED_KEY: Lazy<Mutex<u64>> = Lazy::new(|| Mutex::new(1));
6090
6091/// Accessor for the compiled-expression registry (used by the XPath export
6092/// bridge for `xmlXPathCompiledEval` / `xmlXPathCompiledEvalToBoolean`).
6093pub(crate) fn xpath_compiled_registry() -> &'static Mutex<HashMap<u64, Box<CompiledExpr>>> {
6094    &COMPILED_EXPRS
6095}
6096
6097// ── C extension-function registry ──────────────────────────────────────
6098//
6099// C extension functions registered via xmlXPathRegisterFunc / RegisterFuncNS
6100// are stored here because the Rust XPathFunction signature is incompatible
6101// with the C xmlXPathFunction calling convention (the C function expects a
6102// parser context, not pre-evaluated argument slices). The registration is
6103// stored faithfully; invoking registered C functions from within the Rust
6104// evaluator requires a bridge that is not yet implemented.
6105
6106type CXPathFunc = unsafe extern "C" fn(*mut c_void, c_int);
6107
6108/// Wrapper around `*mut c_void` that implements `Send` + `Sync` so it can
6109/// be used as a key in a `Mutex`-protected global `HashMap`.
6110#[derive(Clone, Copy, PartialEq, Eq, Hash)]
6111struct SendSyncPtr(*mut c_void);
6112unsafe impl Send for SendSyncPtr {}
6113unsafe impl Sync for SendSyncPtr {}
6114
6115static C_FUNCTIONS: Lazy<Mutex<HashMap<(SendSyncPtr, String), CXPathFunc>>> =
6116    Lazy::new(|| Mutex::new(HashMap::new()));
6117
6118/// Look up a C-registered extension function for the context identified by
6119/// `extra` (the internal XPathContext pointer). Used by
6120/// `xmlXPathFunctionLookupNS`.
6121pub(crate) fn xpath_cfunc_lookup(extra: *mut c_void, qualified: &str) -> Option<CXPathFunc> {
6122    C_FUNCTIONS
6123        .lock()
6124        .get(&(SendSyncPtr(extra), qualified.to_string()))
6125        .copied()
6126}
6127
6128/// Drop every C extension-function registration belonging to the context
6129/// identified by `extra` (upstream `xmlXPathRegisteredFuncsCleanup`).
6130pub(crate) fn xpath_cfunc_cleanup(extra: *mut c_void) {
6131    C_FUNCTIONS.lock().retain(|(k, _), _| k.0 != extra);
6132}
6133
6134/// Build the Rust-side closure that bridges a C-registered XPath function
6135/// into the Rust evaluator (see `c_func_call_bridge`). Returns a
6136/// `BoxedXPathFunction` so the closure is coerced with the higher-ranked
6137/// signature the evaluator requires.
6138fn c_func_bridge_closure(c_ctxt: SendSyncPtr, qualified: String) -> BoxedXPathFunction {
6139    let (local_name, ns_uri) = split_qualified(&qualified);
6140    Box::new(move |_ctx: &mut XPathContext, args: &[XPathValue]| {
6141        let cc = c_ctxt;
6142        unsafe {
6143            c_func_call_bridge(
6144                cc.0 as *mut _xmlXPathContext,
6145                &qualified,
6146                &local_name,
6147                ns_uri.as_deref(),
6148                args,
6149            )
6150        }
6151    })
6152}
6153
6154/// Split a registered function key (`{uri}name` — the Clark notation used by
6155/// `xmlXPathRegisterFuncNS` — or a bare `name`) into the LOCAL function name
6156/// and the optional namespace URI. Upstream sets exactly these two on
6157/// `ctxt->context->function` / `functionURI` before invoking a registered C
6158/// function (xpath.c xmlXPathCompOpEval), and PHP's dom/xsl trampolines read
6159/// them back to dispatch to the registered PHP closure.
6160fn split_qualified(qualified: &str) -> (String, Option<String>) {
6161    if let Some(rest) = qualified.strip_prefix('{') {
6162        if let Some(end) = rest.find('}') {
6163            let uri = rest[..end].to_string();
6164            let local = rest[end + 1..].to_string();
6165            return (local, Some(uri));
6166        }
6167    }
6168    (qualified.to_string(), None)
6169}
6170
6171/// Call a C-ABI `xmlXPathFunction` through a synthesized
6172/// `xmlXPathParserContext`: push the evaluated arguments as XPath objects,
6173/// invoke the function, pop and convert the result — the upstream
6174/// `xmlXPathCompOpEval` function-call sequence (xpath.c).
6175///
6176/// # UPSTREAM-PARITY
6177///
6178/// xpath.c xmlXPathCompOpEval (XPATH_OP_FUNCTION) sets the in-context
6179/// function identity before the call and restores it after:
6180///
6181/// ```c
6182/// oldFunc = ctxt->context->function;
6183/// oldFuncURI = ctxt->context->functionURI;
6184/// ctxt->context->function = op->value4;       /* local name */
6185/// ctxt->context->functionURI = op->cacheURI;  /* resolved ns URI or NULL */
6186/// func(ctxt, op->value);
6187/// ctxt->context->function = oldFunc;
6188/// ctxt->context->functionURI = oldFuncURI;
6189/// ```
6190///
6191/// PHP registers ONE trampoline for every custom-namespace XPath function
6192/// and dispatches to the PHP closure by reading `ctxt->context->function` /
6193/// `functionURI`, so without these fields it dereferences garbage
6194/// (SP-14.3.6-dom O1: return_dom_node_from_xpath / registerPhpFunctionNS
6195/// segv).
6196///
6197/// # SAFETY
6198///
6199/// - `fnptr` must be a valid C callback (or None).
6200/// - `c_ctxt` must be the live C XPath context the callback belongs to.
6201/// - `name`/`ns_uri` must be the function's local name / namespace being
6202///   invoked, valid for the duration of the call.
6203pub(crate) unsafe fn call_c_xpath_function(
6204    fnptr: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
6205    c_ctxt: *mut _xmlXPathContext,
6206    name: &str,
6207    ns_uri: Option<&str>,
6208    args: &[XPathValue],
6209) -> Result<XPathValue, String> {
6210    let func = match fnptr {
6211        Some(f) => f,
6212        None => return Err("XPath: missing C function pointer".to_string()),
6213    };
6214    let pc = crate::xml::xpath::parser_context::new_parser_context(ptr::null(), c_ctxt);
6215    if pc.is_null() {
6216        return Err("XPath: parser-context allocation failure".to_string());
6217    }
6218    let mut push_ok = true;
6219    for v in args {
6220        let obj = xpath_to_object(v.clone());
6221        if obj.is_null() || crate::xml::xpath::parser_context::value_push(pc, obj).is_null() {
6222            push_ok = false;
6223            break;
6224        }
6225    }
6226    let result = if push_ok {
6227        // NUL-terminated buffers naming the invoked function, live for the
6228        // callback duration (upstream op->value4 / op->cacheURI).
6229        let mut name_nul: Vec<xmlChar> = name.as_bytes().to_vec();
6230        name_nul.push(0);
6231        let uri_nul: Option<Vec<xmlChar>> = ns_uri.map(|u| {
6232            let mut v = u.as_bytes().to_vec();
6233            v.push(0);
6234            v
6235        });
6236        let saved_function = (*c_ctxt).function;
6237        let saved_function_uri = (*c_ctxt).functionURI;
6238        (*c_ctxt).function = name_nul.as_ptr() as *const xmlChar;
6239        (*c_ctxt).functionURI = uri_nul
6240            .as_ref()
6241            .map_or(ptr::null(), |v| v.as_ptr() as *const xmlChar);
6242        // SAFETY: `func` is a valid C callback; the arguments are on the
6243        // parser-context value stack exactly as upstream would leave them
6244        // and the context names the invoked function.
6245        unsafe { func(pc as *mut c_void, args.len() as c_int) };
6246        (*c_ctxt).function = saved_function;
6247        (*c_ctxt).functionURI = saved_function_uri;
6248        let ret = crate::xml::xpath::parser_context::value_pop(pc);
6249        if ret.is_null() {
6250            Err("XPath: C function returned no value".to_string())
6251        } else {
6252            let v = object_to_xpathvalue(ret);
6253            // The popped object is heap-allocated; free it after converting.
6254            unsafe { xmlXPathFreeObject(ret) };
6255            Ok(v)
6256        }
6257    } else {
6258        Err("XPath: failed to push arguments to C function".to_string())
6259    };
6260    // Free any objects the C function left on the stack, then the context.
6261    unsafe {
6262        loop {
6263            let leftover = crate::xml::xpath::parser_context::value_pop(pc);
6264            if leftover.is_null() {
6265                break;
6266            }
6267            xmlXPathFreeObject(leftover);
6268        }
6269        crate::xml::xpath::parser_context::free_parser_context(pc);
6270    }
6271    result
6272}
6273
6274/// Invoke an XSLT extension / module function through the upstream
6275/// parser-context protocol, with an upstream-layout context.
6276///
6277/// Upstream libxslt stores the transform context in `xmlXPathContext.extra`
6278/// (XSLT_REGISTER_VARIABLE_LOOKUP, variables.h), and PHP's xsl callbacks
6279/// read `parser_ctxt->context->extra` DIRECTLY as the
6280/// `xsltTransformContextPtr` (xsltprocessor.c xsl_proxy_factory). The
6281/// candidate reserves `extra` for the internal Rust `XPathContext`, so this
6282/// bridge synthesises a shallow MIRROR of the C context (same doc/node/…,
6283/// `extra` = transform context) that lives only for the callback duration.
6284/// The real transform XPath context is left untouched; the function name
6285/// is set on the mirror (php's call_custom_ns reads `context->function` /
6286/// `functionURI`), and arguments are pushed in evaluation order (last arg
6287/// on top) exactly as upstream `xmlXPathCompOpEval` leaves them.
6288///
6289/// Returns `Err` when the callback produced no value.
6290///
6291/// # Safety
6292///
6293/// - `fnptr` must be a C `xmlXPathFunction`-compatible callback.
6294/// - `tctxt` / `xpath_ctxt` must be the live transform context pair.
6295/// - `xpath_ctxt` must be the transform context's own `xpathCtxt`.
6296pub(crate) unsafe fn call_xslt_ext_function(
6297    fnptr: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
6298    tctxt: *mut crate::abi::structs::_xsltTransformContext,
6299    xpath_ctxt: *mut _xmlXPathContext,
6300    name: &str,
6301    ns_uri: Option<&str>,
6302    args: &[XPathValue],
6303) -> Result<XPathValue, String> {
6304    let func = match fnptr {
6305        Some(f) => f,
6306        None => return Err("XPath: missing C function pointer".to_string()),
6307    };
6308    if tctxt.is_null() || xpath_ctxt.is_null() {
6309        return Err("XPath: null XSLT context in extension-function bridge".to_string());
6310    }
6311    // Mirror: shallow copy of the C-visible context with `extra` = tctxt
6312    // (upstream layout that php's proxy code dereferences).
6313    let mirror = libc::calloc(1, core::mem::size_of::<_xmlXPathContext>()) as *mut _xmlXPathContext;
6314    if mirror.is_null() {
6315        return Err("XPath: mirror-context allocation failure".to_string());
6316    }
6317    unsafe {
6318        libc::memcpy(
6319            mirror as *mut libc::c_void,
6320            xpath_ctxt as *const libc::c_void,
6321            core::mem::size_of::<_xmlXPathContext>(),
6322        );
6323        (*mirror).extra = tctxt as *mut c_void;
6324        let pc = crate::xml::xpath::parser_context::new_parser_context(ptr::null(), mirror);
6325        if pc.is_null() {
6326            libc::free(mirror as *mut libc::c_void);
6327            return Err("XPath: parser-context allocation failure".to_string());
6328        }
6329        let mut push_ok = true;
6330        for v in args {
6331            let obj = xpath_to_object(v.clone());
6332            if obj.is_null() || crate::xml::xpath::parser_context::value_push(pc, obj).is_null() {
6333                push_ok = false;
6334                break;
6335            }
6336        }
6337        let result = if push_ok {
6338            // NUL-terminated buffers naming the invoked function, live for
6339            // the callback duration (upstream op->value4 / op->cacheURI on
6340            // the eval context).
6341            let mut name_nul: Vec<xmlChar> = name.as_bytes().to_vec();
6342            name_nul.push(0);
6343            let uri_nul: Option<Vec<xmlChar>> = ns_uri.map(|u| {
6344                let mut v = u.as_bytes().to_vec();
6345                v.push(0);
6346                v
6347            });
6348            (*mirror).function = name_nul.as_ptr() as *const xmlChar;
6349            (*mirror).functionURI = uri_nul
6350                .as_ref()
6351                .map_or(ptr::null(), |v| v.as_ptr() as *const xmlChar);
6352            // SAFETY: `func` is a valid C callback; the arguments are on the
6353            // parser-context value stack exactly as upstream would leave them
6354            // and the context names the invoked function.
6355            func(pc as *mut c_void, args.len() as c_int);
6356            let ret = crate::xml::xpath::parser_context::value_pop(pc);
6357            if ret.is_null() {
6358                Err("XPath: C function returned no value".to_string())
6359            } else {
6360                let v = object_to_xpathvalue(ret);
6361                // The popped object is heap-allocated; free it after converting.
6362                xmlXPathFreeObject(ret);
6363                Ok(v)
6364            }
6365        } else {
6366            Err("XPath: failed to push arguments to C function".to_string())
6367        };
6368        // Free any objects the C function left on the stack, then the
6369        // parser context and the mirror.
6370        loop {
6371            let leftover = crate::xml::xpath::parser_context::value_pop(pc);
6372            if leftover.is_null() {
6373                break;
6374            }
6375            xmlXPathFreeObject(leftover);
6376        }
6377        crate::xml::xpath::parser_context::free_parser_context(pc);
6378        libc::free(mirror as *mut libc::c_void);
6379        result
6380    }
6381}
6382
6383/// Rust-side wrapper registered in the internal XPathContext when a C
6384/// extension function is registered (`xmlXPathRegisterFunc[NS]`). This is the
6385/// parser-context bridge: it synthesises the upstream `xmlXPathParserContext`
6386/// (value stack + context pointer), pushes the evaluated arguments as XPath
6387/// objects, invokes the C function, then pops and converts the result — the
6388/// upstream `xmlXPathCompOpEval` function-call sequence (xpath.c).
6389unsafe fn c_func_call_bridge(
6390    c_ctxt: *mut _xmlXPathContext,
6391    qualified: &str,
6392    name: &str,
6393    ns_uri: Option<&str>,
6394    args: &[XPathValue],
6395) -> Result<XPathValue, String> {
6396    if c_ctxt.is_null() {
6397        return Err("XPath: null context in C function bridge".to_string());
6398    }
6399    let func = xpath_cfunc_lookup((*c_ctxt).extra, qualified);
6400    if func.is_none() {
6401        return Err(format!("XPath: unknown C function '{}'", qualified));
6402    }
6403    unsafe { call_c_xpath_function(func, c_ctxt, name, ns_uri, args) }
6404}
6405
6406// ── Public API ─────────────────────────────────────────────────────────
6407
6408/// Create a new XPath context.
6409///
6410/// Allocates a `_xmlXPathContext` and an internal `XPathContext`, storing
6411/// the latter's pointer in the `extra` field.
6412///
6413/// # UPSTREAM-PARITY
6414///
6415/// ```c
6416/// xmlXPathContextPtr xmlXPathNewContext(xmlDocPtr doc);
6417/// ```
6418#[no_mangle]
6419pub unsafe extern "C" fn xmlXPathNewContext(doc: *mut _xmlDoc) -> *mut _xmlXPathContext {
6420    let ctxt = xmlMallocZero(size_of::<_xmlXPathContext>()) as *mut _xmlXPathContext;
6421    if ctxt.is_null() {
6422        return ptr::null_mut();
6423    }
6424
6425    // Initialise the C ABI context fields.
6426    (*ctxt).doc = doc;
6427    (*ctxt).node = ptr::null_mut();
6428    (*ctxt).contextSize = 1;
6429    (*ctxt).proximityPosition = 1;
6430
6431    // Create the internal XPathContext and store it in `extra`.
6432    let mut internal = Box::new(XPathContext::new(doc));
6433    // UPSTREAM-PARITY: the standard function library is implicitly available
6434    // in every context (upstream compiles it in; xmlXPathRegisterAllFunctions
6435    // is a no-op since 2.14.0). Without this, core-function calls such as
6436    // count() would fail as unknown functions.
6437    for (name, func) in crate::xml::xpath::functions::core_functions() {
6438        internal.register_function(&name, func);
6439    }
6440    internal.c_context = ctxt;
6441    (*ctxt).extra = Box::into_raw(internal) as *mut c_void;
6442
6443    ctxt
6444}
6445
6446/// Deallocator for `xmlXPathContext.nsHash` payloads (strdup'd namespace
6447/// URIs; upstream `xmlXPathFreeContext` / `xmlXPathRegisteredNsCleanup` pass
6448/// `xmlFree`).
6449pub(crate) unsafe extern "C" fn free_ns_uri_payload(payload: *mut c_void, _key: *mut xmlChar) {
6450    if !payload.is_null() {
6451        crate::abi::allocator::xmlFreeImpl(payload);
6452    }
6453}
6454
6455/// Free an XPath context.
6456///
6457/// # UPSTREAM-PARITY
6458///
6459/// ```c
6460/// void xmlXPathFreeContext(xmlXPathContextPtr ctxt);
6461/// ```
6462#[no_mangle]
6463pub unsafe extern "C" fn xmlXPathFreeContext(ctxt: *mut _xmlXPathContext) {
6464    if ctxt.is_null() {
6465        return;
6466    }
6467    // Drop the internal XPathContext.
6468    if !(*ctxt).extra.is_null() {
6469        let _ = Box::from_raw((*ctxt).extra as *mut XPathContext);
6470        (*ctxt).extra = ptr::null_mut();
6471    }
6472    // Free the registered-namespace hash (upstream xmlXPathFreeContext:
6473    // xmlHashFree(ctxt->nsHash, xmlFree) — the payloads are strdup'd URIs).
6474    if !(*ctxt).nsHash.is_null() {
6475        xmlHashFree((*ctxt).nsHash, Some(free_ns_uri_payload));
6476        (*ctxt).nsHash = ptr::null_mut();
6477    }
6478    // Free the C ABI context struct.
6479    xmlFreeImpl(ctxt as *mut c_void);
6480}
6481
6482/// Evaluate an XPath expression.
6483///
6484/// # UPSTREAM-PARITY
6485///
6486/// ```c
6487/// xmlXPathObjectPtr xmlXPathEvalExpression(const xmlChar *str,
6488///                                          xmlXPathContextPtr ctxt);
6489/// ```
6490#[no_mangle]
6491pub unsafe extern "C" fn xmlXPathEvalExpression(
6492    str_: *const xmlChar,
6493    ctxt: *mut _xmlXPathContext,
6494) -> *mut _xmlXPathObject {
6495    if str_.is_null() || ctxt.is_null() {
6496        return ptr::null_mut();
6497    }
6498    let expr_str = match CStr::from_ptr(str_ as *const c_char).to_str() {
6499        Ok(s) => s,
6500        Err(_) => return ptr::null_mut(),
6501    };
6502    let internal = (*ctxt).extra as *mut XPathContext;
6503    if internal.is_null() {
6504        return ptr::null_mut();
6505    }
6506    let internal = &mut *internal;
6507    // UPSTREAM-PARITY (xpath.c xmlXPathEvalExpression): the evaluation
6508    // context node and position come from the C context fields — consumers
6509    // (lxml XPathElementEvaluator) set xpathCtxt->node per evaluation — so
6510    // mirror them into the internal context before evaluating. The pre-fix
6511    // code never did, so relative paths ("a", "./a", "a/@i") evaluated
6512    // against a NULL context node and returned an empty node-set (Phase 14
6513    // lxml XPath court).
6514    internal.set_context_node((*ctxt).node);
6515    internal.context_position = (*ctxt).proximityPosition;
6516    internal.context_size = (*ctxt).contextSize;
6517    internal.proximity_position = (*ctxt).proximityPosition;
6518    // Mirror the C context's namespace array (upstream xmlXPathNsLookup
6519    // consults ctxt->namespaces/nsNr first). PHP's DOMXPath fills the array
6520    // with the CONTEXT NODE's in-scope namespaces before evaluating
6521    // (ext/dom xpath.c php_dom_get_in_scope_ns*), so prefixed tests resolve
6522    // without an explicit registerNamespace when the document declares them.
6523    crate::abi::exports_xml2::sync_xpath_context_namespaces(ctxt, internal);
6524    // Clear any stale error so a fresh evaluation either succeeds or records
6525    // its own failure message (the XSLT layer surfaces it verbatim).
6526    internal.clear_error();
6527
6528    match crate::xml::xpath::evaluate_str(expr_str, internal) {
6529        Some(val) => xpath_to_object(val),
6530        None => {
6531            // UPSTREAM-PARITY (xpath.c xmlXPathErrFmt): report the failure
6532            // through the C context (ctxt->lastError pre-fill + ctxt->error
6533            // handler with ctxt->userData) so consumers like lxml's
6534            // _receiveXPathError receive the specific message.
6535            raise_internal_xpath_error(ctxt, internal, expr_str);
6536            ptr::null_mut()
6537        }
6538    }
6539}
6540
6541/// Map an internal XPath error message to its upstream `xmlXPathError` code
6542/// (0-based, xpath.h) and raise it through the C context.
6543pub(crate) unsafe fn raise_internal_xpath_error(
6544    ctxt: *mut _xmlXPathContext,
6545    internal: &mut XPathContext,
6546    expr: &str,
6547) {
6548    let (xpath_code, message) = match internal.error.as_deref() {
6549        Some(m) if m.starts_with("Undefined namespace prefix") => (XPATH_UNDEF_PREFIX_ERROR, m),
6550        Some(m) if m.starts_with("Unregistered function") => (XPATH_UNKNOWN_FUNC_ERROR, m),
6551        Some(m) if m.starts_with("Undefined variable") => (XPATH_UNDEF_VARIABLE_ERROR, m),
6552        Some(m) => (XPATH_EXPR_ERROR, m),
6553        None => {
6554            internal.set_error("Invalid expression");
6555            (XPATH_EXPR_ERROR, "Invalid expression")
6556        }
6557    };
6558    unsafe { raise_xpath_error(ctxt, xpath_code, message, expr) }
6559}
6560
6561/// Mirror the C-visible context's `namespaces[0..nsNr]` array into the
6562/// internal XPath context's prefix map (upstream xmlXPathNsLookup consults
6563/// the array before nsHash). PHP's DOMXPath fills the array with the context
6564/// node's in-scope namespaces (ext/dom xpath.c), which is how prefixed
6565/// location steps resolve against the document's declarations.
6566///
6567/// # Safety
6568///
6569/// - `ctxt` must be a valid `_xmlXPathContext`; `internal` its internal
6570///   Rust context (may be shared).
6571pub(crate) unsafe fn sync_xpath_context_namespaces(
6572    ctxt: *mut _xmlXPathContext,
6573    internal: &mut crate::xml::xpath::context::XPathContext,
6574) {
6575    if ctxt.is_null() {
6576        return;
6577    }
6578    unsafe {
6579        let tab = (*ctxt).namespaces;
6580        if tab.is_null() {
6581            return;
6582        }
6583        let count = (*ctxt).nsNr;
6584        if count <= 0 {
6585            return;
6586        }
6587        let mut i = 0;
6588        while i < count {
6589            let ns = *tab.add(i as usize);
6590            if !ns.is_null() && !(*ns).prefix.is_null() && !(*ns).href.is_null() {
6591                let prefix_len = libc::strlen((*ns).prefix as *const libc::c_char) as usize;
6592                let href_len = libc::strlen((*ns).href as *const libc::c_char) as usize;
6593                let prefix =
6594                    String::from_utf8_lossy(core::slice::from_raw_parts((*ns).prefix, prefix_len))
6595                        .into_owned();
6596                let href =
6597                    String::from_utf8_lossy(core::slice::from_raw_parts((*ns).href, href_len))
6598                        .into_owned();
6599                internal.register_namespace(&prefix, &href);
6600            }
6601            i += 1;
6602        }
6603    }
6604}
6605
6606/// UPSTREAM-PARITY (xpath.c `xmlXPathErrFmt` -> error.c `xmlVRaiseError`):
6607/// deliver an XPath compile/eval failure to the C context. Pre-fills
6608/// `ctxt->lastError` (domain/code/level, the expression as `str1`, `int1` =
6609/// 0) exactly like upstream's message-less pre-fill, then raises through the
6610/// shared streamed path: TLS-global storage + dispatch to `ctxt->error`
6611/// (with `ctxt->userData`), the global structured handler, or the generic
6612/// channel (`xmlFormatError` "XPath error : ..." fragments).
6613///
6614/// `code` is the 0-based `xmlXPathError` value (candidate `XPATH_*_ERROR`
6615/// constants); the delivered structured code is offset by
6616/// `XML_XPATH_EXPRESSION_OK` (1200) like upstream.
6617///
6618/// # SAFETY
6619///
6620/// - `ctxt` must be a valid `_xmlXPathContext`.
6621pub(crate) unsafe fn raise_xpath_error(
6622    ctxt: *mut _xmlXPathContext,
6623    code: c_int,
6624    message: &str,
6625    expr: &str,
6626) {
6627    unsafe {
6628        use crate::xml::errors::{raise_error_streamed, GenericDelivery};
6629        use crate::xml::globals;
6630
6631        // Upstream xmlXPathErr / xmlXPathErrFmt always format with a
6632        // trailing newline ("%s\n"); lxml's _LogEntry.message strips one.
6633        let msg_c = CString::new(format!("{}\n", message)).unwrap_or_default();
6634        let expr_c = CString::new(expr).unwrap_or_default();
6635        let xerr_code = code + XML_XPATH_EXPRESSION_OK;
6636
6637        // Upstream pre-fill of ctxt->lastError (xmlXPathErrFmt): domain,
6638        // code, level, str1 = strdup(base), int1 = cur - base. The message
6639        // stays NULL here; xmlVRaiseError writes it into the TLS global.
6640        globals::free_error_strings(&(*ctxt).lastError);
6641        let pre = _xmlError {
6642            domain: XML_FROM_XPATH,
6643            code: xerr_code,
6644            message: ptr::null_mut(),
6645            level: xmlErrorLevel::XML_ERR_ERROR as c_int,
6646            file: ptr::null_mut(),
6647            line: 0,
6648            str1: xmlMemStrdupImpl(expr_c.as_ptr()) as *mut c_char,
6649            str2: ptr::null_mut(),
6650            str3: ptr::null_mut(),
6651            int1: 0,
6652            int2: 0,
6653            ctxt: ctxt as *mut c_void,
6654            node: (*ctxt).debugNode as *mut c_void,
6655        };
6656        ptr::write(&mut (*ctxt).lastError, pre);
6657
6658        // Cross-DSO channel routing: the whole-archive facade layout embeds a
6659        // per-DSO copy of libxml2's TLS error slots, so PHP's
6660        // xmlSetGenericErrorFunc (registered in the core) is invisible to the
6661        // XSLT engine running inside the libxslt facade. Upstream consumers
6662        // register on the xsltGenericError channel for transform-time
6663        // messages (php's ext/xsl MINIT), and that static IS shared with the
6664        // engine — when a real (non-default) handler is installed there,
6665        // deliver the XPath diagnostic through it exactly like the XSLT error
6666        // channel does (xsltproc leaves the default installed and is
6667        // unaffected).
6668        let xslt_bound = {
6669            let extra = (*ctxt).extra;
6670            if extra.is_null() || !crate::xml::xpath::context::has_signature(extra) {
6671                false
6672            } else {
6673                let internal: *mut crate::xml::xpath::context::XPathContext =
6674                    extra as *mut crate::xml::xpath::context::XPathContext;
6675                !(*internal).func_lookup_data.is_null()
6676            }
6677        };
6678        let xslt_global = crate::abi::data_globals::xsltGenericError;
6679        let xslt_default = crate::abi::data_globals::xslt_default_generic_error_func()
6680            .map_or(ptr::null(), |d| d as *const ());
6681        if xslt_bound {
6682            if let Some(g) = xslt_global {
6683                if g as *const () != xslt_default {
6684                    // SAFETY: the channel is a variadic C callback
6685                    // (upstream xmlGenericErrorFunc ABI); the xslt handler
6686                    // special-cases the "%s" format (php xsl_libxslt_error
6687                    // _handler).
6688                    let hv: unsafe extern "C" fn(*mut c_void, *const c_char, ...) =
6689                        core::mem::transmute(g);
6690                    hv(
6691                        crate::abi::data_globals::xsltGenericErrorContext,
6692                        c"%s".as_ptr() as *const c_char,
6693                        msg_c.as_ptr() as *const c_char,
6694                    );
6695                    return;
6696                }
6697            }
6698        }
6699
6700        // UPSTREAM-PARITY (xpath.c xmlXPathErrFmt channel selection): with no
6701        // structured handler the message goes VERBATIM to the generic channel
6702        // — `channel = xmlGenericError; data = xmlGenericErrorContext`, and
6703        // error.c xmlVRaiseError calls `channel(data, "%s", to->message)`
6704        // because xmlGenericError is NOT one of the parser channels that
6705        // trigger xmlFormatError's fragment stream (which prefixes
6706        // "XPath error : "). PHP's generic handler must receive the message
6707        // text alone (ext/simplexml 008: "Invalid expression", not
6708        // "XPath error : Invalid expression").
6709        let delivery = match globals::get_generic_error_func() {
6710            Some(f) => GenericDelivery::Custom(f, globals::get_generic_error_ctx()),
6711            None => GenericDelivery::Stream,
6712        };
6713
6714        raise_error_streamed(
6715            ctxt as *mut c_void,
6716            XML_FROM_XPATH,
6717            xerr_code,
6718            xmlErrorLevel::XML_ERR_ERROR as c_int,
6719            ptr::null_mut(),
6720            0,
6721            0,
6722            expr_c.as_ptr(),
6723            ptr::null_mut(),
6724            ptr::null_mut(),
6725            0,
6726            msg_c.as_ptr(),
6727            None,
6728            None,
6729            delivery,
6730            None,
6731        );
6732    }
6733}
6734
6735/// Evaluate an XPath expression (simplified alias).
6736///
6737/// # UPSTREAM-PARITY
6738///
6739/// ```c
6740/// xmlXPathObjectPtr xmlXPathEval(const xmlChar *str, xmlXPathContextPtr ctxt);
6741/// ```
6742#[no_mangle]
6743pub unsafe extern "C" fn xmlXPathEval(
6744    str_: *const xmlChar,
6745    ctxt: *mut _xmlXPathContext,
6746) -> *mut _xmlXPathObject {
6747    xmlXPathEvalExpression(str_, ctxt)
6748}
6749
6750/// Free an XPath object.
6751///
6752/// Releases the internal members (string buffer or node-set) and then frees
6753/// the object struct itself.
6754///
6755/// # UPSTREAM-PARITY
6756///
6757/// ```c
6758/// void xmlXPathFreeObject(xmlXPathObjectPtr obj);
6759/// ```
6760#[no_mangle]
6761pub unsafe extern "C" fn xmlXPathFreeObject(obj: *mut _xmlXPathObject) {
6762    if obj.is_null() {
6763        return;
6764    }
6765    let typ = (*obj).type_;
6766    // Free string storage.
6767    if typ == xmlXPathObjectType::XPATH_STRING as c_int && !(*obj).stringval.is_null() {
6768        xmlFreeImpl((*obj).stringval as *mut c_void);
6769        (*obj).stringval = ptr::null_mut();
6770    }
6771    // Free node-set storage.
6772    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
6773        let ns = (*obj).nodesetval as *mut _xmlNodeSet;
6774        if !ns.is_null() {
6775            if !(*ns).nodeTab.is_null() {
6776                xmlFreeImpl((*ns).nodeTab as *mut c_void);
6777            }
6778            xmlFreeImpl(ns as *mut c_void);
6779        }
6780        (*obj).nodesetval = ptr::null_mut();
6781    }
6782    xmlFreeImpl(obj as *mut c_void);
6783}
6784
6785/// Copy an XPath object (deep copy).
6786///
6787/// # UPSTREAM-PARITY
6788///
6789/// ```c
6790/// xmlXPathObjectPtr xmlXPathObjectCopy(xmlXPathObjectPtr val);
6791/// ```
6792///
6793/// Oracle behavior: returns a newly allocated object with the same type
6794/// and value. Node-sets are copied element-by-element; strings are
6795/// duplicated; numbers and booleans are copied by value.
6796#[no_mangle]
6797pub unsafe extern "C" fn xmlXPathObjectCopy(val: *mut _xmlXPathObject) -> *mut _xmlXPathObject {
6798    if val.is_null() {
6799        return ptr::null_mut();
6800    }
6801    let typ = (*val).type_;
6802    let obj = xmlMallocZero(size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject;
6803    if obj.is_null() {
6804        return ptr::null_mut();
6805    }
6806    (*obj).type_ = typ;
6807    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
6808        let src_ns = (*val).nodesetval as *mut _xmlNodeSet;
6809        if !src_ns.is_null() {
6810            let nr = (*src_ns).nodeNr;
6811            let ns = xmlMallocZero(size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
6812            if ns.is_null() {
6813                xmlFreeImpl(obj as *mut c_void);
6814                return ptr::null_mut();
6815            }
6816            (*ns).nodeNr = nr;
6817            (*ns).nodeMax = nr;
6818            if nr > 0 && !(*src_ns).nodeTab.is_null() {
6819                let tab = xmlMallocImpl((nr as usize) * core::mem::size_of::<*mut _xmlNode>())
6820                    as *mut *mut _xmlNode;
6821                if tab.is_null() {
6822                    xmlFreeImpl(ns as *mut c_void);
6823                    xmlFreeImpl(obj as *mut c_void);
6824                    return ptr::null_mut();
6825                }
6826                ptr::copy_nonoverlapping((*src_ns).nodeTab, tab, nr as usize);
6827                (*ns).nodeTab = tab;
6828            } else {
6829                (*ns).nodeTab = ptr::null_mut();
6830            }
6831            (*obj).nodesetval = ns as *mut c_void;
6832        }
6833    } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
6834        (*obj).boolval = (*val).boolval;
6835    } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
6836        (*obj).floatval = (*val).floatval;
6837    } else if typ == xmlXPathObjectType::XPATH_STRING as c_int {
6838        let src = (*val).stringval;
6839        if !src.is_null() {
6840            let len = libc::strlen(src as *const libc::c_char);
6841            let buf = xmlMallocImpl(len + 1) as *mut xmlChar;
6842            if !buf.is_null() {
6843                ptr::copy_nonoverlapping(src, buf, len);
6844                *buf.add(len) = 0;
6845            }
6846            (*obj).stringval = buf;
6847        }
6848    }
6849    obj
6850}
6851
6852/// Cast an XPath object to its string value.
6853///
6854/// Returns a newly allocated string (caller frees with `xmlFree`).
6855///
6856/// # UPSTREAM-PARITY
6857///
6858/// ```c
6859/// xmlChar *xmlXPathCastToString(xmlXPathObjectPtr val);
6860/// ```
6861#[no_mangle]
6862pub unsafe extern "C" fn xmlXPathCastToString(val: *mut _xmlXPathObject) -> *mut xmlChar {
6863    if val.is_null() {
6864        return ptr::null_mut();
6865    }
6866    let typ = (*val).type_;
6867    let mut result: Vec<u8> = Vec::new();
6868    if typ == xmlXPathObjectType::XPATH_STRING as c_int {
6869        if !(*val).stringval.is_null() {
6870            let len = libc::strlen((*val).stringval as *const libc::c_char);
6871            result.extend_from_slice(core::slice::from_raw_parts((*val).stringval, len));
6872        }
6873    } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
6874        // Number → string conversion per XPath 1.0 §4.2:
6875        // - NaN → "NaN"
6876        // - +0/-0 → "0"
6877        // - infinity → "Infinity" / "-Infinity"
6878        // - integer → decimal representation without exponent
6879        let n = (*val).floatval;
6880        result.extend_from_slice(xml_number_to_string(n).as_bytes());
6881    } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
6882        result.extend_from_slice(if (*val).boolval != 0 {
6883            b"true"
6884        } else {
6885            b"false"
6886        });
6887    } else if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
6888        // String value of a node-set is the string value of the first node
6889        // in document order (or empty if empty).
6890        let ns = (*val).nodesetval as *mut _xmlNodeSet;
6891        if !ns.is_null() && (*ns).nodeNr > 0 && !(*ns).nodeTab.is_null() {
6892            let node = *(*ns).nodeTab;
6893            if !node.is_null() {
6894                let content = crate::xml::tree::node_get_content(node);
6895                if !content.is_null() {
6896                    let len = libc::strlen(content as *const libc::c_char);
6897                    result.extend_from_slice(core::slice::from_raw_parts(content, len));
6898                    xmlFreeImpl(content as *mut c_void);
6899                }
6900            }
6901        }
6902    }
6903    // Allocate the C string.
6904    let buf = xmlMallocImpl(result.len() + 1) as *mut xmlChar;
6905    if buf.is_null() {
6906        return ptr::null_mut();
6907    }
6908    if !result.is_empty() {
6909        ptr::copy_nonoverlapping(result.as_ptr(), buf, result.len());
6910    }
6911    *buf.add(result.len()) = 0;
6912    buf
6913}
6914
6915/// Convert an XPath number to its string representation (XPath 1.0 §4.2).
6916///
6917/// Canonical implementation lives in `crate::xml::xpath::types::number_to_string`
6918/// (a port of upstream `xmlXPathCastNumberToString` / `xmlXPathFormatNumber`,
6919/// R-000166); this ABI helper delegates so every number→string conversion
6920/// shares exactly one oracle-verified code path.
6921pub fn xml_number_to_string(n: f64) -> String {
6922    crate::xml::xpath::types::number_to_string(n)
6923}
6924
6925/// Port of upstream xpath.c `xmlXPathStringEvalNumber` (R-000166): see
6926/// `crate::xml::xpath::types::string_bytes_to_number` — the oracle
6927/// accumulates digits directly, caps the fraction at MAX_FRAC=20 digits
6928/// after any leading zeros, applies the exponent with `pow(10.0, exp)`
6929/// (underflowing to 0 below the smallest subnormal), accepts XML whitespace
6930/// around the number, and returns NaN for anything else — including a
6931/// leading '+'.
6932fn xpath_string_eval_number(bytes: &[u8]) -> f64 {
6933    crate::xml::xpath::types::string_bytes_to_number(bytes)
6934}
6935
6936/// Cast a C string to a number per XPath 1.0 §4.2 conversion rules.
6937///
6938/// # UPSTREAM-PARITY
6939///
6940/// ```c
6941/// double xmlXPathCastStringToNumber(const xmlChar *val);
6942/// ```
6943#[no_mangle]
6944pub unsafe extern "C" fn xmlXPathCastStringToNumber(val: *const xmlChar) -> f64 {
6945    if val.is_null() {
6946        return f64::NAN;
6947    }
6948    let len = libc::strlen(val as *const libc::c_char);
6949    let bytes = core::slice::from_raw_parts(val, len);
6950    xpath_string_eval_number(bytes)
6951}
6952
6953/// Compare two nodes in document order.
6954///
6955/// UPSTREAM-PARITY (xpath.c `xmlXPathCmpNodes`): returns **1** when
6956/// `node1` precedes `node2` in document order, **-1** when `node1` follows
6957/// `node2`, 0 for the same node, and -2 for NULL or cross-document
6958/// comparisons. The sign convention was verified against the system oracle
6959/// (libxml2 2.15.3): `xmlXPathCmpNodes(book1, book2)` returns 1.
6960///
6961/// # UPSTREAM-PARITY
6962///
6963/// ```c
6964/// int xmlXPathCmpNodes(xmlNodePtr node1, xmlNodePtr node2);
6965/// ```
6966#[no_mangle]
6967pub unsafe extern "C" fn xmlXPathCmpNodes(node1: *mut _xmlNode, node2: *mut _xmlNode) -> c_int {
6968    if node1.is_null() || node2.is_null() {
6969        return -2;
6970    }
6971    if node1 == node2 {
6972        return 0;
6973    }
6974    // Build ancestor chains.
6975    let mut chain1: Vec<*mut _xmlNode> = Vec::new();
6976    let mut chain2: Vec<*mut _xmlNode> = Vec::new();
6977    let mut n = node1;
6978    while !n.is_null() {
6979        chain1.push(n);
6980        n = (*n).parent;
6981    }
6982    let mut n = node2;
6983    while !n.is_null() {
6984        chain2.push(n);
6985        n = (*n).parent;
6986    }
6987    // Distinct documents (or entities) case.
6988    if chain1[chain1.len() - 1] != chain2[chain2.len() - 1] {
6989        return -2;
6990    }
6991    // Find the nearest common ancestor.
6992    let mut i = chain1.len();
6993    let mut j = chain2.len();
6994    while i > 0 && j > 0 && chain1[i - 1] == chain2[j - 1] {
6995        i -= 1;
6996        j -= 1;
6997    }
6998    // node1 is an ancestor of node2 -> node1 precedes it -> 1.
6999    if i == 0 {
7000        return 1;
7001    }
7002    // node2 is an ancestor of node1 -> node1 follows it -> -1.
7003    if j == 0 {
7004        return -1;
7005    }
7006    // Compare sibling order at the divergence point.
7007    let mut a = chain1[i - 1];
7008    let mut b = chain2[j - 1];
7009    // Climb to the same level.
7010    while !a.is_null() && !b.is_null() {
7011        let pa = (*a).parent;
7012        let pb = (*b).parent;
7013        if pa == pb {
7014            break;
7015        }
7016        a = pa;
7017        b = pb;
7018    }
7019    // Walk forward from the first child of the common parent.
7020    let parent = (*a).parent;
7021    let mut child = if parent.is_null() {
7022        ptr::null_mut()
7023    } else {
7024        (*parent).children
7025    };
7026    while !child.is_null() {
7027        if child == a {
7028            return 1; // a precedes b
7029        }
7030        if child == b {
7031            return -1; // b precedes a
7032        }
7033        child = (*child).next;
7034    }
7035    0
7036}
7037
7038/// Create a node-set from a range of an existing node-set.
7039///
7040/// # UPSTREAM-PARITY
7041///
7042/// ```c
7043/// xmlNodeSetPtr xmlXPathNodeSetCreate(xmlNodePtr val);
7044/// ```
7045///
7046/// With a null `val`, creates an empty node-set.
7047#[no_mangle]
7048pub unsafe extern "C" fn xmlXPathNodeSetCreate(val: *mut _xmlNode) -> *mut _xmlNodeSet {
7049    let ns = xmlMallocZero(size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
7050    if ns.is_null() {
7051        return ptr::null_mut();
7052    }
7053    if val.is_null() {
7054        return ns;
7055    }
7056    let tab = xmlMallocImpl(core::mem::size_of::<*mut _xmlNode>()) as *mut *mut _xmlNode;
7057    if tab.is_null() {
7058        xmlFreeImpl(ns as *mut c_void);
7059        return ptr::null_mut();
7060    }
7061    *tab = val;
7062    (*ns).nodeTab = tab;
7063    (*ns).nodeNr = 1;
7064    (*ns).nodeMax = 1;
7065    ns
7066}
7067
7068/// Free a node-set allocated by `xmlXPathNodeSetCreate` or a node-set
7069/// builder in this library.
7070///
7071/// Frees the node-set structure and its node table; the nodes themselves
7072/// are owned by their document and are not freed.
7073///
7074/// # UPSTREAM-PARITY
7075///
7076/// ```c
7077/// void xmlXPathFreeNodeSet(xmlNodeSetPtr ns);
7078/// ```
7079#[no_mangle]
7080pub unsafe extern "C" fn xmlXPathFreeNodeSet(ns: *mut _xmlNodeSet) {
7081    if ns.is_null() {
7082        return;
7083    }
7084    if !(*ns).nodeTab.is_null() {
7085        xmlFreeImpl((*ns).nodeTab as *mut c_void);
7086        (*ns).nodeTab = ptr::null_mut();
7087    }
7088    (*ns).nodeNr = 0;
7089    (*ns).nodeMax = 0;
7090    xmlFreeImpl(ns as *mut c_void);
7091}
7092
7093/// Compile `expr_str` and store it in the compiled-expression registry,
7094/// returning the opaque key (or the parse error without raising — the caller
7095/// decides delivery).
7096pub(crate) fn xpath_compile_store(
7097    expr_str: &str,
7098) -> Result<*mut c_void, crate::xml::xpath::parser::ParseError> {
7099    match crate::xml::xpath::compile_result(expr_str) {
7100        Ok(compiled) => {
7101            let mut map = COMPILED_EXPRS.lock();
7102            let mut counter = NEXT_COMPILED_KEY.lock();
7103            let key = *counter;
7104            *counter += 1;
7105            map.insert(key, Box::new(compiled));
7106            Ok(key as *mut c_void)
7107        }
7108        Err(e) => Err(e),
7109    }
7110}
7111
7112/// Compile an XPath expression.
7113///
7114/// # UPSTREAM-PARITY
7115///
7116/// ```c
7117/// xmlXPathCompExprPtr xmlXPathCompile(const xmlChar *str);
7118/// ```
7119#[no_mangle]
7120pub unsafe extern "C" fn xmlXPathCompile(str_: *const xmlChar) -> *mut c_void {
7121    if str_.is_null() {
7122        return ptr::null_mut();
7123    }
7124    let expr_str = match CStr::from_ptr(str_ as *const c_char).to_str() {
7125        Ok(s) => s,
7126        Err(_) => return ptr::null_mut(),
7127    };
7128
7129    match xpath_compile_store(expr_str) {
7130        Ok(key) => key,
7131        Err(e) => {
7132            // UPSTREAM-PARITY (xpath.c xmlXPathErrFmt): a failed compile
7133            // reports "XPath error : Invalid expression\n" plus the
7134            // expression and a caret at the error offset through the generic
7135            // channel (HOSTILE-FAILURE F3). The structured code is
7136            // 1200-based like upstream `code + XML_XPATH_EXPRESSION_OK`.
7137            let msg_cstr = std::ffi::CString::new("Invalid expression\n").unwrap_or_default();
7138            let expr_cstr = std::ffi::CString::new(expr_str).unwrap_or_default();
7139            let off = e.pos;
7140            let window = if off < 100 && off < expr_str.len() {
7141                Some((expr_str.as_bytes(), off))
7142            } else {
7143                None
7144            };
7145            unsafe {
7146                crate::xml::errors::raise_error_streamed(
7147                    ptr::null_mut(),
7148                    crate::abi::types::XML_FROM_XPATH,
7149                    crate::abi::types::XPATH_EXPR_ERROR
7150                        + crate::abi::types::XML_XPATH_EXPRESSION_OK,
7151                    crate::abi::types::xmlErrorLevel::XML_ERR_ERROR as c_int,
7152                    ptr::null(),
7153                    0,
7154                    0,
7155                    expr_cstr.as_ptr(),
7156                    ptr::null(),
7157                    ptr::null(),
7158                    off as c_int,
7159                    msg_cstr.as_ptr(),
7160                    window,
7161                    None,
7162                    crate::xml::errors::GenericDelivery::Stream,
7163                    None,
7164                );
7165            }
7166            ptr::null_mut()
7167        }
7168    }
7169}
7170
7171/// Free a compiled XPath expression.
7172///
7173/// # UPSTREAM-PARITY
7174///
7175/// ```c
7176/// void xmlXPathFreeCompExpr(xmlXPathCompExprPtr comp);
7177/// ```
7178#[no_mangle]
7179pub unsafe extern "C" fn xmlXPathFreeCompExpr(comp: *mut c_void) {
7180    if comp.is_null() {
7181        return;
7182    }
7183    let mut map = COMPILED_EXPRS.lock();
7184    map.remove(&(comp as u64));
7185}
7186
7187/// Register an XPath namespace.
7188///
7189/// # UPSTREAM-PARITY
7190///
7191/// ```c
7192/// int xmlXPathRegisterNs(xmlXPathContextPtr ctxt,
7193///                        const xmlChar *prefix, const xmlChar *ns_uri);
7194/// ```
7195#[no_mangle]
7196pub unsafe extern "C" fn xmlXPathRegisterNs(
7197    ctxt: *mut _xmlXPathContext,
7198    prefix: *const xmlChar,
7199    ns_uri: *const xmlChar,
7200) -> c_int {
7201    if ctxt.is_null() || prefix.is_null() || ns_uri.is_null() {
7202        return -1;
7203    }
7204    let internal = (*ctxt).extra as *mut XPathContext;
7205    if internal.is_null() {
7206        return -1;
7207    }
7208    let internal = &mut *internal;
7209
7210    let prefix_str = match CStr::from_ptr(prefix as *const c_char).to_str() {
7211        Ok(s) => s,
7212        Err(_) => return -1,
7213    };
7214    let uri_str = match CStr::from_ptr(ns_uri as *const c_char).to_str() {
7215        Ok(s) => s,
7216        Err(_) => return -1,
7217    };
7218
7219    internal.register_namespace(prefix_str, uri_str);
7220
7221    // UPSTREAM-PARITY (xpath.c xmlXPathRegisterNs): the C context's nsHash
7222    // is a REAL xmlHashTable keyed by prefix with a strdup'd URI payload —
7223    // C consumers (lxml registerExsltFunctions) call xmlHashScan and
7224    // xmlHashLookup on it, so it must be an xmlHashTable, not a Rust map.
7225    // (R-00019x: the pre-fix nsHash held a Box<HashMap<..>>; lxml's
7226    // xmlHashScan interpreted the HashMap as an xmlHashTable and crashed on
7227    // its internal layout.)
7228    if (*ctxt).nsHash.is_null() {
7229        (*ctxt).nsHash = xmlHashCreate(10);
7230    }
7231    if !(*ctxt).nsHash.is_null() {
7232        let uri_dup = crate::xml::string::xml_strdup(ns_uri);
7233        let rc = xmlHashAddEntry((*ctxt).nsHash, prefix, uri_dup as *mut c_void);
7234        if rc != 0 {
7235            // Duplicate prefix: upstream keeps the first mapping (and leaks
7236            // the new strdup'd URI); the candidate frees the unused copy.
7237            crate::abi::allocator::xmlFreeImpl(uri_dup as *mut c_void);
7238        }
7239    }
7240    0
7241}
7242
7243/// Register an XPath function.
7244///
7245/// The C function pointer is stored in a side table keyed by the context.
7246/// A Rust-side stub is registered in the internal context so that the Rust
7247/// evaluator is aware of the function; however, calling the C function
7248/// directly from the Rust evaluator is not yet supported.
7249///
7250/// # UPSTREAM-PARITY
7251///
7252/// ```c
7253/// int xmlXPathRegisterFunc(xmlXPathContextPtr ctxt,
7254///                          const xmlChar *name, xmlXPathFunction f);
7255/// ```
7256#[no_mangle]
7257pub unsafe extern "C" fn xmlXPathRegisterFunc(
7258    ctxt: *mut _xmlXPathContext,
7259    name: *const xmlChar,
7260    f: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
7261) -> c_int {
7262    if ctxt.is_null() || name.is_null() {
7263        return -1;
7264    }
7265    let internal = (*ctxt).extra as *mut XPathContext;
7266    if internal.is_null() {
7267        return -1;
7268    }
7269    let internal = &mut *internal;
7270
7271    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
7272        Ok(s) => s,
7273        Err(_) => return -1,
7274    };
7275
7276    if let Some(func) = f {
7277        // Store the C function pointer in the side table.
7278        let key = (SendSyncPtr((*ctxt).extra), name_str.to_string());
7279        C_FUNCTIONS.lock().insert(key, func);
7280        // Register a Rust closure that bridges to the C function through a
7281        // synthesized xmlXPathParserContext (upstream function-call ABI).
7282        let c_ctxt = SendSyncPtr(ctxt as *mut c_void);
7283        let name_owned = name_str.to_string();
7284        internal.register_function(name_str, c_func_bridge_closure(c_ctxt, name_owned));
7285    }
7286    0
7287}
7288
7289/// Register an XPath function with namespace.
7290///
7291/// # UPSTREAM-PARITY
7292///
7293/// ```c
7294/// int xmlXPathRegisterFuncNS(xmlXPathContextPtr ctxt,
7295///                            const xmlChar *name, const xmlChar *ns_uri,
7296///                            xmlXPathFunction f);
7297/// ```
7298#[no_mangle]
7299pub unsafe extern "C" fn xmlXPathRegisterFuncNS(
7300    ctxt: *mut _xmlXPathContext,
7301    name: *const xmlChar,
7302    ns_uri: *const xmlChar,
7303    f: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
7304) -> c_int {
7305    if ctxt.is_null() || name.is_null() {
7306        return -1;
7307    }
7308    let internal = (*ctxt).extra as *mut XPathContext;
7309    if internal.is_null() {
7310        return -1;
7311    }
7312    let internal = &mut *internal;
7313
7314    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
7315        Ok(s) => s,
7316        Err(_) => return -1,
7317    };
7318    let ns_str = if ns_uri.is_null() {
7319        String::new()
7320    } else {
7321        match CStr::from_ptr(ns_uri as *const c_char).to_str() {
7322            Ok(s) => s.to_string(),
7323            Err(_) => return -1,
7324        }
7325    };
7326
7327    // Use "{ns}:" prefix as part of the key to keep functions unique.
7328    let qualified = if ns_str.is_empty() {
7329        name_str.to_string()
7330    } else {
7331        format!("{{{}}}{}", ns_str, name_str)
7332    };
7333
7334    if let Some(func) = f {
7335        let key = (SendSyncPtr((*ctxt).extra), qualified.clone());
7336        C_FUNCTIONS.lock().insert(key, func);
7337        let c_ctxt = SendSyncPtr(ctxt as *mut c_void);
7338        let qualified_owned = qualified.clone();
7339        internal.register_function(&qualified, c_func_bridge_closure(c_ctxt, qualified_owned));
7340    }
7341    0
7342}
7343
7344/// Register an XPath variable.
7345///
7346/// # UPSTREAM-PARITY
7347///
7348/// ```c
7349/// int xmlXPathRegisterVariable(xmlXPathContextPtr ctxt,
7350///                              const xmlChar *name, xmlXPathObjectPtr value);
7351/// ```
7352#[no_mangle]
7353pub unsafe extern "C" fn xmlXPathRegisterVariable(
7354    ctxt: *mut _xmlXPathContext,
7355    name: *const xmlChar,
7356    value: *mut _xmlXPathObject,
7357) -> c_int {
7358    if ctxt.is_null() || name.is_null() || value.is_null() {
7359        return -1;
7360    }
7361    let internal = (*ctxt).extra as *mut XPathContext;
7362    if internal.is_null() {
7363        return -1;
7364    }
7365    let internal = &mut *internal;
7366
7367    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
7368        Ok(s) => s,
7369        Err(_) => return -1,
7370    };
7371
7372    let xpath_val = object_to_xpathvalue(value);
7373    internal.register_variable(name_str, xpath_val);
7374    0
7375}
7376
7377/// Create an XPath object wrapping a single node in a node-set.
7378///
7379/// # UPSTREAM-PARITY
7380///
7381/// ```c
7382/// xmlXPathObjectPtr xmlXPathNewNodeSet(xmlNodePtr val);
7383/// ```
7384#[no_mangle]
7385pub unsafe extern "C" fn xmlXPathNewNodeSet(val: *mut _xmlNode) -> *mut _xmlXPathObject {
7386    let ns = if val.is_null() {
7387        NodeSet::new()
7388    } else {
7389        NodeSet::singleton(val)
7390    };
7391    xpath_to_object(XPathValue::NodeSet(ns))
7392}
7393
7394/// Create an XPath object from a C string value.
7395///
7396/// # UPSTREAM-PARITY
7397///
7398/// ```c
7399/// xmlXPathObjectPtr xmlXPathNewCString(const xmlChar *val);
7400/// ```
7401#[no_mangle]
7402pub unsafe extern "C" fn xmlXPathNewCString(val: *const xmlChar) -> *mut _xmlXPathObject {
7403    if val.is_null() {
7404        return xpath_to_object(XPathValue::String(String::new()));
7405    }
7406    let s = match CStr::from_ptr(val as *const c_char).to_str() {
7407        Ok(s) => s.to_string(),
7408        Err(_) => return ptr::null_mut(),
7409    };
7410    xpath_to_object(XPathValue::String(s))
7411}
7412
7413/// Create an XPath number object.
7414///
7415/// # UPSTREAM-PARITY
7416///
7417/// ```c
7418/// xmlXPathObjectPtr xmlXPathNewFloat(double val);
7419/// ```
7420#[no_mangle]
7421pub extern "C" fn xmlXPathNewFloat(val: f64) -> *mut _xmlXPathObject {
7422    unsafe { xpath_to_object(XPathValue::Number(val)) }
7423}
7424
7425/// Create an XPath boolean object.
7426///
7427/// # UPSTREAM-PARITY
7428///
7429/// ```c
7430/// xmlXPathObjectPtr xmlXPathNewBoolean(int val);
7431/// ```
7432#[no_mangle]
7433pub extern "C" fn xmlXPathNewBoolean(val: c_int) -> *mut _xmlXPathObject {
7434    unsafe { xpath_to_object(XPathValue::Boolean(val != 0)) }
7435}
7436
7437// ═══════════════════════════════════════════════════════════════════════════════
7438// 14.5. XPointer
7439// ═══════════════════════════════════════════════════════════════════════════════
7440
7441/// Evaluate an XPointer expression.
7442///
7443/// Delegates to the xpointer module.
7444///
7445/// # UPSTREAM-PARITY
7446///
7447/// ```c
7448/// xmlNodePtr xmlXPtrEval(const xmlChar *expr, xmlDocPtr doc);
7449/// ```
7450#[no_mangle]
7451pub unsafe extern "C" fn xmlXPtrEval(expr: *const c_char, doc: *mut _xmlDoc) -> *mut _xmlNode {
7452    crate::xml::xpointer::xmlXPtrEval(expr, doc)
7453}
7454
7455// ═══════════════════════════════════════════════════════════════════════════════
7456// 15. XInclude
7457// ═══════════════════════════════════════════════════════════════════════════════
7458
7459/// Process XInclude nodes in a document.
7460///
7461/// # UPSTREAM-PARITY
7462///
7463/// ```c
7464/// int xmlXIncludeProcess(xmlDocPtr doc);
7465/// ```
7466#[no_mangle]
7467pub unsafe extern "C" fn xmlXIncludeProcess(doc: *mut _xmlDoc) -> c_int {
7468    crate::xml::xinclude::xinclude_process(doc)
7469}
7470
7471/// Process XInclude nodes with flags.
7472///
7473/// # UPSTREAM-PARITY
7474///
7475/// ```c
7476/// int xmlXIncludeProcessFlags(xmlDocPtr doc, int flags);
7477/// ```
7478#[no_mangle]
7479pub unsafe extern "C" fn xmlXIncludeProcessFlags(doc: *mut _xmlDoc, flags: c_int) -> c_int {
7480    crate::xml::xinclude::xinclude_process_flags(doc, flags)
7481}
7482
7483// ═══════════════════════════════════════════════════════════════════════════════
7484// 16. Catalog
7485// ═══════════════════════════════════════════════════════════════════════════════
7486
7487/// Load a catalog.
7488///
7489/// # UPSTREAM-PARITY
7490///
7491/// ```c
7492/// xmlCatalogPtr xmlCatalogLoad(const char *catalogs);
7493/// ```
7494#[no_mangle]
7495pub extern "C" fn xmlCatalogLoad(catalogs: *const c_char) -> *mut c_void {
7496    if catalogs.is_null() {
7497        return ptr::null_mut();
7498    }
7499    crate::xml::catalog::load_catalog(catalogs)
7500}
7501
7502/// Resolve a public ID.
7503///
7504/// # UPSTREAM-PARITY
7505///
7506/// ```c
7507/// xmlCharPtr xmlCatalogResolvePublic(const xmlChar *pubID);
7508/// ```
7509#[no_mangle]
7510pub unsafe extern "C" fn xmlCatalogResolvePublic(pubID: *const xmlChar) -> *mut xmlChar {
7511    if pubID.is_null() {
7512        return ptr::null_mut();
7513    }
7514    crate::xml::catalog::resolve_public(pubID)
7515}
7516
7517/// Resolve a system ID.
7518///
7519/// # UPSTREAM-PARITY
7520///
7521/// ```c
7522/// xmlCharPtr xmlCatalogResolveSystem(const xmlChar *sysID);
7523/// ```
7524#[no_mangle]
7525pub unsafe extern "C" fn xmlCatalogResolveSystem(sysID: *const xmlChar) -> *mut xmlChar {
7526    if sysID.is_null() {
7527        return ptr::null_mut();
7528    }
7529    crate::xml::catalog::resolve_system(sysID)
7530}
7531
7532/// Resolve a URI.
7533///
7534/// # UPSTREAM-PARITY
7535///
7536/// ```c
7537/// xmlCharPtr xmlCatalogResolveURI(const xmlChar *URI);
7538/// ```
7539#[no_mangle]
7540pub unsafe extern "C" fn xmlCatalogResolveURI(URI: *const xmlChar) -> *mut xmlChar {
7541    if URI.is_null() {
7542        return ptr::null_mut();
7543    }
7544    crate::xml::catalog::resolve_uri(URI)
7545}
7546
7547/// Set catalog defaults.
7548///
7549/// # UPSTREAM-PARITY
7550///
7551/// ```c
7552/// void xmlCatalogSetDefaults(xmlCatalogAllowValue allow);
7553/// ```
7554#[no_mangle]
7555pub extern "C" fn xmlCatalogSetDefaults(allow: c_int) {
7556    crate::xml::catalog::set_defaults(allow)
7557}
7558
7559/// Get catalog defaults.
7560///
7561/// # UPSTREAM-PARITY
7562///
7563/// ```c
7564/// xmlCatalogAllowValue xmlCatalogGetDefaults(void);
7565/// ```
7566#[no_mangle]
7567pub extern "C" fn xmlCatalogGetDefaults() -> c_int {
7568    crate::xml::catalog::get_defaults()
7569}
7570
7571/// Add a catalog.
7572///
7573/// # UPSTREAM-PARITY
7574///
7575/// ```c
7576/// int xmlCatalogAdd(const xmlChar *type, const xmlChar *orig, const xmlChar *replace);
7577/// ```
7578#[no_mangle]
7579pub unsafe extern "C" fn xmlCatalogAdd(
7580    type_: *const xmlChar,
7581    orig: *const xmlChar,
7582    replace: *const xmlChar,
7583) -> c_int {
7584    if type_.is_null() || orig.is_null() || replace.is_null() {
7585        return -1;
7586    }
7587    crate::xml::catalog::add(type_, orig, replace)
7588}
7589
7590/// Remove a catalog entry.
7591///
7592/// # UPSTREAM-PARITY
7593///
7594/// ```c
7595/// int xmlCatalogRemove(const xmlChar *value);
7596/// ```
7597#[no_mangle]
7598pub unsafe extern "C" fn xmlCatalogRemove(value: *const xmlChar) -> c_int {
7599    if value.is_null() {
7600        return 0;
7601    }
7602    crate::xml::catalog::remove(value)
7603}
7604
7605/// Dump the catalog in XML format to a FILE* (upstream catalog.h:
7606/// 1-argument form — R-000176, the candidate previously took a spurious
7607/// second `xmlCatalogPtr` argument).
7608///
7609/// # UPSTREAM-PARITY
7610///
7611/// ```c
7612/// void xmlCatalogDump(FILE *out);
7613/// ```
7614#[no_mangle]
7615pub unsafe extern "C" fn xmlCatalogDump(output: *mut c_void) {
7616    if output.is_null() {
7617        return;
7618    }
7619    let doc = crate::xml::catalog::dump_doc();
7620    if doc.is_null() {
7621        return;
7622    }
7623    let mut mem: *mut xmlChar = ptr::null_mut();
7624    let mut size: c_int = 0;
7625    crate::xml::tree::xmlDocDumpFormatMemory(doc, &mut mem, &mut size, 1);
7626    if !mem.is_null() {
7627        libc::fwrite(
7628            mem as *const c_void,
7629            1,
7630            size as usize,
7631            output as *mut libc::FILE,
7632        );
7633        xmlFreeImpl(mem as *mut c_void);
7634    }
7635    crate::xml::tree::free_doc(doc);
7636}
7637
7638/// Save the catalog to a file (upstream `xmlCatalogSave`).
7639///
7640/// Returns 0 on success, -1 on failure.
7641///
7642/// # UPSTREAM-PARITY
7643///
7644/// ```c
7645/// int xmlCatalogSave(const char *filename);
7646/// ```
7647#[no_mangle]
7648pub unsafe extern "C" fn xmlCatalogSave(filename: *const c_char) -> c_int {
7649    if filename.is_null() {
7650        return -1;
7651    }
7652    let doc = crate::xml::catalog::dump_doc();
7653    if doc.is_null() {
7654        return -1;
7655    }
7656    let mut mem: *mut xmlChar = ptr::null_mut();
7657    let mut size: c_int = 0;
7658    crate::xml::tree::xmlDocDumpFormatMemory(doc, &mut mem, &mut size, 1);
7659    let mut ret: c_int = -1;
7660    if !mem.is_null() {
7661        let fp = libc::fopen(filename, c"w".as_ptr() as *const c_char);
7662        if !fp.is_null() {
7663            let written = libc::fwrite(mem as *const c_void, 1, size as usize, fp);
7664            ret = if written == size as usize { 0 } else { -1 };
7665            libc::fclose(fp);
7666        }
7667        xmlFreeImpl(mem as *mut c_void);
7668    }
7669    crate::xml::tree::free_doc(doc);
7670    ret
7671}
7672
7673/// Clean up the catalog subsystem.
7674///
7675/// # UPSTREAM-PARITY
7676///
7677/// ```c
7678/// void xmlCatalogCleanup(void);
7679/// ```
7680#[no_mangle]
7681pub extern "C" fn xmlCatalogCleanup() {
7682    crate::xml::catalog::cleanup();
7683}
7684
7685/// Convert all the SGML catalog entries as XML ones (upstream catalog.c:
7686/// returns 0 on success, -1 otherwise — R-000176, the candidate previously
7687/// returned a dump document).
7688///
7689/// # UPSTREAM-PARITY
7690///
7691/// ```c
7692/// int xmlCatalogConvert(void);
7693/// ```
7694///
7695/// The candidate's catalog stores XML-flavored entries natively (there is no
7696/// separate SGML table to convert), so once the catalog is initialized the
7697/// conversion succeeds as a no-op, matching upstream's successful-return
7698/// contract.
7699#[no_mangle]
7700pub extern "C" fn xmlCatalogConvert() -> c_int {
7701    if !crate::xml::catalog::is_initialized() {
7702        return -1;
7703    }
7704    0
7705}
7706
7707// ═══════════════════════════════════════════════════════════════════════════════
7708// 17. HTML
7709// ═══════════════════════════════════════════════════════════════════════════════
7710
7711/// Parse an HTML document from a file.
7712///
7713/// # UPSTREAM-PARITY
7714///
7715/// ```c
7716/// htmlDocPtr htmlParseFile(const char *filename, const char *encoding);
7717/// ```
7718#[no_mangle]
7719pub const unsafe extern "C" fn htmlParseFile(
7720    _filename: *const c_char,
7721    _encoding: *const c_char,
7722) -> *mut _xmlDoc {
7723    // Phase 1: STUB
7724    ptr::null_mut()
7725}
7726
7727/// Parse an HTML document from memory.
7728///
7729/// # UPSTREAM-PARITY
7730///
7731/// ```c
7732/// htmlDocPtr htmlParseMemory(const char *buffer, int size);
7733/// ```
7734#[no_mangle]
7735pub const unsafe extern "C" fn htmlParseMemory(
7736    _buffer: *const c_char,
7737    _size: c_int,
7738) -> *mut _xmlDoc {
7739    // Phase 1: STUB
7740    ptr::null_mut()
7741}
7742
7743/// Parse an HTML document from a document string.
7744///
7745/// # UPSTREAM-PARITY
7746///
7747/// ```c
7748/// htmlDocPtr htmlParseDoc(const xmlChar *cur, const char *encoding);
7749/// ```
7750#[no_mangle]
7751pub const unsafe extern "C" fn htmlParseDoc(
7752    _cur: *const xmlChar,
7753    _encoding: *const c_char,
7754) -> *mut _xmlDoc {
7755    // Phase 1: STUB
7756    ptr::null_mut()
7757}
7758
7759/// Create an HTML parser context.
7760///
7761/// # UPSTREAM-PARITY
7762///
7763/// ```c
7764/// Free an HTML parser context.
7765///
7766/// # UPSTREAM-PARITY
7767///
7768/// ```c
7769/// void htmlFreeParserCtxt(htmlParserCtxtPtr ctxt);
7770/// ```
7771#[no_mangle]
7772pub extern "C" fn htmlFreeParserCtxt(ctxt: *mut c_void) {
7773    unsafe { crate::xml::html::free_parser_ctxt(ctxt) }
7774}
7775
7776/// Initialize the HTML parser.
7777///
7778/// # UPSTREAM-PARITY
7779///
7780/// ```c
7781/// void htmlInitParser(void);
7782/// ```
7783#[no_mangle]
7784pub const extern "C" fn htmlInitParser() {
7785    // Phase 1: STUB
7786}
7787
7788/// Clean up the HTML parser.
7789///
7790/// # UPSTREAM-PARITY
7791///
7792/// ```c
7793/// void htmlCleanupParser(void);
7794/// ```
7795#[no_mangle]
7796pub const extern "C" fn htmlCleanupParser() {
7797    // Phase 1: STUB
7798}
7799
7800// ═══════════════════════════════════════════════════════════════════════════════
7801// 17.5. Validation (DTD)
7802// ═══════════════════════════════════════════════════════════════════════════════
7803
7804/// Create a new validation context.
7805///
7806/// # UPSTREAM-PARITY
7807///
7808/// ```c
7809/// xmlValidCtxtPtr xmlNewValidCtxt(void);
7810/// ```
7811#[no_mangle]
7812pub unsafe extern "C" fn xmlNewValidCtxt() -> *mut _xmlValidCtxt {
7813    crate::xml::validation::new_valid_ctxt()
7814}
7815
7816/// Free a validation context.
7817///
7818/// # UPSTREAM-PARITY
7819///
7820/// ```c
7821/// void xmlFreeValidCtxt(xmlValidCtxtPtr ctxt);
7822/// ```
7823#[no_mangle]
7824pub unsafe extern "C" fn xmlFreeValidCtxt(ctxt: *mut _xmlValidCtxt) {
7825    crate::xml::validation::free_valid_ctxt(ctxt);
7826}
7827
7828/// Set error and warning callbacks on a validation context.
7829///
7830/// # UPSTREAM-PARITY
7831///
7832/// ```c
7833/// void xmlSetValidErrors(xmlValidCtxtPtr ctxt,
7834///                        xmlGenericErrorFunc err,
7835///                        xmlGenericErrorFunc warn,
7836///                        void *data);
7837/// ```
7838#[no_mangle]
7839pub unsafe extern "C" fn xmlSetValidErrors(
7840    ctxt: *mut _xmlValidCtxt,
7841    err: Option<xmlGenericErrorFunc>,
7842    warn: Option<xmlGenericErrorFunc>,
7843    data: *mut c_void,
7844) {
7845    crate::xml::validation::set_valid_errors(ctxt, err, warn, data);
7846}
7847
7848/// Validate a document against its DTD.
7849///
7850/// # UPSTREAM-PARITY
7851///
7852/// ```c
7853/// int xmlValidateDocument(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
7854/// ```
7855#[no_mangle]
7856pub unsafe extern "C" fn xmlValidateDocument(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
7857    crate::xml::validation::validate_document(ctxt, doc)
7858}
7859
7860/// Final validation pass (check ID/IDREF consistency).
7861///
7862/// # UPSTREAM-PARITY
7863///
7864/// ```c
7865/// int xmlValidateDocumentFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
7866/// ```
7867#[no_mangle]
7868pub unsafe extern "C" fn xmlValidateDocumentFinal(
7869    ctxt: *mut _xmlValidCtxt,
7870    doc: *mut _xmlDoc,
7871) -> c_int {
7872    crate::xml::validation::validate_document_final(ctxt, doc)
7873}
7874
7875/// Validate an element node against its DTD declarations.
7876///
7877/// # UPSTREAM-PARITY
7878///
7879/// ```c
7880/// int xmlValidateElement(xmlValidCtxtPtr ctxt,
7881///                        xmlDocPtr doc,
7882///                        xmlNodePtr elem);
7883/// ```
7884#[no_mangle]
7885pub unsafe extern "C" fn xmlValidateElement(
7886    ctxt: *mut _xmlValidCtxt,
7887    doc: *mut _xmlDoc,
7888    elem: *mut _xmlNode,
7889) -> c_int {
7890    crate::xml::validation::validate_element(ctxt, doc, elem)
7891}
7892
7893/// Validate an attribute declaration.
7894///
7895/// # UPSTREAM-PARITY
7896///
7897/// ```c
7898/// int xmlValidateAttributeDecl(xmlValidCtxt *ctxt,
7899///                              xmlDoc *doc,
7900///                              xmlAttribute *attr);
7901/// ```
7902///
7903/// 11.1-Z.3 signature court: the pre-Z.3 candidate declared a fourth
7904/// `xmlNodePtr elem` argument that does not exist upstream (valid.h 2.15.3).
7905#[no_mangle]
7906pub unsafe extern "C" fn xmlValidateAttributeDecl(
7907    ctxt: *mut _xmlValidCtxt,
7908    doc: *mut _xmlDoc,
7909    attr: *mut _xmlAttribute,
7910) -> c_int {
7911    crate::xml::validation::validate_attribute_decl(ctxt, doc, attr)
7912}
7913
7914/// Validate an attribute value against its declared type.
7915///
7916/// # UPSTREAM-PARITY
7917///
7918/// ```c
7919/// int xmlValidateAttributeValue(int type, const xmlChar *value);
7920/// ```
7921#[no_mangle]
7922pub unsafe extern "C" fn xmlValidateAttributeValue(atype: c_int, value: *const xmlChar) -> c_int {
7923    crate::xml::validation::validate_attribute_value(atype, value)
7924}
7925
7926/// Validate a NOTATION reference.
7927///
7928/// # UPSTREAM-PARITY
7929///
7930/// ```c
7931/// int xmlValidateNotationUse(xmlValidCtxtPtr ctxt,
7932///                            xmlDocPtr doc,
7933///                            const xmlChar *notationName);
7934/// ```
7935#[no_mangle]
7936pub unsafe extern "C" fn xmlValidateNotationUse(
7937    ctxt: *mut _xmlValidCtxt,
7938    doc: *mut _xmlDoc,
7939    notation_name: *const xmlChar,
7940) -> c_int {
7941    crate::xml::validation::validate_notation_use(ctxt, doc, notation_name)
7942}
7943
7944/// Validate an ID value (check uniqueness).
7945///
7946/// # UPSTREAM-PARITY
7947///
7948/// ```c
7949/// int xmlValidateID(xmlValidCtxtPtr ctxt,
7950///                   xmlDocPtr doc,
7951///                   xmlNodePtr node,
7952///                   const xmlChar *value);
7953/// ```
7954#[no_mangle]
7955pub unsafe extern "C" fn xmlValidateID(
7956    ctxt: *mut _xmlValidCtxt,
7957    doc: *mut _xmlDoc,
7958    node: *mut _xmlNode,
7959    value: *const xmlChar,
7960) -> c_int {
7961    crate::xml::validation::validate_id(ctxt, doc, node, value)
7962}
7963
7964/// Validate an IDREF value (check it references a known ID; upstream
7965/// valid.h 2.15 has no `node` argument — R-000176).
7966///
7967/// # UPSTREAM-PARITY
7968///
7969/// ```c
7970/// int xmlValidateIDRef(xmlValidCtxt *ctxt, xmlDoc *doc,
7971///                      const xmlChar *value);
7972/// ```
7973#[no_mangle]
7974pub unsafe extern "C" fn xmlValidateIDRef(
7975    ctxt: *mut _xmlValidCtxt,
7976    doc: *mut _xmlDoc,
7977    value: *const xmlChar,
7978) -> c_int {
7979    crate::xml::validation::validate_id_ref(ctxt, doc, ptr::null_mut(), value)
7980}
7981
7982/// Validate IDREFS (whitespace-separated list of IDREFs; upstream valid.h
7983/// 2.15 has no `node` argument — R-000176).
7984///
7985/// # UPSTREAM-PARITY
7986///
7987/// ```c
7988/// int xmlValidateIDRefs(xmlValidCtxt *ctxt, xmlDoc *doc,
7989///                       const xmlChar *value);
7990/// ```
7991#[no_mangle]
7992pub unsafe extern "C" fn xmlValidateIDRefs(
7993    ctxt: *mut _xmlValidCtxt,
7994    doc: *mut _xmlDoc,
7995    value: *const xmlChar,
7996) -> c_int {
7997    crate::xml::validation::validate_id_refs(ctxt, doc, ptr::null_mut(), value)
7998}
7999
8000/// Validate an NCName value (modern 2-arg form, upstream tree.c).
8001///
8002/// # UPSTREAM-PARITY
8003///
8004/// ```c
8005/// int xmlValidateNCName(const xmlChar *value, int space);
8006/// ```
8007///
8008/// Returns -1 on NULL, 0 if valid, 1 if invalid.
8009#[no_mangle]
8010pub unsafe extern "C" fn xmlValidateNCName(value: *const xmlChar, space: c_int) -> c_int {
8011    crate::xml::validation::validate_ncname(value, space)
8012}
8013
8014/// Validate a QName value (modern 2-arg form, upstream tree.c).
8015///
8016/// # UPSTREAM-PARITY
8017///
8018/// ```c
8019/// int xmlValidateQName(const xmlChar *value, int space);
8020/// ```
8021#[no_mangle]
8022pub unsafe extern "C" fn xmlValidateQName(value: *const xmlChar, space: c_int) -> c_int {
8023    crate::xml::validation::validate_qname(value, space)
8024}
8025
8026/// Validate an XML Name value (modern 2-arg form, upstream tree.c).
8027///
8028/// # UPSTREAM-PARITY / HISTORICAL
8029///
8030/// Since libxml2 2.12 the DSO symbol carries a second `int space` parameter
8031/// with inverted return semantics (0 valid / 1 invalid / -1 NULL); the
8032/// pre-2.12 1-arg form no longer exists in the DSO. The candidate matches
8033/// the current oracle. (The 1-arg semantics live on as xmlValidateNameValue.)
8034///
8035/// ```c
8036/// int xmlValidateName(const xmlChar *value, int space);
8037/// ```
8038#[no_mangle]
8039pub unsafe extern "C" fn xmlValidateName(value: *const xmlChar, space: c_int) -> c_int {
8040    crate::xml::validation::validate_name_space(value, space)
8041}
8042
8043/// Validate an NMToken value (modern 2-arg form, upstream tree.c).
8044///
8045/// # UPSTREAM-PARITY
8046///
8047/// ```c
8048/// int xmlValidateNMToken(const xmlChar *value, int space);
8049/// ```
8050#[no_mangle]
8051pub unsafe extern "C" fn xmlValidateNMToken(value: *const xmlChar, space: c_int) -> c_int {
8052    crate::xml::validation::validate_nmtoken_space(value, space)
8053}
8054
8055/// Validate a Name value (1-arg form, upstream valid.c).
8056///
8057/// # UPSTREAM-PARITY
8058///
8059/// ```c
8060/// int xmlValidateNameValue(const xmlChar *value);
8061/// ```
8062///
8063/// Returns 1 if valid, 0 if not (NULL included).
8064#[no_mangle]
8065pub unsafe extern "C" fn xmlValidateNameValue(value: *const xmlChar) -> c_int {
8066    crate::xml::validation::validate_name_value(value)
8067}
8068
8069/// Validate a whitespace-separated list of Names (separator is exactly
8070/// 0x20, upstream erratum E20).
8071///
8072/// # UPSTREAM-PARITY
8073///
8074/// ```c
8075/// int xmlValidateNamesValue(const xmlChar *value);
8076/// ```
8077#[no_mangle]
8078pub unsafe extern "C" fn xmlValidateNamesValue(value: *const xmlChar) -> c_int {
8079    crate::xml::validation::validate_names_value(value)
8080}
8081
8082/// Validate an Nmtoken value (1-arg form, upstream valid.c).
8083///
8084/// # UPSTREAM-PARITY
8085///
8086/// ```c
8087/// int xmlValidateNmtokenValue(const xmlChar *value);
8088/// ```
8089#[no_mangle]
8090pub unsafe extern "C" fn xmlValidateNmtokenValue(value: *const xmlChar) -> c_int {
8091    crate::xml::validation::validate_nmtoken_value(value)
8092}
8093
8094/// Validate a whitespace-separated list of Nmtokens.
8095///
8096/// # UPSTREAM-PARITY
8097///
8098/// ```c
8099/// int xmlValidateNmtokensValue(const xmlChar *value);
8100/// ```
8101#[no_mangle]
8102pub unsafe extern "C" fn xmlValidateNmtokensValue(value: *const xmlChar) -> c_int {
8103    crate::xml::validation::validate_nmtokens_value(value)
8104}
8105
8106/// Validate a single element declaration (VC: Unique Element Type
8107/// Declaration, VC: No Duplicate Types).
8108///
8109/// # UPSTREAM-PARITY
8110///
8111/// ```c
8112/// int xmlValidateElementDecl(xmlValidCtxtPtr ctxt,
8113///                            xmlDocPtr doc,
8114///                            xmlElementPtr elem);
8115/// ```
8116#[no_mangle]
8117pub unsafe extern "C" fn xmlValidateElementDecl(
8118    ctxt: *mut _xmlValidCtxt,
8119    doc: *mut _xmlDoc,
8120    elem: *mut _xmlElement,
8121) -> c_int {
8122    crate::xml::validation::validate_element_decl(ctxt, doc, elem)
8123}
8124
8125/// Validate a notation declaration.
8126///
8127/// # UPSTREAM-PARITY
8128///
8129/// Modern libxml2 has no validity constraint on notation declarations; the
8130/// oracle returns 1 unconditionally (verified by DSO disassembly).
8131///
8132/// ```c
8133/// int xmlValidateNotationDecl(xmlValidCtxtPtr ctxt,
8134///                             xmlDocPtr doc,
8135///                             xmlNotationPtr nota);
8136/// ```
8137#[no_mangle]
8138pub const unsafe extern "C" fn xmlValidateNotationDecl(
8139    ctxt: *mut _xmlValidCtxt,
8140    doc: *mut _xmlDoc,
8141    nota: *mut _xmlNotation,
8142) -> c_int {
8143    crate::xml::validation::validate_notation_decl(ctxt, doc, nota)
8144}
8145
8146/// Validate a single attribute against its declaration.
8147///
8148/// # UPSTREAM-PARITY
8149///
8150/// ```c
8151/// int xmlValidateOneAttribute(xmlValidCtxtPtr ctxt,
8152///                             xmlDocPtr doc,
8153///                             xmlNodePtr elem,
8154///                             xmlAttrPtr attr,
8155///                             const xmlChar *value);
8156/// ```
8157#[no_mangle]
8158pub unsafe extern "C" fn xmlValidateOneAttribute(
8159    ctxt: *mut _xmlValidCtxt,
8160    doc: *mut _xmlDoc,
8161    elem: *mut _xmlNode,
8162    attr: *mut _xmlAttr,
8163    value: *const xmlChar,
8164) -> c_int {
8165    crate::xml::validation::validate_one_attribute(ctxt, doc, elem, attr, value)
8166}
8167
8168/// Validate a single element against its declaration (without recursing).
8169///
8170/// # UPSTREAM-PARITY
8171///
8172/// ```c
8173/// int xmlValidateOneElement(xmlValidCtxtPtr ctxt,
8174///                           xmlDocPtr doc,
8175///                           xmlNodePtr elem);
8176/// ```
8177#[no_mangle]
8178pub unsafe extern "C" fn xmlValidateOneElement(
8179    ctxt: *mut _xmlValidCtxt,
8180    doc: *mut _xmlDoc,
8181    elem: *mut _xmlNode,
8182) -> c_int {
8183    crate::xml::validation::validate_one_element(ctxt, doc, elem)
8184}
8185
8186/// Validate a namespace declaration attribute.
8187///
8188/// # UPSTREAM-PARITY
8189///
8190/// ```c
8191/// int xmlValidateOneNamespace(xmlValidCtxtPtr ctxt,
8192///                             xmlDocPtr doc,
8193///                             xmlNodePtr elem,
8194///                             const xmlChar *prefix,
8195///                             xmlNsPtr ns,
8196///                             const xmlChar *value);
8197/// ```
8198#[no_mangle]
8199pub unsafe extern "C" fn xmlValidateOneNamespace(
8200    ctxt: *mut _xmlValidCtxt,
8201    doc: *mut _xmlDoc,
8202    elem: *mut _xmlNode,
8203    prefix: *const xmlChar,
8204    ns: *mut _xmlNs,
8205    value: *const xmlChar,
8206) -> c_int {
8207    crate::xml::validation::validate_one_namespace(ctxt, doc, elem, prefix, ns, value)
8208}
8209
8210/// Push a new element start onto the validation stack (streaming DTD
8211/// validation).
8212///
8213/// # UPSTREAM-PARITY
8214///
8215/// ```c
8216/// int xmlValidatePushElement(xmlValidCtxtPtr ctxt,
8217///                            xmlDocPtr doc,
8218///                            xmlNodePtr elem,
8219///                            const xmlChar *qname);
8220/// ```
8221#[no_mangle]
8222pub unsafe extern "C" fn xmlValidatePushElement(
8223    ctxt: *mut _xmlValidCtxt,
8224    doc: *mut _xmlDoc,
8225    elem: *mut _xmlNode,
8226    qname: *const xmlChar,
8227) -> c_int {
8228    crate::xml::validation::validate_push_element(ctxt, doc, elem, qname)
8229}
8230
8231/// Push character data onto the validation stack.
8232///
8233/// # UPSTREAM-PARITY
8234///
8235/// ```c
8236/// int xmlValidatePushCData(xmlValidCtxtPtr ctxt,
8237///                          const xmlChar *data,
8238///                          int len);
8239/// ```
8240#[no_mangle]
8241pub unsafe extern "C" fn xmlValidatePushCData(
8242    ctxt: *mut _xmlValidCtxt,
8243    data: *const xmlChar,
8244    len: c_int,
8245) -> c_int {
8246    crate::xml::validation::validate_push_cdata(ctxt, data, len)
8247}
8248
8249/// Pop an element end from the validation stack.
8250///
8251/// # UPSTREAM-PARITY
8252///
8253/// ```c
8254/// int xmlValidatePopElement(xmlValidCtxtPtr ctxt,
8255///                           xmlDocPtr doc,
8256///                           xmlNodePtr elem,
8257///                           const xmlChar *qname);
8258/// ```
8259#[no_mangle]
8260pub unsafe extern "C" fn xmlValidatePopElement(
8261    ctxt: *mut _xmlValidCtxt,
8262    doc: *mut _xmlDoc,
8263    elem: *mut _xmlNode,
8264    qname: *const xmlChar,
8265) -> c_int {
8266    crate::xml::validation::validate_pop_element(ctxt, doc, elem, qname)
8267}
8268
8269/// Build the content-model automaton for an element declaration.
8270///
8271/// # UPSTREAM-PARITY
8272///
8273/// ```c
8274/// int xmlValidBuildContentModel(xmlValidCtxtPtr ctxt,
8275///                               xmlElementPtr elem);
8276/// ```
8277#[no_mangle]
8278pub unsafe extern "C" fn xmlValidBuildContentModel(
8279    ctxt: *mut _xmlValidCtxt,
8280    elem: *mut _xmlElement,
8281) -> c_int {
8282    crate::xml::validation::validate_build_content_model(ctxt, elem)
8283}
8284
8285/// Add an attribute to the document's ID table.
8286///
8287/// # UPSTREAM-PARITY
8288///
8289/// ```c
8290/// xmlIDPtr xmlAddID(xmlValidCtxtPtr ctxt,
8291///                   xmlDocPtr doc,
8292///                   const xmlChar *value,
8293///                   xmlAttrPtr attr);
8294/// ```
8295#[no_mangle]
8296pub unsafe extern "C" fn xmlAddID(
8297    ctxt: *mut _xmlValidCtxt,
8298    doc: *mut _xmlDoc,
8299    value: *const xmlChar,
8300    attr: *mut _xmlAttr,
8301) -> *mut _xmlID {
8302    crate::xml::validation::add_id(ctxt, doc, value, attr)
8303}
8304
8305/// Remove an attribute from the document's ID table.
8306///
8307/// # UPSTREAM-PARITY
8308///
8309/// ```c
8310/// int xmlRemoveID(xmlDocPtr doc, xmlAttrPtr attr);
8311/// ```
8312#[no_mangle]
8313pub unsafe extern "C" fn xmlRemoveID(doc: *mut _xmlDoc, attr: *mut _xmlAttr) -> c_int {
8314    crate::xml::validation::remove_id(doc, attr)
8315}
8316
8317/// Register an IDREF in the document's ref table.
8318///
8319/// # UPSTREAM-PARITY
8320///
8321/// ```c
8322/// xmlRefPtr xmlAddRef(xmlValidCtxtPtr ctxt,
8323///                     xmlDocPtr doc,
8324///                     const xmlChar *value,
8325///                     xmlAttrPtr attr);
8326/// ```
8327#[no_mangle]
8328pub unsafe extern "C" fn xmlAddRef(
8329    ctxt: *mut _xmlValidCtxt,
8330    doc: *mut _xmlDoc,
8331    value: *const xmlChar,
8332    attr: *mut _xmlAttr,
8333) -> *mut _xmlRef {
8334    crate::xml::validation::add_ref(ctxt, doc, value, attr)
8335}
8336
8337/// Remove an attribute's IDREF entries.
8338///
8339/// # UPSTREAM-PARITY
8340///
8341/// ```c
8342/// int xmlRemoveRef(xmlDocPtr doc, xmlAttrPtr attr);
8343/// ```
8344#[no_mangle]
8345pub unsafe extern "C" fn xmlRemoveRef(doc: *mut _xmlDoc, attr: *mut _xmlAttr) -> c_int {
8346    crate::xml::validation::remove_ref(doc, attr)
8347}
8348
8349/// Add an ID without a validation context (2.13+).
8350///
8351/// # UPSTREAM-PARITY
8352///
8353/// ```c
8354/// int xmlAddIDSafe(xmlAttrPtr attr, const xmlChar *value);
8355/// ```
8356#[no_mangle]
8357pub unsafe extern "C" fn xmlAddIDSafe(attr: *mut _xmlAttr, value: *const xmlChar) -> c_int {
8358    crate::xml::validation::add_id_safe(attr, value)
8359}
8360
8361/// Free an ID hash table.
8362///
8363/// # UPSTREAM-PARITY
8364///
8365/// ```c
8366/// void xmlFreeIDTable(xmlIDTablePtr table);
8367/// ```
8368#[no_mangle]
8369pub unsafe extern "C" fn xmlFreeIDTable(table: *mut c_void) {
8370    crate::xml::validation::free_id_table(table as *mut crate::xml::hash::HashTable);
8371}
8372
8373/// Free an IDREF hash table.
8374///
8375/// # UPSTREAM-PARITY
8376///
8377/// ```c
8378/// void xmlFreeRefTable(xmlRefTablePtr table);
8379/// ```
8380#[no_mangle]
8381pub unsafe extern "C" fn xmlFreeRefTable(table: *mut c_void) {
8382    crate::xml::validation::free_ref_table(table as *mut crate::xml::hash::HashTable);
8383}
8384
8385/// Look up the attribute holding an ID.
8386///
8387/// # UPSTREAM-PARITY
8388///
8389/// ```c
8390/// xmlAttrPtr xmlGetID(xmlDocPtr doc, const xmlChar *ID);
8391/// ```
8392#[no_mangle]
8393pub unsafe extern "C" fn xmlGetID(doc: *mut _xmlDoc, id: *const xmlChar) -> *mut _xmlAttr {
8394    crate::xml::validation::get_id(doc, id)
8395}
8396
8397/// Look up the list of references for an ID.
8398///
8399/// # UPSTREAM-PARITY
8400///
8401/// ```c
8402/// xmlListPtr xmlGetRefs(xmlDocPtr doc, const xmlChar *ID);
8403/// ```
8404#[no_mangle]
8405pub unsafe extern "C" fn xmlGetRefs(doc: *mut _xmlDoc, id: *const xmlChar) -> *mut c_void {
8406    crate::xml::validation::get_refs(doc, id) as *mut c_void
8407}
8408
8409/// Is this attribute an ID?
8410///
8411/// # UPSTREAM-PARITY
8412///
8413/// ```c
8414/// int xmlIsID(xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr);
8415/// ```
8416#[no_mangle]
8417pub unsafe extern "C" fn xmlIsID(
8418    doc: *mut _xmlDoc,
8419    elem: *mut _xmlNode,
8420    attr: *mut _xmlAttr,
8421) -> c_int {
8422    crate::xml::validation::is_id(doc, elem, attr)
8423}
8424
8425/// Is this attribute an IDREF?
8426///
8427/// # UPSTREAM-PARITY
8428///
8429/// ```c
8430/// int xmlIsRef(xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr);
8431/// ```
8432#[no_mangle]
8433pub unsafe extern "C" fn xmlIsRef(
8434    doc: *mut _xmlDoc,
8435    elem: *mut _xmlNode,
8436    attr: *mut _xmlAttr,
8437) -> c_int {
8438    crate::xml::validation::is_ref(doc, elem, attr)
8439}
8440
8441/// Search a DTD for an element declaration (with QName splitting).
8442///
8443/// # UPSTREAM-PARITY
8444///
8445/// ```c
8446/// xmlElementPtr xmlGetDtdElementDesc(xmlDtdPtr dtd, const xmlChar *name);
8447/// ```
8448#[no_mangle]
8449pub unsafe extern "C" fn xmlGetDtdElementDesc(
8450    dtd: *mut _xmlDtd,
8451    name: *const xmlChar,
8452) -> *mut _xmlElement {
8453    crate::xml::validation::get_dtd_element_desc(dtd, name)
8454}
8455
8456/// Search a DTD for an attribute declaration (with QName splitting).
8457///
8458/// # UPSTREAM-PARITY
8459///
8460/// ```c
8461/// xmlAttributePtr xmlGetDtdAttrDesc(xmlDtdPtr dtd,
8462///                                   const xmlChar *elem,
8463///                                   const xmlChar *name);
8464/// ```
8465#[no_mangle]
8466pub unsafe extern "C" fn xmlGetDtdAttrDesc(
8467    dtd: *mut _xmlDtd,
8468    elem: *const xmlChar,
8469    name: *const xmlChar,
8470) -> *mut _xmlAttribute {
8471    crate::xml::validation::get_dtd_attr_desc(dtd, elem, name)
8472}
8473
8474/// Search a DTD for a qualified element declaration.
8475///
8476/// # UPSTREAM-PARITY
8477///
8478/// ```c
8479/// xmlElementPtr xmlGetDtdQElementDesc(xmlDtdPtr dtd,
8480///                                     const xmlChar *name,
8481///                                     const xmlChar *prefix);
8482/// ```
8483#[no_mangle]
8484pub unsafe extern "C" fn xmlGetDtdQElementDesc(
8485    dtd: *mut _xmlDtd,
8486    name: *const xmlChar,
8487    prefix: *const xmlChar,
8488) -> *mut _xmlElement {
8489    crate::xml::validation::get_dtd_qelement_desc(dtd, name, prefix)
8490}
8491
8492/// Search a DTD for a qualified attribute declaration.
8493///
8494/// # UPSTREAM-PARITY
8495///
8496/// ```c
8497/// xmlAttributePtr xmlGetDtdQAttrDesc(xmlDtdPtr dtd,
8498///                                    const xmlChar *elem,
8499///                                    const xmlChar *name,
8500///                                    const xmlChar *prefix);
8501/// ```
8502#[no_mangle]
8503pub unsafe extern "C" fn xmlGetDtdQAttrDesc(
8504    dtd: *mut _xmlDtd,
8505    elem: *const xmlChar,
8506    name: *const xmlChar,
8507    prefix: *const xmlChar,
8508) -> *mut _xmlAttribute {
8509    crate::xml::validation::get_dtd_qattr_desc(dtd, elem, name, prefix)
8510}
8511
8512/// Search a DTD for a notation declaration.
8513///
8514/// # UPSTREAM-PARITY
8515///
8516/// ```c
8517/// xmlNotationPtr xmlGetDtdNotationDesc(xmlDtdPtr dtd, const xmlChar *name);
8518/// ```
8519#[no_mangle]
8520pub unsafe extern "C" fn xmlGetDtdNotationDesc(
8521    dtd: *mut _xmlDtd,
8522    name: *const xmlChar,
8523) -> *mut _xmlNotation {
8524    crate::xml::validation::get_dtd_notation_desc(dtd, name)
8525}
8526
8527/// Validate the root element of a document.
8528///
8529/// # UPSTREAM-PARITY
8530///
8531/// ```c
8532/// int xmlValidateRoot(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
8533/// ```
8534#[no_mangle]
8535pub unsafe extern "C" fn xmlValidateRoot(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
8536    crate::xml::validation::validate_root(ctxt, doc)
8537}
8538
8539/// Validate element content against its content model.
8540///
8541/// # UPSTREAM-PARITY
8542///
8543/// ```c
8544/// int xmlValidateContent(xmlValidCtxtPtr ctxt,
8545///                        xmlNodePtr node,
8546///                        xmlDocPtr doc);
8547/// ```
8548#[no_mangle]
8549pub unsafe extern "C" fn xmlValidateContent(
8550    ctxt: *mut _xmlValidCtxt,
8551    node: *mut _xmlNode,
8552    doc: *mut _xmlDoc,
8553) -> c_int {
8554    crate::xml::validation::validate_content(ctxt, node, doc)
8555}
8556
8557/// Check if an element is declared as mixed content.
8558///
8559/// # UPSTREAM-PARITY
8560///
8561/// ```c
8562/// int xmlIsMixedElement(xmlDocPtr doc, const xmlChar *name);
8563/// ```
8564#[no_mangle]
8565pub unsafe extern "C" fn xmlIsMixedElement(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
8566    crate::xml::validation::is_mixed_element(doc, name)
8567}
8568
8569/// Check if an element is declared as EMPTY.
8570///
8571/// # UPSTREAM-PARITY
8572///
8573/// ```c
8574/// int xmlIsEmptyElement(xmlDocPtr doc, const xmlChar *name);
8575/// ```
8576#[no_mangle]
8577pub unsafe extern "C" fn xmlIsEmptyElement(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
8578    crate::xml::validation::is_empty_element(doc, name)
8579}
8580
8581/// Validate a DTD's declarations.
8582///
8583/// # UPSTREAM-PARITY
8584///
8585/// ```c
8586/// int xmlValidateDtd(xmlValidCtxtPtr ctxt,
8587///                    xmlDocPtr doc,
8588///                    xmlDtdPtr dtd);
8589/// ```
8590#[no_mangle]
8591pub unsafe extern "C" fn xmlValidateDtd(
8592    ctxt: *mut _xmlValidCtxt,
8593    doc: *mut _xmlDoc,
8594    dtd: *mut _xmlDtd,
8595) -> c_int {
8596    crate::xml::validation::validate_dtd(ctxt, doc, dtd)
8597}
8598
8599/// Final DTD validation (ID/IDREF consistency).
8600///
8601/// # UPSTREAM-PARITY
8602///
8603/// ```c
8604/// int xmlValidateDtdFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
8605/// ```
8606#[no_mangle]
8607pub unsafe extern "C" fn xmlValidateDtdFinal(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
8608    crate::xml::validation::validate_dtd_final(ctxt, doc)
8609}
8610
8611/// Validate that a value is in an enumeration.
8612///
8613/// # UPSTREAM-PARITY
8614///
8615/// ```c
8616/// int xmlValidateEnumeration(xmlValidCtxtPtr ctxt,
8617///                            const xmlChar *value,
8618///                            xmlEnumerationPtr tree);
8619/// ```
8620#[no_mangle]
8621pub unsafe extern "C" fn xmlValidateEnumeration(
8622    ctxt: *mut _xmlValidCtxt,
8623    value: *const xmlChar,
8624    tree: *mut _xmlEnumeration,
8625) -> c_int {
8626    crate::xml::validation::validate_enumeration(ctxt, value, tree)
8627}
8628
8629// ═══════════════════════════════════════════════════════════════════════════════
8630// 18. Debug / Miscellaneous
8631// ═══════════════════════════════════════════════════════════════════════════════
8632
8633/// Dump a document to a file for debugging.
8634/// Get the path to the current executable.
8635///
8636/// # UPSTREAM-PARITY
8637///
8638/// ```c
8639/// char *xmlGetBinaryPath(void);
8640/// ```
8641#[no_mangle]
8642pub const extern "C" fn xmlGetBinaryPath() -> *mut c_char {
8643    // Phase 1: STUB
8644    ptr::null_mut()
8645}
8646
8647/// Get the path to the current executable's home directory.
8648///
8649/// # UPSTREAM-PARITY
8650///
8651/// ```c
8652/// char *xmlGetHomeOfBinary(void);
8653/// ```
8654#[no_mangle]
8655pub const extern "C" fn xmlGetHomeOfBinary() -> *mut c_char {
8656    // Phase 1: STUB
8657    ptr::null_mut()
8658}
8659
8660// ═══════════════════════════════════════════════════════════════════════════════
8661// SAX2 default callback entry points (upstream SAX2.c)
8662// ═══════════════════════════════════════════════════════════════════════════════
8663//
8664// These are the public `xmlSAX2*` callback functions that downstream code
8665// installs into `xmlSAXHandler` structures. They are the same implementations
8666// the candidate's default SAX handler uses; exporting them under the
8667// upstream names is required for ABI parity (R-000136 closure).
8668
8669/// Upstream SAX2.c `xmlSAX2StartDocument` — public entry point of the default handler.
8670#[no_mangle]
8671pub unsafe extern "C" fn xmlSAX2StartDocument(ctx: *mut c_void) {
8672    crate::xml::sax::default::default_sax_handler::startDocument(ctx)
8673}
8674
8675/// Upstream SAX2.c `xmlSAX2EndDocument` — public entry point of the default handler.
8676#[no_mangle]
8677pub unsafe extern "C" fn xmlSAX2EndDocument(ctx: *mut c_void) {
8678    crate::xml::sax::default::default_sax_handler::endDocument(ctx)
8679}
8680
8681/// Upstream SAX2.c `xmlSAX2StartElementNs` — public entry point of the default handler.
8682#[no_mangle]
8683pub unsafe extern "C" fn xmlSAX2StartElementNs(
8684    ctx: *mut c_void,
8685    localname: *const xmlChar,
8686    prefix: *const xmlChar,
8687    URI: *const xmlChar,
8688    nb_namespaces: c_int,
8689    namespaces: *mut *const xmlChar,
8690    nb_attributes: c_int,
8691    nb_defaulted: c_int,
8692    attributes: *mut *const xmlChar,
8693) {
8694    crate::xml::sax::default::default_sax_handler::startElementNs(
8695        ctx,
8696        localname,
8697        prefix,
8698        URI,
8699        nb_namespaces,
8700        namespaces,
8701        nb_attributes,
8702        nb_defaulted,
8703        attributes,
8704    )
8705}
8706
8707/// Upstream SAX2.c `xmlSAX2EndElementNs` — public entry point of the default handler.
8708#[no_mangle]
8709pub unsafe extern "C" fn xmlSAX2EndElementNs(
8710    ctx: *mut c_void,
8711    localname: *const xmlChar,
8712    prefix: *const xmlChar,
8713    URI: *const xmlChar,
8714) {
8715    crate::xml::sax::default::default_sax_handler::endElementNs(ctx, localname, prefix, URI)
8716}
8717
8718/// Upstream SAX2.c `xmlSAX2Characters` — public entry point of the default handler.
8719#[no_mangle]
8720pub unsafe extern "C" fn xmlSAX2Characters(ctx: *mut c_void, ch: *const xmlChar, len: c_int) {
8721    crate::xml::sax::default::default_sax_handler::characters(ctx, ch, len)
8722}
8723
8724/// Upstream SAX2.c `xmlSAX2IgnorableWhitespace` — public entry point of the default handler.
8725#[no_mangle]
8726pub unsafe extern "C" fn xmlSAX2IgnorableWhitespace(
8727    ctx: *mut c_void,
8728    ch: *const xmlChar,
8729    len: c_int,
8730) {
8731    crate::xml::sax::default::default_sax_handler::ignorableWhitespace(ctx, ch, len)
8732}
8733
8734/// Upstream SAX2.c `xmlSAX2Comment` — public entry point of the default handler.
8735#[no_mangle]
8736pub unsafe extern "C" fn xmlSAX2Comment(ctx: *mut c_void, value: *const xmlChar) {
8737    crate::xml::sax::default::default_sax_handler::comment(ctx, value)
8738}
8739
8740/// Upstream SAX2.c `xmlSAX2ProcessingInstruction` — public entry point of the default handler.
8741#[no_mangle]
8742pub unsafe extern "C" fn xmlSAX2ProcessingInstruction(
8743    ctx: *mut c_void,
8744    target: *const xmlChar,
8745    data: *const xmlChar,
8746) {
8747    crate::xml::sax::default::default_sax_handler::processingInstruction(ctx, target, data)
8748}
8749
8750/// Upstream SAX2.c `xmlSAX2CDataBlock` — public entry point of the default handler.
8751#[no_mangle]
8752pub unsafe extern "C" fn xmlSAX2CDataBlock(ctx: *mut c_void, value: *const xmlChar, len: c_int) {
8753    crate::xml::sax::default::default_sax_handler::cdataBlock(ctx, value, len)
8754}
8755
8756/// Upstream SAX2.c `xmlSAX2InternalSubset` — public entry point of the default handler.
8757#[no_mangle]
8758pub unsafe extern "C" fn xmlSAX2InternalSubset(
8759    ctx: *mut c_void,
8760    name: *const xmlChar,
8761    ExternalID: *const xmlChar,
8762    SystemID: *const xmlChar,
8763) {
8764    crate::xml::sax::default::default_sax_handler::internalSubset(ctx, name, ExternalID, SystemID)
8765}
8766
8767/// Upstream SAX2.c `xmlSAX2ExternalSubset` — public entry point of the default handler.
8768#[no_mangle]
8769pub unsafe extern "C" fn xmlSAX2ExternalSubset(
8770    ctx: *mut c_void,
8771    name: *const xmlChar,
8772    ExternalID: *const xmlChar,
8773    SystemID: *const xmlChar,
8774) {
8775    crate::xml::sax::default::default_sax_handler::externalSubset(ctx, name, ExternalID, SystemID)
8776}
8777
8778/// Upstream SAX2.c `xmlSAX2EntityDecl` — public entry point of the default handler.
8779#[no_mangle]
8780pub unsafe extern "C" fn xmlSAX2EntityDecl(
8781    ctx: *mut c_void,
8782    name: *const xmlChar,
8783    type_: c_int,
8784    publicId: *const xmlChar,
8785    systemId: *const xmlChar,
8786    content: *mut xmlChar,
8787) {
8788    crate::xml::sax::default::default_sax_handler::entityDecl(
8789        ctx, name, type_, publicId, systemId, content,
8790    )
8791}
8792
8793/// Upstream SAX2.c `xmlSAX2AttributeDecl` — public entry point of the default handler.
8794#[no_mangle]
8795pub const unsafe extern "C" fn xmlSAX2AttributeDecl(
8796    ctx: *mut c_void,
8797    elem: *const xmlChar,
8798    fullname: *const xmlChar,
8799    type_: c_int,
8800    def: c_int,
8801    defaultValue: *const xmlChar,
8802    tree: *mut crate::abi::structs::_xmlEnumeration,
8803) {
8804    crate::xml::sax::default::default_sax_handler::attributeDecl(
8805        ctx,
8806        elem,
8807        fullname,
8808        type_,
8809        def,
8810        defaultValue,
8811        tree,
8812    )
8813}
8814
8815/// Upstream SAX2.c `xmlSAX2ElementDecl` — public entry point of the default handler.
8816#[no_mangle]
8817pub const unsafe extern "C" fn xmlSAX2ElementDecl(
8818    ctx: *mut c_void,
8819    name: *const xmlChar,
8820    type_: c_int,
8821    content: *mut crate::abi::structs::_xmlElementContent,
8822) {
8823    crate::xml::sax::default::default_sax_handler::elementDecl(ctx, name, type_, content)
8824}
8825
8826/// Upstream SAX2.c `xmlSAX2NotationDecl` — public entry point of the default handler.
8827#[no_mangle]
8828pub const unsafe extern "C" fn xmlSAX2NotationDecl(
8829    ctx: *mut c_void,
8830    name: *const xmlChar,
8831    publicId: *const xmlChar,
8832    systemId: *const xmlChar,
8833) {
8834    crate::xml::sax::default::default_sax_handler::notationDecl(ctx, name, publicId, systemId)
8835}
8836
8837/// Upstream SAX2.c `xmlSAX2UnparsedEntityDecl` — public entry point of the default handler.
8838#[no_mangle]
8839pub const unsafe extern "C" fn xmlSAX2UnparsedEntityDecl(
8840    ctx: *mut c_void,
8841    name: *const xmlChar,
8842    publicId: *const xmlChar,
8843    systemId: *const xmlChar,
8844    notationName: *const xmlChar,
8845) {
8846    crate::xml::sax::default::default_sax_handler::unparsedEntityDecl(
8847        ctx,
8848        name,
8849        publicId,
8850        systemId,
8851        notationName,
8852    )
8853}
8854
8855/// Upstream SAX2.c `xmlSAX2ResolveEntity` — public entry point of the default handler.
8856#[no_mangle]
8857pub const unsafe extern "C" fn xmlSAX2ResolveEntity(
8858    ctx: *mut c_void,
8859    publicId: *const xmlChar,
8860    systemId: *const xmlChar,
8861) -> *mut crate::abi::structs::_xmlParserInput {
8862    crate::xml::sax::default::default_sax_handler::resolveEntity(ctx, publicId, systemId)
8863}
8864
8865/// Upstream SAX2.c `xmlSAX2IsStandalone` — public entry point of the default handler.
8866#[no_mangle]
8867pub const unsafe extern "C" fn xmlSAX2IsStandalone(ctx: *mut c_void) -> c_int {
8868    crate::xml::sax::default::default_sax_handler::isStandalone(ctx)
8869}
8870
8871/// Upstream SAX2.c `xmlSAX2HasInternalSubset` — public entry point of the default handler.
8872#[no_mangle]
8873pub unsafe extern "C" fn xmlSAX2HasInternalSubset(ctx: *mut c_void) -> c_int {
8874    crate::xml::sax::default::default_sax_handler::hasInternalSubset(ctx)
8875}
8876
8877/// Upstream SAX2.c `xmlSAX2HasExternalSubset` — public entry point of the default handler.
8878#[no_mangle]
8879pub unsafe extern "C" fn xmlSAX2HasExternalSubset(ctx: *mut c_void) -> c_int {
8880    crate::xml::sax::default::default_sax_handler::hasExternalSubset(ctx)
8881}
8882
8883/// Upstream SAX2.c `xmlSAX2GetEntity` — public entry point of the default handler.
8884#[no_mangle]
8885pub unsafe extern "C" fn xmlSAX2GetEntity(
8886    ctx: *mut c_void,
8887    name: *const xmlChar,
8888) -> *mut crate::abi::structs::_xmlEntity {
8889    crate::xml::sax::default::default_sax_handler::getEntity(ctx, name)
8890}
8891
8892/// Upstream SAX2.c `xmlSAX2GetParameterEntity` — public entry point of the default handler.
8893#[no_mangle]
8894pub unsafe extern "C" fn xmlSAX2GetParameterEntity(
8895    ctx: *mut c_void,
8896    name: *const xmlChar,
8897) -> *mut crate::abi::structs::_xmlEntity {
8898    crate::xml::sax::default::default_sax_handler::getParameterEntity(ctx, name)
8899}
8900
8901/// Upstream SAX2.c `xmlSAX2GetLineNumber` — public entry point of the
8902/// default handler (SAX locator callback).
8903#[no_mangle]
8904pub unsafe extern "C" fn xmlSAX2GetLineNumber(ctx: *mut c_void) -> c_int {
8905    crate::xml::sax::default::default_sax_handler::getLineNumber(ctx)
8906}
8907
8908/// Upstream SAX2.c `xmlSAX2GetColumnNumber`.
8909#[no_mangle]
8910pub unsafe extern "C" fn xmlSAX2GetColumnNumber(ctx: *mut c_void) -> c_int {
8911    crate::xml::sax::default::default_sax_handler::getColumnNumber(ctx)
8912}
8913
8914/// Upstream SAX2.c `xmlSAX2GetPublicId`.
8915#[no_mangle]
8916pub const unsafe extern "C" fn xmlSAX2GetPublicId(ctx: *mut c_void) -> *const xmlChar {
8917    crate::xml::sax::default::default_sax_handler::getPublicId(ctx)
8918}
8919
8920/// Upstream SAX2.c `xmlSAX2GetSystemId`.
8921#[no_mangle]
8922pub unsafe extern "C" fn xmlSAX2GetSystemId(ctx: *mut c_void) -> *const xmlChar {
8923    crate::xml::sax::default::default_sax_handler::getSystemId(ctx)
8924}
8925
8926/// Upstream SAX2.c `xmlSAX2StartElement` — SAX1 start-element entry point.
8927/// The candidate parser dispatches through the SAX2 (namespaced) callbacks;
8928/// this wrapper maps to the SAX1 handler when installed.
8929#[no_mangle]
8930pub unsafe extern "C" fn xmlSAX2StartElement(
8931    ctx: *mut c_void,
8932    name: *const xmlChar,
8933    atts: *mut *const xmlChar,
8934) {
8935    // The parser core invokes startElementNs; the SAX1 shim is provided by
8936    // the dispatch layer. When this entry point is installed directly on a
8937    // handler, route through the internal SAX1 path.
8938    crate::xml::sax::dispatch::SaxDispatcher::sax1_start_element(ctx, name, atts);
8939}
8940
8941/// Upstream SAX2.c `xmlSAX2EndElement` — SAX1 end-element entry point.
8942#[no_mangle]
8943pub unsafe extern "C" fn xmlSAX2EndElement(ctx: *mut c_void, name: *const xmlChar) {
8944    crate::xml::sax::dispatch::SaxDispatcher::sax1_end_element(ctx, name);
8945}
8946
8947/// Upstream SAX2.c `xmlSAX2SetDocumentLocator` — public entry point of the default handler.
8948#[no_mangle]
8949pub const unsafe extern "C" fn xmlSAX2SetDocumentLocator(
8950    ctx: *mut c_void,
8951    loc: *mut crate::abi::callbacks::_xmlSAXLocator,
8952) {
8953    crate::xml::sax::default::default_sax_handler::setDocumentLocator(ctx, loc)
8954}
8955
8956/// Upstream SAX2.c `xmlSAX2Reference` — public entry point of the default handler.
8957#[no_mangle]
8958pub unsafe extern "C" fn xmlSAX2Reference(ctx: *mut c_void, name: *const xmlChar) {
8959    crate::xml::sax::default::default_sax_handler::reference(ctx, name)
8960}
8961
8962#[cfg(test)]
8963mod tests {
8964    use super::xml_number_to_string;
8965
8966    /// R-000166: number-to-string follows upstream xmlXPathFormatNumber —
8967    /// verified byte-identical against the oracle (xsltproc) on the t4/n3
8968    /// differential corpora. Cases here are exact doubles or
8969    /// rounding-robust formats (parser-dependent literals are covered by the
8970    /// differential corpora, not unit tests).
8971    #[allow(clippy::approx_constant)]
8972    #[test]
8973    fn test_xml_number_to_string_parity_cases() {
8974        let cases: &[(f64, &str)] = &[
8975            (1234567.891, "1234567.891"),
8976            (0.1 + 0.2, "0.3"),
8977            (1.0 / 3.0, "0.333333333333333"),
8978            (1e20, "1e+20"),
8979            (1e-5, "0.00001"),
8980            (123456789012345678901234567890.0, "1.23456789012346e+29"),
8981            (1e100, "1e+100"),
8982            (-1e100, "-1e+100"),
8983            (1.5e-100, "1.5e-100"),
8984            (1e9, "1000000000"),
8985            (0.00001, "0.00001"),
8986            (9.99e-6, "9.99e-06"),
8987            (2147483646.0, "2147483646"),
8988            (2147483648.0, "2.147483648e+09"),
8989            (-2147483647.0, "-2147483647"),
8990            (-2147483649.0, "-2.147483649e+09"),
8991            (0.5, "0.5"),
8992            (1.0 / 7.0, "0.142857142857143"),
8993            (2.675, "2.675"),
8994            (3.141592653589793, "3.141592653589793"),
8995            (-0.0, "0"),
8996            (0.0, "0"),
8997            (f64::INFINITY, "Infinity"),
8998            (f64::NEG_INFINITY, "-Infinity"),
8999            (f64::NAN, "NaN"),
9000            (0.30000000000000004, "0.3"),
9001            (2.2250738585072014e-308, "2.2250738585072e-308"),
9002            (5e-324, "4.94065645841247e-324"),
9003        ];
9004        for (n, expected) in cases {
9005            assert_eq!(&xml_number_to_string(*n), expected, "value: {}", n);
9006        }
9007    }
9008
9009    /// xmlNewChild with a non-NULL content creates the element and appends a
9010    /// text child (upstream tree.c xmlNewChild -> xmlNewDocNode ->
9011    /// xmlNewDocText + xmlAddChild; tree2.c relies on it — Phase-12
9012    /// EXTERNAL-CONSUMERS court).
9013    ///
9014    /// # Safety
9015    ///
9016    /// - The doc and nodes are created and freed exactly once within the
9017    ///   test; pointers are asserted non-NULL before dereference.
9018    #[test]
9019    fn test_xml_new_child_with_content() {
9020        unsafe {
9021            let doc =
9022                crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9023            assert!(!doc.is_null());
9024            let root = crate::xml::tree::new_node(
9025                core::ptr::null_mut(),
9026                c"root".as_ptr() as *const crate::abi::types::xmlChar,
9027            );
9028            assert!(!root.is_null());
9029            crate::xml::tree::doc_set_root_element(doc, root);
9030
9031            let child = super::xmlNewChild(
9032                root,
9033                core::ptr::null_mut(),
9034                c"node1".as_ptr() as *const crate::abi::types::xmlChar,
9035                c"content of node 1".as_ptr() as *const crate::abi::types::xmlChar,
9036            );
9037            assert!(!child.is_null());
9038            assert!(
9039                !(*child).children.is_null(),
9040                "content must become a text child"
9041            );
9042            assert_eq!(
9043                crate::abi::types::xmlElementType::XML_TEXT_NODE as i32,
9044                (*(*child).children).type_
9045            );
9046            let text = crate::xml::string::xmlstr_to_bytes((*(*child).children).content);
9047            assert_eq!(text, b"content of node 1");
9048
9049            // NULL content stays childless
9050            let empty = super::xmlNewChild(
9051                root,
9052                core::ptr::null_mut(),
9053                c"node2".as_ptr() as *const crate::abi::types::xmlChar,
9054                core::ptr::null(),
9055            );
9056            assert!(!empty.is_null());
9057            assert!((*empty).children.is_null());
9058
9059            crate::xml::tree::free_doc(doc);
9060        }
9061    }
9062
9063    /// xmlNewChild content is parsed as an ATTRIBUTE VALUE (upstream tree.c
9064    /// xmlNewChild -> xmlNewDocNode -> xmlNewElem -> xmlNodeParseAttValue):
9065    /// an EMPTY content adds NO text child (`<bar/>`, SimpleXML bug76712),
9066    /// character references are decoded (`a &#38; b` -> `a & b`, SimpleXML
9067    /// bug44478) and a declared general entity becomes an entity-ref child.
9068    /// The old raw text storage appended an empty text node for "" and kept
9069    /// the reference text verbatim.
9070    ///
9071    /// # Safety
9072    ///
9073    /// - doc/root/child are created and freed exactly once; the text child
9074    ///   content string is read while live.
9075    #[test]
9076    fn test_xml_new_child_parses_content_as_att_value() {
9077        unsafe {
9078            let doc =
9079                crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9080            assert!(!doc.is_null());
9081            let root = crate::xml::tree::new_node(
9082                core::ptr::null_mut(),
9083                c"root".as_ptr() as *const crate::abi::types::xmlChar,
9084            );
9085            assert!(!root.is_null());
9086            crate::xml::tree::doc_set_root_element(doc, root);
9087
9088            // Empty content -> NO text child (upstream value[0] == 0 early
9089            // out); serializes as `<empty/>`.
9090            let e = super::xmlNewChild(
9091                root,
9092                core::ptr::null_mut(),
9093                c"empty".as_ptr() as *const crate::abi::types::xmlChar,
9094                c"".as_ptr() as *const crate::abi::types::xmlChar,
9095            );
9096            assert!(!e.is_null());
9097            assert!(
9098                (*e).children.is_null(),
9099                "empty content must not add a text child"
9100            );
9101
9102            // Character reference content is DECODED into the text child.
9103            let r = super::xmlNewChild(
9104                root,
9105                core::ptr::null_mut(),
9106                c"ref".as_ptr() as *const crate::abi::types::xmlChar,
9107                c"a &#38; b".as_ptr() as *const crate::abi::types::xmlChar,
9108            );
9109            assert!(!r.is_null());
9110            assert!(!(*r).children.is_null());
9111            let txt = crate::xml::string::xmlstr_to_bytes((*(*r).children).content);
9112            assert_eq!(txt, b"a & b");
9113
9114            // A bare '&' (no terminating ';') consumes the '&' and keeps the
9115            // rest as text (upstream xmlNodeParseAttValue, "x & y" -> "x  y").
9116            let b = super::xmlNewChild(
9117                root,
9118                core::ptr::null_mut(),
9119                c"bare".as_ptr() as *const crate::abi::types::xmlChar,
9120                c"x & y".as_ptr() as *const crate::abi::types::xmlChar,
9121            );
9122            assert!(!b.is_null());
9123            assert!(!(*b).children.is_null());
9124            let txt = crate::xml::string::xmlstr_to_bytes((*(*b).children).content);
9125            assert_eq!(txt, b"x  y");
9126
9127            crate::xml::tree::free_doc(doc);
9128        }
9129    }
9130
9131    /// Phase 14.3 Bug-2 regression: `xmlFreeProp` must not free a
9132    /// dict-interned attribute name. PHP's SimpleXML unset path
9133    /// (`sxe_unlink_node` -> `php_libxml_node_free` -> `xmlFreeProp`) frees an
9134    /// attribute whose name the parser interned in the document dictionary;
9135    /// the pre-fix `free_prop_impl` freed the interned string, and
9136    /// `xmlDictFree` at doc teardown freed it again (double free). Mirrors the
9137    /// PHP sequence: unlink the attribute, free it via `xmlFreeProp`, then
9138    /// free the document.
9139    ///
9140    /// # Safety
9141    ///
9142    /// - doc/dict/root/attr are built and freed exactly once; a double free
9143    ///   (the bug) aborts the test process under glibc tcache detection.
9144    #[test]
9145    fn test_xml_free_prop_preserves_dict_interned_attr_name() {
9146        unsafe {
9147            use crate::abi::allocator::xmlMallocZero;
9148            use crate::abi::structs::{_xmlAttr, _xmlNode};
9149            use core::mem::size_of;
9150
9151            let dict = super::xmlDictCreate();
9152            assert!(!dict.is_null());
9153            let doc =
9154                crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9155            assert!(!doc.is_null());
9156            (*doc).dict = dict;
9157            let root = crate::xml::tree::new_node(
9158                core::ptr::null_mut(),
9159                c"root".as_ptr() as *const crate::abi::types::xmlChar,
9160            );
9161            assert!(!root.is_null());
9162            crate::xml::tree::doc_set_root_element(doc, root);
9163
9164            // Intern the attribute name exactly as the dictNames parser does.
9165            let iname = super::xmlDictLookup(
9166                dict,
9167                c"id".as_ptr() as *const crate::abi::types::xmlChar,
9168                -1,
9169            );
9170            assert!(!iname.is_null());
9171
9172            // Build the attribute node with the borrowed dict-interned name
9173            // (mirrors parser_set_prop attribute creation).
9174            let attr = xmlMallocZero(size_of::<_xmlAttr>()) as *mut _xmlAttr;
9175            assert!(!attr.is_null());
9176            (*attr).type_ = crate::abi::types::xmlElementType::XML_ATTRIBUTE_NODE as i32;
9177            (*attr).name = iname as *mut crate::abi::types::xmlChar;
9178            (*attr).parent = root;
9179            (*attr).doc = doc;
9180            (*root).properties = attr;
9181
9182            // PHP SimpleXML unset: xmlUnlinkNode(attr) then xmlFreeProp(attr).
9183            crate::xml::tree::unlink_node(attr as *mut _xmlNode);
9184            crate::abi::exports_tree::xmlFreeProp(attr);
9185
9186            // Teardown: xmlDictFree reaches refcount 0 and frees the interned
9187            // string once. A pre-fix double free aborts here.
9188            crate::xml::tree::free_doc(doc);
9189        }
9190    }
9191
9192    /// Phase 14.3 regression: `xmlNodeListGetString` over a non-text node
9193    /// list must return a NUL-terminated EMPTY string. The pre-fix
9194    /// `xml_strdup(b"")` idiom handed xml_strdup a dangling 0x1 pointer
9195    /// (Rust zero-length byte-string literal), crashing in xml_strlen when
9196    /// SimpleXML string-casts an element whose children produce no text
9197    /// (ext/simplexml 027/028).
9198    ///
9199    /// # Safety
9200    ///
9201    /// - doc/root/person are built and freed exactly once; returned strings
9202    ///   are freed with `xmlFreeImpl`.
9203    #[test]
9204    fn test_nodelist_getstring_empty_from_element_chain() {
9205        unsafe {
9206            let doc =
9207                crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9208            assert!(!doc.is_null());
9209            let root = crate::xml::tree::new_node(
9210                core::ptr::null_mut(),
9211                c"people".as_ptr() as *const crate::abi::types::xmlChar,
9212            );
9213            assert!(!root.is_null());
9214            crate::xml::tree::doc_set_root_element(doc, root);
9215            let person = crate::abi::exports_tree::xmlNewTextChild(
9216                root,
9217                core::ptr::null_mut(),
9218                c"person".as_ptr() as *const crate::abi::types::xmlChar,
9219                c"Joe".as_ptr() as *const crate::abi::types::xmlChar,
9220            );
9221            assert!(!person.is_null());
9222            super::xmlSetProp(
9223                person,
9224                c"gender".as_ptr() as *const crate::abi::types::xmlChar,
9225                c"male".as_ptr() as *const crate::abi::types::xmlChar,
9226            );
9227
9228            // Element list head yields an empty string (pre-fix: crash).
9229            let s1 = crate::abi::exports_treedump::xmlNodeListGetString(doc, (*root).children, 1);
9230            assert!(!s1.is_null());
9231            assert_eq!(*s1 as u8, 0);
9232            crate::abi::allocator::xmlFreeImpl(s1 as *mut core::ffi::c_void);
9233
9234            // Text child list yields the element text.
9235            let s2 = crate::abi::exports_treedump::xmlNodeListGetString(doc, (*person).children, 1);
9236            assert!(!s2.is_null());
9237            let b = crate::xml::string::xmlstr_to_bytes(s2);
9238            assert_eq!(b, b"Joe");
9239            crate::abi::allocator::xmlFreeImpl(s2 as *mut core::ffi::c_void);
9240
9241            crate::xml::tree::free_doc(doc);
9242        }
9243    }
9244
9245    /// Phase 14.3 (simplexml S3 / ext/simplexml 008): with no structured
9246    /// handler, a failed XPath compile delivers the message VERBATIM to the
9247    /// generic channel — upstream xpath.c xmlXPathErrFmt sets
9248    /// `channel = xmlGenericError; data = xmlGenericErrorContext`, and
9249    /// xmlVRaiseError calls `channel(data, "%s", to->message)` because the
9250    /// generic channel is NOT one of the parser channels that trigger
9251    /// xmlFormatError's fragment stream (which would prefix "XPath error :").
9252    /// PHP installs a generic handler at request start (php_libxml_issue_
9253    /// warning), so the raw text "Invalid expression\n" must arrive alone;
9254    /// a pre-fix `GenericDelivery::Stream` reached PHP's handler with the
9255    /// fragment prefix and ext/simplexml 008 warned "XPath error : Invalid
9256    /// expression".
9257    ///
9258    /// # Safety
9259    ///
9260    /// - doc/ctxt are created and freed exactly once; `captured` lives on
9261    ///   the stack for the duration of the call; the generic handler slot is
9262    ///   restored to the default printer before the test ends.
9263    #[test]
9264    fn test_xpath_compile_error_verbatim_to_generic_channel() {
9265        use crate::abi::callbacks::xmlGenericErrorFunc;
9266        use core::ffi::{c_char, c_void};
9267
9268        // Serialized against the handler-slot tests in xml::globals (11.1-X)
9269        // and xml::errors: the generic handler slot is shared global state.
9270        let _guard = crate::xml::globals::ERROR_HANDLER_TEST_LOCK.lock();
9271        unsafe {
9272            let mut captured: Vec<u8> = Vec::new();
9273            let captured_ptr = &mut captured as *mut Vec<u8> as *mut c_void;
9274
9275            unsafe extern "C" fn record(ctx: *mut c_void, msg: *const c_char) {
9276                if msg.is_null() {
9277                    return;
9278                }
9279                let out = &mut *(ctx as *mut Vec<u8>);
9280                let bytes = std::ffi::CStr::from_ptr(msg).to_bytes();
9281                out.extend_from_slice(bytes);
9282            }
9283
9284            super::xmlSetGenericErrorFunc(captured_ptr, Some(record as xmlGenericErrorFunc));
9285
9286            let doc =
9287                crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9288            assert!(!doc.is_null());
9289            let ctxt = super::xmlXPathNewContext(doc);
9290            assert!(!ctxt.is_null());
9291            // No structured handler on the context (ctxt->error stays NULL)
9292            // so the generic channel is the delivery target.
9293            (*ctxt).error = None;
9294
9295            let comp = crate::xml::xpath::exports::xmlXPathCtxtCompile(
9296                ctxt,
9297                c"**".as_ptr() as *const crate::abi::types::xmlChar,
9298            );
9299            assert!(comp.is_null(), "`**` must fail to compile");
9300
9301            assert_eq!(
9302                captured, b"Invalid expression\n",
9303                "generic channel must receive the raw message, no \"XPath error : \" prefix"
9304            );
9305
9306            // Restore the generic handler slot to the default printer.
9307            super::xmlSetGenericErrorFunc(core::ptr::null_mut(), None);
9308            super::xmlXPathFreeContext(ctxt);
9309            crate::xml::tree::free_doc(doc);
9310        }
9311    }
9312
9313    /// Phase 14.3 (simplexml S7 / bug63575): node/document copies must NOT
9314    /// carry the source `_private` — upstream xmlStaticCopyNode zeroes the
9315    /// new node and xmlCopyNamespaceList never copies _private. PHP keys its
9316    /// wrapper registrations on `_private` (php_libxml_node_ptr), so a
9317    /// copied subtree that inherits the original's registrations binds the
9318    /// clone to the ORIGINAL document: SimpleXML root-element clone
9319    /// (xmlCopyDoc) then resolved XPath and mutations into the original's
9320    /// tree. The copy must look UNREGISTERED.
9321    ///
9322    /// # Safety
9323    ///
9324    /// - doc/root/marker are created and freed exactly once within the test;
9325    ///   pointers are asserted non-NULL before dereference.
9326    #[test]
9327    fn test_copies_do_not_carry_private() {
9328        unsafe {
9329            let doc =
9330                crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9331            assert!(!doc.is_null());
9332            let root = crate::xml::tree::new_node(
9333                core::ptr::null_mut(),
9334                c"a".as_ptr() as *const crate::abi::types::xmlChar,
9335            );
9336            assert!(!root.is_null());
9337            crate::xml::tree::doc_set_root_element(doc, root);
9338
9339            // PHP-style registration marker on the SOURCE node.
9340            let marker: usize = 0x5A5A;
9341            (*root)._private = marker as *mut core::ffi::c_void;
9342
9343            // xmlCopyDoc: the new root must be unregistered.
9344            let cdoc = super::xmlCopyDoc(doc, 1);
9345            assert!(!cdoc.is_null());
9346            let croot = (*cdoc).children;
9347            assert!(!croot.is_null());
9348            assert!(
9349                (*croot)._private.is_null(),
9350                "xmlCopyDoc must not carry the source node _private"
9351            );
9352            assert_eq!(
9353                (*root)._private as usize,
9354                marker,
9355                "source _private is untouched"
9356            );
9357            crate::xml::tree::free_doc(cdoc);
9358
9359            // xmlDocCopyNode into the same doc: the copy must be unregistered.
9360            let copy = crate::abi::exports_treedump::xmlDocCopyNode(root, doc, 1);
9361            assert!(!copy.is_null());
9362            assert!(
9363                (*copy)._private.is_null(),
9364                "xmlDocCopyNode must not carry the source node's _private"
9365            );
9366            // The detached copy owns a duplicated name string: free it
9367            // directly, then the document.
9368            super::xmlFreeNode(copy);
9369            crate::xml::tree::free_doc(doc);
9370        }
9371    }
9372
9373    /// The C-extension-function bridge must expose the invoked function's
9374    /// LOCAL name and namespace URI on `ctxt->context->function` /
9375    /// `functionURI` for the duration of the call, and restore the previous
9376    /// values afterwards (upstream xpath.c xmlXPathCompOpEval, XPATH_OP_
9377    /// FUNCTION). PHP registers ONE trampoline for every custom-namespace
9378    /// XPath function and dispatches to the PHP closure from those two
9379    /// fields — without them the dom/xsl php:function callbacks dereference
9380    /// garbage (SP-14.3.6-dom O1: return_dom_node_from_xpath /
9381    /// registerPhpFunctionNS / gh22077 segv).
9382    ///
9383    /// # Safety
9384    ///
9385    /// - doc/ctxt/result are created and freed exactly once; the callback
9386    ///   reads only the two fields the bridge must set.
9387    #[test]
9388    fn test_c_xpath_function_bridge_exposes_function_and_uri() {
9389        unsafe {
9390            use crate::xml::xpath::exports::{xmlXPathNewString, xmlXPathValuePush};
9391            use crate::xml::xpath::parser_context::XmlXPathParserContext;
9392            use std::os::raw::{c_char, c_int};
9393
9394            /// Mirrors PHP's dom_xpath_ext_fetch_intern: read the function
9395            /// identity the invoker set on the context.
9396            unsafe extern "C" fn capture_identity(ctxt: *mut core::ffi::c_void, _nargs: c_int) {
9397                let pc = ctxt as *mut XmlXPathParserContext;
9398                let ctx = (*pc).context;
9399                assert!(!ctx.is_null());
9400                let name = (*ctx).function;
9401                let uri = (*ctx).functionURI;
9402                assert!(!name.is_null());
9403                let name_s = std::ffi::CStr::from_ptr(name as *const c_char)
9404                    .to_string_lossy()
9405                    .into_owned();
9406                let uri_s = if uri.is_null() {
9407                    "(null)".to_string()
9408                } else {
9409                    std::ffi::CStr::from_ptr(uri as *const c_char)
9410                        .to_string_lossy()
9411                        .into_owned()
9412                };
9413                let out = std::ffi::CString::new(format!("{}@{}", name_s, uri_s)).unwrap();
9414                let obj = xmlXPathNewString(out.as_ptr() as *const crate::abi::types::xmlChar);
9415                assert!(!obj.is_null());
9416                assert_eq!(xmlXPathValuePush(ctxt, obj), 0);
9417            }
9418
9419            let doc =
9420                crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9421            assert!(!doc.is_null());
9422            let ctxt = super::xmlXPathNewContext(doc);
9423            assert!(!ctxt.is_null());
9424
9425            super::xmlXPathRegisterNs(
9426                ctxt,
9427                c"t".as_ptr() as *const crate::abi::types::xmlChar,
9428                c"urn:t".as_ptr() as *const crate::abi::types::xmlChar,
9429            );
9430            super::xmlXPathRegisterFuncNS(
9431                ctxt,
9432                c"capture".as_ptr() as *const crate::abi::types::xmlChar,
9433                c"urn:t".as_ptr() as *const crate::abi::types::xmlChar,
9434                Some(capture_identity),
9435            );
9436
9437            let res = super::xmlXPathEvalExpression(
9438                c"t:capture()".as_ptr() as *const crate::abi::types::xmlChar,
9439                ctxt,
9440            );
9441            assert!(!res.is_null());
9442            let s = crate::xml::string::xmlstr_to_bytes((*res).stringval);
9443            assert_eq!(
9444                s, b"capture@urn:t",
9445                "bridge must set context->function (local name) and ->functionURI (ns)"
9446            );
9447            super::xmlXPathFreeObject(res);
9448            super::xmlXPathFreeContext(ctxt);
9449            crate::xml::tree::free_doc(doc);
9450        }
9451    }
9452}