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 & 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 ( is 5; "
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"<",
2523 b'>' => b">",
2524 b'&' => b"&",
2525 b'"' => b""",
2526 b'\r' => b" ",
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 ->
2807 // xmlNewInputFromFile): the registered
2808 // xmlParserInputBufferCreateFilenameDefault (php streams loader) is
2809 // consulted first; a NULL loader result raises xmlCtxtErrIO — "I/O
2810 // warning : failed to load \"%s\": %s\n" — and the load fails.
2811 let input = match crate::abi::exports_parser::open_filename_routed(URL) {
2812 crate::abi::exports_parser::RoutedFileOpen::Loaded(i) => i,
2813 crate::abi::exports_parser::RoutedFileOpen::Failed => {
2814 crate::abi::exports_parser::emit_io_warning(
2815 ctxt,
2816 crate::abi::exports_parser::io_load_failure_message(URL),
2817 );
2818 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2819 return ptr::null_mut();
2820 }
2821 crate::abi::exports_parser::RoutedFileOpen::Builtin => {
2822 match crate::xml::parser::helpers::input_from_file(URL) {
2823 Ok(input) => input,
2824 Err(_) => {
2825 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2826 return ptr::null_mut();
2827 }
2828 }
2829 }
2830 };
2831 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2832 (*ctxt).options = options;
2833 if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
2834 let doc = (*ctxt).myDoc;
2835 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2836 // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
2837 // partially built document is discarded and NULL is returned; with
2838 // XML_PARSE_RECOVER the partial tree is kept.
2839 if options & 1 << 0 != 0 {
2840 return doc;
2841 }
2842 if !doc.is_null() {
2843 crate::xml::tree::free_doc(doc);
2844 }
2845 return ptr::null_mut();
2846 }
2847 let doc = (*ctxt).myDoc;
2848 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2849 doc
2850}
2851
2852/// Recover-parse a document from a string (upstream parser.h): same as
2853/// `xmlReadDoc` with XML_PARSE_RECOVER forced.
2854///
2855/// # UPSTREAM-PARITY
2856///
2857/// ```c
2858/// xmlDocPtr xmlRecoverDoc(const xmlChar *cur);
2859/// ```
2860#[no_mangle]
2861pub unsafe extern "C" fn xmlRecoverDoc(cur: *const xmlChar) -> *mut _xmlDoc {
2862 unsafe { xmlReadDoc(cur, ptr::null(), ptr::null(), 1 << 0) }
2863}
2864
2865/// Recover-parse a document from a file (upstream parser.h).
2866///
2867/// # UPSTREAM-PARITY
2868///
2869/// ```c
2870/// xmlDocPtr xmlRecoverFile(const char *filename);
2871/// ```
2872#[no_mangle]
2873pub unsafe extern "C" fn xmlRecoverFile(filename: *const c_char) -> *mut _xmlDoc {
2874 unsafe { xmlReadFile(filename, ptr::null(), 1 << 0) }
2875}
2876
2877/// Recover-parse a document from memory (upstream parser.h).
2878///
2879/// # UPSTREAM-PARITY
2880///
2881/// ```c
2882/// xmlDocPtr xmlRecoverMemory(const char *buffer, int size);
2883/// ```
2884#[no_mangle]
2885pub unsafe extern "C" fn xmlRecoverMemory(buffer: *const c_char, size: c_int) -> *mut _xmlDoc {
2886 unsafe { xmlReadMemory(buffer, size, ptr::null(), ptr::null(), 1 << 0) }
2887}
2888
2889/// Read an XML document from a file (upstream parser.h).
2890/// Canonically record an explicit input `encoding` on `doc->encoding` when
2891/// the caller supplied one and the document has no encoding of its own.
2892///
2893/// Mirrors upstream: the encoding name is canonicalized via the encoding
2894/// handler table (so `utf-8`/`UTF8` become `UTF-8`, `latin1` becomes
2895/// `ISO-8859-1`, …) rather than stored verbatim.
2896///
2897/// # SAFETY
2898///
2899/// - `doc` must be a valid `_xmlDoc` with a NULL `encoding` field.
2900/// - `encoding` must be a valid NUL-terminated C string.
2901unsafe fn canonical_doc_encoding(doc: *mut _xmlDoc, encoding: *const c_char) {
2902 let handler = crate::xml::encoding::xmlFindCharEncodingHandler(encoding);
2903 if handler.is_null() {
2904 return;
2905 }
2906 // SAFETY: handler is non-NULL; name is a NUL-terminated owned buffer.
2907 let name = unsafe { (*handler).name }; // *mut c_char
2908 if name.is_null() {
2909 return;
2910 }
2911 // SAFETY: name is a valid NUL-terminated string; caller frees via xmlFree.
2912 unsafe {
2913 (*doc).encoding = crate::xml::string::xml_strdup(name as *const xmlChar);
2914 }
2915}
2916
2917/// Parse an XML document from a C memory buffer.
2918///
2919/// # UPSTREAM-PARITY
2920///
2921/// ```c
2922/// xmlDocPtr xmlReadMemory(const char *buffer, int size,
2923/// const char *URL, const char *encoding, int options);
2924/// ```
2925#[no_mangle]
2926pub unsafe extern "C" fn xmlReadMemory(
2927 buffer: *const c_char,
2928 size: c_int,
2929 URL: *const c_char,
2930 encoding: *const c_char,
2931 options: c_int,
2932) -> *mut _xmlDoc {
2933 // SAFETY: buffer must be a valid pointer with at least `size` readable
2934 // bytes. An empty input (size 0) is still parsed — upstream reports
2935 // "Document is empty".
2936 if buffer.is_null() || size < 0 {
2937 return ptr::null_mut();
2938 }
2939 // UPSTREAM-PARITY + HOSTILE-ABI hardening (parser.c 2.15 xmlReadMemory):
2940 // upstream only rejects `size < 0` and then streams from the caller's
2941 // buffer, so a size at or beyond INT_MAX turns into an unsized wild read
2942 // (the oracle's own outcome for xmlReadMemory("<a/>", INT_MAX, ...) is a
2943 // NULL document — or a crash of the oracle itself depending on the heap
2944 // layout). The candidate rejects such sizes up front instead of copying
2945 // ~2 GiB from the caller's buffer; the observable result matches the
2946 // oracle's deterministic probe outcome (HOSTILE-ABI D1).
2947 if size == c_int::MAX {
2948 return ptr::null_mut();
2949 }
2950 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
2951 if ctxt.is_null() {
2952 return ptr::null_mut();
2953 }
2954 // UPSTREAM-PARITY: the URL becomes the input's filename (feeds the
2955 // `file:line:` error prefix and doc->URL).
2956 let input = crate::xml::parser::helpers::input_from_memory_named(buffer, size, URL);
2957 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
2958 // UPSTREAM-PARITY (xmlReadMemory -> xmlCtxtReadMemory): the parse
2959 // options are mirrored into the context members (dictNames, keepBlanks,
2960 // recovery, ...) before parsing starts.
2961 crate::abi::exports_parser::apply_options(ctxt, options);
2962 let parsed = crate::xml::parser::helpers::parse_document(ctxt);
2963 let doc = (*ctxt).myDoc;
2964 // UPSTREAM-PARITY: the URL is attached to the document on success AND on
2965 // the recovery path (the partial tree keeps the document identity).
2966 if !doc.is_null() && !URL.is_null() && (*doc).URL.is_null() {
2967 (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
2968 }
2969 // UPSTREAM-PARITY (xmlCtxtReadMemory): an explicit `encoding` argument
2970 // is recorded on the document when the document carries no encoding
2971 // declaration of its own, so `doc->encoding` (nokogiri Document#encoding)
2972 // reflects what the caller requested.
2973 if !doc.is_null() && (*doc).encoding.is_null() && !encoding.is_null() {
2974 canonical_doc_encoding(doc, encoding);
2975 }
2976 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
2977 if parsed != 0 {
2978 // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
2979 // partially built document is discarded and NULL is returned; with
2980 // XML_PARSE_RECOVER the partial tree is kept.
2981 if options & 1 << 0 != 0 {
2982 return doc;
2983 }
2984 if !doc.is_null() {
2985 crate::xml::tree::free_doc(doc);
2986 }
2987 return ptr::null_mut();
2988 }
2989 doc
2990}
2991
2992/// Load a list of catalogs (upstream `xmlLoadCatalogs`).
2993///
2994/// # SAFETY
2995///
2996/// - `catalogs` must be a valid NUL-terminated string or NULL.
2997#[no_mangle]
2998pub unsafe extern "C" fn xmlLoadCatalogs(catalogs: *const c_char) {
2999 if !catalogs.is_null() {
3000 crate::xml::catalog::load_catalog(catalogs);
3001 }
3002}
3003
3004/// Load a single catalog (upstream `xmlLoadCatalog`).
3005///
3006/// # SAFETY
3007///
3008/// - `catalogs` must be a valid NUL-terminated string or NULL.
3009#[no_mangle]
3010pub unsafe extern "C" fn xmlLoadCatalog(catalogs: *const c_char) -> c_int {
3011 // UPSTREAM-PARITY (catalog.c xmlLoadCatalog): returns 0 on success,
3012 // 1 on error (unlike xmlCatalogLoad which returns the catalog handle).
3013 let handle = crate::xml::catalog::load_catalog(catalogs);
3014 if handle.is_null() {
3015 1
3016 } else {
3017 0
3018 }
3019}
3020
3021/// Read an XML document from a file descriptor.
3022///
3023/// # UPSTREAM-PARITY
3024///
3025/// ```c
3026/// xmlDocPtr xmlReadFd(int fd, const char *URL, const char *encoding, int options);
3027/// ```
3028#[no_mangle]
3029pub unsafe extern "C" fn xmlReadFd(
3030 fd: c_int,
3031 URL: *const c_char,
3032 encoding: *const c_char,
3033 options: c_int,
3034) -> *mut _xmlDoc {
3035 // SAFETY: fd must be a valid open file descriptor.
3036 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3037 if ctxt.is_null() {
3038 return ptr::null_mut();
3039 }
3040 // Read all data from the fd
3041 let mut buf = Vec::new();
3042 let mut tmp = [0u8; 4096];
3043 loop {
3044 let n = libc::read(fd, tmp.as_mut_ptr() as *mut c_void, tmp.len());
3045 if n <= 0 {
3046 break;
3047 }
3048 buf.extend_from_slice(&tmp[..n as usize]);
3049 }
3050 let input = crate::xml::parser::helpers::input_from_memory(
3051 buf.as_ptr() as *const c_char,
3052 buf.len() as c_int,
3053 );
3054 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3055 (*ctxt).options = options;
3056 if crate::xml::parser::helpers::parse_document(ctxt) != 0 {
3057 let doc = (*ctxt).myDoc;
3058 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3059 return doc;
3060 }
3061 let doc = (*ctxt).myDoc;
3062 if !doc.is_null() && !URL.is_null() {
3063 (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
3064 }
3065 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3066 doc
3067}
3068
3069/// Read an XML document from I/O callbacks.
3070///
3071/// # UPSTREAM-PARITY
3072///
3073/// ```c
3074/// xmlDocPtr xmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
3075/// void *ioctx, const char *URL, const char *encoding, int options);
3076/// ```
3077#[no_mangle]
3078pub unsafe extern "C" fn xmlReadIO(
3079 ioread: Option<xmlInputReadCallback>,
3080 ioclose: Option<xmlInputCloseCallback>,
3081 ioctx: *mut c_void,
3082 URL: *const c_char,
3083 encoding: *const c_char,
3084 options: c_int,
3085) -> *mut _xmlDoc {
3086 // SAFETY: callbacks must be valid function pointers if non-NULL.
3087 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3088 if ctxt.is_null() {
3089 return ptr::null_mut();
3090 }
3091 let input = crate::xml::parser::helpers::input_from_io(ioread, ioclose, ioctx);
3092 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3093 (*ctxt).options = options;
3094 let parsed = crate::xml::parser::helpers::parse_document(ctxt);
3095 let doc = (*ctxt).myDoc;
3096 // UPSTREAM-PARITY (xmlReadIO -> xmlCtxtReadIO): the URL is attached to the
3097 // document on success AND on the recovery path (the partial tree keeps the
3098 // document identity).
3099 if !doc.is_null() && !URL.is_null() && (*doc).URL.is_null() {
3100 (*doc).URL = crate::xml::string::xml_strdup(URL as *const xmlChar);
3101 }
3102 if !doc.is_null() && (*doc).encoding.is_null() && !encoding.is_null() {
3103 canonical_doc_encoding(doc, encoding);
3104 }
3105 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3106 if parsed != 0 {
3107 // UPSTREAM-PARITY: on a hard (non-recoverable) parse error the
3108 // partially built document is discarded and NULL is returned; only with
3109 // XML_PARSE_RECOVER is the partial tree kept. nokogiri's read_io/strict
3110 // path relies on NULL here to raise a SyntaxError.
3111 if options & 1 << 0 != 0 {
3112 return doc;
3113 }
3114 if !doc.is_null() {
3115 crate::xml::tree::free_doc(doc);
3116 }
3117 return ptr::null_mut();
3118 }
3119 doc
3120}
3121
3122/// Parse an XML document (SAX1).
3123///
3124/// # UPSTREAM-PARITY
3125///
3126/// ```c
3127/// xmlDocPtr xmlSAXParseDoc(xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery);
3128/// ```
3129#[no_mangle]
3130pub unsafe extern "C" fn xmlSAXParseDoc(
3131 sax: *mut _xmlSAXHandler,
3132 cur: *const xmlChar,
3133 recovery: c_int,
3134) -> *mut _xmlDoc {
3135 // SAFETY: cur must be a valid null-terminated xmlChar string.
3136 if cur.is_null() {
3137 return ptr::null_mut();
3138 }
3139 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3140 if ctxt.is_null() {
3141 return ptr::null_mut();
3142 }
3143 if !sax.is_null() {
3144 (*ctxt).sax = sax;
3145 (*ctxt).userData = (*ctxt).sax as *mut c_void;
3146 }
3147 if recovery != 0 {
3148 (*ctxt).recovery = 1;
3149 (*ctxt).options |= 1; // XML_PARSE_RECOVER
3150 }
3151 let len = crate::xml::string::xml_strlen(cur);
3152 let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
3153 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3154 crate::xml::parser::helpers::parse_document(ctxt);
3155 let doc = (*ctxt).myDoc;
3156 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3157 doc
3158}
3159
3160/// Parse an XML document (SAX1) with user data (upstream parser.h
3161/// `xmlSAXParseDocWithData`): `user_data` is passed to the SAX callbacks.
3162///
3163/// # UPSTREAM-PARITY
3164///
3165/// ```c
3166/// xmlDocPtr xmlSAXParseDocWithData(xmlSAXHandlerPtr sax, const xmlChar *cur,
3167/// int recovery, void *data);
3168/// ```
3169#[no_mangle]
3170pub unsafe extern "C" fn xmlSAXParseDocWithData(
3171 sax: *mut _xmlSAXHandler,
3172 cur: *const xmlChar,
3173 recovery: c_int,
3174 data: *mut c_void,
3175) -> *mut _xmlDoc {
3176 // SAFETY: cur must be a valid null-terminated xmlChar string.
3177 if cur.is_null() {
3178 return ptr::null_mut();
3179 }
3180 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3181 if ctxt.is_null() {
3182 return ptr::null_mut();
3183 }
3184 if !sax.is_null() {
3185 (*ctxt).sax = sax;
3186 }
3187 (*ctxt).userData = data;
3188 if recovery != 0 {
3189 (*ctxt).recovery = 1;
3190 (*ctxt).options |= 1; // XML_PARSE_RECOVER
3191 }
3192 let len = crate::xml::string::xml_strlen(cur);
3193 let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
3194 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3195 crate::xml::parser::helpers::parse_document(ctxt);
3196 let doc = (*ctxt).myDoc;
3197 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3198 doc
3199}
3200
3201/// Parse an XML file (SAX1) with user data (upstream parser.h
3202/// `xmlSAXParseFileWithData`).
3203///
3204/// # UPSTREAM-PARITY
3205///
3206/// ```c
3207/// xmlDocPtr xmlSAXParseFileWithData(xmlSAXHandlerPtr sax, const char *filename,
3208/// int recovery, void *data);
3209/// ```
3210#[no_mangle]
3211pub unsafe extern "C" fn xmlSAXParseFileWithData(
3212 sax: *mut _xmlSAXHandler,
3213 filename: *const c_char,
3214 recovery: c_int,
3215 data: *mut c_void,
3216) -> *mut _xmlDoc {
3217 // SAFETY: filename must be a valid C string or NULL.
3218 if filename.is_null() {
3219 return ptr::null_mut();
3220 }
3221 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3222 if ctxt.is_null() {
3223 return ptr::null_mut();
3224 }
3225 if !sax.is_null() {
3226 (*ctxt).sax = sax;
3227 }
3228 (*ctxt).userData = data;
3229 if recovery != 0 {
3230 (*ctxt).recovery = 1;
3231 (*ctxt).options |= 1; // XML_PARSE_RECOVER
3232 }
3233 let input = match crate::abi::exports_parser::open_filename_routed(filename) {
3234 crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3235 crate::abi::exports_parser::RoutedFileOpen::Failed => {
3236 crate::abi::exports_parser::emit_io_warning(
3237 ctxt,
3238 crate::abi::exports_parser::io_load_failure_message(filename),
3239 );
3240 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3241 return ptr::null_mut();
3242 }
3243 crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3244 match crate::xml::parser::helpers::input_from_file(filename) {
3245 Ok(input) => input,
3246 Err(_) => {
3247 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3248 return ptr::null_mut();
3249 }
3250 }
3251 }
3252 };
3253 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3254 crate::xml::parser::helpers::parse_document(ctxt);
3255 let doc = (*ctxt).myDoc;
3256 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3257 doc
3258}
3259
3260/// Parse an XML document (SAX1) with user data from memory (upstream
3261/// parser.h `xmlSAXParseMemoryWithData`).
3262///
3263/// # UPSTREAM-PARITY
3264///
3265/// ```c
3266/// xmlDocPtr xmlSAXParseMemoryWithData(xmlSAXHandlerPtr sax, const char *buffer,
3267/// int size, int recovery, void *data);
3268/// ```
3269#[no_mangle]
3270pub unsafe extern "C" fn xmlSAXParseMemoryWithData(
3271 sax: *mut _xmlSAXHandler,
3272 buffer: *const c_char,
3273 size: c_int,
3274 recovery: c_int,
3275 data: *mut c_void,
3276) -> *mut _xmlDoc {
3277 // SAFETY: buffer must be a valid pointer with `size` readable bytes.
3278 if buffer.is_null() || size <= 0 {
3279 return ptr::null_mut();
3280 }
3281 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3282 if ctxt.is_null() {
3283 return ptr::null_mut();
3284 }
3285 if !sax.is_null() {
3286 (*ctxt).sax = sax;
3287 }
3288 (*ctxt).userData = data;
3289 if recovery != 0 {
3290 (*ctxt).recovery = 1;
3291 (*ctxt).options |= 1; // XML_PARSE_RECOVER
3292 }
3293 let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3294 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3295 crate::xml::parser::helpers::parse_document(ctxt);
3296 let doc = (*ctxt).myDoc;
3297 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3298 doc
3299}
3300
3301/// Parse an XML file (SAX1).
3302///
3303/// # UPSTREAM-PARITY
3304///
3305/// ```c
3306/// xmlDocPtr xmlSAXParseFile(xmlSAXHandlerPtr sax, const char *filename, int recovery);
3307/// ```
3308#[no_mangle]
3309pub unsafe extern "C" fn xmlSAXParseFile(
3310 sax: *mut _xmlSAXHandler,
3311 filename: *const c_char,
3312 recovery: c_int,
3313) -> *mut _xmlDoc {
3314 // SAFETY: filename must be a valid C string.
3315 if filename.is_null() {
3316 return ptr::null_mut();
3317 }
3318 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3319 if ctxt.is_null() {
3320 return ptr::null_mut();
3321 }
3322 if !sax.is_null() {
3323 (*ctxt).sax = sax;
3324 (*ctxt).userData = (*ctxt).sax as *mut c_void;
3325 }
3326 if recovery != 0 {
3327 (*ctxt).recovery = 1;
3328 (*ctxt).options |= 1;
3329 }
3330 let input = match crate::abi::exports_parser::open_filename_routed(filename) {
3331 crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3332 crate::abi::exports_parser::RoutedFileOpen::Failed => {
3333 crate::abi::exports_parser::emit_io_warning(
3334 ctxt,
3335 crate::abi::exports_parser::io_load_failure_message(filename),
3336 );
3337 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3338 return ptr::null_mut();
3339 }
3340 crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3341 match crate::xml::parser::helpers::input_from_file(filename) {
3342 Ok(input) => input,
3343 Err(_) => {
3344 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3345 return ptr::null_mut();
3346 }
3347 }
3348 }
3349 };
3350 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3351 crate::xml::parser::helpers::parse_document(ctxt);
3352 let doc = (*ctxt).myDoc;
3353 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3354 doc
3355}
3356
3357/// Parse an XML document from memory (SAX1).
3358///
3359/// # UPSTREAM-PARITY
3360///
3361/// ```c
3362/// xmlDocPtr xmlSAXParseMemory(xmlSAXHandlerPtr sax,
3363/// const char *buffer, int size, int recovery);
3364/// ```
3365#[no_mangle]
3366pub unsafe extern "C" fn xmlSAXParseMemory(
3367 sax: *mut _xmlSAXHandler,
3368 buffer: *const c_char,
3369 size: c_int,
3370 recovery: c_int,
3371) -> *mut _xmlDoc {
3372 // SAFETY: buffer must be valid with at least `size` bytes.
3373 if buffer.is_null() || size <= 0 {
3374 return ptr::null_mut();
3375 }
3376 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3377 if ctxt.is_null() {
3378 return ptr::null_mut();
3379 }
3380 if !sax.is_null() {
3381 (*ctxt).sax = sax;
3382 (*ctxt).userData = (*ctxt).sax as *mut c_void;
3383 }
3384 if recovery != 0 {
3385 (*ctxt).recovery = 1;
3386 (*ctxt).options |= 1;
3387 }
3388 let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3389 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3390 crate::xml::parser::helpers::parse_document(ctxt);
3391 let doc = (*ctxt).myDoc;
3392 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3393 doc
3394}
3395
3396/// SAX user parse file.
3397///
3398/// # UPSTREAM-PARITY
3399///
3400/// ```c
3401/// int xmlSAXUserParseFile(xmlSAXHandlerPtr sax, void *user_data,
3402/// const char *filename);
3403/// ```
3404#[no_mangle]
3405pub unsafe extern "C" fn xmlSAXUserParseFile(
3406 sax: *mut _xmlSAXHandler,
3407 user_data: *mut c_void,
3408 filename: *const c_char,
3409) -> c_int {
3410 // SAFETY: filename must be a valid C string. sax and user_data may be NULL.
3411 if filename.is_null() {
3412 return -1;
3413 }
3414 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3415 if ctxt.is_null() {
3416 return -1;
3417 }
3418 if !sax.is_null() {
3419 // UPSTREAM-PARITY (parser.c xmlSAXUserParseFile): same copy-into-
3420 //-own-storage contract as xmlSAXUserParseMemory (HOSTILE-CALLBACKS
3421 // C10 class).
3422 if unsafe { (*sax).initialized } == XML_SAX2_MAGIC as c_uint {
3423 unsafe {
3424 ptr::copy_nonoverlapping(sax as *const _xmlSAXHandler, (*ctxt).sax, 1);
3425 }
3426 } else {
3427 unsafe {
3428 ptr::copy_nonoverlapping(
3429 sax as *const u8,
3430 (*ctxt).sax as *mut u8,
3431 size_of::<crate::abi::structs::_xmlSAXHandlerV1>(),
3432 );
3433 }
3434 }
3435 }
3436 (*ctxt).userData = if !user_data.is_null() {
3437 user_data
3438 } else {
3439 ctxt as *mut c_void
3440 };
3441 let input = match crate::abi::exports_parser::open_filename_routed(filename) {
3442 crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3443 crate::abi::exports_parser::RoutedFileOpen::Failed => {
3444 crate::abi::exports_parser::emit_io_warning(
3445 ctxt,
3446 crate::abi::exports_parser::io_load_failure_message(filename),
3447 );
3448 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3449 return -1;
3450 }
3451 crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3452 match crate::xml::parser::helpers::input_from_file(filename) {
3453 Ok(input) => input,
3454 Err(_) => {
3455 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3456 return -1;
3457 }
3458 }
3459 }
3460 };
3461 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3462 let ret = crate::xml::parser::helpers::parse_document(ctxt);
3463 // UPSTREAM-PARITY (parser.c xmlSAXUserParseFile): 0 when well-formed,
3464 // otherwise the recorded errNo (or -1).
3465 let ret = if ret == 0 {
3466 0
3467 } else {
3468 let err = unsafe { (*ctxt).errNo };
3469 if err != crate::abi::types::XML_ERR_OK {
3470 err
3471 } else {
3472 -1
3473 }
3474 };
3475 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3476 ret
3477}
3478
3479/// SAX user parse memory.
3480///
3481/// # UPSTREAM-PARITY
3482///
3483/// ```c
3484/// int xmlSAXUserParseMemory(xmlSAXHandlerPtr sax, void *user_data,
3485/// const char *buffer, int size);
3486/// ```
3487#[no_mangle]
3488pub unsafe extern "C" fn xmlSAXUserParseMemory(
3489 sax: *mut _xmlSAXHandler,
3490 user_data: *mut c_void,
3491 buffer: *const c_char,
3492 size: c_int,
3493) -> c_int {
3494 // SAFETY: buffer must be valid with at least `size` bytes.
3495 if buffer.is_null() || size <= 0 {
3496 return -1;
3497 }
3498 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3499 if ctxt.is_null() {
3500 return -1;
3501 }
3502 if !sax.is_null() {
3503 // UPSTREAM-PARITY (parser.c xmlSAXUserParseMemory): the caller's
3504 // handler is COPIED into the context's own SAX struct — never
3505 // borrowed — so xmlFreeParserCtxt frees only the copy. SAX2-magic
3506 // handlers are copied in full; legacy handlers expose only the V1
3507 // prefix (HOSTILE-CALLBACKS C10: borrowing the caller's struct made
3508 // xmlFreeParserCtxt free a stack object).
3509 if unsafe { (*sax).initialized } == XML_SAX2_MAGIC as c_uint {
3510 unsafe {
3511 ptr::copy_nonoverlapping(sax as *const _xmlSAXHandler, (*ctxt).sax, 1);
3512 }
3513 } else {
3514 unsafe {
3515 ptr::copy_nonoverlapping(
3516 sax as *const u8,
3517 (*ctxt).sax as *mut u8,
3518 size_of::<crate::abi::structs::_xmlSAXHandlerV1>(),
3519 );
3520 }
3521 }
3522 }
3523 (*ctxt).userData = if !user_data.is_null() {
3524 user_data
3525 } else {
3526 ctxt as *mut c_void
3527 };
3528 let input = crate::xml::parser::helpers::input_from_memory(buffer, size);
3529 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3530 let ret = crate::xml::parser::helpers::parse_document(ctxt);
3531 // UPSTREAM-PARITY (parser.c xmlSAXUserParseMemory): the return value is
3532 // 0 when well-formed, otherwise the recorded errNo (or -1).
3533 let ret = if ret == 0 {
3534 0
3535 } else {
3536 let err = unsafe { (*ctxt).errNo };
3537 if err != crate::abi::types::XML_ERR_OK {
3538 err
3539 } else {
3540 -1
3541 }
3542 };
3543 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3544 ret
3545}
3546
3547/// Parse an XML document from a string (DOM).
3548///
3549/// # UPSTREAM-PARITY
3550///
3551/// ```c
3552/// xmlDocPtr xmlParseDoc(const xmlChar *cur);
3553/// ```
3554#[no_mangle]
3555pub unsafe extern "C" fn xmlParseDoc(cur: *const xmlChar) -> *mut _xmlDoc {
3556 // SAFETY: cur must be a valid null-terminated xmlChar string.
3557 if cur.is_null() {
3558 return ptr::null_mut();
3559 }
3560 xmlReadDoc(cur, ptr::null(), ptr::null(), 0)
3561}
3562
3563/// Parse an XML file (DOM).
3564///
3565/// # UPSTREAM-PARITY
3566///
3567/// ```c
3568/// xmlDocPtr xmlParseFile(const char *filename);
3569/// ```
3570#[no_mangle]
3571pub unsafe extern "C" fn xmlParseFile(filename: *const c_char) -> *mut _xmlDoc {
3572 // SAFETY: filename must be a valid C string.
3573 if filename.is_null() {
3574 return ptr::null_mut();
3575 }
3576 xmlReadFile(filename, ptr::null(), 0)
3577}
3578
3579/// Parse an XML document from memory (DOM).
3580///
3581/// # UPSTREAM-PARITY
3582///
3583/// ```c
3584/// xmlDocPtr xmlParseMemory(const char *buffer, int size);
3585/// ```
3586#[no_mangle]
3587pub unsafe extern "C" fn xmlParseMemory(buffer: *const c_char, size: c_int) -> *mut _xmlDoc {
3588 // SAFETY: buffer must be valid with at least `size` bytes.
3589 if buffer.is_null() || size <= 0 {
3590 return ptr::null_mut();
3591 }
3592 xmlReadMemory(buffer, size, ptr::null(), ptr::null(), 0)
3593}
3594
3595/// Create a file parser context.
3596///
3597/// # UPSTREAM-PARITY
3598///
3599/// ```c
3600/// xmlParserCtxtPtr xmlCreateFileParserCtxt(const char *filename);
3601/// ```
3602#[no_mangle]
3603pub unsafe extern "C" fn xmlCreateFileParserCtxt(filename: *const c_char) -> *mut _xmlParserCtxt {
3604 // SAFETY: filename must be a valid C string.
3605 if filename.is_null() {
3606 return ptr::null_mut();
3607 }
3608 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3609 if ctxt.is_null() {
3610 return ptr::null_mut();
3611 }
3612 let input = match crate::abi::exports_parser::open_filename_routed(filename) {
3613 crate::abi::exports_parser::RoutedFileOpen::Loaded(input) => input,
3614 crate::abi::exports_parser::RoutedFileOpen::Failed => {
3615 // UPSTREAM-PARITY (parser.c xmlCreateFileParserCtxt ->
3616 // xmlNewInputFromFile): a failed open raises the xmlCtxtErrIO
3617 // warning through the context channel.
3618 crate::abi::exports_parser::emit_io_warning(
3619 ctxt,
3620 crate::abi::exports_parser::io_load_failure_message(filename),
3621 );
3622 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3623 return ptr::null_mut();
3624 }
3625 crate::abi::exports_parser::RoutedFileOpen::Builtin => {
3626 match crate::xml::parser::helpers::input_from_file(filename) {
3627 Ok(input) => input,
3628 Err(_) => {
3629 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3630 return ptr::null_mut();
3631 }
3632 }
3633 }
3634 };
3635 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3636 ctxt
3637}
3638
3639/// Create a document parser context.
3640///
3641/// # UPSTREAM-PARITY
3642///
3643/// ```c
3644/// xmlParserCtxtPtr xmlCreateDocParserCtxt(const xmlChar *cur);
3645/// ```
3646#[no_mangle]
3647pub unsafe extern "C" fn xmlCreateDocParserCtxt(cur: *const xmlChar) -> *mut _xmlParserCtxt {
3648 // SAFETY: cur must be a valid null-terminated xmlChar string.
3649 if cur.is_null() {
3650 return ptr::null_mut();
3651 }
3652 let ctxt = crate::xml::parser::helpers::create_parser_ctxt();
3653 if ctxt.is_null() {
3654 return ptr::null_mut();
3655 }
3656 let len = crate::xml::string::xml_strlen(cur);
3657 let input = crate::xml::parser::helpers::input_from_memory(cur as *const c_char, len as c_int);
3658 crate::xml::parser::helpers::setup_parser_input(ctxt, input);
3659 ctxt
3660}
3661
3662/// Parse a document using an existing parser context.
3663///
3664/// # UPSTREAM-PARITY
3665///
3666/// ```c
3667/// int xmlParseDocument(xmlParserCtxtPtr ctxt);
3668/// ```
3669#[no_mangle]
3670pub unsafe extern "C" fn xmlParseDocument(ctxt: *mut _xmlParserCtxt) -> c_int {
3671 // SAFETY: ctxt must be a valid parser context.
3672 if ctxt.is_null() {
3673 return -1;
3674 }
3675 crate::xml::parser::helpers::parse_document(ctxt)
3676}
3677
3678/// Free a parser context.
3679///
3680/// # UPSTREAM-PARITY
3681///
3682/// ```c
3683/// void xmlFreeParserCtxt(xmlParserCtxtPtr ctxt);
3684/// ```
3685#[no_mangle]
3686pub unsafe extern "C" fn xmlFreeParserCtxt(ctxt: *mut _xmlParserCtxt) {
3687 if ctxt.is_null() {
3688 return;
3689 }
3690 crate::xml::parser::helpers::free_parser_ctxt(ctxt);
3691}
3692
3693/// Set parser options.
3694///
3695/// # UPSTREAM-PARITY
3696///
3697/// ```c
3698/// int xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options);
3699/// ```
3700#[no_mangle]
3701pub unsafe extern "C" fn xmlCtxtUseOptions(ctxt: *mut _xmlParserCtxt, options: c_int) -> c_int {
3702 if ctxt.is_null() {
3703 return -1;
3704 }
3705 // UPSTREAM-PARITY (parser.c 2.15 xmlCtxtUseOptions ->
3706 // xmlCtxtSetOptionsInternal): options in the keep mask can only ever be
3707 // enabled (historic never-clear bits); the remaining handled bits are
3708 // taken from the caller's `options`. The historical struct members
3709 // (recovery / replaceEntities / loadsubset / validate / pedantic /
3710 // keepBlanks / dictNames) are derived from the option bits exactly like
3711 // upstream, because deprecated APIs and consumers (e.g. PHP's expat
3712 // compat layer, which sanitizes then calls xmlCtxtUseOptions with
3713 // XML_PARSE_OLDSAX | XML_PARSE_NOENT) read those members directly.
3714 const KEEP_MASK: c_int = XML_PARSE_NOERROR
3715 | XML_PARSE_NOWARNING
3716 | XML_PARSE_NONET
3717 | XML_PARSE_NSCLEAN
3718 | XML_PARSE_NOCDATA
3719 | XML_PARSE_COMPACT
3720 | XML_PARSE_OLD10
3721 | XML_PARSE_HUGE
3722 | XML_PARSE_OLDSAX
3723 | XML_PARSE_IGNORE_ENC
3724 | XML_PARSE_BIG_LINES;
3725 const ALL_MASK: c_int = XML_PARSE_RECOVER
3726 | XML_PARSE_NOENT
3727 | XML_PARSE_DTDLOAD
3728 | XML_PARSE_DTDATTR
3729 | XML_PARSE_DTDVALID
3730 | XML_PARSE_NOERROR
3731 | XML_PARSE_NOWARNING
3732 | XML_PARSE_PEDANTIC
3733 | XML_PARSE_NOBLANKS
3734 | XML_PARSE_SAX1
3735 | XML_PARSE_NONET
3736 | XML_PARSE_NODICT
3737 | XML_PARSE_NSCLEAN
3738 | XML_PARSE_NOCDATA
3739 | XML_PARSE_COMPACT
3740 | XML_PARSE_OLD10
3741 | XML_PARSE_HUGE
3742 | XML_PARSE_OLDSAX
3743 | XML_PARSE_IGNORE_ENC
3744 | XML_PARSE_BIG_LINES
3745 | XML_PARSE_NO_XXE;
3746 unsafe {
3747 let merged = ((*ctxt).options & KEEP_MASK) | (options & ALL_MASK);
3748 crate::abi::exports_parser::apply_options(ctxt, merged);
3749 }
3750 options & !ALL_MASK
3751}
3752
3753/// Parse a well-balanced chunk (for push parsing).
3754///
3755/// # UPSTREAM-PARITY
3756///
3757/// ```c
3758/// xmlParserErrors xmlParseChunk(xmlParserCtxtPtr ctxt,
3759/// const char *chunk, int size, int terminate);
3760/// ```
3761#[no_mangle]
3762pub unsafe extern "C" fn xmlParseChunk(
3763 ctxt: *mut _xmlParserCtxt,
3764 chunk: *const c_char,
3765 size: c_int,
3766 terminate: c_int,
3767) -> c_int {
3768 // SAFETY: ctxt must be a valid parser context.
3769 // chunk may be NULL if terminate is set (finalize without data).
3770 //
3771 // UPSTREAM-PARITY (parser.c 2.15 xmlParseChunk): NULL context, negative
3772 // sizes and NULL chunk with positive size all return XML_ERR_ARGUMENT
3773 // (115), never -1 — HOSTILE-ABI B10/B13/D2.
3774 if ctxt.is_null() || size < 0 || (chunk.is_null() && size > 0) {
3775 return XML_ERR_ARGUMENT;
3776 }
3777 crate::xml::parser::helpers::parse_chunk(ctxt, chunk, size, terminate)
3778}
3779
3780/// Create a memory parser input buffer.
3781///
3782/// # UPSTREAM-PARITY
3783///
3784/// ```c
3785/// xmlParserInputBufferPtr xmlParserInputBufferCreateMem(const char *buffer, int size, int enc);
3786/// ```
3787#[no_mangle]
3788pub unsafe extern "C" fn xmlParserInputBufferCreateMem(
3789 buffer: *const c_char,
3790 size: c_int,
3791 enc: c_int,
3792) -> *mut _xmlParserInputBuffer {
3793 // SAFETY: buffer must be valid with at least `size` bytes.
3794 if buffer.is_null() || size <= 0 {
3795 return ptr::null_mut();
3796 }
3797 // UPSTREAM-PARITY (xmlIO.c xmlParserInputBufferCreateMem): the content
3798 // is copied into the buffer (readcallback stays NULL — PHP's
3799 // XMLReader::XML()/fromString() parse from the buffer's own bytes).
3800 // The enc argument selects an input converter upstream; the candidate
3801 // parser handles declared encodings itself, so it is not stored.
3802 let _ = enc;
3803 crate::xml::parser::helpers::alloc_parser_input_buffer_with_mem(buffer, size)
3804}
3805
3806/// Create a file parser input buffer.
3807///
3808/// # UPSTREAM-PARITY
3809///
3810/// ```c
3811/// xmlParserInputBufferPtr xmlParserInputBufferCreateFilename(const char *URI, int enc);
3812/// ```
3813#[no_mangle]
3814pub unsafe extern "C" fn xmlParserInputBufferCreateFilename(
3815 URI: *const c_char,
3816 enc: c_int,
3817) -> *mut _xmlParserInputBuffer {
3818 // SAFETY: URI must be a valid C string or NULL.
3819 if URI.is_null() {
3820 return ptr::null_mut();
3821 }
3822 crate::xml::parser::helpers::alloc_parser_input_buffer()
3823}
3824
3825/// Create an I/O parser input buffer.
3826///
3827/// # UPSTREAM-PARITY
3828///
3829/// ```c
3830/// xmlParserInputBufferPtr xmlParserInputBufferCreateIO(
3831/// xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
3832/// void *ioctx, int enc);
3833/// ```
3834#[no_mangle]
3835pub unsafe extern "C" fn xmlParserInputBufferCreateIO(
3836 ioread: Option<xmlInputReadCallback>,
3837 ioclose: Option<xmlInputCloseCallback>,
3838 ioctx: *mut c_void,
3839 enc: c_int,
3840) -> *mut _xmlParserInputBuffer {
3841 // SAFETY: ioread must be a valid callback if Some. ioctx may be NULL.
3842 let buf = crate::xml::parser::helpers::alloc_parser_input_buffer();
3843 if !buf.is_null() {
3844 (*buf).readcallback = ioread;
3845 (*buf).closecallback = ioclose;
3846 (*buf).context = ioctx;
3847 }
3848 buf
3849}
3850
3851/// Free a parser input buffer.
3852///
3853/// # UPSTREAM-PARITY
3854///
3855/// ```c
3856/// void xmlFreeParserInputBuffer(xmlParserInputBufferPtr buf);
3857/// ```
3858#[no_mangle]
3859pub unsafe extern "C" fn xmlFreeParserInputBuffer(buf: *mut _xmlParserInputBuffer) {
3860 if buf.is_null() {
3861 return;
3862 }
3863 crate::xml::parser::helpers::free_parser_input_buffer(buf);
3864}
3865
3866/// Create a new parser input.
3867///
3868/// # UPSTREAM-PARITY
3869///
3870/// ```c
3871/// xmlParserInputPtr xmlNewInputFromFile(xmlParserCtxtPtr ctxt, const char *filename);
3872/// ```
3873#[no_mangle]
3874pub unsafe extern "C" fn xmlNewInputFromFile(
3875 ctxt: *mut _xmlParserCtxt,
3876 filename: *const c_char,
3877) -> *mut _xmlParserInput {
3878 // SAFETY: filename must be a valid C string. ctxt may be NULL.
3879 // This function allocates a _xmlParserInput. The caller owns it.
3880 // Note: The InputBuffer backing data is NOT leaked here (no ctxt._private
3881 // to store it). Use xmlCreateFileParserCtxt + xmlParseDocument instead.
3882 if filename.is_null() {
3883 return ptr::null_mut();
3884 }
3885 crate::xml::parser::helpers::alloc_parser_input_buffer() as *mut _xmlParserInput
3886}
3887
3888/// Free a parser input.
3889///
3890/// # UPSTREAM-PARITY
3891///
3892/// ```c
3893/// void xmlFreeInputStream(xmlParserInputPtr input);
3894/// ```
3895#[no_mangle]
3896pub unsafe extern "C" fn xmlFreeInputStream(input: *mut _xmlParserInput) {
3897 if input.is_null() {
3898 return;
3899 }
3900 crate::xml::parser::helpers::free_parser_input(input);
3901}
3902
3903// ═══════════════════════════════════════════════════════════════════════════════
3904// 8. I/O
3905// ═══════════════════════════════════════════════════════════════════════════════
3906
3907/// Create an output buffer for a file.
3908///
3909/// # UPSTREAM-PARITY
3910///
3911/// ```c
3912/// xmlOutputBufferPtr xmlOutputBufferCreateFilename(const char *URI,
3913/// xmlCharEncodingHandlerPtr encoder,
3914/// int compression);
3915/// ```
3916#[no_mangle]
3917pub unsafe extern "C" fn xmlOutputBufferCreateFilename(
3918 URI: *const c_char,
3919 encoder: *mut c_void,
3920 compression: c_int,
3921) -> *mut _xmlOutputBuffer {
3922 if URI.is_null() {
3923 return ptr::null_mut();
3924 }
3925 // UPSTREAM-PARITY (xmlIO.c xmlOutputBufferCreateFilename): a default
3926 // create-filename callback registered via xmlOutputBufferCreateFilenameDefault
3927 // is consulted first (PHP installs php_libxml_output_buffer_create_filename at
3928 // request init, so every filename open routes through the PHP streams layer);
3929 // otherwise the builtin file open runs.
3930 crate::xml::io::output_buffer_create_filename_routed(
3931 URI,
3932 encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3933 compression,
3934 )
3935}
3936
3937/// Create an output buffer for a file descriptor.
3938///
3939/// # UPSTREAM-PARITY
3940///
3941/// ```c
3942/// xmlOutputBufferPtr xmlOutputBufferCreateFd(int fd,
3943/// xmlCharEncodingHandlerPtr encoder);
3944/// ```
3945#[no_mangle]
3946pub unsafe extern "C" fn xmlOutputBufferCreateFd(
3947 fd: c_int,
3948 encoder: *mut c_void,
3949) -> *mut _xmlOutputBuffer {
3950 if fd < 0 {
3951 return ptr::null_mut();
3952 }
3953 crate::xml::io::output_buffer_create_fd(
3954 fd,
3955 encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3956 )
3957}
3958
3959/// Create an output buffer from I/O callbacks.
3960///
3961/// # UPSTREAM-PARITY
3962///
3963/// ```c
3964/// xmlOutputBufferPtr xmlOutputBufferCreateIO(
3965/// xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose,
3966/// void *ioctx, xmlCharEncodingHandlerPtr encoder);
3967/// ```
3968#[no_mangle]
3969pub unsafe extern "C" fn xmlOutputBufferCreateIO(
3970 iowrite: Option<xmlOutputWriteCallback>,
3971 ioclose: Option<xmlOutputCloseCallback>,
3972 ioctx: *mut c_void,
3973 encoder: *mut c_void,
3974) -> *mut _xmlOutputBuffer {
3975 crate::xml::io::output_buffer_create_io(
3976 iowrite,
3977 ioclose,
3978 ioctx,
3979 encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
3980 )
3981}
3982
3983/// Free an output buffer.
3984///
3985/// # UPSTREAM-PARITY
3986///
3987/// ```c
3988/// void xmlOutputBufferClose(xmlOutputBufferPtr out);
3989/// ```
3990#[no_mangle]
3991pub unsafe extern "C" fn xmlOutputBufferClose(out: *mut _xmlOutputBuffer) -> c_int {
3992 if out.is_null() {
3993 return -1;
3994 }
3995 crate::xml::io::output_buffer_close(out)
3996}
3997
3998/// Flush an output buffer.
3999///
4000/// # UPSTREAM-PARITY
4001///
4002/// ```c
4003/// int xmlOutputBufferFlush(xmlOutputBufferPtr out);
4004/// ```
4005#[no_mangle]
4006pub unsafe extern "C" fn xmlOutputBufferFlush(out: *mut _xmlOutputBuffer) -> c_int {
4007 if out.is_null() {
4008 return -1;
4009 }
4010 crate::xml::io::output_buffer_flush(out)
4011}
4012
4013/// Write to an output buffer.
4014///
4015/// # UPSTREAM-PARITY
4016///
4017/// ```c
4018/// int xmlOutputBufferWrite(xmlOutputBufferPtr out, int len, const char *data);
4019/// ```
4020#[no_mangle]
4021pub unsafe extern "C" fn xmlOutputBufferWrite(
4022 out: *mut _xmlOutputBuffer,
4023 len: c_int,
4024 data: *const c_char,
4025) -> c_int {
4026 // UPSTREAM-PARITY (xmlIO.c xmlOutputBufferWrite): a zero-length write
4027 // is a legal no-op returning 0 — PHP's W3C DOM-Parsing serializer
4028 // (ext/dom xml_serializer.c dom_xml_common_text_serialization) issues
4029 // xmlOutputBufferWrite(out, 0, p) when a text/attribute run starts with
4030 // a character that needs escaping; -1 there aborts the whole save with
4031 // "Could not save document".
4032 if out.is_null() || data.is_null() || len < 0 {
4033 return -1;
4034 }
4035 if len == 0 {
4036 return 0;
4037 }
4038 crate::xml::io::output_buffer_write(out, len, data)
4039}
4040
4041/// Write a string to an output buffer.
4042///
4043/// # UPSTREAM-PARITY
4044///
4045/// ```c
4046/// int xmlOutputBufferWriteString(xmlOutputBufferPtr out, const char *str);
4047/// ```
4048#[no_mangle]
4049pub unsafe extern "C" fn xmlOutputBufferWriteString(
4050 out: *mut _xmlOutputBuffer,
4051 str: *const c_char,
4052) -> c_int {
4053 if str.is_null() {
4054 return 0;
4055 }
4056 unsafe { xmlOutputBufferWrite(out, xmlStrlen(str as *const xmlChar), str) }
4057}
4058
4059/// Allocate an output buffer with no I/O target (upstream xmlAllocOutputBuffer).
4060///
4061/// # UPSTREAM-PARITY
4062///
4063/// ```c
4064/// xmlOutputBufferPtr xmlAllocOutputBuffer(xmlCharEncodingHandlerPtr encoder);
4065/// ```
4066#[no_mangle]
4067pub unsafe extern "C" fn xmlAllocOutputBuffer(encoder: *mut c_void) -> *mut _xmlOutputBuffer {
4068 crate::xml::io::output_buffer_create(
4069 encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
4070 )
4071}
4072
4073/// Create an output buffer that writes into a `_xmlBuffer` (upstream
4074/// xmlOutputBufferCreateBuffer).
4075///
4076/// # UPSTREAM-PARITY
4077///
4078/// ```c
4079/// xmlOutputBufferPtr xmlOutputBufferCreateBuffer(xmlBufferPtr buffer,
4080/// xmlCharEncodingHandlerPtr encoder);
4081/// ```
4082///
4083/// # SAFETY
4084///
4085/// - `buffer` must be a valid `_xmlBuffer`.
4086#[no_mangle]
4087pub unsafe extern "C" fn xmlOutputBufferCreateBuffer(
4088 buffer: *mut crate::abi::structs::_xmlBuffer,
4089 encoder: *mut c_void,
4090) -> *mut _xmlOutputBuffer {
4091 crate::xml::io::output_buffer_create_buffer(
4092 buffer,
4093 encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
4094 )
4095}
4096
4097/// Create an output buffer writing to a `FILE *` (upstream
4098/// xmlOutputBufferCreateFile): the FILE is the I/O context with a
4099/// write callback wrapping `fwrite` and a close callback wrapping `fflush`.
4100///
4101/// # SAFETY
4102///
4103/// - `file` must be a valid `FILE *` or NULL.
4104#[no_mangle]
4105pub unsafe extern "C" fn xmlOutputBufferCreateFile(
4106 file: *mut libc::FILE,
4107 encoder: *mut c_void,
4108) -> *mut _xmlOutputBuffer {
4109 crate::xml::io::output_buffer_create_file(
4110 file,
4111 encoder as *mut crate::abi::structs::_xmlCharEncodingHandler,
4112 )
4113}
4114
4115/// Get the current content of an output buffer (upstream xmlOutputBufferGetContent).
4116///
4117/// # SAFETY
4118///
4119/// - `out` must be a valid output buffer.
4120#[no_mangle]
4121pub unsafe extern "C" fn xmlOutputBufferGetContent(out: *mut _xmlOutputBuffer) -> *const c_char {
4122 crate::xml::io::output_buffer_get_content(out) as *const c_char
4123}
4124
4125/// Get the number of bytes currently in the output buffer (upstream
4126/// xmlOutputBufferGetSize: `size_t`, 0 on NULL/error — 11.1-Z.3 signature
4127/// court: the pre-Z.3 candidate returned `int` with -1 on error).
4128///
4129/// # SAFETY
4130///
4131/// - `out` must be a valid output buffer.
4132#[no_mangle]
4133pub unsafe extern "C" fn xmlOutputBufferGetSize(out: *mut _xmlOutputBuffer) -> usize {
4134 crate::xml::io::output_buffer_get_size(out)
4135}
4136
4137/// Write to an output buffer, escaping special characters with the given
4138/// escape function (upstream xmlOutputBufferWriteEscape).
4139///
4140/// # SAFETY
4141///
4142/// - `out` must be a valid output buffer; `str` a NUL-terminated string;
4143/// `escaping` a valid escape callback or NULL.
4144#[no_mangle]
4145pub unsafe extern "C" fn xmlOutputBufferWriteEscape(
4146 out: *mut _xmlOutputBuffer,
4147 str: *const xmlChar,
4148 escaping: Option<xmlCharEncodingOutputFunc>,
4149) -> c_int {
4150 if out.is_null() || str.is_null() {
4151 return -1;
4152 }
4153 crate::xml::io::output_buffer_write_escape(out, str, escaping)
4154}
4155
4156/// Set/query the default output-buffer filename callback
4157/// (upstream xmlOutputBufferCreateFilenameDefault).
4158///
4159/// Stored per-thread in the same cell the I/O layer consults
4160/// (`xml::globals::OUTPUT_CREATE_FILENAME`, upstream's
4161/// `xmlOutputBufferCreateFilenameValue`); the deprecated plain-global
4162/// accessor `__xmlOutputBufferCreateFilename` returns a pointer to it.
4163///
4164/// # SAFETY
4165///
4166/// - `func` must be a valid function pointer or NULL.
4167/// - The previous value (NULL when none was registered) is returned.
4168#[no_mangle]
4169pub unsafe extern "C" fn xmlOutputBufferCreateFilenameDefault(
4170 func: Option<
4171 unsafe extern "C" fn(
4172 *const c_char,
4173 *mut crate::abi::structs::_xmlCharEncodingHandler,
4174 c_int,
4175 ) -> *mut _xmlOutputBuffer,
4176 >,
4177) -> Option<
4178 unsafe extern "C" fn(
4179 *const c_char,
4180 *mut crate::abi::structs::_xmlCharEncodingHandler,
4181 c_int,
4182 ) -> *mut _xmlOutputBuffer,
4183> {
4184 // UPSTREAM-PARITY (xmlIO.c): set only when func is non-NULL, return the
4185 // previously registered value (NULL when none). Same per-thread slot the
4186 // thrDef variant and the I/O routing consult.
4187 let old = crate::xml::globals::get_output_buffer_create_filename_value();
4188 if func.is_some() {
4189 crate::xml::globals::set_output_buffer_create_filename_value(func);
4190 }
4191 old
4192}
4193
4194/// `__xmlOutputBufferCreateFilename` — accessor returning a pointer to the
4195/// default callback (upstream xmlIO.c).
4196#[no_mangle]
4197pub unsafe extern "C" fn __xmlOutputBufferCreateFilename() -> *mut Option<
4198 unsafe extern "C" fn(
4199 *const c_char,
4200 *mut crate::abi::structs::_xmlCharEncodingHandler,
4201 c_int,
4202 ) -> *mut _xmlOutputBuffer,
4203> {
4204 crate::xml::globals::output_create_filename_ptr()
4205}
4206
4207// ═══════════════════════════════════════════════════════════════════════════════
4208// 9. Dictionary
4209// ═══════════════════════════════════════════════════════════════════════════════
4210
4211/// Create a new dictionary.
4212///
4213/// # UPSTREAM-PARITY
4214///
4215/// ```c
4216/// xmlDictPtr xmlDictCreate(void);
4217/// ```
4218#[no_mangle]
4219pub extern "C" fn xmlDictCreate() -> *mut c_void {
4220 // The creator holds the base reference (Dict.ref_count = 1, upstream
4221 // ref_counter); xmlDictReference adds to it and xmlDictFree decrements,
4222 // freeing the dictionary when it reaches zero. The count lives in the
4223 // shared dict memory (R-000177: cross-DSO coherent).
4224 crate::xml::dictionary::dict_create() as *mut c_void
4225}
4226
4227/// Create a sub-dictionary.
4228///
4229/// # UPSTREAM-PARITY
4230///
4231/// ```c
4232/// xmlDictPtr xmlDictCreateSub(xmlDictPtr sub);
4233/// ```
4234#[no_mangle]
4235pub extern "C" fn xmlDictCreateSub(sub: *mut c_void) -> *mut c_void {
4236 // Base reference lives in the shared dict memory (Dict.ref_count).
4237 unsafe {
4238 crate::xml::dictionary::dict_create_sub(sub as *mut crate::xml::dictionary::Dict)
4239 as *mut c_void
4240 }
4241}
4242
4243/// Look up a string in the dictionary.
4244///
4245/// # UPSTREAM-PARITY
4246///
4247/// ```c
4248/// const xmlChar *xmlDictLookup(xmlDictPtr dict, const xmlChar *name, int len);
4249/// ```
4250///
4251/// Returns an interned string pointer (valid as long as the dictionary exists).
4252/// - If `len` < 0, `name` must be null-terminated.
4253/// - If `len` >= 0, exactly `len` bytes are used.
4254#[no_mangle]
4255pub unsafe extern "C" fn xmlDictLookup(
4256 dict: *mut c_void,
4257 name: *const xmlChar,
4258 len: c_int,
4259) -> *const xmlChar {
4260 unsafe {
4261 crate::xml::dictionary::dict_lookup(dict as *mut crate::xml::dictionary::Dict, name, len)
4262 }
4263}
4264
4265/// Check if a string exists in the dictionary.
4266///
4267/// # UPSTREAM-PARITY
4268///
4269/// ```c
4270/// const xmlChar *xmlDictExists(xmlDictPtr dict, const xmlChar *name, int len);
4271/// ```
4272#[no_mangle]
4273pub unsafe extern "C" fn xmlDictExists(
4274 dict: *mut c_void,
4275 name: *const xmlChar,
4276 len: c_int,
4277) -> *const xmlChar {
4278 unsafe {
4279 crate::xml::dictionary::dict_exists(dict as *mut crate::xml::dictionary::Dict, name, len)
4280 }
4281}
4282
4283/// Query dictionary size.
4284///
4285/// # UPSTREAM-PARITY
4286///
4287/// ```c
4288/// int xmlDictSize(const xmlDictPtr dict);
4289/// ```
4290#[no_mangle]
4291pub const extern "C" fn xmlDictSize(dict: *const c_void) -> c_int {
4292 {
4293 crate::xml::dictionary::dict_size(dict as *const crate::xml::dictionary::Dict)
4294 }
4295}
4296
4297/// Free a dictionary.
4298///
4299/// # UPSTREAM-PARITY
4300///
4301/// ```c
4302/// void xmlDictFree(xmlDictPtr dict);
4303/// ```
4304///
4305/// The reference counter added by `xmlDictReference` is honored: the
4306/// underlying dictionary is destroyed only when the last reference is
4307/// released (the base owner counts as one implicit reference).
4308#[no_mangle]
4309pub extern "C" fn xmlDictFree(dict: *mut c_void) {
4310 if dict.is_null() {
4311 return;
4312 }
4313 // The reference count lives IN the shared dict memory (R-000177): a
4314 // decrement through one DSO observes references made through every
4315 // other DSO, so a dict created by libxml2.so.16 is never freed early by
4316 // libxslt.so.1's teardown. The pre-fix per-DSO side table partitioned
4317 // the count and unconditionally freed unknown dicts.
4318 let d = dict as *mut crate::xml::dictionary::Dict;
4319 let prev = unsafe {
4320 (*d).ref_count
4321 .fetch_sub(1, core::sync::atomic::Ordering::Relaxed)
4322 };
4323 if prev == 1 {
4324 unsafe { crate::xml::dictionary::dict_free(dict as *mut crate::xml::dictionary::Dict) };
4325 }
4326}
4327
4328/// Set the dictionary size limit.
4329///
4330/// # UPSTREAM-PARITY
4331///
4332/// ```c
4333/// size_t xmlDictSetLimit(xmlDictPtr dict, size_t limit);
4334/// ```
4335#[no_mangle]
4336pub extern "C" fn xmlDictSetLimit(dict: *mut c_void, limit: usize) -> usize {
4337 {
4338 crate::xml::dictionary::dict_set_limit(dict as *mut crate::xml::dictionary::Dict, limit)
4339 }
4340}
4341
4342/// Get current dictionary usage.
4343///
4344/// # UPSTREAM-PARITY
4345///
4346/// ```c
4347/// size_t xmlDictGetUsage(const xmlDictPtr dict);
4348/// ```
4349#[no_mangle]
4350pub extern "C" fn xmlDictGetUsage(dict: *const c_void) -> usize {
4351 {
4352 crate::xml::dictionary::dict_get_usage(dict as *mut crate::xml::dictionary::Dict)
4353 }
4354}
4355
4356// ═══════════════════════════════════════════════════════════════════════════════
4357// 10. Hash Table
4358// ═══════════════════════════════════════════════════════════════════════════════
4359
4360/// Create a new hash table.
4361///
4362/// # UPSTREAM-PARITY
4363///
4364/// ```c
4365/// xmlHashTablePtr xmlHashCreate(int size);
4366/// ```
4367#[no_mangle]
4368pub extern "C" fn xmlHashCreate(size: c_int) -> *mut c_void {
4369 crate::xml::hash::hash_create(size) as *mut c_void
4370}
4371
4372/// Create a new hash table with a dictionary.
4373///
4374/// # UPSTREAM-PARITY
4375///
4376/// ```c
4377/// xmlHashTablePtr xmlHashCreateDict(int size, xmlDictPtr dict);
4378/// ```
4379#[no_mangle]
4380pub extern "C" fn xmlHashCreateDict(size: c_int, dict: *mut c_void) -> *mut c_void {
4381 crate::xml::hash::hash_create_dict(size, dict) as *mut c_void
4382}
4383
4384/// Free a hash table.
4385///
4386/// # UPSTREAM-PARITY
4387///
4388/// ```c
4389/// void xmlHashFree(xmlHashTablePtr table, xmlHashDeallocator f);
4390/// ```
4391#[no_mangle]
4392pub extern "C" fn xmlHashFree(
4393 table: *mut c_void,
4394 f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4395) {
4396 unsafe { crate::xml::hash::hash_free(table as *mut crate::xml::hash::HashTable, f) }
4397}
4398
4399/// Add an entry to a hash table.
4400///
4401/// # UPSTREAM-PARITY
4402///
4403/// ```c
4404/// int xmlHashAddEntry(xmlHashTablePtr table, const xmlChar *name, void *userdata);
4405/// ```
4406#[no_mangle]
4407pub unsafe extern "C" fn xmlHashAddEntry(
4408 table: *mut c_void,
4409 name: *const xmlChar,
4410 userdata: *mut c_void,
4411) -> c_int {
4412 unsafe {
4413 crate::xml::hash::hash_add_entry(table as *mut crate::xml::hash::HashTable, name, userdata)
4414 }
4415}
4416
4417/// Add a 2-key entry.
4418///
4419/// # UPSTREAM-PARITY
4420///
4421/// ```c
4422/// int xmlHashAddEntry2(xmlHashTablePtr table, const xmlChar *name,
4423/// const xmlChar *name2, void *userdata);
4424/// ```
4425#[no_mangle]
4426pub unsafe extern "C" fn xmlHashAddEntry2(
4427 table: *mut c_void,
4428 name: *const xmlChar,
4429 name2: *const xmlChar,
4430 userdata: *mut c_void,
4431) -> c_int {
4432 unsafe {
4433 crate::xml::hash::hash_add_entry2(
4434 table as *mut crate::xml::hash::HashTable,
4435 name,
4436 name2,
4437 userdata,
4438 )
4439 }
4440}
4441
4442/// Add a 3-key entry.
4443///
4444/// # UPSTREAM-PARITY
4445///
4446/// ```c
4447/// int xmlHashAddEntry3(xmlHashTablePtr table, const xmlChar *name,
4448/// const xmlChar *name2, const xmlChar *name3, void *userdata);
4449/// ```
4450#[no_mangle]
4451pub unsafe extern "C" fn xmlHashAddEntry3(
4452 table: *mut c_void,
4453 name: *const xmlChar,
4454 name2: *const xmlChar,
4455 name3: *const xmlChar,
4456 userdata: *mut c_void,
4457) -> c_int {
4458 unsafe {
4459 crate::xml::hash::hash_add_entry3(
4460 table as *mut crate::xml::hash::HashTable,
4461 name,
4462 name2,
4463 name3,
4464 userdata,
4465 )
4466 }
4467}
4468
4469/// Update or add an entry.
4470///
4471/// # UPSTREAM-PARITY
4472///
4473/// ```c
4474/// int xmlHashUpdateEntry(xmlHashTablePtr table, const xmlChar *name,
4475/// void *userdata, xmlHashDeallocator f);
4476/// ```
4477#[no_mangle]
4478pub unsafe extern "C" fn xmlHashUpdateEntry(
4479 table: *mut c_void,
4480 name: *const xmlChar,
4481 userdata: *mut c_void,
4482 f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4483) -> c_int {
4484 unsafe {
4485 crate::xml::hash::hash_update_entry(
4486 table as *mut crate::xml::hash::HashTable,
4487 name,
4488 userdata,
4489 f,
4490 )
4491 }
4492}
4493
4494/// Update or add a 2-key entry.
4495#[no_mangle]
4496pub unsafe extern "C" fn xmlHashUpdateEntry2(
4497 table: *mut c_void,
4498 name: *const xmlChar,
4499 name2: *const xmlChar,
4500 userdata: *mut c_void,
4501 f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4502) -> c_int {
4503 unsafe {
4504 crate::xml::hash::hash_update_entry2(
4505 table as *mut crate::xml::hash::HashTable,
4506 name,
4507 name2,
4508 userdata,
4509 f,
4510 )
4511 }
4512}
4513
4514/// Update or add a 3-key entry.
4515#[no_mangle]
4516pub unsafe extern "C" fn xmlHashUpdateEntry3(
4517 table: *mut c_void,
4518 name: *const xmlChar,
4519 name2: *const xmlChar,
4520 name3: *const xmlChar,
4521 userdata: *mut c_void,
4522 f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4523) -> c_int {
4524 unsafe {
4525 crate::xml::hash::hash_update_entry3(
4526 table as *mut crate::xml::hash::HashTable,
4527 name,
4528 name2,
4529 name3,
4530 userdata,
4531 f,
4532 )
4533 }
4534}
4535
4536/// Look up an entry.
4537///
4538/// # UPSTREAM-PARITY
4539///
4540/// ```c
4541/// void *xmlHashLookup(xmlHashTablePtr table, const xmlChar *name);
4542/// ```
4543#[no_mangle]
4544pub unsafe extern "C" fn xmlHashLookup(table: *mut c_void, name: *const xmlChar) -> *mut c_void {
4545 unsafe { crate::xml::hash::hash_lookup(table as *mut crate::xml::hash::HashTable, name) }
4546}
4547
4548/// Look up a 2-key entry.
4549#[no_mangle]
4550pub unsafe extern "C" fn xmlHashLookup2(
4551 table: *mut c_void,
4552 name: *const xmlChar,
4553 name2: *const xmlChar,
4554) -> *mut c_void {
4555 unsafe {
4556 crate::xml::hash::hash_lookup2(table as *mut crate::xml::hash::HashTable, name, name2)
4557 }
4558}
4559
4560/// Look up a 3-key entry.
4561#[no_mangle]
4562pub unsafe extern "C" fn xmlHashLookup3(
4563 table: *mut c_void,
4564 name: *const xmlChar,
4565 name2: *const xmlChar,
4566 name3: *const xmlChar,
4567) -> *mut c_void {
4568 unsafe {
4569 crate::xml::hash::hash_lookup3(
4570 table as *mut crate::xml::hash::HashTable,
4571 name,
4572 name2,
4573 name3,
4574 )
4575 }
4576}
4577
4578/// Get the size of a hash table.
4579///
4580/// # UPSTREAM-PARITY
4581///
4582/// ```c
4583/// int xmlHashSize(xmlHashTablePtr table);
4584/// ```
4585#[no_mangle]
4586pub extern "C" fn xmlHashSize(table: *mut c_void) -> c_int {
4587 crate::xml::hash::hash_size(table as *mut crate::xml::hash::HashTable)
4588}
4589
4590/// Remove an entry.
4591///
4592/// # UPSTREAM-PARITY
4593///
4594/// ```c
4595/// int xmlHashRemoveEntry(xmlHashTablePtr table, const xmlChar *name,
4596/// xmlHashDeallocator f);
4597/// ```
4598#[no_mangle]
4599pub unsafe extern "C" fn xmlHashRemoveEntry(
4600 table: *mut c_void,
4601 name: *const xmlChar,
4602 f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4603) -> c_int {
4604 unsafe {
4605 crate::xml::hash::hash_remove_entry(table as *mut crate::xml::hash::HashTable, name, f)
4606 }
4607}
4608
4609/// Remove a 2-key entry.
4610#[no_mangle]
4611pub unsafe extern "C" fn xmlHashRemoveEntry2(
4612 table: *mut c_void,
4613 name: *const xmlChar,
4614 name2: *const xmlChar,
4615 f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4616) -> c_int {
4617 unsafe {
4618 crate::xml::hash::hash_remove_entry2(
4619 table as *mut crate::xml::hash::HashTable,
4620 name,
4621 name2,
4622 f,
4623 )
4624 }
4625}
4626
4627/// Remove a 3-key entry.
4628#[no_mangle]
4629pub unsafe extern "C" fn xmlHashRemoveEntry3(
4630 table: *mut c_void,
4631 name: *const xmlChar,
4632 name2: *const xmlChar,
4633 name3: *const xmlChar,
4634 f: Option<unsafe extern "C" fn(*mut c_void, *mut xmlChar)>,
4635) -> c_int {
4636 unsafe {
4637 crate::xml::hash::hash_remove_entry3(
4638 table as *mut crate::xml::hash::HashTable,
4639 name,
4640 name2,
4641 name3,
4642 f,
4643 )
4644 }
4645}
4646
4647/// Scan a hash table with a scanner function.
4648///
4649/// # UPSTREAM-PARITY
4650///
4651/// ```c
4652/// void xmlHashScan(xmlHashTablePtr table, xmlHashScanner f, void *data);
4653/// ```
4654#[no_mangle]
4655pub extern "C" fn xmlHashScan(table: *mut c_void, f: Option<xmlHashScanner>, data: *mut c_void) {
4656 unsafe { crate::xml::hash::hash_scan(table as *mut crate::xml::hash::HashTable, f, data) }
4657}
4658
4659/// Scan a hash table with a full scanner function.
4660#[no_mangle]
4661pub extern "C" fn xmlHashScanFull(
4662 table: *mut c_void,
4663 f: Option<xmlHashScannerFull>,
4664 data: *mut c_void,
4665) {
4666 unsafe { crate::xml::hash::hash_scan_full(table as *mut crate::xml::hash::HashTable, f, data) }
4667}
4668
4669/// Copy a hash table.
4670///
4671/// # UPSTREAM-PARITY
4672///
4673/// ```c
4674/// xmlHashTablePtr xmlHashCopy(xmlHashTablePtr table, xmlHashCopier f);
4675/// ```
4676#[no_mangle]
4677pub extern "C" fn xmlHashCopy(
4678 table: *mut c_void,
4679 f: Option<unsafe extern "C" fn(*mut c_void, *const xmlChar) -> *mut c_void>,
4680) -> *mut c_void {
4681 unsafe {
4682 crate::xml::hash::hash_copy(table as *mut crate::xml::hash::HashTable, f) as *mut c_void
4683 }
4684}
4685
4686// ═══════════════════════════════════════════════════════════════════════════════
4687// 11. List
4688// ═══════════════════════════════════════════════════════════════════════════════
4689
4690/// Create a new list.
4691///
4692/// # UPSTREAM-PARITY
4693///
4694/// ```c
4695/// xmlListPtr xmlListCreate(xmlListDeallocator deallocator,
4696/// xmlListDataCompare compare);
4697/// ```
4698#[no_mangle]
4699pub extern "C" fn xmlListCreate(
4700 deallocator: Option<unsafe extern "C" fn(*mut c_void)>,
4701 compare: Option<unsafe extern "C" fn(*const c_void, *const c_void) -> c_int>,
4702) -> *mut c_void {
4703 crate::xml::list::list_create(deallocator, compare) as *mut c_void
4704}
4705
4706/// Delete a list.
4707///
4708/// # UPSTREAM-PARITY
4709///
4710/// ```c
4711/// void xmlListDelete(xmlListPtr list);
4712/// ```
4713#[no_mangle]
4714pub extern "C" fn xmlListDelete(list: *mut c_void) {
4715 unsafe { crate::xml::list::list_delete(list as *mut crate::xml::list::List) }
4716}
4717
4718/// Search a list.
4719///
4720/// # UPSTREAM-PARITY
4721///
4722/// ```c
4723/// void *xmlListSearch(xmlListPtr list, void *data);
4724/// ```
4725#[no_mangle]
4726pub extern "C" fn xmlListSearch(list: *mut c_void, data: *mut c_void) -> *mut c_void {
4727 unsafe { crate::xml::list::list_search(list as *mut crate::xml::list::List, data) }
4728}
4729
4730/// Walk a list.
4731///
4732/// # UPSTREAM-PARITY
4733///
4734/// ```c
4735/// void xmlListWalk(xmlListPtr list, xmlListWalker walker, void *data);
4736/// ```
4737#[no_mangle]
4738pub extern "C" fn xmlListWalk(
4739 list: *mut c_void,
4740 walker: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
4741 data: *mut c_void,
4742) {
4743 unsafe { crate::xml::list::list_walk(list as *mut crate::xml::list::List, walker, data) }
4744}
4745
4746/// Push to back.
4747///
4748/// # UPSTREAM-PARITY
4749///
4750/// ```c
4751/// int xmlListPushBack(xmlListPtr list, void *data);
4752/// ```
4753#[no_mangle]
4754pub extern "C" fn xmlListPushBack(list: *mut c_void, data: *mut c_void) -> c_int {
4755 unsafe { crate::xml::list::list_push_back(list as *mut crate::xml::list::List, data) }
4756}
4757
4758/// Push to front.
4759///
4760/// # UPSTREAM-PARITY
4761///
4762/// ```c
4763/// int xmlListPushFront(xmlListPtr list, void *data);
4764/// ```
4765#[no_mangle]
4766pub extern "C" fn xmlListPushFront(list: *mut c_void, data: *mut c_void) -> c_int {
4767 unsafe { crate::xml::list::list_push_front(list as *mut crate::xml::list::List, data) }
4768}
4769
4770/// Pop from back.
4771#[no_mangle]
4772pub extern "C" fn xmlListPopBack(list: *mut c_void) {
4773 unsafe { crate::xml::list::list_pop_back(list as *mut crate::xml::list::List) }
4774}
4775
4776/// Pop from front.
4777#[no_mangle]
4778pub extern "C" fn xmlListPopFront(list: *mut c_void) {
4779 unsafe { crate::xml::list::list_pop_front(list as *mut crate::xml::list::List) }
4780}
4781
4782/// Insert into sorted list.
4783///
4784/// # UPSTREAM-PARITY
4785///
4786/// ```c
4787/// int xmlListInsert(xmlListPtr list, void *data);
4788/// ```
4789#[no_mangle]
4790pub extern "C" fn xmlListInsert(list: *mut c_void, data: *mut c_void) -> c_int {
4791 unsafe { crate::xml::list::list_insert(list as *mut crate::xml::list::List, data) }
4792}
4793
4794/// Append to list.
4795#[no_mangle]
4796pub extern "C" fn xmlListAppend(list: *mut c_void, data: *mut c_void) -> c_int {
4797 unsafe { crate::xml::list::list_append(list as *mut crate::xml::list::List, data) }
4798}
4799
4800/// Remove first matching element.
4801#[no_mangle]
4802pub extern "C" fn xmlListRemoveFirst(list: *mut c_void, data: *mut c_void) -> c_int {
4803 unsafe { crate::xml::list::list_remove_first(list as *mut crate::xml::list::List, data) }
4804}
4805
4806/// Remove last matching element.
4807#[no_mangle]
4808pub extern "C" fn xmlListRemoveLast(list: *mut c_void, data: *mut c_void) -> c_int {
4809 unsafe { crate::xml::list::list_remove_last(list as *mut crate::xml::list::List, data) }
4810}
4811
4812/// Remove all matching elements.
4813#[no_mangle]
4814pub extern "C" fn xmlListRemoveAll(list: *mut c_void, data: *mut c_void) -> c_int {
4815 unsafe { crate::xml::list::list_remove_all(list as *mut crate::xml::list::List, data) }
4816}
4817
4818/// Clear a list.
4819#[no_mangle]
4820pub extern "C" fn xmlListClear(list: *mut c_void) {
4821 unsafe { crate::xml::list::list_clear(list as *mut crate::xml::list::List) }
4822}
4823
4824/// Check if list is empty.
4825///
4826/// # UPSTREAM-PARITY
4827///
4828/// ```c
4829/// int xmlListEmpty(xmlListPtr list);
4830/// ```
4831#[no_mangle]
4832pub extern "C" fn xmlListEmpty(list: *mut c_void) -> c_int {
4833 crate::xml::list::list_empty(list as *mut crate::xml::list::List)
4834}
4835
4836/// Get front element.
4837///
4838/// # UPSTREAM-PARITY
4839///
4840/// ```c
4841/// void *xmlListFront(xmlListPtr list);
4842/// ```
4843#[no_mangle]
4844pub extern "C" fn xmlListFront(list: *mut c_void) -> *mut c_void {
4845 crate::xml::list::list_front(list as *mut crate::xml::list::List)
4846}
4847
4848/// Get back element.
4849///
4850/// # UPSTREAM-PARITY
4851///
4852/// ```c
4853/// void *xmlListBack(xmlListPtr list);
4854/// ```
4855#[no_mangle]
4856pub extern "C" fn xmlListBack(list: *mut c_void) -> *mut c_void {
4857 crate::xml::list::list_back(list as *mut crate::xml::list::List)
4858}
4859
4860/// Get list size.
4861///
4862/// # UPSTREAM-PARITY
4863///
4864/// ```c
4865/// int xmlListSize(xmlListPtr list);
4866/// ```
4867#[no_mangle]
4868pub extern "C" fn xmlListSize(list: *mut c_void) -> c_int {
4869 crate::xml::list::list_size(list as *mut crate::xml::list::List)
4870}
4871
4872/// Sort a list.
4873#[no_mangle]
4874pub extern "C" fn xmlListSort(list: *mut c_void) {
4875 unsafe { crate::xml::list::list_sort(list as *mut crate::xml::list::List) }
4876}
4877
4878/// Reverse a list.
4879#[no_mangle]
4880pub extern "C" fn xmlListReverse(list: *mut c_void) {
4881 unsafe { crate::xml::list::list_reverse(list as *mut crate::xml::list::List) }
4882}
4883
4884/// Reverse a list in-place.
4885#[no_mangle]
4886pub extern "C" fn xmlListReverseSplice(list: *mut c_void, list2: *mut c_void) {
4887 unsafe {
4888 crate::xml::list::list_reverse_splice(
4889 list as *mut crate::xml::list::List,
4890 list2 as *mut crate::xml::list::List,
4891 )
4892 }
4893}
4894
4895/// Merge two sorted lists.
4896#[no_mangle]
4897pub extern "C" fn xmlListMerge(list: *mut c_void, list2: *mut c_void) {
4898 unsafe {
4899 crate::xml::list::list_merge(
4900 list as *mut crate::xml::list::List,
4901 list2 as *mut crate::xml::list::List,
4902 )
4903 }
4904}
4905/// Return the last element of a list (upstream list.h).
4906///
4907/// # UPSTREAM-PARITY
4908///
4909/// ```c
4910/// void *xmlListEnd(xmlListPtr l);
4911/// ```
4912#[no_mangle]
4913pub unsafe extern "C" fn xmlListEnd(l: *mut c_void) -> *mut c_void {
4914 crate::xml::list::list_end(l as *mut crate::xml::list::List)
4915}
4916
4917/// Reverse-search a list (upstream list.h).
4918///
4919/// # UPSTREAM-PARITY
4920///
4921/// ```c
4922/// void *xmlListReverseSearch(xmlListPtr l, void *data);
4923/// ```
4924#[no_mangle]
4925pub unsafe extern "C" fn xmlListReverseSearch(l: *mut c_void, data: *mut c_void) -> *mut c_void {
4926 crate::xml::list::list_reverse_search(l as *mut crate::xml::list::List, data)
4927}
4928
4929/// Walk a list in reverse (upstream list.h).
4930///
4931/// # UPSTREAM-PARITY
4932///
4933/// ```c
4934/// void xmlListReverseWalk(xmlListPtr l, xmlListWalker walker, void *data);
4935/// ```
4936#[no_mangle]
4937pub unsafe extern "C" fn xmlListReverseWalk(
4938 l: *mut c_void,
4939 walker: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
4940 data: *mut c_void,
4941) {
4942 crate::xml::list::list_reverse_walk(l as *mut crate::xml::list::List, walker, data)
4943}
4944
4945/// Duplicate a list (upstream list.h).
4946///
4947/// # UPSTREAM-PARITY
4948///
4949/// ```c
4950/// xmlListPtr xmlListDup(xmlListPtr l);
4951/// ```
4952#[no_mangle]
4953pub unsafe extern "C" fn xmlListDup(l: *mut c_void) -> *mut c_void {
4954 crate::xml::list::list_dup(l as *mut crate::xml::list::List) as *mut c_void
4955}
4956
4957/// Copy the contents of `old` into the existing list `cur` (upstream
4958/// list.h — R-000176, the candidate previously passed a copier callback).
4959///
4960/// # UPSTREAM-PARITY
4961///
4962/// ```c
4963/// int xmlListCopy(xmlListPtr cur, const xmlListPtr old);
4964/// ```
4965///
4966/// Returns 0 on success, 1 on error (upstream list.c).
4967#[no_mangle]
4968pub unsafe extern "C" fn xmlListCopy(cur: *mut c_void, old: *mut c_void) -> c_int {
4969 crate::xml::list::list_copy(
4970 cur as *mut crate::xml::list::List,
4971 old as *mut crate::xml::list::List,
4972 )
4973}
4974
4975/// Return the data of a link (upstream list.h).
4976///
4977/// # UPSTREAM-PARITY
4978///
4979/// ```c
4980/// void *xmlLinkGetData(xmlLinkPtr lk);
4981/// ```
4982#[no_mangle]
4983pub unsafe extern "C" fn xmlLinkGetData(lk: *mut c_void) -> *mut c_void {
4984 crate::xml::list::link_get_data(lk)
4985}
4986
4987// ═══════════════════════════════════════════════════════════════════════════════
4988// 12. Buffer
4989// ═══════════════════════════════════════════════════════════════════════════════
4990
4991/// Create a new buffer.
4992///
4993/// # UPSTREAM-PARITY
4994///
4995/// ```c
4996/// xmlBufferPtr xmlBufferCreate(void);
4997/// ```
4998#[no_mangle]
4999pub extern "C" fn xmlBufferCreate() -> *mut _xmlBuffer {
5000 // UPSTREAM-PARITY (buf.c 2.15): xmlBufferCreate = size 256, alloc scheme
5001 // XML_BUFFER_ALLOC_IO, content[0] = 0. (The pre-Phase-13 path used the
5002 // internal default-size DOUBLEIT helper, which diverged from the oracle
5003 // for negative/huge CreateSize arguments — HOSTILE-ABI finding.)
5004 unsafe { xml_buffer_create_upstream(256) }
5005}
5006
5007/// Create a new buffer of a given size.
5008///
5009/// # UPSTREAM-PARITY
5010///
5011/// ```c
5012/// xmlBufferPtr xmlBufferCreateSize(size_t size);
5013/// ```
5014///
5015/// Upstream buf.c 2.15: `size >= INT_MAX` returns NULL; `size == 0` returns
5016/// a buffer with a NULL content; otherwise the content is `size + 1` bytes
5017/// (the extra byte is the NUL terminator). The alloc scheme is
5018/// XML_BUFFER_ALLOC_IO.
5019#[no_mangle]
5020pub extern "C" fn xmlBufferCreateSize(size: usize) -> *mut _xmlBuffer {
5021 // UPSTREAM-PARITY (buf.c 2.15 xmlBufferCreateSize): sizes at or beyond
5022 // INT_MAX are rejected up front — a C caller passing -1 (huge size_t)
5023 // gets NULL exactly like the oracle (HOSTILE-ABI finding).
5024 if size >= c_int::MAX as usize {
5025 return ptr::null_mut();
5026 }
5027 unsafe { xml_buffer_create_upstream(size) }
5028}
5029
5030/// Upstream `xmlBufferCreateSize` body (buf.c 2.15): allocate the struct,
5031/// then `size + 1` content bytes when size != 0 (zero-size buffers have a
5032/// NULL content), alloc scheme XML_BUFFER_ALLOC_IO, content[0] = 0.
5033///
5034/// # Safety
5035///
5036/// - No caller-provided pointers; every allocation is checked for NULL and
5037/// the struct is freed on content-allocation failure.
5038unsafe fn xml_buffer_create_upstream(size: usize) -> *mut _xmlBuffer {
5039 let ret = unsafe { xmlMallocImpl(size_of::<_xmlBuffer>()) as *mut _xmlBuffer };
5040 if ret.is_null() {
5041 return ptr::null_mut();
5042 }
5043 let sz = if size != 0 { size + 1 } else { 0 };
5044 unsafe {
5045 if sz != 0 {
5046 let content = xmlMallocImpl(sz) as *mut xmlChar;
5047 if content.is_null() {
5048 xmlFreeImpl(ret as *mut c_void);
5049 return ptr::null_mut();
5050 }
5051 *content = 0;
5052 (*ret).content = content;
5053 (*ret).contentIO = content;
5054 } else {
5055 (*ret).content = ptr::null_mut();
5056 (*ret).contentIO = ptr::null_mut();
5057 }
5058 (*ret).use_ = 0;
5059 (*ret).size = sz as c_uint;
5060 (*ret).alloc = crate::abi::types::xmlBufferAllocationScheme::XML_BUFFER_ALLOC_IO as c_int;
5061 }
5062 ret
5063}
5064
5065/// Create a buffer from a static string.
5066///
5067/// # UPSTREAM-PARITY
5068///
5069/// ```c
5070/// xmlBufferPtr xmlBufferCreateStatic(void *mem, size_t size);
5071/// ```
5072#[no_mangle]
5073pub extern "C" fn xmlBufferCreateStatic(mem: *mut c_void, size: usize) -> *mut _xmlBuffer {
5074 if mem.is_null() || size == 0 {
5075 return ptr::null_mut();
5076 }
5077 crate::xml::io::buf_create_static(mem as *const xmlChar, size as c_int)
5078}
5079
5080/// Free a buffer.
5081///
5082/// # UPSTREAM-PARITY
5083///
5084/// ```c
5085/// void xmlBufferFree(xmlBufferPtr buf);
5086/// ```
5087#[no_mangle]
5088pub extern "C" fn xmlBufferFree(buf: *mut _xmlBuffer) {
5089 crate::xml::io::buf_free(buf)
5090}
5091
5092/// Empty a buffer.
5093///
5094/// # UPSTREAM-PARITY
5095///
5096/// ```c
5097/// void xmlBufferEmpty(xmlBufferPtr buf);
5098/// ```
5099#[no_mangle]
5100pub extern "C" fn xmlBufferEmpty(buf: *mut _xmlBuffer) {
5101 if buf.is_null() {
5102 return;
5103 }
5104 unsafe {
5105 if !(*buf).content.is_null() {
5106 *(*buf).content = 0;
5107 }
5108 (*buf).use_ = 0;
5109 }
5110}
5111
5112/// Get buffer content.
5113///
5114/// # UPSTREAM-PARITY
5115///
5116/// ```c
5117/// xmlChar *xmlBufferContent(const xmlBuffer *buf);
5118/// ```
5119#[no_mangle]
5120pub extern "C" fn xmlBufferContent(buf: *const _xmlBuffer) -> *mut xmlChar {
5121 crate::xml::io::buf_content(buf as *mut _xmlBuffer)
5122}
5123
5124/// Get buffer length.
5125///
5126/// # UPSTREAM-PARITY
5127///
5128/// ```c
5129/// int xmlBufferLength(const xmlBuffer *buf);
5130/// ```
5131#[no_mangle]
5132pub extern "C" fn xmlBufferLength(buf: *const _xmlBuffer) -> c_int {
5133 crate::xml::io::buf_length(buf as *mut _xmlBuffer)
5134}
5135
5136/// Write to a buffer.
5137///
5138/// # UPSTREAM-PARITY
5139///
5140/// ```c
5141/// int xmlBufferAdd(xmlBufferPtr buf, const xmlChar *str, int len);
5142/// ```
5143#[no_mangle]
5144pub unsafe extern "C" fn xmlBufferAdd(
5145 buf: *mut _xmlBuffer,
5146 str: *const xmlChar,
5147 len: c_int,
5148) -> c_int {
5149 crate::xml::io::buf_add(buf, str, len)
5150}
5151
5152/// Write to a buffer at a position.
5153///
5154/// # UPSTREAM-PARITY
5155///
5156/// ```c
5157/// int xmlBufferAddHead(xmlBufferPtr buf, const xmlChar *str, int len);
5158/// ```
5159#[no_mangle]
5160pub unsafe extern "C" fn xmlBufferAddHead(
5161 buf: *mut _xmlBuffer,
5162 str: *const xmlChar,
5163 len: c_int,
5164) -> c_int {
5165 crate::xml::io::buf_add_head(buf, str, len)
5166}
5167
5168/// Write a C string to a buffer.
5169///
5170/// # UPSTREAM-PARITY
5171///
5172/// ```c
5173/// int xmlBufferCat(xmlBufferPtr buf, const xmlChar *str);
5174/// ```
5175#[no_mangle]
5176pub unsafe extern "C" fn xmlBufferCat(buf: *mut _xmlBuffer, str: *const xmlChar) -> c_int {
5177 if str.is_null() {
5178 return -1;
5179 }
5180 let len = crate::xml::string::xml_strlen(str) as c_int;
5181 crate::xml::io::buf_add(buf, str, len)
5182}
5183
5184/// Set buffer allocation scheme.
5185///
5186/// # UPSTREAM-PARITY
5187///
5188/// ```c
5189/// void xmlBufferSetAllocationScheme(xmlBufferPtr buf,
5190/// xmlBufferAllocationScheme scheme);
5191/// ```
5192#[no_mangle]
5193pub extern "C" fn xmlBufferSetAllocationScheme(buf: *mut _xmlBuffer, scheme: c_int) {
5194 if buf.is_null() {
5195 return;
5196 }
5197 unsafe {
5198 (*buf).alloc = scheme;
5199 }
5200}
5201
5202/// Shrink buffer.
5203///
5204/// # UPSTREAM-PARITY
5205///
5206/// ```c
5207/// int xmlBufferShrink(xmlBufferPtr buf, unsigned int len);
5208/// ```
5209///
5210/// Oracle buf.c semantics (11.1-Z.3 alignment): -1 on NULL or `len` larger
5211/// than the buffer content, 0 for `len == 0`, else the removed byte count.
5212#[no_mangle]
5213pub extern "C" fn xmlBufferShrink(buf: *mut _xmlBuffer, len: c_uint) -> c_int {
5214 if buf.is_null() {
5215 return -1;
5216 }
5217 if len == 0 {
5218 return 0;
5219 }
5220 unsafe {
5221 let b = &mut *buf;
5222 if len > b.use_ {
5223 return -1;
5224 }
5225 let remaining = b.use_ - len;
5226 if remaining > 0 {
5227 core::ptr::copy(b.content.add(len as usize), b.content, remaining as usize);
5228 }
5229 *b.content.add(remaining as usize) = 0;
5230 b.use_ = remaining;
5231 }
5232 len as c_int
5233}
5234
5235/// Grow buffer.
5236///
5237/// # UPSTREAM-PARITY
5238///
5239/// ```c
5240/// int xmlBufferGrow(xmlBufferPtr buf, unsigned int len);
5241/// ```
5242#[no_mangle]
5243pub extern "C" fn xmlBufferGrow(buf: *mut _xmlBuffer, len: c_uint) -> c_int {
5244 if buf.is_null() || len == 0 {
5245 return 0;
5246 }
5247 let cur_use = unsafe { (*buf).use_ };
5248 let new_size = cur_use + len + 1;
5249 crate::xml::io::buf_grow(buf, new_size)
5250}
5251
5252/// Reserve buffer space.
5253///
5254/// # UPSTREAM-PARITY
5255///
5256/// ```c
5257/// int xmlBufferReserve(xmlBufferPtr buf, int len);
5258/// ```
5259#[no_mangle]
5260pub extern "C" fn xmlBufferReserve(buf: *mut _xmlBuffer, len: c_int) -> c_int {
5261 xmlBufferGrow(buf, len as c_uint)
5262}
5263
5264/// Detach buffer content.
5265///
5266/// # UPSTREAM-PARITY
5267///
5268/// ```c
5269/// xmlChar *xmlBufferDetach(xmlBufferPtr buf);
5270/// ```
5271#[no_mangle]
5272pub extern "C" fn xmlBufferDetach(buf: *mut _xmlBuffer) -> *mut xmlChar {
5273 if buf.is_null() {
5274 return ptr::null_mut();
5275 }
5276 unsafe {
5277 let content = (*buf).content;
5278 (*buf).content = ptr::null_mut();
5279 (*buf).use_ = 0;
5280 (*buf).size = 0;
5281 content
5282 }
5283}
5284
5285// ═══════════════════════════════════════════════════════════════════════════════
5286// 13. Encoding
5287// ═══════════════════════════════════════════════════════════════════════════════
5288
5289/// Get encoding from a name string.
5290///
5291/// # UPSTREAM-PARITY
5292///
5293/// ```c
5294/// xmlCharEncoding xmlGetCharEncoding(const char *name);
5295/// ```
5296#[no_mangle]
5297pub extern "C" fn xmlGetCharEncoding(name: *const c_char) -> c_int {
5298 if name.is_null() {
5299 return 0; // XML_CHAR_ENCODING_NONE
5300 }
5301 let name_bytes = unsafe {
5302 let len = libc::strlen(name);
5303 core::slice::from_raw_parts(name as *const u8, len)
5304 };
5305 crate::xml::encoding::encoding_from_name(name_bytes) as c_int
5306}
5307
5308/// Find an encoding handler.
5309///
5310/// # UPSTREAM-PARITY
5311///
5312/// ```c
5313/// xmlCharEncodingHandlerPtr xmlFindCharEncodingHandler(const char *name);
5314/// ```
5315#[no_mangle]
5316pub extern "C" fn xmlFindCharEncodingHandler(name: *const c_char) -> *mut c_void {
5317 if name.is_null() {
5318 return ptr::null_mut();
5319 }
5320 // Upstream hands the caller an OWNED handler it must release with
5321 // xmlCharEncCloseFunc (PHP's dom_document_encoding_write closes it after
5322 // every $dom->encoding= write) — except UTF-8, where the handler is static
5323 // and close is a no-op. Returning the persistent registry pointer directly
5324 // would let a non-UTF-8 caller's close free a still-registered handler (the
5325 // use-after-free behind DOMDocument::$encoding='UTF-16' crashing the next
5326 // registry lookup). See xmlFindCharEncodingHandler_owned.
5327 crate::xml::encoding::xmlFindCharEncodingHandler_owned(
5328 name as *const crate::abi::types::xmlChar,
5329 ) as *mut c_void
5330}
5331
5332/// Close an encoding handler.
5333///
5334/// # UPSTREAM-PARITY
5335///
5336/// ```c
5337/// int xmlCharEncCloseFunc(xmlCharEncodingHandlerPtr handler);
5338/// ```
5339#[no_mangle]
5340pub extern "C" fn xmlCharEncCloseFunc(handler: *mut c_void) -> c_int {
5341 if handler.is_null() {
5342 return -1;
5343 }
5344 // Upstream xmlCharEncCloseFunc (encoding.c): a handler flagged
5345 // XML_HANDLER_STATIC (UTF-8's default handler, or any static table
5346 // handler) is not owned by the caller and must not be released.
5347 unsafe {
5348 let h = handler as *mut crate::abi::structs::_xmlCharEncodingHandler;
5349 if (*h).flags & crate::xml::encoding::XML_HANDLER_STATIC != 0 {
5350 return 0;
5351 }
5352 if !(*h).name.is_null() {
5353 crate::abi::allocator::xmlFreeImpl((*h).name as *mut c_void);
5354 }
5355 // Run any conversion-context destructor before freeing the struct,
5356 // matching upstream's ordering (name, then ctxtDtor, then struct).
5357 if let Some(dtor) = (*h).ctxtDtor {
5358 if !(*h).inputCtxt.is_null() {
5359 dtor((*h).inputCtxt);
5360 }
5361 if !(*h).outputCtxt.is_null() {
5362 dtor((*h).outputCtxt);
5363 }
5364 }
5365 crate::abi::allocator::xmlFreeImpl(handler);
5366 }
5367 0
5368}
5369
5370/// Convert a block of ISO-8859-1 bytes to UTF-8 (upstream encoding.c
5371/// `xmlIsolat1ToUTF8`; R-000165 closure).
5372///
5373/// `*outlen`/`*inlen` are updated with the bytes produced/consumed; returns
5374/// the number of bytes written or an xmlCharEncError code.
5375///
5376/// # SAFETY
5377///
5378/// `out`/`in` must be valid buffers for `*outlen`/`*inlen` bytes.
5379#[no_mangle]
5380pub unsafe extern "C" fn xmlIsolat1ToUTF8(
5381 out: *mut u8,
5382 outlen: *mut c_int,
5383 input: *const u8,
5384 inlen: *mut c_int,
5385) -> c_int {
5386 // xmlCharEncError (encoding.h): SUCCESS 0, INTERNAL -1, SPACE -2.
5387 const XML_ENC_ERR_SPACE: c_int = -2;
5388 const XML_ENC_ERR_INTERNAL: c_int = -1;
5389 unsafe {
5390 if out.is_null() || input.is_null() || outlen.is_null() || inlen.is_null() {
5391 return XML_ENC_ERR_INTERNAL;
5392 }
5393 let outstart = out;
5394 let instart = input;
5395 let outend = out.add(*outlen as usize);
5396 let inend = input.add(*inlen as usize);
5397 let mut cur = input;
5398 let mut o = out;
5399 while cur < inend {
5400 let c = *cur;
5401 if c < 0x80 {
5402 if o >= outend {
5403 break;
5404 }
5405 *o = c;
5406 o = o.add(1);
5407 } else {
5408 if (outend as usize) - (o as usize) < 2 {
5409 break;
5410 }
5411 *o = (c >> 6) | 0xC0;
5412 *o.add(1) = (c & 0x3F) | 0x80;
5413 o = o.add(2);
5414 }
5415 cur = cur.add(1);
5416 }
5417 let mut ret = XML_ENC_ERR_SPACE;
5418 if cur == inend {
5419 ret = (o as usize - outstart as usize) as c_int;
5420 }
5421 *outlen = (o as usize - outstart as usize) as c_int;
5422 *inlen = (cur as usize - instart as usize) as c_int;
5423 ret
5424 }
5425}
5426
5427/// Convert a block of UTF-8 to ISO-8859-1 (upstream encoding.c
5428/// `xmlUTF8ToIsolat1`; R-000165 closure).
5429///
5430/// # SAFETY
5431///
5432/// `out`/`in` must be valid buffers for `*outlen`/`*inlen` bytes.
5433#[no_mangle]
5434pub unsafe extern "C" fn xmlUTF8ToIsolat1(
5435 out: *mut u8,
5436 outlen: *mut c_int,
5437 input: *const u8,
5438 inlen: *mut c_int,
5439) -> c_int {
5440 const XML_ENC_ERR_SPACE: c_int = -2;
5441 const XML_ENC_ERR_INTERNAL: c_int = -1;
5442 const XML_ENC_ERR_INPUT: c_int = -3;
5443 const XML_ENC_ERR_SUCCESS: c_int = 0;
5444 unsafe {
5445 if out.is_null() || outlen.is_null() || inlen.is_null() {
5446 return XML_ENC_ERR_INTERNAL;
5447 }
5448 if input.is_null() {
5449 *inlen = 0;
5450 *outlen = 0;
5451 return XML_ENC_ERR_SUCCESS;
5452 }
5453 let outstart = out;
5454 let instart = input;
5455 let outend = out.add(*outlen as usize);
5456 let inend = input.add(*inlen as usize);
5457 let mut cur = input;
5458 let mut o = out;
5459 let mut ret = XML_ENC_ERR_SPACE;
5460 while cur < inend {
5461 if o >= outend {
5462 break;
5463 }
5464 let c = *cur;
5465 if c < 0x80 {
5466 *o = c;
5467 o = o.add(1);
5468 } else if (0xC2..=0xC3).contains(&c) {
5469 if (inend as usize) - (cur as usize) < 2 {
5470 break;
5471 }
5472 cur = cur.add(1);
5473 *o = (c << 6) | (*cur & 0x3F);
5474 o = o.add(1);
5475 } else {
5476 ret = XML_ENC_ERR_INPUT;
5477 break;
5478 }
5479 cur = cur.add(1);
5480 }
5481 if ret != XML_ENC_ERR_INPUT {
5482 ret = (o as usize - outstart as usize) as c_int;
5483 }
5484 *outlen = (o as usize - outstart as usize) as c_int;
5485 *inlen = (cur as usize - instart as usize) as c_int;
5486 ret
5487 }
5488}
5489
5490/// Return the name of a character encoding (upstream encoding.h).
5491///
5492/// # UPSTREAM-PARITY
5493///
5494/// ```c
5495/// const char *xmlGetCharEncodingName(xmlCharEncoding enc);
5496/// ```
5497#[no_mangle]
5498pub extern "C" fn xmlGetCharEncodingName(enc: c_int) -> *const c_char {
5499 /* Values outside the local enum resolve against the upstream
5500 * defaultHandlers table (XML_CHAR_ENCODING_UTF16=23, HTML=24,
5501 * WINDOWS_1252=31); anything else is unknown (NULL). */
5502 if !(-1..=22).contains(&enc) {
5503 return match enc {
5504 23 => c"UTF-16".as_ptr(),
5505 24 => c"HTML".as_ptr(),
5506 31 => c"windows-1252".as_ptr(),
5507 _ => ptr::null(),
5508 };
5509 }
5510 let e: crate::abi::types::xmlCharEncoding = unsafe { core::mem::transmute(enc) };
5511 crate::xml::encoding::xmlGetCharEncodingName(e)
5512}
5513
5514/// Parse an encoding name into an xmlCharEncoding value (upstream encoding.h).
5515///
5516/// # UPSTREAM-PARITY
5517///
5518/// ```c
5519/// xmlCharEncoding xmlParseCharEncoding(const char *name);
5520/// ```
5521///
5522/// Returns the encoding value or XML_CHAR_ENCODING_ERROR (-1).
5523#[no_mangle]
5524pub extern "C" fn xmlParseCharEncoding(name: *const c_char) -> c_int {
5525 crate::xml::encoding::xmlParseCharEncoding(name)
5526}
5527
5528/// Add an encoding alias (upstream encoding.h).
5529///
5530/// # UPSTREAM-PARITY
5531///
5532/// ```c
5533/// int xmlAddEncodingAlias(const char *name, const char *alias);
5534/// ```
5535#[no_mangle]
5536pub extern "C" fn xmlAddEncodingAlias(name: *const c_char, alias: *const c_char) -> c_int {
5537 crate::xml::encoding::add_encoding_alias(name, alias)
5538}
5539
5540/// Delete an encoding alias (upstream encoding.h).
5541///
5542/// # UPSTREAM-PARITY
5543///
5544/// ```c
5545/// int xmlDelEncodingAlias(const char *alias);
5546/// ```
5547#[no_mangle]
5548pub extern "C" fn xmlDelEncodingAlias(alias: *const c_char) -> c_int {
5549 crate::xml::encoding::del_encoding_alias(alias)
5550}
5551
5552/// Look up an encoding alias (upstream encoding.h).
5553///
5554/// # UPSTREAM-PARITY
5555///
5556/// ```c
5557/// const char *xmlGetEncodingAlias(const char *alias);
5558/// ```
5559#[no_mangle]
5560pub extern "C" fn xmlGetEncodingAlias(alias: *const c_char) -> *const c_char {
5561 crate::xml::encoding::get_encoding_alias(alias)
5562}
5563
5564/// Clean up the encoding alias table (upstream encoding.h).
5565///
5566/// # UPSTREAM-PARITY
5567///
5568/// ```c
5569/// void xmlCleanupEncodingAliases(void);
5570/// ```
5571#[no_mangle]
5572pub extern "C" fn xmlCleanupEncodingAliases() {
5573 crate::xml::encoding::cleanup_encoding_aliases();
5574}
5575
5576/// Convert the input buffer using an encoding handler (upstream encoding.h).
5577///
5578/// # UPSTREAM-PARITY
5579///
5580/// ```c
5581/// int xmlCharEncInFunc(xmlCharEncodingHandler *handler,
5582/// xmlBufferPtr out, xmlBufferPtr in);
5583/// ```
5584#[no_mangle]
5585pub extern "C" fn xmlCharEncInFunc(
5586 handler: *mut c_void,
5587 out: *mut c_void,
5588 in_: *mut c_void,
5589) -> c_int {
5590 crate::xml::encoding::xmlCharEncInFunc(
5591 handler as *mut crate::abi::structs::_xmlCharEncodingHandler,
5592 out as *mut crate::abi::structs::_xmlBuffer,
5593 in_ as *mut crate::abi::structs::_xmlBuffer,
5594 )
5595}
5596
5597/// Convert the output buffer using an encoding handler (upstream encoding.h).
5598///
5599/// # UPSTREAM-PARITY
5600///
5601/// ```c
5602/// int xmlCharEncOutFunc(xmlCharEncodingHandler *handler,
5603/// xmlBufferPtr out, xmlBufferPtr in);
5604/// ```
5605#[no_mangle]
5606pub extern "C" fn xmlCharEncOutFunc(
5607 handler: *mut c_void,
5608 out: *mut c_void,
5609 in_: *mut c_void,
5610) -> c_int {
5611 crate::xml::encoding::xmlCharEncOutFunc(
5612 handler as *mut crate::abi::structs::_xmlCharEncodingHandler,
5613 out as *mut crate::abi::structs::_xmlBuffer,
5614 in_ as *mut crate::abi::structs::_xmlBuffer,
5615 )
5616}
5617
5618/// Create a new encoding handler (upstream encoding.h).
5619///
5620/// # UPSTREAM-PARITY
5621///
5622/// ```c
5623/// xmlCharEncodingHandlerPtr xmlNewCharEncodingHandler(
5624/// const char *name, xmlCharEncodingInputFunc input,
5625/// xmlCharEncodingOutputFunc output);
5626/// ```
5627#[no_mangle]
5628pub extern "C" fn xmlNewCharEncodingHandler(
5629 name: *const c_char,
5630 input: crate::abi::callbacks::xmlCharEncodingInputFunc,
5631 output: crate::abi::callbacks::xmlCharEncodingOutputFunc,
5632) -> *mut c_void {
5633 crate::xml::encoding::xmlNewCharEncodingHandler(name, input, output) as *mut c_void
5634}
5635
5636/// Initialize the built-in encoding handlers (upstream encoding.h).
5637///
5638/// # UPSTREAM-PARITY
5639///
5640/// ```c
5641/// void xmlInitCharEncodingHandlers(void);
5642/// ```
5643#[no_mangle]
5644pub extern "C" fn xmlInitCharEncodingHandlers() {
5645 crate::xml::encoding::xmlInitCharEncodingHandlers();
5646}
5647
5648/// Clean up the encoding handlers (upstream encoding.h).
5649///
5650/// # UPSTREAM-PARITY
5651///
5652/// ```c
5653/// void xmlCleanupCharEncodingHandlers(void);
5654/// ```
5655#[no_mangle]
5656pub extern "C" fn xmlCleanupCharEncodingHandlers() {
5657 crate::xml::encoding::xmlCleanupCharEncodingHandlers();
5658}
5659
5660/// Look up a built-in encoding handler by `xmlCharEncoding` value.
5661///
5662/// Returns an `xmlParserErrors` code; on success `*out` receives the static
5663/// handler (NULL for UTF-8, which needs no conversion).
5664///
5665/// # UPSTREAM-PARITY
5666///
5667/// ```c
5668/// xmlParserErrors xmlLookupCharEncodingHandler(xmlCharEncoding enc,
5669/// xmlCharEncodingHandler **out);
5670/// ```
5671#[no_mangle]
5672pub extern "C" fn xmlLookupCharEncodingHandler(enc: c_int, out: *mut *mut c_void) -> c_int {
5673 crate::xml::encoding::xmlLookupCharEncodingHandler(enc, out)
5674}
5675
5676/// Get the encoding handler for an `xmlCharEncoding` value (deprecated).
5677///
5678/// # UPSTREAM-PARITY
5679///
5680/// ```c
5681/// xmlCharEncodingHandler *xmlGetCharEncodingHandler(xmlCharEncoding enc);
5682/// ```
5683#[no_mangle]
5684pub extern "C" fn xmlGetCharEncodingHandler(enc: c_int) -> *mut c_void {
5685 crate::xml::encoding::xmlGetCharEncodingHandler(enc)
5686}
5687
5688/// Find or create an encoding handler by name for one conversion direction.
5689///
5690/// # UPSTREAM-PARITY
5691///
5692/// ```c
5693/// xmlParserErrors xmlOpenCharEncodingHandler(const char *name, int output,
5694/// xmlCharEncodingHandler **out);
5695/// ```
5696#[no_mangle]
5697pub extern "C" fn xmlOpenCharEncodingHandler(
5698 name: *const c_char,
5699 output: c_int,
5700 out: *mut *mut c_void,
5701) -> c_int {
5702 crate::xml::encoding::xmlOpenCharEncodingHandler(name, output, out)
5703}
5704
5705/// Find or create an encoding handler by name with flags and an optional
5706/// custom conversion implementation.
5707///
5708/// # UPSTREAM-PARITY
5709///
5710/// ```c
5711/// xmlParserErrors xmlCreateCharEncodingHandler(
5712/// const char *name, xmlCharEncFlags flags, xmlCharEncConvImpl impl,
5713/// void *implCtxt, xmlCharEncodingHandler **out);
5714/// ```
5715#[no_mangle]
5716pub extern "C" fn xmlCreateCharEncodingHandler(
5717 name: *const c_char,
5718 flags: c_int,
5719 impl_: Option<crate::abi::callbacks::xmlCharEncConvImpl>,
5720 implCtxt: *mut c_void,
5721 out: *mut *mut c_void,
5722) -> c_int {
5723 crate::xml::encoding::xmlCreateCharEncodingHandler(name, flags, impl_, implCtxt, out)
5724}
5725
5726/// Create an encoding handler backed by modern conversion callbacks.
5727///
5728/// # UPSTREAM-PARITY
5729///
5730/// ```c
5731/// xmlParserErrors xmlCharEncNewCustomHandler(
5732/// const char *name, xmlCharEncConvFunc input, xmlCharEncConvFunc output,
5733/// xmlCharEncConvCtxtDtor ctxtDtor, void *inputCtxt, void *outputCtxt,
5734/// xmlCharEncodingHandler **out);
5735/// ```
5736#[no_mangle]
5737pub extern "C" fn xmlCharEncNewCustomHandler(
5738 name: *const c_char,
5739 input: crate::abi::callbacks::xmlCharEncConvFunc,
5740 output: crate::abi::callbacks::xmlCharEncConvFunc,
5741 ctxtDtor: Option<crate::abi::callbacks::xmlCharEncConvCtxtDtor>,
5742 inputCtxt: *mut c_void,
5743 outputCtxt: *mut c_void,
5744 out: *mut *mut c_void,
5745) -> c_int {
5746 crate::xml::encoding::xmlCharEncNewCustomHandler(
5747 name, input, output, ctxtDtor, inputCtxt, outputCtxt, out,
5748 )
5749}
5750
5751/// Convert an input buffer's encoding.
5752///
5753/// # UPSTREAM-PARITY
5754///
5755/// ```c
5756/// int xmlCharEncInput(xmlParserInputBufferPtr input, int to);
5757/// ```
5758#[no_mangle]
5759pub unsafe extern "C" fn xmlCharEncInput(input: *mut _xmlParserInputBuffer, _to: c_int) -> c_int {
5760 if input.is_null() {
5761 return -1;
5762 }
5763 let handler = (*input).encoder as *mut crate::abi::structs::_xmlCharEncodingHandler;
5764 if handler.is_null() {
5765 return -1;
5766 }
5767 let raw = (*input).raw as *mut crate::abi::structs::_xmlBuffer;
5768 let buf = (*input).buffer as *mut crate::abi::structs::_xmlBuffer;
5769 if raw.is_null() || buf.is_null() {
5770 return -1;
5771 }
5772 crate::xml::encoding::char_enc_in(handler, buf, raw)
5773}
5774
5775/// Convert an output buffer's encoding.
5776///
5777/// # UPSTREAM-PARITY
5778///
5779/// ```c
5780/// int xmlCharEncOutput(xmlOutputBufferPtr output, int to);
5781/// ```
5782#[no_mangle]
5783pub unsafe extern "C" fn xmlCharEncOutput(output: *mut _xmlOutputBuffer, _to: c_int) -> c_int {
5784 if output.is_null() {
5785 return -1;
5786 }
5787 let handler = (*output).encoder as *mut crate::abi::structs::_xmlCharEncodingHandler;
5788 if handler.is_null() {
5789 return -1;
5790 }
5791 let buf = (*output).buffer as *mut crate::abi::structs::_xmlBuffer;
5792 let conv = (*output).conv as *mut crate::abi::structs::_xmlBuffer;
5793 if buf.is_null() || conv.is_null() {
5794 return -1;
5795 }
5796 crate::xml::encoding::char_enc_out(handler, conv, buf)
5797}
5798
5799// ═══════════════════════════════════════════════════════════════════════════════
5800// URI
5801// ═══════════════════════════════════════════════════════════════════════════════
5802
5803/// Parse a URI string.
5804///
5805/// # UPSTREAM-PARITY
5806///
5807/// ```c
5808/// xmlURIPtr xmlParseURI(const char *str);
5809/// ```
5810#[no_mangle]
5811pub unsafe extern "C" fn xmlParseURI(str: *const c_char) -> *mut c_void {
5812 crate::xml::uri::xmlParseURI(str)
5813}
5814
5815/// Parse a URI string (raw version).
5816///
5817/// # UPSTREAM-PARITY
5818///
5819/// ```c
5820/// xmlURIPtr xmlParseURIRaw(const char *str, int raw);
5821/// ```
5822#[no_mangle]
5823pub unsafe extern "C" fn xmlParseURIRaw(str: *const c_char, raw: c_int) -> *mut c_void {
5824 let _ = raw;
5825 crate::xml::uri::xmlParseURI(str)
5826}
5827
5828/// Free a URI structure.
5829///
5830/// # UPSTREAM-PARITY
5831///
5832/// ```c
5833/// void xmlFreeURI(xmlURIPtr uri);
5834/// ```
5835#[no_mangle]
5836pub unsafe extern "C" fn xmlFreeURI(uri: *mut c_void) {
5837 crate::xml::uri::xmlFreeURI(uri)
5838}
5839
5840/// Create an empty URI.
5841///
5842/// # UPSTREAM-PARITY
5843///
5844/// ```c
5845/// xmlURIPtr xmlCreateURI(void);
5846/// ```
5847#[no_mangle]
5848pub extern "C" fn xmlCreateURI() -> *mut c_void {
5849 crate::xml::uri::xmlCreateURI()
5850}
5851
5852/// Save a URI structure to a string.
5853///
5854/// # UPSTREAM-PARITY
5855///
5856/// ```c
5857/// xmlChar *xmlSaveUri(xmlURIPtr uri);
5858/// ```
5859#[no_mangle]
5860pub unsafe extern "C" fn xmlSaveUri(uri: *mut c_void) -> *mut xmlChar {
5861 crate::xml::uri::xmlSaveUri(uri)
5862}
5863
5864/// Parse a URI string into an existing URI structure (upstream uri.h).
5865///
5866/// # UPSTREAM-PARITY
5867///
5868/// ```c
5869/// int xmlParseURIReference(xmlURIPtr uri, const char *str);
5870/// ```
5871///
5872/// Returns 0 on success, -1 on failure (the URI structure is left
5873/// untouched on failure).
5874///
5875/// # Safety
5876///
5877/// - `uri` must be a valid pointer from `xmlParseURI`/`xmlCreateURI`.
5878/// - `str` must be a valid null-terminated C string.
5879#[no_mangle]
5880pub unsafe extern "C" fn xmlParseURIReference(uri: *mut c_void, str: *const c_char) -> c_int {
5881 crate::xml::uri::xmlParseURIReference(uri, str)
5882}
5883
5884/// Normalize a URI path in place (upstream uri.h).
5885///
5886/// # UPSTREAM-PARITY
5887///
5888/// ```c
5889/// int xmlNormalizeURIPath(char *path);
5890/// ```
5891///
5892/// Returns 0 on success, -1 if the path is NULL, not absolute, or contains
5893/// `..` segments that climb above the root.
5894///
5895/// # Safety
5896///
5897/// `path` must be a valid writable null-terminated C string buffer.
5898#[no_mangle]
5899pub unsafe extern "C" fn xmlNormalizeURIPath(path: *mut c_char) -> c_int {
5900 crate::xml::uri::xmlNormalizeURIPath(path)
5901}
5902
5903/// Escape a URI string.
5904///
5905/// # UPSTREAM-PARITY
5906///
5907/// ```c
5908/// xmlChar *xmlURIEscapeStr(const xmlChar *str, const xmlChar *list);
5909/// ```
5910#[no_mangle]
5911pub unsafe extern "C" fn xmlURIEscapeStr(
5912 str: *const xmlChar,
5913 list: *const xmlChar,
5914) -> *mut xmlChar {
5915 crate::xml::uri::xmlURIEscapeStr(str, list)
5916}
5917
5918/// Unescape a URI string.
5919///
5920/// # UPSTREAM-PARITY
5921///
5922/// ```c
5923/// char *xmlURIUnescapeString(const char *str, int len, char *target);
5924/// ```
5925#[no_mangle]
5926pub unsafe extern "C" fn xmlURIUnescapeString(
5927 str: *const c_char,
5928 len: c_int,
5929 target: *mut c_char,
5930) -> *mut c_char {
5931 crate::xml::uri::xmlURIUnescapeString(str, len, target)
5932}
5933
5934// ═══════════════════════════════════════════════════════════════════════════════
5935// 14. XPath
5936// ═══════════════════════════════════════════════════════════════════════════════
5937
5938// ── Helper functions ────────────────────────────────────────────────────
5939
5940/// Convert an internal `XPathValue` to a C ABI `_xmlXPathObject`.
5941///
5942/// The returned pointer is heap-allocated via `xmlMallocZero` and must be
5943/// freed with `xmlXPathFreeObject`.
5944///
5945/// # Safety
5946///
5947/// Must be called from a context where `xmlMalloc` is safe to call.
5948unsafe fn xpath_to_object(val: XPathValue) -> *mut _xmlXPathObject {
5949 let obj = xmlMallocZero(size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject;
5950 if obj.is_null() {
5951 return ptr::null_mut();
5952 }
5953 match val {
5954 XPathValue::NodeSet(ns) => {
5955 (*obj).type_ = xmlXPathObjectType::XPATH_NODESET as c_int;
5956 (*obj).nodesetval = ns.to_raw() as *mut c_void;
5957 }
5958 XPathValue::Boolean(b) => {
5959 (*obj).type_ = xmlXPathObjectType::XPATH_BOOLEAN as c_int;
5960 (*obj).boolval = if b { 1 } else { 0 };
5961 }
5962 XPathValue::Number(n) => {
5963 (*obj).type_ = xmlXPathObjectType::XPATH_NUMBER as c_int;
5964 (*obj).floatval = n;
5965 }
5966 XPathValue::String(s) => {
5967 (*obj).type_ = xmlXPathObjectType::XPATH_STRING as c_int;
5968 let bytes = s.as_bytes();
5969 let len = bytes.len();
5970 let buf = xmlMallocImpl(len + 1) as *mut xmlChar;
5971 if !buf.is_null() {
5972 ptr::copy_nonoverlapping(bytes.as_ptr(), buf, len);
5973 *buf.add(len) = 0; // null terminator
5974 }
5975 (*obj).stringval = buf;
5976 }
5977 }
5978 obj
5979}
5980
5981/// Extract an internal `XPathValue` from a C ABI `_xmlXPathObject`.
5982///
5983/// # Safety
5984///
5985/// `obj` must be a valid, non-null pointer to a properly initialised
5986/// `_xmlXPathObject`.
5987unsafe fn object_to_xpathvalue(obj: *mut _xmlXPathObject) -> XPathValue {
5988 let typ = (*obj).type_;
5989 if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
5990 let ns_ptr = (*obj).nodesetval as *mut _xmlNodeSet;
5991 if ns_ptr.is_null() {
5992 return XPathValue::NodeSet(NodeSet::new());
5993 }
5994 let node_nr = (*ns_ptr).nodeNr;
5995 let node_tab = (*ns_ptr).nodeTab;
5996 let mut ns = NodeSet::new();
5997 if !node_tab.is_null() {
5998 for i in 0..node_nr as isize {
5999 let node = *node_tab.add(i as usize);
6000 ns.push(node);
6001 }
6002 }
6003 XPathValue::NodeSet(ns)
6004 } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
6005 XPathValue::Boolean((*obj).boolval != 0)
6006 } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
6007 XPathValue::Number((*obj).floatval)
6008 } else if typ == xmlXPathObjectType::XPATH_STRING as c_int {
6009 let s_ptr = (*obj).stringval;
6010 if s_ptr.is_null() {
6011 XPathValue::String(String::new())
6012 } else {
6013 let s = CStr::from_ptr(s_ptr as *const c_char)
6014 .to_string_lossy()
6015 .into_owned();
6016 XPathValue::String(s)
6017 }
6018 } else if typ == xmlXPathObjectType::XPATH_XSLT_TREE as c_int {
6019 // A result tree fragment: node-set containing the fragment's
6020 // document node (matching how global RTF variables are bound), so
6021 // local RTF variables stringify to their text and remain navigable
6022 // via exsl:node-set.
6023 let frag_doc = (*obj).nodesetval as *mut _xmlDoc;
6024 if frag_doc.is_null() {
6025 XPathValue::NodeSet(NodeSet::new())
6026 } else {
6027 let mut ns = NodeSet::new();
6028 ns.push(frag_doc as *mut _xmlNode);
6029 XPathValue::NodeSet(ns)
6030 }
6031 } else {
6032 // Undefined / unknown type — return boolean false as a safe default.
6033 XPathValue::Boolean(false)
6034 }
6035}
6036
6037/// Public wrapper for `xpath_to_object` (used by the XPath export bridge).
6038///
6039/// # Safety
6040///
6041/// - `val` is consumed and converted into a heap-allocated `_xmlXPathObject`.
6042pub unsafe fn xpath_to_object_pub(val: XPathValue) -> *mut _xmlXPathObject {
6043 xpath_to_object(val)
6044}
6045
6046/// Public wrapper for `object_to_xpathvalue` (used by the XSLT engine).
6047///
6048/// # Safety
6049///
6050/// `obj` must be a valid, non-null pointer to a properly initialised
6051/// `_xmlXPathObject`.
6052pub unsafe fn object_to_xpathvalue_pub(obj: *mut _xmlXPathObject) -> XPathValue {
6053 object_to_xpathvalue(obj)
6054}
6055
6056// ── Compiled expression registry ────────────────────────────────────────
6057//
6058// Compiled XPath expressions are opaque pointers returned by xmlXPathCompile.
6059// We store them in a global registry keyed by a monotonically increasing ID.
6060
6061static COMPILED_EXPRS: Lazy<Mutex<HashMap<u64, Box<CompiledExpr>>>> =
6062 Lazy::new(|| Mutex::new(HashMap::new()));
6063static NEXT_COMPILED_KEY: Lazy<Mutex<u64>> = Lazy::new(|| Mutex::new(1));
6064
6065/// Accessor for the compiled-expression registry (used by the XPath export
6066/// bridge for `xmlXPathCompiledEval` / `xmlXPathCompiledEvalToBoolean`).
6067pub(crate) fn xpath_compiled_registry() -> &'static Mutex<HashMap<u64, Box<CompiledExpr>>> {
6068 &COMPILED_EXPRS
6069}
6070
6071// ── C extension-function registry ──────────────────────────────────────
6072//
6073// C extension functions registered via xmlXPathRegisterFunc / RegisterFuncNS
6074// are stored here because the Rust XPathFunction signature is incompatible
6075// with the C xmlXPathFunction calling convention (the C function expects a
6076// parser context, not pre-evaluated argument slices). The registration is
6077// stored faithfully; invoking registered C functions from within the Rust
6078// evaluator requires a bridge that is not yet implemented.
6079
6080type CXPathFunc = unsafe extern "C" fn(*mut c_void, c_int);
6081
6082/// Wrapper around `*mut c_void` that implements `Send` + `Sync` so it can
6083/// be used as a key in a `Mutex`-protected global `HashMap`.
6084#[derive(Clone, Copy, PartialEq, Eq, Hash)]
6085struct SendSyncPtr(*mut c_void);
6086unsafe impl Send for SendSyncPtr {}
6087unsafe impl Sync for SendSyncPtr {}
6088
6089static C_FUNCTIONS: Lazy<Mutex<HashMap<(SendSyncPtr, String), CXPathFunc>>> =
6090 Lazy::new(|| Mutex::new(HashMap::new()));
6091
6092/// Look up a C-registered extension function for the context identified by
6093/// `extra` (the internal XPathContext pointer). Used by
6094/// `xmlXPathFunctionLookupNS`.
6095pub(crate) fn xpath_cfunc_lookup(extra: *mut c_void, qualified: &str) -> Option<CXPathFunc> {
6096 C_FUNCTIONS
6097 .lock()
6098 .get(&(SendSyncPtr(extra), qualified.to_string()))
6099 .copied()
6100}
6101
6102/// Drop every C extension-function registration belonging to the context
6103/// identified by `extra` (upstream `xmlXPathRegisteredFuncsCleanup`).
6104pub(crate) fn xpath_cfunc_cleanup(extra: *mut c_void) {
6105 C_FUNCTIONS.lock().retain(|(k, _), _| k.0 != extra);
6106}
6107
6108/// Build the Rust-side closure that bridges a C-registered XPath function
6109/// into the Rust evaluator (see `c_func_call_bridge`). Returns a
6110/// `BoxedXPathFunction` so the closure is coerced with the higher-ranked
6111/// signature the evaluator requires.
6112fn c_func_bridge_closure(c_ctxt: SendSyncPtr, qualified: String) -> BoxedXPathFunction {
6113 let (local_name, ns_uri) = split_qualified(&qualified);
6114 Box::new(move |_ctx: &mut XPathContext, args: &[XPathValue]| {
6115 let cc = c_ctxt;
6116 unsafe {
6117 c_func_call_bridge(
6118 cc.0 as *mut _xmlXPathContext,
6119 &qualified,
6120 &local_name,
6121 ns_uri.as_deref(),
6122 args,
6123 )
6124 }
6125 })
6126}
6127
6128/// Split a registered function key (`{uri}name` — the Clark notation used by
6129/// `xmlXPathRegisterFuncNS` — or a bare `name`) into the LOCAL function name
6130/// and the optional namespace URI. Upstream sets exactly these two on
6131/// `ctxt->context->function` / `functionURI` before invoking a registered C
6132/// function (xpath.c xmlXPathCompOpEval), and PHP's dom/xsl trampolines read
6133/// them back to dispatch to the registered PHP closure.
6134fn split_qualified(qualified: &str) -> (String, Option<String>) {
6135 if let Some(rest) = qualified.strip_prefix('{') {
6136 if let Some(end) = rest.find('}') {
6137 let uri = rest[..end].to_string();
6138 let local = rest[end + 1..].to_string();
6139 return (local, Some(uri));
6140 }
6141 }
6142 (qualified.to_string(), None)
6143}
6144
6145/// Call a C-ABI `xmlXPathFunction` through a synthesized
6146/// `xmlXPathParserContext`: push the evaluated arguments as XPath objects,
6147/// invoke the function, pop and convert the result — the upstream
6148/// `xmlXPathCompOpEval` function-call sequence (xpath.c).
6149///
6150/// # UPSTREAM-PARITY
6151///
6152/// xpath.c xmlXPathCompOpEval (XPATH_OP_FUNCTION) sets the in-context
6153/// function identity before the call and restores it after:
6154///
6155/// ```c
6156/// oldFunc = ctxt->context->function;
6157/// oldFuncURI = ctxt->context->functionURI;
6158/// ctxt->context->function = op->value4; /* local name */
6159/// ctxt->context->functionURI = op->cacheURI; /* resolved ns URI or NULL */
6160/// func(ctxt, op->value);
6161/// ctxt->context->function = oldFunc;
6162/// ctxt->context->functionURI = oldFuncURI;
6163/// ```
6164///
6165/// PHP registers ONE trampoline for every custom-namespace XPath function
6166/// and dispatches to the PHP closure by reading `ctxt->context->function` /
6167/// `functionURI`, so without these fields it dereferences garbage
6168/// (SP-14.3.6-dom O1: return_dom_node_from_xpath / registerPhpFunctionNS
6169/// segv).
6170///
6171/// # SAFETY
6172///
6173/// - `fnptr` must be a valid C callback (or None).
6174/// - `c_ctxt` must be the live C XPath context the callback belongs to.
6175/// - `name`/`ns_uri` must be the function's local name / namespace being
6176/// invoked, valid for the duration of the call.
6177pub(crate) unsafe fn call_c_xpath_function(
6178 fnptr: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
6179 c_ctxt: *mut _xmlXPathContext,
6180 name: &str,
6181 ns_uri: Option<&str>,
6182 args: &[XPathValue],
6183) -> Result<XPathValue, String> {
6184 let func = match fnptr {
6185 Some(f) => f,
6186 None => return Err("XPath: missing C function pointer".to_string()),
6187 };
6188 let pc = crate::xml::xpath::parser_context::new_parser_context(ptr::null(), c_ctxt);
6189 if pc.is_null() {
6190 return Err("XPath: parser-context allocation failure".to_string());
6191 }
6192 let mut push_ok = true;
6193 for v in args {
6194 let obj = xpath_to_object(v.clone());
6195 if obj.is_null() || crate::xml::xpath::parser_context::value_push(pc, obj).is_null() {
6196 push_ok = false;
6197 break;
6198 }
6199 }
6200 let result = if push_ok {
6201 // NUL-terminated buffers naming the invoked function, live for the
6202 // callback duration (upstream op->value4 / op->cacheURI).
6203 let mut name_nul: Vec<xmlChar> = name.as_bytes().to_vec();
6204 name_nul.push(0);
6205 let uri_nul: Option<Vec<xmlChar>> = ns_uri.map(|u| {
6206 let mut v = u.as_bytes().to_vec();
6207 v.push(0);
6208 v
6209 });
6210 let saved_function = (*c_ctxt).function;
6211 let saved_function_uri = (*c_ctxt).functionURI;
6212 (*c_ctxt).function = name_nul.as_ptr() as *const xmlChar;
6213 (*c_ctxt).functionURI = uri_nul
6214 .as_ref()
6215 .map_or(ptr::null(), |v| v.as_ptr() as *const xmlChar);
6216 // SAFETY: `func` is a valid C callback; the arguments are on the
6217 // parser-context value stack exactly as upstream would leave them
6218 // and the context names the invoked function.
6219 unsafe { func(pc as *mut c_void, args.len() as c_int) };
6220 (*c_ctxt).function = saved_function;
6221 (*c_ctxt).functionURI = saved_function_uri;
6222 let ret = crate::xml::xpath::parser_context::value_pop(pc);
6223 if ret.is_null() {
6224 Err("XPath: C function returned no value".to_string())
6225 } else {
6226 let v = object_to_xpathvalue(ret);
6227 // The popped object is heap-allocated; free it after converting.
6228 unsafe { xmlXPathFreeObject(ret) };
6229 Ok(v)
6230 }
6231 } else {
6232 Err("XPath: failed to push arguments to C function".to_string())
6233 };
6234 // Free any objects the C function left on the stack, then the context.
6235 unsafe {
6236 loop {
6237 let leftover = crate::xml::xpath::parser_context::value_pop(pc);
6238 if leftover.is_null() {
6239 break;
6240 }
6241 xmlXPathFreeObject(leftover);
6242 }
6243 crate::xml::xpath::parser_context::free_parser_context(pc);
6244 }
6245 result
6246}
6247
6248/// Invoke an XSLT extension / module function through the upstream
6249/// parser-context protocol, with an upstream-layout context.
6250///
6251/// Upstream libxslt stores the transform context in `xmlXPathContext.extra`
6252/// (XSLT_REGISTER_VARIABLE_LOOKUP, variables.h), and PHP's xsl callbacks
6253/// read `parser_ctxt->context->extra` DIRECTLY as the
6254/// `xsltTransformContextPtr` (xsltprocessor.c xsl_proxy_factory). The
6255/// candidate reserves `extra` for the internal Rust `XPathContext`, so this
6256/// bridge synthesises a shallow MIRROR of the C context (same doc/node/…,
6257/// `extra` = transform context) that lives only for the callback duration.
6258/// The real transform XPath context is left untouched; the function name
6259/// is set on the mirror (php's call_custom_ns reads `context->function` /
6260/// `functionURI`), and arguments are pushed in evaluation order (last arg
6261/// on top) exactly as upstream `xmlXPathCompOpEval` leaves them.
6262///
6263/// Returns `Err` when the callback produced no value.
6264///
6265/// # Safety
6266///
6267/// - `fnptr` must be a C `xmlXPathFunction`-compatible callback.
6268/// - `tctxt` / `xpath_ctxt` must be the live transform context pair.
6269/// - `xpath_ctxt` must be the transform context's own `xpathCtxt`.
6270pub(crate) unsafe fn call_xslt_ext_function(
6271 fnptr: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
6272 tctxt: *mut crate::abi::structs::_xsltTransformContext,
6273 xpath_ctxt: *mut _xmlXPathContext,
6274 name: &str,
6275 ns_uri: Option<&str>,
6276 args: &[XPathValue],
6277) -> Result<XPathValue, String> {
6278 let func = match fnptr {
6279 Some(f) => f,
6280 None => return Err("XPath: missing C function pointer".to_string()),
6281 };
6282 if tctxt.is_null() || xpath_ctxt.is_null() {
6283 return Err("XPath: null XSLT context in extension-function bridge".to_string());
6284 }
6285 // Mirror: shallow copy of the C-visible context with `extra` = tctxt
6286 // (upstream layout that php's proxy code dereferences).
6287 let mirror = libc::calloc(1, core::mem::size_of::<_xmlXPathContext>()) as *mut _xmlXPathContext;
6288 if mirror.is_null() {
6289 return Err("XPath: mirror-context allocation failure".to_string());
6290 }
6291 unsafe {
6292 libc::memcpy(
6293 mirror as *mut libc::c_void,
6294 xpath_ctxt as *const libc::c_void,
6295 core::mem::size_of::<_xmlXPathContext>(),
6296 );
6297 (*mirror).extra = tctxt as *mut c_void;
6298 let pc = crate::xml::xpath::parser_context::new_parser_context(ptr::null(), mirror);
6299 if pc.is_null() {
6300 libc::free(mirror as *mut libc::c_void);
6301 return Err("XPath: parser-context allocation failure".to_string());
6302 }
6303 let mut push_ok = true;
6304 for v in args {
6305 let obj = xpath_to_object(v.clone());
6306 if obj.is_null() || crate::xml::xpath::parser_context::value_push(pc, obj).is_null() {
6307 push_ok = false;
6308 break;
6309 }
6310 }
6311 let result = if push_ok {
6312 // NUL-terminated buffers naming the invoked function, live for
6313 // the callback duration (upstream op->value4 / op->cacheURI on
6314 // the eval context).
6315 let mut name_nul: Vec<xmlChar> = name.as_bytes().to_vec();
6316 name_nul.push(0);
6317 let uri_nul: Option<Vec<xmlChar>> = ns_uri.map(|u| {
6318 let mut v = u.as_bytes().to_vec();
6319 v.push(0);
6320 v
6321 });
6322 (*mirror).function = name_nul.as_ptr() as *const xmlChar;
6323 (*mirror).functionURI = uri_nul
6324 .as_ref()
6325 .map_or(ptr::null(), |v| v.as_ptr() as *const xmlChar);
6326 // SAFETY: `func` is a valid C callback; the arguments are on the
6327 // parser-context value stack exactly as upstream would leave them
6328 // and the context names the invoked function.
6329 func(pc as *mut c_void, args.len() as c_int);
6330 let ret = crate::xml::xpath::parser_context::value_pop(pc);
6331 if ret.is_null() {
6332 Err("XPath: C function returned no value".to_string())
6333 } else {
6334 let v = object_to_xpathvalue(ret);
6335 // The popped object is heap-allocated; free it after converting.
6336 xmlXPathFreeObject(ret);
6337 Ok(v)
6338 }
6339 } else {
6340 Err("XPath: failed to push arguments to C function".to_string())
6341 };
6342 // Free any objects the C function left on the stack, then the
6343 // parser context and the mirror.
6344 loop {
6345 let leftover = crate::xml::xpath::parser_context::value_pop(pc);
6346 if leftover.is_null() {
6347 break;
6348 }
6349 xmlXPathFreeObject(leftover);
6350 }
6351 crate::xml::xpath::parser_context::free_parser_context(pc);
6352 libc::free(mirror as *mut libc::c_void);
6353 result
6354 }
6355}
6356
6357/// Rust-side wrapper registered in the internal XPathContext when a C
6358/// extension function is registered (`xmlXPathRegisterFunc[NS]`). This is the
6359/// parser-context bridge: it synthesises the upstream `xmlXPathParserContext`
6360/// (value stack + context pointer), pushes the evaluated arguments as XPath
6361/// objects, invokes the C function, then pops and converts the result — the
6362/// upstream `xmlXPathCompOpEval` function-call sequence (xpath.c).
6363unsafe fn c_func_call_bridge(
6364 c_ctxt: *mut _xmlXPathContext,
6365 qualified: &str,
6366 name: &str,
6367 ns_uri: Option<&str>,
6368 args: &[XPathValue],
6369) -> Result<XPathValue, String> {
6370 if c_ctxt.is_null() {
6371 return Err("XPath: null context in C function bridge".to_string());
6372 }
6373 let func = xpath_cfunc_lookup((*c_ctxt).extra, qualified);
6374 if func.is_none() {
6375 return Err(format!("XPath: unknown C function '{}'", qualified));
6376 }
6377 unsafe { call_c_xpath_function(func, c_ctxt, name, ns_uri, args) }
6378}
6379
6380// ── Public API ─────────────────────────────────────────────────────────
6381
6382/// Create a new XPath context.
6383///
6384/// Allocates a `_xmlXPathContext` and an internal `XPathContext`, storing
6385/// the latter's pointer in the `extra` field.
6386///
6387/// # UPSTREAM-PARITY
6388///
6389/// ```c
6390/// xmlXPathContextPtr xmlXPathNewContext(xmlDocPtr doc);
6391/// ```
6392#[no_mangle]
6393pub unsafe extern "C" fn xmlXPathNewContext(doc: *mut _xmlDoc) -> *mut _xmlXPathContext {
6394 let ctxt = xmlMallocZero(size_of::<_xmlXPathContext>()) as *mut _xmlXPathContext;
6395 if ctxt.is_null() {
6396 return ptr::null_mut();
6397 }
6398
6399 // Initialise the C ABI context fields.
6400 (*ctxt).doc = doc;
6401 (*ctxt).node = ptr::null_mut();
6402 (*ctxt).contextSize = 1;
6403 (*ctxt).proximityPosition = 1;
6404
6405 // Create the internal XPathContext and store it in `extra`.
6406 let mut internal = Box::new(XPathContext::new(doc));
6407 // UPSTREAM-PARITY: the standard function library is implicitly available
6408 // in every context (upstream compiles it in; xmlXPathRegisterAllFunctions
6409 // is a no-op since 2.14.0). Without this, core-function calls such as
6410 // count() would fail as unknown functions.
6411 for (name, func) in crate::xml::xpath::functions::core_functions() {
6412 internal.register_function(&name, func);
6413 }
6414 internal.c_context = ctxt;
6415 (*ctxt).extra = Box::into_raw(internal) as *mut c_void;
6416
6417 ctxt
6418}
6419
6420/// Deallocator for `xmlXPathContext.nsHash` payloads (strdup'd namespace
6421/// URIs; upstream `xmlXPathFreeContext` / `xmlXPathRegisteredNsCleanup` pass
6422/// `xmlFree`).
6423pub(crate) unsafe extern "C" fn free_ns_uri_payload(payload: *mut c_void, _key: *mut xmlChar) {
6424 if !payload.is_null() {
6425 crate::abi::allocator::xmlFreeImpl(payload);
6426 }
6427}
6428
6429/// Free an XPath context.
6430///
6431/// # UPSTREAM-PARITY
6432///
6433/// ```c
6434/// void xmlXPathFreeContext(xmlXPathContextPtr ctxt);
6435/// ```
6436#[no_mangle]
6437pub unsafe extern "C" fn xmlXPathFreeContext(ctxt: *mut _xmlXPathContext) {
6438 if ctxt.is_null() {
6439 return;
6440 }
6441 // Drop the internal XPathContext.
6442 if !(*ctxt).extra.is_null() {
6443 let _ = Box::from_raw((*ctxt).extra as *mut XPathContext);
6444 (*ctxt).extra = ptr::null_mut();
6445 }
6446 // Free the registered-namespace hash (upstream xmlXPathFreeContext:
6447 // xmlHashFree(ctxt->nsHash, xmlFree) — the payloads are strdup'd URIs).
6448 if !(*ctxt).nsHash.is_null() {
6449 xmlHashFree((*ctxt).nsHash, Some(free_ns_uri_payload));
6450 (*ctxt).nsHash = ptr::null_mut();
6451 }
6452 // Free the C ABI context struct.
6453 xmlFreeImpl(ctxt as *mut c_void);
6454}
6455
6456/// Evaluate an XPath expression.
6457///
6458/// # UPSTREAM-PARITY
6459///
6460/// ```c
6461/// xmlXPathObjectPtr xmlXPathEvalExpression(const xmlChar *str,
6462/// xmlXPathContextPtr ctxt);
6463/// ```
6464#[no_mangle]
6465pub unsafe extern "C" fn xmlXPathEvalExpression(
6466 str_: *const xmlChar,
6467 ctxt: *mut _xmlXPathContext,
6468) -> *mut _xmlXPathObject {
6469 if str_.is_null() || ctxt.is_null() {
6470 return ptr::null_mut();
6471 }
6472 let expr_str = match CStr::from_ptr(str_ as *const c_char).to_str() {
6473 Ok(s) => s,
6474 Err(_) => return ptr::null_mut(),
6475 };
6476 let internal = (*ctxt).extra as *mut XPathContext;
6477 if internal.is_null() {
6478 return ptr::null_mut();
6479 }
6480 let internal = &mut *internal;
6481 // UPSTREAM-PARITY (xpath.c xmlXPathEvalExpression): the evaluation
6482 // context node and position come from the C context fields — consumers
6483 // (lxml XPathElementEvaluator) set xpathCtxt->node per evaluation — so
6484 // mirror them into the internal context before evaluating. The pre-fix
6485 // code never did, so relative paths ("a", "./a", "a/@i") evaluated
6486 // against a NULL context node and returned an empty node-set (Phase 14
6487 // lxml XPath court).
6488 internal.set_context_node((*ctxt).node);
6489 internal.context_position = (*ctxt).proximityPosition;
6490 internal.context_size = (*ctxt).contextSize;
6491 internal.proximity_position = (*ctxt).proximityPosition;
6492 // Mirror the C context's namespace array (upstream xmlXPathNsLookup
6493 // consults ctxt->namespaces/nsNr first). PHP's DOMXPath fills the array
6494 // with the CONTEXT NODE's in-scope namespaces before evaluating
6495 // (ext/dom xpath.c php_dom_get_in_scope_ns*), so prefixed tests resolve
6496 // without an explicit registerNamespace when the document declares them.
6497 crate::abi::exports_xml2::sync_xpath_context_namespaces(ctxt, internal);
6498 // Clear any stale error so a fresh evaluation either succeeds or records
6499 // its own failure message (the XSLT layer surfaces it verbatim).
6500 internal.clear_error();
6501
6502 match crate::xml::xpath::evaluate_str(expr_str, internal) {
6503 Some(val) => xpath_to_object(val),
6504 None => {
6505 // UPSTREAM-PARITY (xpath.c xmlXPathErrFmt): report the failure
6506 // through the C context (ctxt->lastError pre-fill + ctxt->error
6507 // handler with ctxt->userData) so consumers like lxml's
6508 // _receiveXPathError receive the specific message.
6509 raise_internal_xpath_error(ctxt, internal, expr_str);
6510 ptr::null_mut()
6511 }
6512 }
6513}
6514
6515/// Map an internal XPath error message to its upstream `xmlXPathError` code
6516/// (0-based, xpath.h) and raise it through the C context.
6517pub(crate) unsafe fn raise_internal_xpath_error(
6518 ctxt: *mut _xmlXPathContext,
6519 internal: &mut XPathContext,
6520 expr: &str,
6521) {
6522 let (xpath_code, message) = match internal.error.as_deref() {
6523 Some(m) if m.starts_with("Undefined namespace prefix") => (XPATH_UNDEF_PREFIX_ERROR, m),
6524 Some(m) if m.starts_with("Unregistered function") => (XPATH_UNKNOWN_FUNC_ERROR, m),
6525 Some(m) if m.starts_with("Undefined variable") => (XPATH_UNDEF_VARIABLE_ERROR, m),
6526 Some(m) => (XPATH_EXPR_ERROR, m),
6527 None => {
6528 internal.set_error("Invalid expression");
6529 (XPATH_EXPR_ERROR, "Invalid expression")
6530 }
6531 };
6532 unsafe { raise_xpath_error(ctxt, xpath_code, message, expr) }
6533}
6534
6535/// Mirror the C-visible context's `namespaces[0..nsNr]` array into the
6536/// internal XPath context's prefix map (upstream xmlXPathNsLookup consults
6537/// the array before nsHash). PHP's DOMXPath fills the array with the context
6538/// node's in-scope namespaces (ext/dom xpath.c), which is how prefixed
6539/// location steps resolve against the document's declarations.
6540///
6541/// # Safety
6542///
6543/// - `ctxt` must be a valid `_xmlXPathContext`; `internal` its internal
6544/// Rust context (may be shared).
6545pub(crate) unsafe fn sync_xpath_context_namespaces(
6546 ctxt: *mut _xmlXPathContext,
6547 internal: &mut crate::xml::xpath::context::XPathContext,
6548) {
6549 if ctxt.is_null() {
6550 return;
6551 }
6552 unsafe {
6553 let tab = (*ctxt).namespaces;
6554 if tab.is_null() {
6555 return;
6556 }
6557 let count = (*ctxt).nsNr;
6558 if count <= 0 {
6559 return;
6560 }
6561 let mut i = 0;
6562 while i < count {
6563 let ns = *tab.add(i as usize);
6564 if !ns.is_null() && !(*ns).prefix.is_null() && !(*ns).href.is_null() {
6565 let prefix_len = libc::strlen((*ns).prefix as *const libc::c_char) as usize;
6566 let href_len = libc::strlen((*ns).href as *const libc::c_char) as usize;
6567 let prefix =
6568 String::from_utf8_lossy(core::slice::from_raw_parts((*ns).prefix, prefix_len))
6569 .into_owned();
6570 let href =
6571 String::from_utf8_lossy(core::slice::from_raw_parts((*ns).href, href_len))
6572 .into_owned();
6573 internal.register_namespace(&prefix, &href);
6574 }
6575 i += 1;
6576 }
6577 }
6578}
6579
6580/// UPSTREAM-PARITY (xpath.c `xmlXPathErrFmt` -> error.c `xmlVRaiseError`):
6581/// deliver an XPath compile/eval failure to the C context. Pre-fills
6582/// `ctxt->lastError` (domain/code/level, the expression as `str1`, `int1` =
6583/// 0) exactly like upstream's message-less pre-fill, then raises through the
6584/// shared streamed path: TLS-global storage + dispatch to `ctxt->error`
6585/// (with `ctxt->userData`), the global structured handler, or the generic
6586/// channel (`xmlFormatError` "XPath error : ..." fragments).
6587///
6588/// `code` is the 0-based `xmlXPathError` value (candidate `XPATH_*_ERROR`
6589/// constants); the delivered structured code is offset by
6590/// `XML_XPATH_EXPRESSION_OK` (1200) like upstream.
6591///
6592/// # SAFETY
6593///
6594/// - `ctxt` must be a valid `_xmlXPathContext`.
6595pub(crate) unsafe fn raise_xpath_error(
6596 ctxt: *mut _xmlXPathContext,
6597 code: c_int,
6598 message: &str,
6599 expr: &str,
6600) {
6601 unsafe {
6602 use crate::xml::errors::{raise_error_streamed, GenericDelivery};
6603 use crate::xml::globals;
6604
6605 // Upstream xmlXPathErr / xmlXPathErrFmt always format with a
6606 // trailing newline ("%s\n"); lxml's _LogEntry.message strips one.
6607 let msg_c = CString::new(format!("{}\n", message)).unwrap_or_default();
6608 let expr_c = CString::new(expr).unwrap_or_default();
6609 let xerr_code = code + XML_XPATH_EXPRESSION_OK;
6610
6611 // Upstream pre-fill of ctxt->lastError (xmlXPathErrFmt): domain,
6612 // code, level, str1 = strdup(base), int1 = cur - base. The message
6613 // stays NULL here; xmlVRaiseError writes it into the TLS global.
6614 globals::free_error_strings(&(*ctxt).lastError);
6615 let pre = _xmlError {
6616 domain: XML_FROM_XPATH,
6617 code: xerr_code,
6618 message: ptr::null_mut(),
6619 level: xmlErrorLevel::XML_ERR_ERROR as c_int,
6620 file: ptr::null_mut(),
6621 line: 0,
6622 str1: xmlMemStrdupImpl(expr_c.as_ptr()) as *mut c_char,
6623 str2: ptr::null_mut(),
6624 str3: ptr::null_mut(),
6625 int1: 0,
6626 int2: 0,
6627 ctxt: ctxt as *mut c_void,
6628 node: (*ctxt).debugNode as *mut c_void,
6629 };
6630 ptr::write(&mut (*ctxt).lastError, pre);
6631
6632 // Cross-DSO channel routing: the whole-archive facade layout embeds a
6633 // per-DSO copy of libxml2's TLS error slots, so PHP's
6634 // xmlSetGenericErrorFunc (registered in the core) is invisible to the
6635 // XSLT engine running inside the libxslt facade. Upstream consumers
6636 // register on the xsltGenericError channel for transform-time
6637 // messages (php's ext/xsl MINIT), and that static IS shared with the
6638 // engine — when a real (non-default) handler is installed there,
6639 // deliver the XPath diagnostic through it exactly like the XSLT error
6640 // channel does (xsltproc leaves the default installed and is
6641 // unaffected).
6642 let xslt_bound = {
6643 let extra = (*ctxt).extra;
6644 if extra.is_null() || !crate::xml::xpath::context::has_signature(extra) {
6645 false
6646 } else {
6647 let internal: *mut crate::xml::xpath::context::XPathContext =
6648 extra as *mut crate::xml::xpath::context::XPathContext;
6649 !(*internal).func_lookup_data.is_null()
6650 }
6651 };
6652 let xslt_global = crate::abi::data_globals::xsltGenericError;
6653 let xslt_default = crate::abi::data_globals::xslt_default_generic_error_func()
6654 .map_or(ptr::null(), |d| d as *const ());
6655 if xslt_bound {
6656 if let Some(g) = xslt_global {
6657 if g as *const () != xslt_default {
6658 // SAFETY: the channel is a variadic C callback
6659 // (upstream xmlGenericErrorFunc ABI); the xslt handler
6660 // special-cases the "%s" format (php xsl_libxslt_error
6661 // _handler).
6662 let hv: unsafe extern "C" fn(*mut c_void, *const c_char, ...) =
6663 core::mem::transmute(g);
6664 hv(
6665 crate::abi::data_globals::xsltGenericErrorContext,
6666 c"%s".as_ptr() as *const c_char,
6667 msg_c.as_ptr() as *const c_char,
6668 );
6669 return;
6670 }
6671 }
6672 }
6673
6674 // UPSTREAM-PARITY (xpath.c xmlXPathErrFmt channel selection): with no
6675 // structured handler the message goes VERBATIM to the generic channel
6676 // — `channel = xmlGenericError; data = xmlGenericErrorContext`, and
6677 // error.c xmlVRaiseError calls `channel(data, "%s", to->message)`
6678 // because xmlGenericError is NOT one of the parser channels that
6679 // trigger xmlFormatError's fragment stream (which prefixes
6680 // "XPath error : "). PHP's generic handler must receive the message
6681 // text alone (ext/simplexml 008: "Invalid expression", not
6682 // "XPath error : Invalid expression").
6683 let delivery = match globals::get_generic_error_func() {
6684 Some(f) => GenericDelivery::Custom(f, globals::get_generic_error_ctx()),
6685 None => GenericDelivery::Stream,
6686 };
6687
6688 raise_error_streamed(
6689 ctxt as *mut c_void,
6690 XML_FROM_XPATH,
6691 xerr_code,
6692 xmlErrorLevel::XML_ERR_ERROR as c_int,
6693 ptr::null_mut(),
6694 0,
6695 0,
6696 expr_c.as_ptr(),
6697 ptr::null_mut(),
6698 ptr::null_mut(),
6699 0,
6700 msg_c.as_ptr(),
6701 None,
6702 None,
6703 delivery,
6704 None,
6705 );
6706 }
6707}
6708
6709/// Evaluate an XPath expression (simplified alias).
6710///
6711/// # UPSTREAM-PARITY
6712///
6713/// ```c
6714/// xmlXPathObjectPtr xmlXPathEval(const xmlChar *str, xmlXPathContextPtr ctxt);
6715/// ```
6716#[no_mangle]
6717pub unsafe extern "C" fn xmlXPathEval(
6718 str_: *const xmlChar,
6719 ctxt: *mut _xmlXPathContext,
6720) -> *mut _xmlXPathObject {
6721 xmlXPathEvalExpression(str_, ctxt)
6722}
6723
6724/// Free an XPath object.
6725///
6726/// Releases the internal members (string buffer or node-set) and then frees
6727/// the object struct itself.
6728///
6729/// # UPSTREAM-PARITY
6730///
6731/// ```c
6732/// void xmlXPathFreeObject(xmlXPathObjectPtr obj);
6733/// ```
6734#[no_mangle]
6735pub unsafe extern "C" fn xmlXPathFreeObject(obj: *mut _xmlXPathObject) {
6736 if obj.is_null() {
6737 return;
6738 }
6739 let typ = (*obj).type_;
6740 // Free string storage.
6741 if typ == xmlXPathObjectType::XPATH_STRING as c_int && !(*obj).stringval.is_null() {
6742 xmlFreeImpl((*obj).stringval as *mut c_void);
6743 (*obj).stringval = ptr::null_mut();
6744 }
6745 // Free node-set storage.
6746 if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
6747 let ns = (*obj).nodesetval as *mut _xmlNodeSet;
6748 if !ns.is_null() {
6749 if !(*ns).nodeTab.is_null() {
6750 xmlFreeImpl((*ns).nodeTab as *mut c_void);
6751 }
6752 xmlFreeImpl(ns as *mut c_void);
6753 }
6754 (*obj).nodesetval = ptr::null_mut();
6755 }
6756 xmlFreeImpl(obj as *mut c_void);
6757}
6758
6759/// Copy an XPath object (deep copy).
6760///
6761/// # UPSTREAM-PARITY
6762///
6763/// ```c
6764/// xmlXPathObjectPtr xmlXPathObjectCopy(xmlXPathObjectPtr val);
6765/// ```
6766///
6767/// Oracle behavior: returns a newly allocated object with the same type
6768/// and value. Node-sets are copied element-by-element; strings are
6769/// duplicated; numbers and booleans are copied by value.
6770#[no_mangle]
6771pub unsafe extern "C" fn xmlXPathObjectCopy(val: *mut _xmlXPathObject) -> *mut _xmlXPathObject {
6772 if val.is_null() {
6773 return ptr::null_mut();
6774 }
6775 let typ = (*val).type_;
6776 let obj = xmlMallocZero(size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject;
6777 if obj.is_null() {
6778 return ptr::null_mut();
6779 }
6780 (*obj).type_ = typ;
6781 if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
6782 let src_ns = (*val).nodesetval as *mut _xmlNodeSet;
6783 if !src_ns.is_null() {
6784 let nr = (*src_ns).nodeNr;
6785 let ns = xmlMallocZero(size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
6786 if ns.is_null() {
6787 xmlFreeImpl(obj as *mut c_void);
6788 return ptr::null_mut();
6789 }
6790 (*ns).nodeNr = nr;
6791 (*ns).nodeMax = nr;
6792 if nr > 0 && !(*src_ns).nodeTab.is_null() {
6793 let tab = xmlMallocImpl((nr as usize) * core::mem::size_of::<*mut _xmlNode>())
6794 as *mut *mut _xmlNode;
6795 if tab.is_null() {
6796 xmlFreeImpl(ns as *mut c_void);
6797 xmlFreeImpl(obj as *mut c_void);
6798 return ptr::null_mut();
6799 }
6800 ptr::copy_nonoverlapping((*src_ns).nodeTab, tab, nr as usize);
6801 (*ns).nodeTab = tab;
6802 } else {
6803 (*ns).nodeTab = ptr::null_mut();
6804 }
6805 (*obj).nodesetval = ns as *mut c_void;
6806 }
6807 } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
6808 (*obj).boolval = (*val).boolval;
6809 } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
6810 (*obj).floatval = (*val).floatval;
6811 } else if typ == xmlXPathObjectType::XPATH_STRING as c_int {
6812 let src = (*val).stringval;
6813 if !src.is_null() {
6814 let len = libc::strlen(src as *const libc::c_char);
6815 let buf = xmlMallocImpl(len + 1) as *mut xmlChar;
6816 if !buf.is_null() {
6817 ptr::copy_nonoverlapping(src, buf, len);
6818 *buf.add(len) = 0;
6819 }
6820 (*obj).stringval = buf;
6821 }
6822 }
6823 obj
6824}
6825
6826/// Cast an XPath object to its string value.
6827///
6828/// Returns a newly allocated string (caller frees with `xmlFree`).
6829///
6830/// # UPSTREAM-PARITY
6831///
6832/// ```c
6833/// xmlChar *xmlXPathCastToString(xmlXPathObjectPtr val);
6834/// ```
6835#[no_mangle]
6836pub unsafe extern "C" fn xmlXPathCastToString(val: *mut _xmlXPathObject) -> *mut xmlChar {
6837 if val.is_null() {
6838 return ptr::null_mut();
6839 }
6840 let typ = (*val).type_;
6841 let mut result: Vec<u8> = Vec::new();
6842 if typ == xmlXPathObjectType::XPATH_STRING as c_int {
6843 if !(*val).stringval.is_null() {
6844 let len = libc::strlen((*val).stringval as *const libc::c_char);
6845 result.extend_from_slice(core::slice::from_raw_parts((*val).stringval, len));
6846 }
6847 } else if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
6848 // Number → string conversion per XPath 1.0 §4.2:
6849 // - NaN → "NaN"
6850 // - +0/-0 → "0"
6851 // - infinity → "Infinity" / "-Infinity"
6852 // - integer → decimal representation without exponent
6853 let n = (*val).floatval;
6854 result.extend_from_slice(xml_number_to_string(n).as_bytes());
6855 } else if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
6856 result.extend_from_slice(if (*val).boolval != 0 {
6857 b"true"
6858 } else {
6859 b"false"
6860 });
6861 } else if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
6862 // String value of a node-set is the string value of the first node
6863 // in document order (or empty if empty).
6864 let ns = (*val).nodesetval as *mut _xmlNodeSet;
6865 if !ns.is_null() && (*ns).nodeNr > 0 && !(*ns).nodeTab.is_null() {
6866 let node = *(*ns).nodeTab;
6867 if !node.is_null() {
6868 let content = crate::xml::tree::node_get_content(node);
6869 if !content.is_null() {
6870 let len = libc::strlen(content as *const libc::c_char);
6871 result.extend_from_slice(core::slice::from_raw_parts(content, len));
6872 xmlFreeImpl(content as *mut c_void);
6873 }
6874 }
6875 }
6876 }
6877 // Allocate the C string.
6878 let buf = xmlMallocImpl(result.len() + 1) as *mut xmlChar;
6879 if buf.is_null() {
6880 return ptr::null_mut();
6881 }
6882 if !result.is_empty() {
6883 ptr::copy_nonoverlapping(result.as_ptr(), buf, result.len());
6884 }
6885 *buf.add(result.len()) = 0;
6886 buf
6887}
6888
6889/// Convert an XPath number to its string representation (XPath 1.0 §4.2).
6890///
6891/// Canonical implementation lives in `crate::xml::xpath::types::number_to_string`
6892/// (a port of upstream `xmlXPathCastNumberToString` / `xmlXPathFormatNumber`,
6893/// R-000166); this ABI helper delegates so every number→string conversion
6894/// shares exactly one oracle-verified code path.
6895pub fn xml_number_to_string(n: f64) -> String {
6896 crate::xml::xpath::types::number_to_string(n)
6897}
6898
6899/// Port of upstream xpath.c `xmlXPathStringEvalNumber` (R-000166): see
6900/// `crate::xml::xpath::types::string_bytes_to_number` — the oracle
6901/// accumulates digits directly, caps the fraction at MAX_FRAC=20 digits
6902/// after any leading zeros, applies the exponent with `pow(10.0, exp)`
6903/// (underflowing to 0 below the smallest subnormal), accepts XML whitespace
6904/// around the number, and returns NaN for anything else — including a
6905/// leading '+'.
6906fn xpath_string_eval_number(bytes: &[u8]) -> f64 {
6907 crate::xml::xpath::types::string_bytes_to_number(bytes)
6908}
6909
6910/// Cast a C string to a number per XPath 1.0 §4.2 conversion rules.
6911///
6912/// # UPSTREAM-PARITY
6913///
6914/// ```c
6915/// double xmlXPathCastStringToNumber(const xmlChar *val);
6916/// ```
6917#[no_mangle]
6918pub unsafe extern "C" fn xmlXPathCastStringToNumber(val: *const xmlChar) -> f64 {
6919 if val.is_null() {
6920 return f64::NAN;
6921 }
6922 let len = libc::strlen(val as *const libc::c_char);
6923 let bytes = core::slice::from_raw_parts(val, len);
6924 xpath_string_eval_number(bytes)
6925}
6926
6927/// Compare two nodes in document order.
6928///
6929/// UPSTREAM-PARITY (xpath.c `xmlXPathCmpNodes`): returns **1** when
6930/// `node1` precedes `node2` in document order, **-1** when `node1` follows
6931/// `node2`, 0 for the same node, and -2 for NULL or cross-document
6932/// comparisons. The sign convention was verified against the system oracle
6933/// (libxml2 2.15.3): `xmlXPathCmpNodes(book1, book2)` returns 1.
6934///
6935/// # UPSTREAM-PARITY
6936///
6937/// ```c
6938/// int xmlXPathCmpNodes(xmlNodePtr node1, xmlNodePtr node2);
6939/// ```
6940#[no_mangle]
6941pub unsafe extern "C" fn xmlXPathCmpNodes(node1: *mut _xmlNode, node2: *mut _xmlNode) -> c_int {
6942 if node1.is_null() || node2.is_null() {
6943 return -2;
6944 }
6945 if node1 == node2 {
6946 return 0;
6947 }
6948 // Build ancestor chains.
6949 let mut chain1: Vec<*mut _xmlNode> = Vec::new();
6950 let mut chain2: Vec<*mut _xmlNode> = Vec::new();
6951 let mut n = node1;
6952 while !n.is_null() {
6953 chain1.push(n);
6954 n = (*n).parent;
6955 }
6956 let mut n = node2;
6957 while !n.is_null() {
6958 chain2.push(n);
6959 n = (*n).parent;
6960 }
6961 // Distinct documents (or entities) case.
6962 if chain1[chain1.len() - 1] != chain2[chain2.len() - 1] {
6963 return -2;
6964 }
6965 // Find the nearest common ancestor.
6966 let mut i = chain1.len();
6967 let mut j = chain2.len();
6968 while i > 0 && j > 0 && chain1[i - 1] == chain2[j - 1] {
6969 i -= 1;
6970 j -= 1;
6971 }
6972 // node1 is an ancestor of node2 -> node1 precedes it -> 1.
6973 if i == 0 {
6974 return 1;
6975 }
6976 // node2 is an ancestor of node1 -> node1 follows it -> -1.
6977 if j == 0 {
6978 return -1;
6979 }
6980 // Compare sibling order at the divergence point.
6981 let mut a = chain1[i - 1];
6982 let mut b = chain2[j - 1];
6983 // Climb to the same level.
6984 while !a.is_null() && !b.is_null() {
6985 let pa = (*a).parent;
6986 let pb = (*b).parent;
6987 if pa == pb {
6988 break;
6989 }
6990 a = pa;
6991 b = pb;
6992 }
6993 // Walk forward from the first child of the common parent.
6994 let parent = (*a).parent;
6995 let mut child = if parent.is_null() {
6996 ptr::null_mut()
6997 } else {
6998 (*parent).children
6999 };
7000 while !child.is_null() {
7001 if child == a {
7002 return 1; // a precedes b
7003 }
7004 if child == b {
7005 return -1; // b precedes a
7006 }
7007 child = (*child).next;
7008 }
7009 0
7010}
7011
7012/// Create a node-set from a range of an existing node-set.
7013///
7014/// # UPSTREAM-PARITY
7015///
7016/// ```c
7017/// xmlNodeSetPtr xmlXPathNodeSetCreate(xmlNodePtr val);
7018/// ```
7019///
7020/// With a null `val`, creates an empty node-set.
7021#[no_mangle]
7022pub unsafe extern "C" fn xmlXPathNodeSetCreate(val: *mut _xmlNode) -> *mut _xmlNodeSet {
7023 let ns = xmlMallocZero(size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
7024 if ns.is_null() {
7025 return ptr::null_mut();
7026 }
7027 if val.is_null() {
7028 return ns;
7029 }
7030 let tab = xmlMallocImpl(core::mem::size_of::<*mut _xmlNode>()) as *mut *mut _xmlNode;
7031 if tab.is_null() {
7032 xmlFreeImpl(ns as *mut c_void);
7033 return ptr::null_mut();
7034 }
7035 *tab = val;
7036 (*ns).nodeTab = tab;
7037 (*ns).nodeNr = 1;
7038 (*ns).nodeMax = 1;
7039 ns
7040}
7041
7042/// Free a node-set allocated by `xmlXPathNodeSetCreate` or a node-set
7043/// builder in this library.
7044///
7045/// Frees the node-set structure and its node table; the nodes themselves
7046/// are owned by their document and are not freed.
7047///
7048/// # UPSTREAM-PARITY
7049///
7050/// ```c
7051/// void xmlXPathFreeNodeSet(xmlNodeSetPtr ns);
7052/// ```
7053#[no_mangle]
7054pub unsafe extern "C" fn xmlXPathFreeNodeSet(ns: *mut _xmlNodeSet) {
7055 if ns.is_null() {
7056 return;
7057 }
7058 if !(*ns).nodeTab.is_null() {
7059 xmlFreeImpl((*ns).nodeTab as *mut c_void);
7060 (*ns).nodeTab = ptr::null_mut();
7061 }
7062 (*ns).nodeNr = 0;
7063 (*ns).nodeMax = 0;
7064 xmlFreeImpl(ns as *mut c_void);
7065}
7066
7067/// Compile `expr_str` and store it in the compiled-expression registry,
7068/// returning the opaque key (or the parse error without raising — the caller
7069/// decides delivery).
7070pub(crate) fn xpath_compile_store(
7071 expr_str: &str,
7072) -> Result<*mut c_void, crate::xml::xpath::parser::ParseError> {
7073 match crate::xml::xpath::compile_result(expr_str) {
7074 Ok(compiled) => {
7075 let mut map = COMPILED_EXPRS.lock();
7076 let mut counter = NEXT_COMPILED_KEY.lock();
7077 let key = *counter;
7078 *counter += 1;
7079 map.insert(key, Box::new(compiled));
7080 Ok(key as *mut c_void)
7081 }
7082 Err(e) => Err(e),
7083 }
7084}
7085
7086/// Compile an XPath expression.
7087///
7088/// # UPSTREAM-PARITY
7089///
7090/// ```c
7091/// xmlXPathCompExprPtr xmlXPathCompile(const xmlChar *str);
7092/// ```
7093#[no_mangle]
7094pub unsafe extern "C" fn xmlXPathCompile(str_: *const xmlChar) -> *mut c_void {
7095 if str_.is_null() {
7096 return ptr::null_mut();
7097 }
7098 let expr_str = match CStr::from_ptr(str_ as *const c_char).to_str() {
7099 Ok(s) => s,
7100 Err(_) => return ptr::null_mut(),
7101 };
7102
7103 match xpath_compile_store(expr_str) {
7104 Ok(key) => key,
7105 Err(e) => {
7106 // UPSTREAM-PARITY (xpath.c xmlXPathErrFmt): a failed compile
7107 // reports "XPath error : Invalid expression\n" plus the
7108 // expression and a caret at the error offset through the generic
7109 // channel (HOSTILE-FAILURE F3). The structured code is
7110 // 1200-based like upstream `code + XML_XPATH_EXPRESSION_OK`.
7111 let msg_cstr = std::ffi::CString::new("Invalid expression\n").unwrap_or_default();
7112 let expr_cstr = std::ffi::CString::new(expr_str).unwrap_or_default();
7113 let off = e.pos;
7114 let window = if off < 100 && off < expr_str.len() {
7115 Some((expr_str.as_bytes(), off))
7116 } else {
7117 None
7118 };
7119 unsafe {
7120 crate::xml::errors::raise_error_streamed(
7121 ptr::null_mut(),
7122 crate::abi::types::XML_FROM_XPATH,
7123 crate::abi::types::XPATH_EXPR_ERROR
7124 + crate::abi::types::XML_XPATH_EXPRESSION_OK,
7125 crate::abi::types::xmlErrorLevel::XML_ERR_ERROR as c_int,
7126 ptr::null(),
7127 0,
7128 0,
7129 expr_cstr.as_ptr(),
7130 ptr::null(),
7131 ptr::null(),
7132 off as c_int,
7133 msg_cstr.as_ptr(),
7134 window,
7135 None,
7136 crate::xml::errors::GenericDelivery::Stream,
7137 None,
7138 );
7139 }
7140 ptr::null_mut()
7141 }
7142 }
7143}
7144
7145/// Free a compiled XPath expression.
7146///
7147/// # UPSTREAM-PARITY
7148///
7149/// ```c
7150/// void xmlXPathFreeCompExpr(xmlXPathCompExprPtr comp);
7151/// ```
7152#[no_mangle]
7153pub unsafe extern "C" fn xmlXPathFreeCompExpr(comp: *mut c_void) {
7154 if comp.is_null() {
7155 return;
7156 }
7157 let mut map = COMPILED_EXPRS.lock();
7158 map.remove(&(comp as u64));
7159}
7160
7161/// Register an XPath namespace.
7162///
7163/// # UPSTREAM-PARITY
7164///
7165/// ```c
7166/// int xmlXPathRegisterNs(xmlXPathContextPtr ctxt,
7167/// const xmlChar *prefix, const xmlChar *ns_uri);
7168/// ```
7169#[no_mangle]
7170pub unsafe extern "C" fn xmlXPathRegisterNs(
7171 ctxt: *mut _xmlXPathContext,
7172 prefix: *const xmlChar,
7173 ns_uri: *const xmlChar,
7174) -> c_int {
7175 if ctxt.is_null() || prefix.is_null() || ns_uri.is_null() {
7176 return -1;
7177 }
7178 let internal = (*ctxt).extra as *mut XPathContext;
7179 if internal.is_null() {
7180 return -1;
7181 }
7182 let internal = &mut *internal;
7183
7184 let prefix_str = match CStr::from_ptr(prefix as *const c_char).to_str() {
7185 Ok(s) => s,
7186 Err(_) => return -1,
7187 };
7188 let uri_str = match CStr::from_ptr(ns_uri as *const c_char).to_str() {
7189 Ok(s) => s,
7190 Err(_) => return -1,
7191 };
7192
7193 internal.register_namespace(prefix_str, uri_str);
7194
7195 // UPSTREAM-PARITY (xpath.c xmlXPathRegisterNs): the C context's nsHash
7196 // is a REAL xmlHashTable keyed by prefix with a strdup'd URI payload —
7197 // C consumers (lxml registerExsltFunctions) call xmlHashScan and
7198 // xmlHashLookup on it, so it must be an xmlHashTable, not a Rust map.
7199 // (R-00019x: the pre-fix nsHash held a Box<HashMap<..>>; lxml's
7200 // xmlHashScan interpreted the HashMap as an xmlHashTable and crashed on
7201 // its internal layout.)
7202 if (*ctxt).nsHash.is_null() {
7203 (*ctxt).nsHash = xmlHashCreate(10);
7204 }
7205 if !(*ctxt).nsHash.is_null() {
7206 let uri_dup = crate::xml::string::xml_strdup(ns_uri);
7207 let rc = xmlHashAddEntry((*ctxt).nsHash, prefix, uri_dup as *mut c_void);
7208 if rc != 0 {
7209 // Duplicate prefix: upstream keeps the first mapping (and leaks
7210 // the new strdup'd URI); the candidate frees the unused copy.
7211 crate::abi::allocator::xmlFreeImpl(uri_dup as *mut c_void);
7212 }
7213 }
7214 0
7215}
7216
7217/// Register an XPath function.
7218///
7219/// The C function pointer is stored in a side table keyed by the context.
7220/// A Rust-side stub is registered in the internal context so that the Rust
7221/// evaluator is aware of the function; however, calling the C function
7222/// directly from the Rust evaluator is not yet supported.
7223///
7224/// # UPSTREAM-PARITY
7225///
7226/// ```c
7227/// int xmlXPathRegisterFunc(xmlXPathContextPtr ctxt,
7228/// const xmlChar *name, xmlXPathFunction f);
7229/// ```
7230#[no_mangle]
7231pub unsafe extern "C" fn xmlXPathRegisterFunc(
7232 ctxt: *mut _xmlXPathContext,
7233 name: *const xmlChar,
7234 f: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
7235) -> c_int {
7236 if ctxt.is_null() || name.is_null() {
7237 return -1;
7238 }
7239 let internal = (*ctxt).extra as *mut XPathContext;
7240 if internal.is_null() {
7241 return -1;
7242 }
7243 let internal = &mut *internal;
7244
7245 let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
7246 Ok(s) => s,
7247 Err(_) => return -1,
7248 };
7249
7250 if let Some(func) = f {
7251 // Store the C function pointer in the side table.
7252 let key = (SendSyncPtr((*ctxt).extra), name_str.to_string());
7253 C_FUNCTIONS.lock().insert(key, func);
7254 // Register a Rust closure that bridges to the C function through a
7255 // synthesized xmlXPathParserContext (upstream function-call ABI).
7256 let c_ctxt = SendSyncPtr(ctxt as *mut c_void);
7257 let name_owned = name_str.to_string();
7258 internal.register_function(name_str, c_func_bridge_closure(c_ctxt, name_owned));
7259 }
7260 0
7261}
7262
7263/// Register an XPath function with namespace.
7264///
7265/// # UPSTREAM-PARITY
7266///
7267/// ```c
7268/// int xmlXPathRegisterFuncNS(xmlXPathContextPtr ctxt,
7269/// const xmlChar *name, const xmlChar *ns_uri,
7270/// xmlXPathFunction f);
7271/// ```
7272#[no_mangle]
7273pub unsafe extern "C" fn xmlXPathRegisterFuncNS(
7274 ctxt: *mut _xmlXPathContext,
7275 name: *const xmlChar,
7276 ns_uri: *const xmlChar,
7277 f: Option<unsafe extern "C" fn(*mut c_void, c_int)>,
7278) -> c_int {
7279 if ctxt.is_null() || name.is_null() {
7280 return -1;
7281 }
7282 let internal = (*ctxt).extra as *mut XPathContext;
7283 if internal.is_null() {
7284 return -1;
7285 }
7286 let internal = &mut *internal;
7287
7288 let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
7289 Ok(s) => s,
7290 Err(_) => return -1,
7291 };
7292 let ns_str = if ns_uri.is_null() {
7293 String::new()
7294 } else {
7295 match CStr::from_ptr(ns_uri as *const c_char).to_str() {
7296 Ok(s) => s.to_string(),
7297 Err(_) => return -1,
7298 }
7299 };
7300
7301 // Use "{ns}:" prefix as part of the key to keep functions unique.
7302 let qualified = if ns_str.is_empty() {
7303 name_str.to_string()
7304 } else {
7305 format!("{{{}}}{}", ns_str, name_str)
7306 };
7307
7308 if let Some(func) = f {
7309 let key = (SendSyncPtr((*ctxt).extra), qualified.clone());
7310 C_FUNCTIONS.lock().insert(key, func);
7311 let c_ctxt = SendSyncPtr(ctxt as *mut c_void);
7312 let qualified_owned = qualified.clone();
7313 internal.register_function(&qualified, c_func_bridge_closure(c_ctxt, qualified_owned));
7314 }
7315 0
7316}
7317
7318/// Register an XPath variable.
7319///
7320/// # UPSTREAM-PARITY
7321///
7322/// ```c
7323/// int xmlXPathRegisterVariable(xmlXPathContextPtr ctxt,
7324/// const xmlChar *name, xmlXPathObjectPtr value);
7325/// ```
7326#[no_mangle]
7327pub unsafe extern "C" fn xmlXPathRegisterVariable(
7328 ctxt: *mut _xmlXPathContext,
7329 name: *const xmlChar,
7330 value: *mut _xmlXPathObject,
7331) -> c_int {
7332 if ctxt.is_null() || name.is_null() || value.is_null() {
7333 return -1;
7334 }
7335 let internal = (*ctxt).extra as *mut XPathContext;
7336 if internal.is_null() {
7337 return -1;
7338 }
7339 let internal = &mut *internal;
7340
7341 let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
7342 Ok(s) => s,
7343 Err(_) => return -1,
7344 };
7345
7346 let xpath_val = object_to_xpathvalue(value);
7347 internal.register_variable(name_str, xpath_val);
7348 0
7349}
7350
7351/// Create an XPath object wrapping a single node in a node-set.
7352///
7353/// # UPSTREAM-PARITY
7354///
7355/// ```c
7356/// xmlXPathObjectPtr xmlXPathNewNodeSet(xmlNodePtr val);
7357/// ```
7358#[no_mangle]
7359pub unsafe extern "C" fn xmlXPathNewNodeSet(val: *mut _xmlNode) -> *mut _xmlXPathObject {
7360 let ns = if val.is_null() {
7361 NodeSet::new()
7362 } else {
7363 NodeSet::singleton(val)
7364 };
7365 xpath_to_object(XPathValue::NodeSet(ns))
7366}
7367
7368/// Create an XPath object from a C string value.
7369///
7370/// # UPSTREAM-PARITY
7371///
7372/// ```c
7373/// xmlXPathObjectPtr xmlXPathNewCString(const xmlChar *val);
7374/// ```
7375#[no_mangle]
7376pub unsafe extern "C" fn xmlXPathNewCString(val: *const xmlChar) -> *mut _xmlXPathObject {
7377 if val.is_null() {
7378 return xpath_to_object(XPathValue::String(String::new()));
7379 }
7380 let s = match CStr::from_ptr(val as *const c_char).to_str() {
7381 Ok(s) => s.to_string(),
7382 Err(_) => return ptr::null_mut(),
7383 };
7384 xpath_to_object(XPathValue::String(s))
7385}
7386
7387/// Create an XPath number object.
7388///
7389/// # UPSTREAM-PARITY
7390///
7391/// ```c
7392/// xmlXPathObjectPtr xmlXPathNewFloat(double val);
7393/// ```
7394#[no_mangle]
7395pub extern "C" fn xmlXPathNewFloat(val: f64) -> *mut _xmlXPathObject {
7396 unsafe { xpath_to_object(XPathValue::Number(val)) }
7397}
7398
7399/// Create an XPath boolean object.
7400///
7401/// # UPSTREAM-PARITY
7402///
7403/// ```c
7404/// xmlXPathObjectPtr xmlXPathNewBoolean(int val);
7405/// ```
7406#[no_mangle]
7407pub extern "C" fn xmlXPathNewBoolean(val: c_int) -> *mut _xmlXPathObject {
7408 unsafe { xpath_to_object(XPathValue::Boolean(val != 0)) }
7409}
7410
7411// ═══════════════════════════════════════════════════════════════════════════════
7412// 14.5. XPointer
7413// ═══════════════════════════════════════════════════════════════════════════════
7414
7415/// Evaluate an XPointer expression.
7416///
7417/// Delegates to the xpointer module.
7418///
7419/// # UPSTREAM-PARITY
7420///
7421/// ```c
7422/// xmlNodePtr xmlXPtrEval(const xmlChar *expr, xmlDocPtr doc);
7423/// ```
7424#[no_mangle]
7425pub unsafe extern "C" fn xmlXPtrEval(expr: *const c_char, doc: *mut _xmlDoc) -> *mut _xmlNode {
7426 crate::xml::xpointer::xmlXPtrEval(expr, doc)
7427}
7428
7429// ═══════════════════════════════════════════════════════════════════════════════
7430// 15. XInclude
7431// ═══════════════════════════════════════════════════════════════════════════════
7432
7433/// Process XInclude nodes in a document.
7434///
7435/// # UPSTREAM-PARITY
7436///
7437/// ```c
7438/// int xmlXIncludeProcess(xmlDocPtr doc);
7439/// ```
7440#[no_mangle]
7441pub unsafe extern "C" fn xmlXIncludeProcess(doc: *mut _xmlDoc) -> c_int {
7442 crate::xml::xinclude::xinclude_process(doc)
7443}
7444
7445/// Process XInclude nodes with flags.
7446///
7447/// # UPSTREAM-PARITY
7448///
7449/// ```c
7450/// int xmlXIncludeProcessFlags(xmlDocPtr doc, int flags);
7451/// ```
7452#[no_mangle]
7453pub unsafe extern "C" fn xmlXIncludeProcessFlags(doc: *mut _xmlDoc, flags: c_int) -> c_int {
7454 crate::xml::xinclude::xinclude_process_flags(doc, flags)
7455}
7456
7457// ═══════════════════════════════════════════════════════════════════════════════
7458// 16. Catalog
7459// ═══════════════════════════════════════════════════════════════════════════════
7460
7461/// Load a catalog.
7462///
7463/// # UPSTREAM-PARITY
7464///
7465/// ```c
7466/// xmlCatalogPtr xmlCatalogLoad(const char *catalogs);
7467/// ```
7468#[no_mangle]
7469pub extern "C" fn xmlCatalogLoad(catalogs: *const c_char) -> *mut c_void {
7470 if catalogs.is_null() {
7471 return ptr::null_mut();
7472 }
7473 crate::xml::catalog::load_catalog(catalogs)
7474}
7475
7476/// Resolve a public ID.
7477///
7478/// # UPSTREAM-PARITY
7479///
7480/// ```c
7481/// xmlCharPtr xmlCatalogResolvePublic(const xmlChar *pubID);
7482/// ```
7483#[no_mangle]
7484pub unsafe extern "C" fn xmlCatalogResolvePublic(pubID: *const xmlChar) -> *mut xmlChar {
7485 if pubID.is_null() {
7486 return ptr::null_mut();
7487 }
7488 crate::xml::catalog::resolve_public(pubID)
7489}
7490
7491/// Resolve a system ID.
7492///
7493/// # UPSTREAM-PARITY
7494///
7495/// ```c
7496/// xmlCharPtr xmlCatalogResolveSystem(const xmlChar *sysID);
7497/// ```
7498#[no_mangle]
7499pub unsafe extern "C" fn xmlCatalogResolveSystem(sysID: *const xmlChar) -> *mut xmlChar {
7500 if sysID.is_null() {
7501 return ptr::null_mut();
7502 }
7503 crate::xml::catalog::resolve_system(sysID)
7504}
7505
7506/// Resolve a URI.
7507///
7508/// # UPSTREAM-PARITY
7509///
7510/// ```c
7511/// xmlCharPtr xmlCatalogResolveURI(const xmlChar *URI);
7512/// ```
7513#[no_mangle]
7514pub unsafe extern "C" fn xmlCatalogResolveURI(URI: *const xmlChar) -> *mut xmlChar {
7515 if URI.is_null() {
7516 return ptr::null_mut();
7517 }
7518 crate::xml::catalog::resolve_uri(URI)
7519}
7520
7521/// Set catalog defaults.
7522///
7523/// # UPSTREAM-PARITY
7524///
7525/// ```c
7526/// void xmlCatalogSetDefaults(xmlCatalogAllowValue allow);
7527/// ```
7528#[no_mangle]
7529pub extern "C" fn xmlCatalogSetDefaults(allow: c_int) {
7530 crate::xml::catalog::set_defaults(allow)
7531}
7532
7533/// Get catalog defaults.
7534///
7535/// # UPSTREAM-PARITY
7536///
7537/// ```c
7538/// xmlCatalogAllowValue xmlCatalogGetDefaults(void);
7539/// ```
7540#[no_mangle]
7541pub extern "C" fn xmlCatalogGetDefaults() -> c_int {
7542 crate::xml::catalog::get_defaults()
7543}
7544
7545/// Add a catalog.
7546///
7547/// # UPSTREAM-PARITY
7548///
7549/// ```c
7550/// int xmlCatalogAdd(const xmlChar *type, const xmlChar *orig, const xmlChar *replace);
7551/// ```
7552#[no_mangle]
7553pub unsafe extern "C" fn xmlCatalogAdd(
7554 type_: *const xmlChar,
7555 orig: *const xmlChar,
7556 replace: *const xmlChar,
7557) -> c_int {
7558 if type_.is_null() || orig.is_null() || replace.is_null() {
7559 return -1;
7560 }
7561 crate::xml::catalog::add(type_, orig, replace)
7562}
7563
7564/// Remove a catalog entry.
7565///
7566/// # UPSTREAM-PARITY
7567///
7568/// ```c
7569/// int xmlCatalogRemove(const xmlChar *value);
7570/// ```
7571#[no_mangle]
7572pub unsafe extern "C" fn xmlCatalogRemove(value: *const xmlChar) -> c_int {
7573 if value.is_null() {
7574 return 0;
7575 }
7576 crate::xml::catalog::remove(value)
7577}
7578
7579/// Dump the catalog in XML format to a FILE* (upstream catalog.h:
7580/// 1-argument form — R-000176, the candidate previously took a spurious
7581/// second `xmlCatalogPtr` argument).
7582///
7583/// # UPSTREAM-PARITY
7584///
7585/// ```c
7586/// void xmlCatalogDump(FILE *out);
7587/// ```
7588#[no_mangle]
7589pub unsafe extern "C" fn xmlCatalogDump(output: *mut c_void) {
7590 if output.is_null() {
7591 return;
7592 }
7593 let doc = crate::xml::catalog::dump_doc();
7594 if doc.is_null() {
7595 return;
7596 }
7597 let mut mem: *mut xmlChar = ptr::null_mut();
7598 let mut size: c_int = 0;
7599 crate::xml::tree::xmlDocDumpFormatMemory(doc, &mut mem, &mut size, 1);
7600 if !mem.is_null() {
7601 libc::fwrite(
7602 mem as *const c_void,
7603 1,
7604 size as usize,
7605 output as *mut libc::FILE,
7606 );
7607 xmlFreeImpl(mem as *mut c_void);
7608 }
7609 crate::xml::tree::free_doc(doc);
7610}
7611
7612/// Save the catalog to a file (upstream `xmlCatalogSave`).
7613///
7614/// Returns 0 on success, -1 on failure.
7615///
7616/// # UPSTREAM-PARITY
7617///
7618/// ```c
7619/// int xmlCatalogSave(const char *filename);
7620/// ```
7621#[no_mangle]
7622pub unsafe extern "C" fn xmlCatalogSave(filename: *const c_char) -> c_int {
7623 if filename.is_null() {
7624 return -1;
7625 }
7626 let doc = crate::xml::catalog::dump_doc();
7627 if doc.is_null() {
7628 return -1;
7629 }
7630 let mut mem: *mut xmlChar = ptr::null_mut();
7631 let mut size: c_int = 0;
7632 crate::xml::tree::xmlDocDumpFormatMemory(doc, &mut mem, &mut size, 1);
7633 let mut ret: c_int = -1;
7634 if !mem.is_null() {
7635 let fp = libc::fopen(filename, c"w".as_ptr() as *const c_char);
7636 if !fp.is_null() {
7637 let written = libc::fwrite(mem as *const c_void, 1, size as usize, fp);
7638 ret = if written == size as usize { 0 } else { -1 };
7639 libc::fclose(fp);
7640 }
7641 xmlFreeImpl(mem as *mut c_void);
7642 }
7643 crate::xml::tree::free_doc(doc);
7644 ret
7645}
7646
7647/// Clean up the catalog subsystem.
7648///
7649/// # UPSTREAM-PARITY
7650///
7651/// ```c
7652/// void xmlCatalogCleanup(void);
7653/// ```
7654#[no_mangle]
7655pub extern "C" fn xmlCatalogCleanup() {
7656 crate::xml::catalog::cleanup();
7657}
7658
7659/// Convert all the SGML catalog entries as XML ones (upstream catalog.c:
7660/// returns 0 on success, -1 otherwise — R-000176, the candidate previously
7661/// returned a dump document).
7662///
7663/// # UPSTREAM-PARITY
7664///
7665/// ```c
7666/// int xmlCatalogConvert(void);
7667/// ```
7668///
7669/// The candidate's catalog stores XML-flavored entries natively (there is no
7670/// separate SGML table to convert), so once the catalog is initialized the
7671/// conversion succeeds as a no-op, matching upstream's successful-return
7672/// contract.
7673#[no_mangle]
7674pub extern "C" fn xmlCatalogConvert() -> c_int {
7675 if !crate::xml::catalog::is_initialized() {
7676 return -1;
7677 }
7678 0
7679}
7680
7681// ═══════════════════════════════════════════════════════════════════════════════
7682// 17. HTML
7683// ═══════════════════════════════════════════════════════════════════════════════
7684
7685/// Parse an HTML document from a file.
7686///
7687/// # UPSTREAM-PARITY
7688///
7689/// ```c
7690/// htmlDocPtr htmlParseFile(const char *filename, const char *encoding);
7691/// ```
7692#[no_mangle]
7693pub const unsafe extern "C" fn htmlParseFile(
7694 _filename: *const c_char,
7695 _encoding: *const c_char,
7696) -> *mut _xmlDoc {
7697 // Phase 1: STUB
7698 ptr::null_mut()
7699}
7700
7701/// Parse an HTML document from memory.
7702///
7703/// # UPSTREAM-PARITY
7704///
7705/// ```c
7706/// htmlDocPtr htmlParseMemory(const char *buffer, int size);
7707/// ```
7708#[no_mangle]
7709pub const unsafe extern "C" fn htmlParseMemory(
7710 _buffer: *const c_char,
7711 _size: c_int,
7712) -> *mut _xmlDoc {
7713 // Phase 1: STUB
7714 ptr::null_mut()
7715}
7716
7717/// Parse an HTML document from a document string.
7718///
7719/// # UPSTREAM-PARITY
7720///
7721/// ```c
7722/// htmlDocPtr htmlParseDoc(const xmlChar *cur, const char *encoding);
7723/// ```
7724#[no_mangle]
7725pub const unsafe extern "C" fn htmlParseDoc(
7726 _cur: *const xmlChar,
7727 _encoding: *const c_char,
7728) -> *mut _xmlDoc {
7729 // Phase 1: STUB
7730 ptr::null_mut()
7731}
7732
7733/// Create an HTML parser context.
7734///
7735/// # UPSTREAM-PARITY
7736///
7737/// ```c
7738/// Free an HTML parser context.
7739///
7740/// # UPSTREAM-PARITY
7741///
7742/// ```c
7743/// void htmlFreeParserCtxt(htmlParserCtxtPtr ctxt);
7744/// ```
7745#[no_mangle]
7746pub extern "C" fn htmlFreeParserCtxt(ctxt: *mut c_void) {
7747 unsafe { crate::xml::html::free_parser_ctxt(ctxt) }
7748}
7749
7750/// Initialize the HTML parser.
7751///
7752/// # UPSTREAM-PARITY
7753///
7754/// ```c
7755/// void htmlInitParser(void);
7756/// ```
7757#[no_mangle]
7758pub const extern "C" fn htmlInitParser() {
7759 // Phase 1: STUB
7760}
7761
7762/// Clean up the HTML parser.
7763///
7764/// # UPSTREAM-PARITY
7765///
7766/// ```c
7767/// void htmlCleanupParser(void);
7768/// ```
7769#[no_mangle]
7770pub const extern "C" fn htmlCleanupParser() {
7771 // Phase 1: STUB
7772}
7773
7774// ═══════════════════════════════════════════════════════════════════════════════
7775// 17.5. Validation (DTD)
7776// ═══════════════════════════════════════════════════════════════════════════════
7777
7778/// Create a new validation context.
7779///
7780/// # UPSTREAM-PARITY
7781///
7782/// ```c
7783/// xmlValidCtxtPtr xmlNewValidCtxt(void);
7784/// ```
7785#[no_mangle]
7786pub unsafe extern "C" fn xmlNewValidCtxt() -> *mut _xmlValidCtxt {
7787 crate::xml::validation::new_valid_ctxt()
7788}
7789
7790/// Free a validation context.
7791///
7792/// # UPSTREAM-PARITY
7793///
7794/// ```c
7795/// void xmlFreeValidCtxt(xmlValidCtxtPtr ctxt);
7796/// ```
7797#[no_mangle]
7798pub unsafe extern "C" fn xmlFreeValidCtxt(ctxt: *mut _xmlValidCtxt) {
7799 crate::xml::validation::free_valid_ctxt(ctxt);
7800}
7801
7802/// Set error and warning callbacks on a validation context.
7803///
7804/// # UPSTREAM-PARITY
7805///
7806/// ```c
7807/// void xmlSetValidErrors(xmlValidCtxtPtr ctxt,
7808/// xmlGenericErrorFunc err,
7809/// xmlGenericErrorFunc warn,
7810/// void *data);
7811/// ```
7812#[no_mangle]
7813pub unsafe extern "C" fn xmlSetValidErrors(
7814 ctxt: *mut _xmlValidCtxt,
7815 err: Option<xmlGenericErrorFunc>,
7816 warn: Option<xmlGenericErrorFunc>,
7817 data: *mut c_void,
7818) {
7819 crate::xml::validation::set_valid_errors(ctxt, err, warn, data);
7820}
7821
7822/// Validate a document against its DTD.
7823///
7824/// # UPSTREAM-PARITY
7825///
7826/// ```c
7827/// int xmlValidateDocument(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
7828/// ```
7829#[no_mangle]
7830pub unsafe extern "C" fn xmlValidateDocument(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
7831 crate::xml::validation::validate_document(ctxt, doc)
7832}
7833
7834/// Final validation pass (check ID/IDREF consistency).
7835///
7836/// # UPSTREAM-PARITY
7837///
7838/// ```c
7839/// int xmlValidateDocumentFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
7840/// ```
7841#[no_mangle]
7842pub unsafe extern "C" fn xmlValidateDocumentFinal(
7843 ctxt: *mut _xmlValidCtxt,
7844 doc: *mut _xmlDoc,
7845) -> c_int {
7846 crate::xml::validation::validate_document_final(ctxt, doc)
7847}
7848
7849/// Validate an element node against its DTD declarations.
7850///
7851/// # UPSTREAM-PARITY
7852///
7853/// ```c
7854/// int xmlValidateElement(xmlValidCtxtPtr ctxt,
7855/// xmlDocPtr doc,
7856/// xmlNodePtr elem);
7857/// ```
7858#[no_mangle]
7859pub unsafe extern "C" fn xmlValidateElement(
7860 ctxt: *mut _xmlValidCtxt,
7861 doc: *mut _xmlDoc,
7862 elem: *mut _xmlNode,
7863) -> c_int {
7864 crate::xml::validation::validate_element(ctxt, doc, elem)
7865}
7866
7867/// Validate an attribute declaration.
7868///
7869/// # UPSTREAM-PARITY
7870///
7871/// ```c
7872/// int xmlValidateAttributeDecl(xmlValidCtxt *ctxt,
7873/// xmlDoc *doc,
7874/// xmlAttribute *attr);
7875/// ```
7876///
7877/// 11.1-Z.3 signature court: the pre-Z.3 candidate declared a fourth
7878/// `xmlNodePtr elem` argument that does not exist upstream (valid.h 2.15.3).
7879#[no_mangle]
7880pub unsafe extern "C" fn xmlValidateAttributeDecl(
7881 ctxt: *mut _xmlValidCtxt,
7882 doc: *mut _xmlDoc,
7883 attr: *mut _xmlAttribute,
7884) -> c_int {
7885 crate::xml::validation::validate_attribute_decl(ctxt, doc, attr)
7886}
7887
7888/// Validate an attribute value against its declared type.
7889///
7890/// # UPSTREAM-PARITY
7891///
7892/// ```c
7893/// int xmlValidateAttributeValue(int type, const xmlChar *value);
7894/// ```
7895#[no_mangle]
7896pub unsafe extern "C" fn xmlValidateAttributeValue(atype: c_int, value: *const xmlChar) -> c_int {
7897 crate::xml::validation::validate_attribute_value(atype, value)
7898}
7899
7900/// Validate a NOTATION reference.
7901///
7902/// # UPSTREAM-PARITY
7903///
7904/// ```c
7905/// int xmlValidateNotationUse(xmlValidCtxtPtr ctxt,
7906/// xmlDocPtr doc,
7907/// const xmlChar *notationName);
7908/// ```
7909#[no_mangle]
7910pub unsafe extern "C" fn xmlValidateNotationUse(
7911 ctxt: *mut _xmlValidCtxt,
7912 doc: *mut _xmlDoc,
7913 notation_name: *const xmlChar,
7914) -> c_int {
7915 crate::xml::validation::validate_notation_use(ctxt, doc, notation_name)
7916}
7917
7918/// Validate an ID value (check uniqueness).
7919///
7920/// # UPSTREAM-PARITY
7921///
7922/// ```c
7923/// int xmlValidateID(xmlValidCtxtPtr ctxt,
7924/// xmlDocPtr doc,
7925/// xmlNodePtr node,
7926/// const xmlChar *value);
7927/// ```
7928#[no_mangle]
7929pub unsafe extern "C" fn xmlValidateID(
7930 ctxt: *mut _xmlValidCtxt,
7931 doc: *mut _xmlDoc,
7932 node: *mut _xmlNode,
7933 value: *const xmlChar,
7934) -> c_int {
7935 crate::xml::validation::validate_id(ctxt, doc, node, value)
7936}
7937
7938/// Validate an IDREF value (check it references a known ID; upstream
7939/// valid.h 2.15 has no `node` argument — R-000176).
7940///
7941/// # UPSTREAM-PARITY
7942///
7943/// ```c
7944/// int xmlValidateIDRef(xmlValidCtxt *ctxt, xmlDoc *doc,
7945/// const xmlChar *value);
7946/// ```
7947#[no_mangle]
7948pub unsafe extern "C" fn xmlValidateIDRef(
7949 ctxt: *mut _xmlValidCtxt,
7950 doc: *mut _xmlDoc,
7951 value: *const xmlChar,
7952) -> c_int {
7953 crate::xml::validation::validate_id_ref(ctxt, doc, ptr::null_mut(), value)
7954}
7955
7956/// Validate IDREFS (whitespace-separated list of IDREFs; upstream valid.h
7957/// 2.15 has no `node` argument — R-000176).
7958///
7959/// # UPSTREAM-PARITY
7960///
7961/// ```c
7962/// int xmlValidateIDRefs(xmlValidCtxt *ctxt, xmlDoc *doc,
7963/// const xmlChar *value);
7964/// ```
7965#[no_mangle]
7966pub unsafe extern "C" fn xmlValidateIDRefs(
7967 ctxt: *mut _xmlValidCtxt,
7968 doc: *mut _xmlDoc,
7969 value: *const xmlChar,
7970) -> c_int {
7971 crate::xml::validation::validate_id_refs(ctxt, doc, ptr::null_mut(), value)
7972}
7973
7974/// Validate an NCName value (modern 2-arg form, upstream tree.c).
7975///
7976/// # UPSTREAM-PARITY
7977///
7978/// ```c
7979/// int xmlValidateNCName(const xmlChar *value, int space);
7980/// ```
7981///
7982/// Returns -1 on NULL, 0 if valid, 1 if invalid.
7983#[no_mangle]
7984pub unsafe extern "C" fn xmlValidateNCName(value: *const xmlChar, space: c_int) -> c_int {
7985 crate::xml::validation::validate_ncname(value, space)
7986}
7987
7988/// Validate a QName value (modern 2-arg form, upstream tree.c).
7989///
7990/// # UPSTREAM-PARITY
7991///
7992/// ```c
7993/// int xmlValidateQName(const xmlChar *value, int space);
7994/// ```
7995#[no_mangle]
7996pub unsafe extern "C" fn xmlValidateQName(value: *const xmlChar, space: c_int) -> c_int {
7997 crate::xml::validation::validate_qname(value, space)
7998}
7999
8000/// Validate an XML Name value (modern 2-arg form, upstream tree.c).
8001///
8002/// # UPSTREAM-PARITY / HISTORICAL
8003///
8004/// Since libxml2 2.12 the DSO symbol carries a second `int space` parameter
8005/// with inverted return semantics (0 valid / 1 invalid / -1 NULL); the
8006/// pre-2.12 1-arg form no longer exists in the DSO. The candidate matches
8007/// the current oracle. (The 1-arg semantics live on as xmlValidateNameValue.)
8008///
8009/// ```c
8010/// int xmlValidateName(const xmlChar *value, int space);
8011/// ```
8012#[no_mangle]
8013pub unsafe extern "C" fn xmlValidateName(value: *const xmlChar, space: c_int) -> c_int {
8014 crate::xml::validation::validate_name_space(value, space)
8015}
8016
8017/// Validate an NMToken value (modern 2-arg form, upstream tree.c).
8018///
8019/// # UPSTREAM-PARITY
8020///
8021/// ```c
8022/// int xmlValidateNMToken(const xmlChar *value, int space);
8023/// ```
8024#[no_mangle]
8025pub unsafe extern "C" fn xmlValidateNMToken(value: *const xmlChar, space: c_int) -> c_int {
8026 crate::xml::validation::validate_nmtoken_space(value, space)
8027}
8028
8029/// Validate a Name value (1-arg form, upstream valid.c).
8030///
8031/// # UPSTREAM-PARITY
8032///
8033/// ```c
8034/// int xmlValidateNameValue(const xmlChar *value);
8035/// ```
8036///
8037/// Returns 1 if valid, 0 if not (NULL included).
8038#[no_mangle]
8039pub unsafe extern "C" fn xmlValidateNameValue(value: *const xmlChar) -> c_int {
8040 crate::xml::validation::validate_name_value(value)
8041}
8042
8043/// Validate a whitespace-separated list of Names (separator is exactly
8044/// 0x20, upstream erratum E20).
8045///
8046/// # UPSTREAM-PARITY
8047///
8048/// ```c
8049/// int xmlValidateNamesValue(const xmlChar *value);
8050/// ```
8051#[no_mangle]
8052pub unsafe extern "C" fn xmlValidateNamesValue(value: *const xmlChar) -> c_int {
8053 crate::xml::validation::validate_names_value(value)
8054}
8055
8056/// Validate an Nmtoken value (1-arg form, upstream valid.c).
8057///
8058/// # UPSTREAM-PARITY
8059///
8060/// ```c
8061/// int xmlValidateNmtokenValue(const xmlChar *value);
8062/// ```
8063#[no_mangle]
8064pub unsafe extern "C" fn xmlValidateNmtokenValue(value: *const xmlChar) -> c_int {
8065 crate::xml::validation::validate_nmtoken_value(value)
8066}
8067
8068/// Validate a whitespace-separated list of Nmtokens.
8069///
8070/// # UPSTREAM-PARITY
8071///
8072/// ```c
8073/// int xmlValidateNmtokensValue(const xmlChar *value);
8074/// ```
8075#[no_mangle]
8076pub unsafe extern "C" fn xmlValidateNmtokensValue(value: *const xmlChar) -> c_int {
8077 crate::xml::validation::validate_nmtokens_value(value)
8078}
8079
8080/// Validate a single element declaration (VC: Unique Element Type
8081/// Declaration, VC: No Duplicate Types).
8082///
8083/// # UPSTREAM-PARITY
8084///
8085/// ```c
8086/// int xmlValidateElementDecl(xmlValidCtxtPtr ctxt,
8087/// xmlDocPtr doc,
8088/// xmlElementPtr elem);
8089/// ```
8090#[no_mangle]
8091pub unsafe extern "C" fn xmlValidateElementDecl(
8092 ctxt: *mut _xmlValidCtxt,
8093 doc: *mut _xmlDoc,
8094 elem: *mut _xmlElement,
8095) -> c_int {
8096 crate::xml::validation::validate_element_decl(ctxt, doc, elem)
8097}
8098
8099/// Validate a notation declaration.
8100///
8101/// # UPSTREAM-PARITY
8102///
8103/// Modern libxml2 has no validity constraint on notation declarations; the
8104/// oracle returns 1 unconditionally (verified by DSO disassembly).
8105///
8106/// ```c
8107/// int xmlValidateNotationDecl(xmlValidCtxtPtr ctxt,
8108/// xmlDocPtr doc,
8109/// xmlNotationPtr nota);
8110/// ```
8111#[no_mangle]
8112pub const unsafe extern "C" fn xmlValidateNotationDecl(
8113 ctxt: *mut _xmlValidCtxt,
8114 doc: *mut _xmlDoc,
8115 nota: *mut _xmlNotation,
8116) -> c_int {
8117 crate::xml::validation::validate_notation_decl(ctxt, doc, nota)
8118}
8119
8120/// Validate a single attribute against its declaration.
8121///
8122/// # UPSTREAM-PARITY
8123///
8124/// ```c
8125/// int xmlValidateOneAttribute(xmlValidCtxtPtr ctxt,
8126/// xmlDocPtr doc,
8127/// xmlNodePtr elem,
8128/// xmlAttrPtr attr,
8129/// const xmlChar *value);
8130/// ```
8131#[no_mangle]
8132pub unsafe extern "C" fn xmlValidateOneAttribute(
8133 ctxt: *mut _xmlValidCtxt,
8134 doc: *mut _xmlDoc,
8135 elem: *mut _xmlNode,
8136 attr: *mut _xmlAttr,
8137 value: *const xmlChar,
8138) -> c_int {
8139 crate::xml::validation::validate_one_attribute(ctxt, doc, elem, attr, value)
8140}
8141
8142/// Validate a single element against its declaration (without recursing).
8143///
8144/// # UPSTREAM-PARITY
8145///
8146/// ```c
8147/// int xmlValidateOneElement(xmlValidCtxtPtr ctxt,
8148/// xmlDocPtr doc,
8149/// xmlNodePtr elem);
8150/// ```
8151#[no_mangle]
8152pub unsafe extern "C" fn xmlValidateOneElement(
8153 ctxt: *mut _xmlValidCtxt,
8154 doc: *mut _xmlDoc,
8155 elem: *mut _xmlNode,
8156) -> c_int {
8157 crate::xml::validation::validate_one_element(ctxt, doc, elem)
8158}
8159
8160/// Validate a namespace declaration attribute.
8161///
8162/// # UPSTREAM-PARITY
8163///
8164/// ```c
8165/// int xmlValidateOneNamespace(xmlValidCtxtPtr ctxt,
8166/// xmlDocPtr doc,
8167/// xmlNodePtr elem,
8168/// const xmlChar *prefix,
8169/// xmlNsPtr ns,
8170/// const xmlChar *value);
8171/// ```
8172#[no_mangle]
8173pub unsafe extern "C" fn xmlValidateOneNamespace(
8174 ctxt: *mut _xmlValidCtxt,
8175 doc: *mut _xmlDoc,
8176 elem: *mut _xmlNode,
8177 prefix: *const xmlChar,
8178 ns: *mut _xmlNs,
8179 value: *const xmlChar,
8180) -> c_int {
8181 crate::xml::validation::validate_one_namespace(ctxt, doc, elem, prefix, ns, value)
8182}
8183
8184/// Push a new element start onto the validation stack (streaming DTD
8185/// validation).
8186///
8187/// # UPSTREAM-PARITY
8188///
8189/// ```c
8190/// int xmlValidatePushElement(xmlValidCtxtPtr ctxt,
8191/// xmlDocPtr doc,
8192/// xmlNodePtr elem,
8193/// const xmlChar *qname);
8194/// ```
8195#[no_mangle]
8196pub unsafe extern "C" fn xmlValidatePushElement(
8197 ctxt: *mut _xmlValidCtxt,
8198 doc: *mut _xmlDoc,
8199 elem: *mut _xmlNode,
8200 qname: *const xmlChar,
8201) -> c_int {
8202 crate::xml::validation::validate_push_element(ctxt, doc, elem, qname)
8203}
8204
8205/// Push character data onto the validation stack.
8206///
8207/// # UPSTREAM-PARITY
8208///
8209/// ```c
8210/// int xmlValidatePushCData(xmlValidCtxtPtr ctxt,
8211/// const xmlChar *data,
8212/// int len);
8213/// ```
8214#[no_mangle]
8215pub unsafe extern "C" fn xmlValidatePushCData(
8216 ctxt: *mut _xmlValidCtxt,
8217 data: *const xmlChar,
8218 len: c_int,
8219) -> c_int {
8220 crate::xml::validation::validate_push_cdata(ctxt, data, len)
8221}
8222
8223/// Pop an element end from the validation stack.
8224///
8225/// # UPSTREAM-PARITY
8226///
8227/// ```c
8228/// int xmlValidatePopElement(xmlValidCtxtPtr ctxt,
8229/// xmlDocPtr doc,
8230/// xmlNodePtr elem,
8231/// const xmlChar *qname);
8232/// ```
8233#[no_mangle]
8234pub unsafe extern "C" fn xmlValidatePopElement(
8235 ctxt: *mut _xmlValidCtxt,
8236 doc: *mut _xmlDoc,
8237 elem: *mut _xmlNode,
8238 qname: *const xmlChar,
8239) -> c_int {
8240 crate::xml::validation::validate_pop_element(ctxt, doc, elem, qname)
8241}
8242
8243/// Build the content-model automaton for an element declaration.
8244///
8245/// # UPSTREAM-PARITY
8246///
8247/// ```c
8248/// int xmlValidBuildContentModel(xmlValidCtxtPtr ctxt,
8249/// xmlElementPtr elem);
8250/// ```
8251#[no_mangle]
8252pub unsafe extern "C" fn xmlValidBuildContentModel(
8253 ctxt: *mut _xmlValidCtxt,
8254 elem: *mut _xmlElement,
8255) -> c_int {
8256 crate::xml::validation::validate_build_content_model(ctxt, elem)
8257}
8258
8259/// Add an attribute to the document's ID table.
8260///
8261/// # UPSTREAM-PARITY
8262///
8263/// ```c
8264/// xmlIDPtr xmlAddID(xmlValidCtxtPtr ctxt,
8265/// xmlDocPtr doc,
8266/// const xmlChar *value,
8267/// xmlAttrPtr attr);
8268/// ```
8269#[no_mangle]
8270pub unsafe extern "C" fn xmlAddID(
8271 ctxt: *mut _xmlValidCtxt,
8272 doc: *mut _xmlDoc,
8273 value: *const xmlChar,
8274 attr: *mut _xmlAttr,
8275) -> *mut _xmlID {
8276 crate::xml::validation::add_id(ctxt, doc, value, attr)
8277}
8278
8279/// Remove an attribute from the document's ID table.
8280///
8281/// # UPSTREAM-PARITY
8282///
8283/// ```c
8284/// int xmlRemoveID(xmlDocPtr doc, xmlAttrPtr attr);
8285/// ```
8286#[no_mangle]
8287pub unsafe extern "C" fn xmlRemoveID(doc: *mut _xmlDoc, attr: *mut _xmlAttr) -> c_int {
8288 crate::xml::validation::remove_id(doc, attr)
8289}
8290
8291/// Register an IDREF in the document's ref table.
8292///
8293/// # UPSTREAM-PARITY
8294///
8295/// ```c
8296/// xmlRefPtr xmlAddRef(xmlValidCtxtPtr ctxt,
8297/// xmlDocPtr doc,
8298/// const xmlChar *value,
8299/// xmlAttrPtr attr);
8300/// ```
8301#[no_mangle]
8302pub unsafe extern "C" fn xmlAddRef(
8303 ctxt: *mut _xmlValidCtxt,
8304 doc: *mut _xmlDoc,
8305 value: *const xmlChar,
8306 attr: *mut _xmlAttr,
8307) -> *mut _xmlRef {
8308 crate::xml::validation::add_ref(ctxt, doc, value, attr)
8309}
8310
8311/// Remove an attribute's IDREF entries.
8312///
8313/// # UPSTREAM-PARITY
8314///
8315/// ```c
8316/// int xmlRemoveRef(xmlDocPtr doc, xmlAttrPtr attr);
8317/// ```
8318#[no_mangle]
8319pub unsafe extern "C" fn xmlRemoveRef(doc: *mut _xmlDoc, attr: *mut _xmlAttr) -> c_int {
8320 crate::xml::validation::remove_ref(doc, attr)
8321}
8322
8323/// Add an ID without a validation context (2.13+).
8324///
8325/// # UPSTREAM-PARITY
8326///
8327/// ```c
8328/// int xmlAddIDSafe(xmlAttrPtr attr, const xmlChar *value);
8329/// ```
8330#[no_mangle]
8331pub unsafe extern "C" fn xmlAddIDSafe(attr: *mut _xmlAttr, value: *const xmlChar) -> c_int {
8332 crate::xml::validation::add_id_safe(attr, value)
8333}
8334
8335/// Free an ID hash table.
8336///
8337/// # UPSTREAM-PARITY
8338///
8339/// ```c
8340/// void xmlFreeIDTable(xmlIDTablePtr table);
8341/// ```
8342#[no_mangle]
8343pub unsafe extern "C" fn xmlFreeIDTable(table: *mut c_void) {
8344 crate::xml::validation::free_id_table(table as *mut crate::xml::hash::HashTable);
8345}
8346
8347/// Free an IDREF hash table.
8348///
8349/// # UPSTREAM-PARITY
8350///
8351/// ```c
8352/// void xmlFreeRefTable(xmlRefTablePtr table);
8353/// ```
8354#[no_mangle]
8355pub unsafe extern "C" fn xmlFreeRefTable(table: *mut c_void) {
8356 crate::xml::validation::free_ref_table(table as *mut crate::xml::hash::HashTable);
8357}
8358
8359/// Look up the attribute holding an ID.
8360///
8361/// # UPSTREAM-PARITY
8362///
8363/// ```c
8364/// xmlAttrPtr xmlGetID(xmlDocPtr doc, const xmlChar *ID);
8365/// ```
8366#[no_mangle]
8367pub unsafe extern "C" fn xmlGetID(doc: *mut _xmlDoc, id: *const xmlChar) -> *mut _xmlAttr {
8368 crate::xml::validation::get_id(doc, id)
8369}
8370
8371/// Look up the list of references for an ID.
8372///
8373/// # UPSTREAM-PARITY
8374///
8375/// ```c
8376/// xmlListPtr xmlGetRefs(xmlDocPtr doc, const xmlChar *ID);
8377/// ```
8378#[no_mangle]
8379pub unsafe extern "C" fn xmlGetRefs(doc: *mut _xmlDoc, id: *const xmlChar) -> *mut c_void {
8380 crate::xml::validation::get_refs(doc, id) as *mut c_void
8381}
8382
8383/// Is this attribute an ID?
8384///
8385/// # UPSTREAM-PARITY
8386///
8387/// ```c
8388/// int xmlIsID(xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr);
8389/// ```
8390#[no_mangle]
8391pub unsafe extern "C" fn xmlIsID(
8392 doc: *mut _xmlDoc,
8393 elem: *mut _xmlNode,
8394 attr: *mut _xmlAttr,
8395) -> c_int {
8396 crate::xml::validation::is_id(doc, elem, attr)
8397}
8398
8399/// Is this attribute an IDREF?
8400///
8401/// # UPSTREAM-PARITY
8402///
8403/// ```c
8404/// int xmlIsRef(xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr);
8405/// ```
8406#[no_mangle]
8407pub unsafe extern "C" fn xmlIsRef(
8408 doc: *mut _xmlDoc,
8409 elem: *mut _xmlNode,
8410 attr: *mut _xmlAttr,
8411) -> c_int {
8412 crate::xml::validation::is_ref(doc, elem, attr)
8413}
8414
8415/// Search a DTD for an element declaration (with QName splitting).
8416///
8417/// # UPSTREAM-PARITY
8418///
8419/// ```c
8420/// xmlElementPtr xmlGetDtdElementDesc(xmlDtdPtr dtd, const xmlChar *name);
8421/// ```
8422#[no_mangle]
8423pub unsafe extern "C" fn xmlGetDtdElementDesc(
8424 dtd: *mut _xmlDtd,
8425 name: *const xmlChar,
8426) -> *mut _xmlElement {
8427 crate::xml::validation::get_dtd_element_desc(dtd, name)
8428}
8429
8430/// Search a DTD for an attribute declaration (with QName splitting).
8431///
8432/// # UPSTREAM-PARITY
8433///
8434/// ```c
8435/// xmlAttributePtr xmlGetDtdAttrDesc(xmlDtdPtr dtd,
8436/// const xmlChar *elem,
8437/// const xmlChar *name);
8438/// ```
8439#[no_mangle]
8440pub unsafe extern "C" fn xmlGetDtdAttrDesc(
8441 dtd: *mut _xmlDtd,
8442 elem: *const xmlChar,
8443 name: *const xmlChar,
8444) -> *mut _xmlAttribute {
8445 crate::xml::validation::get_dtd_attr_desc(dtd, elem, name)
8446}
8447
8448/// Search a DTD for a qualified element declaration.
8449///
8450/// # UPSTREAM-PARITY
8451///
8452/// ```c
8453/// xmlElementPtr xmlGetDtdQElementDesc(xmlDtdPtr dtd,
8454/// const xmlChar *name,
8455/// const xmlChar *prefix);
8456/// ```
8457#[no_mangle]
8458pub unsafe extern "C" fn xmlGetDtdQElementDesc(
8459 dtd: *mut _xmlDtd,
8460 name: *const xmlChar,
8461 prefix: *const xmlChar,
8462) -> *mut _xmlElement {
8463 crate::xml::validation::get_dtd_qelement_desc(dtd, name, prefix)
8464}
8465
8466/// Search a DTD for a qualified attribute declaration.
8467///
8468/// # UPSTREAM-PARITY
8469///
8470/// ```c
8471/// xmlAttributePtr xmlGetDtdQAttrDesc(xmlDtdPtr dtd,
8472/// const xmlChar *elem,
8473/// const xmlChar *name,
8474/// const xmlChar *prefix);
8475/// ```
8476#[no_mangle]
8477pub unsafe extern "C" fn xmlGetDtdQAttrDesc(
8478 dtd: *mut _xmlDtd,
8479 elem: *const xmlChar,
8480 name: *const xmlChar,
8481 prefix: *const xmlChar,
8482) -> *mut _xmlAttribute {
8483 crate::xml::validation::get_dtd_qattr_desc(dtd, elem, name, prefix)
8484}
8485
8486/// Search a DTD for a notation declaration.
8487///
8488/// # UPSTREAM-PARITY
8489///
8490/// ```c
8491/// xmlNotationPtr xmlGetDtdNotationDesc(xmlDtdPtr dtd, const xmlChar *name);
8492/// ```
8493#[no_mangle]
8494pub unsafe extern "C" fn xmlGetDtdNotationDesc(
8495 dtd: *mut _xmlDtd,
8496 name: *const xmlChar,
8497) -> *mut _xmlNotation {
8498 crate::xml::validation::get_dtd_notation_desc(dtd, name)
8499}
8500
8501/// Validate the root element of a document.
8502///
8503/// # UPSTREAM-PARITY
8504///
8505/// ```c
8506/// int xmlValidateRoot(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
8507/// ```
8508#[no_mangle]
8509pub unsafe extern "C" fn xmlValidateRoot(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
8510 crate::xml::validation::validate_root(ctxt, doc)
8511}
8512
8513/// Validate element content against its content model.
8514///
8515/// # UPSTREAM-PARITY
8516///
8517/// ```c
8518/// int xmlValidateContent(xmlValidCtxtPtr ctxt,
8519/// xmlNodePtr node,
8520/// xmlDocPtr doc);
8521/// ```
8522#[no_mangle]
8523pub unsafe extern "C" fn xmlValidateContent(
8524 ctxt: *mut _xmlValidCtxt,
8525 node: *mut _xmlNode,
8526 doc: *mut _xmlDoc,
8527) -> c_int {
8528 crate::xml::validation::validate_content(ctxt, node, doc)
8529}
8530
8531/// Check if an element is declared as mixed content.
8532///
8533/// # UPSTREAM-PARITY
8534///
8535/// ```c
8536/// int xmlIsMixedElement(xmlDocPtr doc, const xmlChar *name);
8537/// ```
8538#[no_mangle]
8539pub unsafe extern "C" fn xmlIsMixedElement(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
8540 crate::xml::validation::is_mixed_element(doc, name)
8541}
8542
8543/// Check if an element is declared as EMPTY.
8544///
8545/// # UPSTREAM-PARITY
8546///
8547/// ```c
8548/// int xmlIsEmptyElement(xmlDocPtr doc, const xmlChar *name);
8549/// ```
8550#[no_mangle]
8551pub unsafe extern "C" fn xmlIsEmptyElement(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
8552 crate::xml::validation::is_empty_element(doc, name)
8553}
8554
8555/// Validate a DTD's declarations.
8556///
8557/// # UPSTREAM-PARITY
8558///
8559/// ```c
8560/// int xmlValidateDtd(xmlValidCtxtPtr ctxt,
8561/// xmlDocPtr doc,
8562/// xmlDtdPtr dtd);
8563/// ```
8564#[no_mangle]
8565pub unsafe extern "C" fn xmlValidateDtd(
8566 ctxt: *mut _xmlValidCtxt,
8567 doc: *mut _xmlDoc,
8568 dtd: *mut _xmlDtd,
8569) -> c_int {
8570 crate::xml::validation::validate_dtd(ctxt, doc, dtd)
8571}
8572
8573/// Final DTD validation (ID/IDREF consistency).
8574///
8575/// # UPSTREAM-PARITY
8576///
8577/// ```c
8578/// int xmlValidateDtdFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc);
8579/// ```
8580#[no_mangle]
8581pub unsafe extern "C" fn xmlValidateDtdFinal(ctxt: *mut _xmlValidCtxt, doc: *mut _xmlDoc) -> c_int {
8582 crate::xml::validation::validate_dtd_final(ctxt, doc)
8583}
8584
8585/// Validate that a value is in an enumeration.
8586///
8587/// # UPSTREAM-PARITY
8588///
8589/// ```c
8590/// int xmlValidateEnumeration(xmlValidCtxtPtr ctxt,
8591/// const xmlChar *value,
8592/// xmlEnumerationPtr tree);
8593/// ```
8594#[no_mangle]
8595pub unsafe extern "C" fn xmlValidateEnumeration(
8596 ctxt: *mut _xmlValidCtxt,
8597 value: *const xmlChar,
8598 tree: *mut _xmlEnumeration,
8599) -> c_int {
8600 crate::xml::validation::validate_enumeration(ctxt, value, tree)
8601}
8602
8603// ═══════════════════════════════════════════════════════════════════════════════
8604// 18. Debug / Miscellaneous
8605// ═══════════════════════════════════════════════════════════════════════════════
8606
8607/// Dump a document to a file for debugging.
8608/// Get the path to the current executable.
8609///
8610/// # UPSTREAM-PARITY
8611///
8612/// ```c
8613/// char *xmlGetBinaryPath(void);
8614/// ```
8615#[no_mangle]
8616pub const extern "C" fn xmlGetBinaryPath() -> *mut c_char {
8617 // Phase 1: STUB
8618 ptr::null_mut()
8619}
8620
8621/// Get the path to the current executable's home directory.
8622///
8623/// # UPSTREAM-PARITY
8624///
8625/// ```c
8626/// char *xmlGetHomeOfBinary(void);
8627/// ```
8628#[no_mangle]
8629pub const extern "C" fn xmlGetHomeOfBinary() -> *mut c_char {
8630 // Phase 1: STUB
8631 ptr::null_mut()
8632}
8633
8634// ═══════════════════════════════════════════════════════════════════════════════
8635// SAX2 default callback entry points (upstream SAX2.c)
8636// ═══════════════════════════════════════════════════════════════════════════════
8637//
8638// These are the public `xmlSAX2*` callback functions that downstream code
8639// installs into `xmlSAXHandler` structures. They are the same implementations
8640// the candidate's default SAX handler uses; exporting them under the
8641// upstream names is required for ABI parity (R-000136 closure).
8642
8643/// Upstream SAX2.c `xmlSAX2StartDocument` — public entry point of the default handler.
8644#[no_mangle]
8645pub unsafe extern "C" fn xmlSAX2StartDocument(ctx: *mut c_void) {
8646 crate::xml::sax::default::default_sax_handler::startDocument(ctx)
8647}
8648
8649/// Upstream SAX2.c `xmlSAX2EndDocument` — public entry point of the default handler.
8650#[no_mangle]
8651pub unsafe extern "C" fn xmlSAX2EndDocument(ctx: *mut c_void) {
8652 crate::xml::sax::default::default_sax_handler::endDocument(ctx)
8653}
8654
8655/// Upstream SAX2.c `xmlSAX2StartElementNs` — public entry point of the default handler.
8656#[no_mangle]
8657pub unsafe extern "C" fn xmlSAX2StartElementNs(
8658 ctx: *mut c_void,
8659 localname: *const xmlChar,
8660 prefix: *const xmlChar,
8661 URI: *const xmlChar,
8662 nb_namespaces: c_int,
8663 namespaces: *mut *const xmlChar,
8664 nb_attributes: c_int,
8665 nb_defaulted: c_int,
8666 attributes: *mut *const xmlChar,
8667) {
8668 crate::xml::sax::default::default_sax_handler::startElementNs(
8669 ctx,
8670 localname,
8671 prefix,
8672 URI,
8673 nb_namespaces,
8674 namespaces,
8675 nb_attributes,
8676 nb_defaulted,
8677 attributes,
8678 )
8679}
8680
8681/// Upstream SAX2.c `xmlSAX2EndElementNs` — public entry point of the default handler.
8682#[no_mangle]
8683pub unsafe extern "C" fn xmlSAX2EndElementNs(
8684 ctx: *mut c_void,
8685 localname: *const xmlChar,
8686 prefix: *const xmlChar,
8687 URI: *const xmlChar,
8688) {
8689 crate::xml::sax::default::default_sax_handler::endElementNs(ctx, localname, prefix, URI)
8690}
8691
8692/// Upstream SAX2.c `xmlSAX2Characters` — public entry point of the default handler.
8693#[no_mangle]
8694pub unsafe extern "C" fn xmlSAX2Characters(ctx: *mut c_void, ch: *const xmlChar, len: c_int) {
8695 crate::xml::sax::default::default_sax_handler::characters(ctx, ch, len)
8696}
8697
8698/// Upstream SAX2.c `xmlSAX2IgnorableWhitespace` — public entry point of the default handler.
8699#[no_mangle]
8700pub unsafe extern "C" fn xmlSAX2IgnorableWhitespace(
8701 ctx: *mut c_void,
8702 ch: *const xmlChar,
8703 len: c_int,
8704) {
8705 crate::xml::sax::default::default_sax_handler::ignorableWhitespace(ctx, ch, len)
8706}
8707
8708/// Upstream SAX2.c `xmlSAX2Comment` — public entry point of the default handler.
8709#[no_mangle]
8710pub unsafe extern "C" fn xmlSAX2Comment(ctx: *mut c_void, value: *const xmlChar) {
8711 crate::xml::sax::default::default_sax_handler::comment(ctx, value)
8712}
8713
8714/// Upstream SAX2.c `xmlSAX2ProcessingInstruction` — public entry point of the default handler.
8715#[no_mangle]
8716pub unsafe extern "C" fn xmlSAX2ProcessingInstruction(
8717 ctx: *mut c_void,
8718 target: *const xmlChar,
8719 data: *const xmlChar,
8720) {
8721 crate::xml::sax::default::default_sax_handler::processingInstruction(ctx, target, data)
8722}
8723
8724/// Upstream SAX2.c `xmlSAX2CDataBlock` — public entry point of the default handler.
8725#[no_mangle]
8726pub unsafe extern "C" fn xmlSAX2CDataBlock(ctx: *mut c_void, value: *const xmlChar, len: c_int) {
8727 crate::xml::sax::default::default_sax_handler::cdataBlock(ctx, value, len)
8728}
8729
8730/// Upstream SAX2.c `xmlSAX2InternalSubset` — public entry point of the default handler.
8731#[no_mangle]
8732pub unsafe extern "C" fn xmlSAX2InternalSubset(
8733 ctx: *mut c_void,
8734 name: *const xmlChar,
8735 ExternalID: *const xmlChar,
8736 SystemID: *const xmlChar,
8737) {
8738 crate::xml::sax::default::default_sax_handler::internalSubset(ctx, name, ExternalID, SystemID)
8739}
8740
8741/// Upstream SAX2.c `xmlSAX2ExternalSubset` — public entry point of the default handler.
8742#[no_mangle]
8743pub unsafe extern "C" fn xmlSAX2ExternalSubset(
8744 ctx: *mut c_void,
8745 name: *const xmlChar,
8746 ExternalID: *const xmlChar,
8747 SystemID: *const xmlChar,
8748) {
8749 crate::xml::sax::default::default_sax_handler::externalSubset(ctx, name, ExternalID, SystemID)
8750}
8751
8752/// Upstream SAX2.c `xmlSAX2EntityDecl` — public entry point of the default handler.
8753#[no_mangle]
8754pub unsafe extern "C" fn xmlSAX2EntityDecl(
8755 ctx: *mut c_void,
8756 name: *const xmlChar,
8757 type_: c_int,
8758 publicId: *const xmlChar,
8759 systemId: *const xmlChar,
8760 content: *mut xmlChar,
8761) {
8762 crate::xml::sax::default::default_sax_handler::entityDecl(
8763 ctx, name, type_, publicId, systemId, content,
8764 )
8765}
8766
8767/// Upstream SAX2.c `xmlSAX2AttributeDecl` — public entry point of the default handler.
8768#[no_mangle]
8769pub const unsafe extern "C" fn xmlSAX2AttributeDecl(
8770 ctx: *mut c_void,
8771 elem: *const xmlChar,
8772 fullname: *const xmlChar,
8773 type_: c_int,
8774 def: c_int,
8775 defaultValue: *const xmlChar,
8776 tree: *mut crate::abi::structs::_xmlEnumeration,
8777) {
8778 crate::xml::sax::default::default_sax_handler::attributeDecl(
8779 ctx,
8780 elem,
8781 fullname,
8782 type_,
8783 def,
8784 defaultValue,
8785 tree,
8786 )
8787}
8788
8789/// Upstream SAX2.c `xmlSAX2ElementDecl` — public entry point of the default handler.
8790#[no_mangle]
8791pub const unsafe extern "C" fn xmlSAX2ElementDecl(
8792 ctx: *mut c_void,
8793 name: *const xmlChar,
8794 type_: c_int,
8795 content: *mut crate::abi::structs::_xmlElementContent,
8796) {
8797 crate::xml::sax::default::default_sax_handler::elementDecl(ctx, name, type_, content)
8798}
8799
8800/// Upstream SAX2.c `xmlSAX2NotationDecl` — public entry point of the default handler.
8801#[no_mangle]
8802pub const unsafe extern "C" fn xmlSAX2NotationDecl(
8803 ctx: *mut c_void,
8804 name: *const xmlChar,
8805 publicId: *const xmlChar,
8806 systemId: *const xmlChar,
8807) {
8808 crate::xml::sax::default::default_sax_handler::notationDecl(ctx, name, publicId, systemId)
8809}
8810
8811/// Upstream SAX2.c `xmlSAX2UnparsedEntityDecl` — public entry point of the default handler.
8812#[no_mangle]
8813pub const unsafe extern "C" fn xmlSAX2UnparsedEntityDecl(
8814 ctx: *mut c_void,
8815 name: *const xmlChar,
8816 publicId: *const xmlChar,
8817 systemId: *const xmlChar,
8818 notationName: *const xmlChar,
8819) {
8820 crate::xml::sax::default::default_sax_handler::unparsedEntityDecl(
8821 ctx,
8822 name,
8823 publicId,
8824 systemId,
8825 notationName,
8826 )
8827}
8828
8829/// Upstream SAX2.c `xmlSAX2ResolveEntity` — public entry point of the default handler.
8830#[no_mangle]
8831pub const unsafe extern "C" fn xmlSAX2ResolveEntity(
8832 ctx: *mut c_void,
8833 publicId: *const xmlChar,
8834 systemId: *const xmlChar,
8835) -> *mut crate::abi::structs::_xmlParserInput {
8836 crate::xml::sax::default::default_sax_handler::resolveEntity(ctx, publicId, systemId)
8837}
8838
8839/// Upstream SAX2.c `xmlSAX2IsStandalone` — public entry point of the default handler.
8840#[no_mangle]
8841pub const unsafe extern "C" fn xmlSAX2IsStandalone(ctx: *mut c_void) -> c_int {
8842 crate::xml::sax::default::default_sax_handler::isStandalone(ctx)
8843}
8844
8845/// Upstream SAX2.c `xmlSAX2HasInternalSubset` — public entry point of the default handler.
8846#[no_mangle]
8847pub unsafe extern "C" fn xmlSAX2HasInternalSubset(ctx: *mut c_void) -> c_int {
8848 crate::xml::sax::default::default_sax_handler::hasInternalSubset(ctx)
8849}
8850
8851/// Upstream SAX2.c `xmlSAX2HasExternalSubset` — public entry point of the default handler.
8852#[no_mangle]
8853pub unsafe extern "C" fn xmlSAX2HasExternalSubset(ctx: *mut c_void) -> c_int {
8854 crate::xml::sax::default::default_sax_handler::hasExternalSubset(ctx)
8855}
8856
8857/// Upstream SAX2.c `xmlSAX2GetEntity` — public entry point of the default handler.
8858#[no_mangle]
8859pub unsafe extern "C" fn xmlSAX2GetEntity(
8860 ctx: *mut c_void,
8861 name: *const xmlChar,
8862) -> *mut crate::abi::structs::_xmlEntity {
8863 crate::xml::sax::default::default_sax_handler::getEntity(ctx, name)
8864}
8865
8866/// Upstream SAX2.c `xmlSAX2GetParameterEntity` — public entry point of the default handler.
8867#[no_mangle]
8868pub unsafe extern "C" fn xmlSAX2GetParameterEntity(
8869 ctx: *mut c_void,
8870 name: *const xmlChar,
8871) -> *mut crate::abi::structs::_xmlEntity {
8872 crate::xml::sax::default::default_sax_handler::getParameterEntity(ctx, name)
8873}
8874
8875/// Upstream SAX2.c `xmlSAX2GetLineNumber` — public entry point of the
8876/// default handler (SAX locator callback).
8877#[no_mangle]
8878pub unsafe extern "C" fn xmlSAX2GetLineNumber(ctx: *mut c_void) -> c_int {
8879 crate::xml::sax::default::default_sax_handler::getLineNumber(ctx)
8880}
8881
8882/// Upstream SAX2.c `xmlSAX2GetColumnNumber`.
8883#[no_mangle]
8884pub unsafe extern "C" fn xmlSAX2GetColumnNumber(ctx: *mut c_void) -> c_int {
8885 crate::xml::sax::default::default_sax_handler::getColumnNumber(ctx)
8886}
8887
8888/// Upstream SAX2.c `xmlSAX2GetPublicId`.
8889#[no_mangle]
8890pub const unsafe extern "C" fn xmlSAX2GetPublicId(ctx: *mut c_void) -> *const xmlChar {
8891 crate::xml::sax::default::default_sax_handler::getPublicId(ctx)
8892}
8893
8894/// Upstream SAX2.c `xmlSAX2GetSystemId`.
8895#[no_mangle]
8896pub unsafe extern "C" fn xmlSAX2GetSystemId(ctx: *mut c_void) -> *const xmlChar {
8897 crate::xml::sax::default::default_sax_handler::getSystemId(ctx)
8898}
8899
8900/// Upstream SAX2.c `xmlSAX2StartElement` — SAX1 start-element entry point.
8901/// The candidate parser dispatches through the SAX2 (namespaced) callbacks;
8902/// this wrapper maps to the SAX1 handler when installed.
8903#[no_mangle]
8904pub unsafe extern "C" fn xmlSAX2StartElement(
8905 ctx: *mut c_void,
8906 name: *const xmlChar,
8907 atts: *mut *const xmlChar,
8908) {
8909 // The parser core invokes startElementNs; the SAX1 shim is provided by
8910 // the dispatch layer. When this entry point is installed directly on a
8911 // handler, route through the internal SAX1 path.
8912 crate::xml::sax::dispatch::SaxDispatcher::sax1_start_element(ctx, name, atts);
8913}
8914
8915/// Upstream SAX2.c `xmlSAX2EndElement` — SAX1 end-element entry point.
8916#[no_mangle]
8917pub unsafe extern "C" fn xmlSAX2EndElement(ctx: *mut c_void, name: *const xmlChar) {
8918 crate::xml::sax::dispatch::SaxDispatcher::sax1_end_element(ctx, name);
8919}
8920
8921/// Upstream SAX2.c `xmlSAX2SetDocumentLocator` — public entry point of the default handler.
8922#[no_mangle]
8923pub const unsafe extern "C" fn xmlSAX2SetDocumentLocator(
8924 ctx: *mut c_void,
8925 loc: *mut crate::abi::callbacks::_xmlSAXLocator,
8926) {
8927 crate::xml::sax::default::default_sax_handler::setDocumentLocator(ctx, loc)
8928}
8929
8930/// Upstream SAX2.c `xmlSAX2Reference` — public entry point of the default handler.
8931#[no_mangle]
8932pub unsafe extern "C" fn xmlSAX2Reference(ctx: *mut c_void, name: *const xmlChar) {
8933 crate::xml::sax::default::default_sax_handler::reference(ctx, name)
8934}
8935
8936#[cfg(test)]
8937mod tests {
8938 use super::xml_number_to_string;
8939
8940 /// R-000166: number-to-string follows upstream xmlXPathFormatNumber —
8941 /// verified byte-identical against the oracle (xsltproc) on the t4/n3
8942 /// differential corpora. Cases here are exact doubles or
8943 /// rounding-robust formats (parser-dependent literals are covered by the
8944 /// differential corpora, not unit tests).
8945 #[allow(clippy::approx_constant)]
8946 #[test]
8947 fn test_xml_number_to_string_parity_cases() {
8948 let cases: &[(f64, &str)] = &[
8949 (1234567.891, "1234567.891"),
8950 (0.1 + 0.2, "0.3"),
8951 (1.0 / 3.0, "0.333333333333333"),
8952 (1e20, "1e+20"),
8953 (1e-5, "0.00001"),
8954 (123456789012345678901234567890.0, "1.23456789012346e+29"),
8955 (1e100, "1e+100"),
8956 (-1e100, "-1e+100"),
8957 (1.5e-100, "1.5e-100"),
8958 (1e9, "1000000000"),
8959 (0.00001, "0.00001"),
8960 (9.99e-6, "9.99e-06"),
8961 (2147483646.0, "2147483646"),
8962 (2147483648.0, "2.147483648e+09"),
8963 (-2147483647.0, "-2147483647"),
8964 (-2147483649.0, "-2.147483649e+09"),
8965 (0.5, "0.5"),
8966 (1.0 / 7.0, "0.142857142857143"),
8967 (2.675, "2.675"),
8968 (3.141592653589793, "3.141592653589793"),
8969 (-0.0, "0"),
8970 (0.0, "0"),
8971 (f64::INFINITY, "Infinity"),
8972 (f64::NEG_INFINITY, "-Infinity"),
8973 (f64::NAN, "NaN"),
8974 (0.30000000000000004, "0.3"),
8975 (2.2250738585072014e-308, "2.2250738585072e-308"),
8976 (5e-324, "4.94065645841247e-324"),
8977 ];
8978 for (n, expected) in cases {
8979 assert_eq!(&xml_number_to_string(*n), expected, "value: {}", n);
8980 }
8981 }
8982
8983 /// xmlNewChild with a non-NULL content creates the element and appends a
8984 /// text child (upstream tree.c xmlNewChild -> xmlNewDocNode ->
8985 /// xmlNewDocText + xmlAddChild; tree2.c relies on it — Phase-12
8986 /// EXTERNAL-CONSUMERS court).
8987 ///
8988 /// # Safety
8989 ///
8990 /// - The doc and nodes are created and freed exactly once within the
8991 /// test; pointers are asserted non-NULL before dereference.
8992 #[test]
8993 fn test_xml_new_child_with_content() {
8994 unsafe {
8995 let doc =
8996 crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
8997 assert!(!doc.is_null());
8998 let root = crate::xml::tree::new_node(
8999 core::ptr::null_mut(),
9000 c"root".as_ptr() as *const crate::abi::types::xmlChar,
9001 );
9002 assert!(!root.is_null());
9003 crate::xml::tree::doc_set_root_element(doc, root);
9004
9005 let child = super::xmlNewChild(
9006 root,
9007 core::ptr::null_mut(),
9008 c"node1".as_ptr() as *const crate::abi::types::xmlChar,
9009 c"content of node 1".as_ptr() as *const crate::abi::types::xmlChar,
9010 );
9011 assert!(!child.is_null());
9012 assert!(
9013 !(*child).children.is_null(),
9014 "content must become a text child"
9015 );
9016 assert_eq!(
9017 crate::abi::types::xmlElementType::XML_TEXT_NODE as i32,
9018 (*(*child).children).type_
9019 );
9020 let text = crate::xml::string::xmlstr_to_bytes((*(*child).children).content);
9021 assert_eq!(text, b"content of node 1");
9022
9023 // NULL content stays childless
9024 let empty = super::xmlNewChild(
9025 root,
9026 core::ptr::null_mut(),
9027 c"node2".as_ptr() as *const crate::abi::types::xmlChar,
9028 core::ptr::null(),
9029 );
9030 assert!(!empty.is_null());
9031 assert!((*empty).children.is_null());
9032
9033 crate::xml::tree::free_doc(doc);
9034 }
9035 }
9036
9037 /// xmlNewChild content is parsed as an ATTRIBUTE VALUE (upstream tree.c
9038 /// xmlNewChild -> xmlNewDocNode -> xmlNewElem -> xmlNodeParseAttValue):
9039 /// an EMPTY content adds NO text child (`<bar/>`, SimpleXML bug76712),
9040 /// character references are decoded (`a & b` -> `a & b`, SimpleXML
9041 /// bug44478) and a declared general entity becomes an entity-ref child.
9042 /// The old raw text storage appended an empty text node for "" and kept
9043 /// the reference text verbatim.
9044 ///
9045 /// # Safety
9046 ///
9047 /// - doc/root/child are created and freed exactly once; the text child
9048 /// content string is read while live.
9049 #[test]
9050 fn test_xml_new_child_parses_content_as_att_value() {
9051 unsafe {
9052 let doc =
9053 crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9054 assert!(!doc.is_null());
9055 let root = crate::xml::tree::new_node(
9056 core::ptr::null_mut(),
9057 c"root".as_ptr() as *const crate::abi::types::xmlChar,
9058 );
9059 assert!(!root.is_null());
9060 crate::xml::tree::doc_set_root_element(doc, root);
9061
9062 // Empty content -> NO text child (upstream value[0] == 0 early
9063 // out); serializes as `<empty/>`.
9064 let e = super::xmlNewChild(
9065 root,
9066 core::ptr::null_mut(),
9067 c"empty".as_ptr() as *const crate::abi::types::xmlChar,
9068 c"".as_ptr() as *const crate::abi::types::xmlChar,
9069 );
9070 assert!(!e.is_null());
9071 assert!(
9072 (*e).children.is_null(),
9073 "empty content must not add a text child"
9074 );
9075
9076 // Character reference content is DECODED into the text child.
9077 let r = super::xmlNewChild(
9078 root,
9079 core::ptr::null_mut(),
9080 c"ref".as_ptr() as *const crate::abi::types::xmlChar,
9081 c"a & b".as_ptr() as *const crate::abi::types::xmlChar,
9082 );
9083 assert!(!r.is_null());
9084 assert!(!(*r).children.is_null());
9085 let txt = crate::xml::string::xmlstr_to_bytes((*(*r).children).content);
9086 assert_eq!(txt, b"a & b");
9087
9088 // A bare '&' (no terminating ';') consumes the '&' and keeps the
9089 // rest as text (upstream xmlNodeParseAttValue, "x & y" -> "x y").
9090 let b = super::xmlNewChild(
9091 root,
9092 core::ptr::null_mut(),
9093 c"bare".as_ptr() as *const crate::abi::types::xmlChar,
9094 c"x & y".as_ptr() as *const crate::abi::types::xmlChar,
9095 );
9096 assert!(!b.is_null());
9097 assert!(!(*b).children.is_null());
9098 let txt = crate::xml::string::xmlstr_to_bytes((*(*b).children).content);
9099 assert_eq!(txt, b"x y");
9100
9101 crate::xml::tree::free_doc(doc);
9102 }
9103 }
9104
9105 /// Phase 14.3 Bug-2 regression: `xmlFreeProp` must not free a
9106 /// dict-interned attribute name. PHP's SimpleXML unset path
9107 /// (`sxe_unlink_node` -> `php_libxml_node_free` -> `xmlFreeProp`) frees an
9108 /// attribute whose name the parser interned in the document dictionary;
9109 /// the pre-fix `free_prop_impl` freed the interned string, and
9110 /// `xmlDictFree` at doc teardown freed it again (double free). Mirrors the
9111 /// PHP sequence: unlink the attribute, free it via `xmlFreeProp`, then
9112 /// free the document.
9113 ///
9114 /// # Safety
9115 ///
9116 /// - doc/dict/root/attr are built and freed exactly once; a double free
9117 /// (the bug) aborts the test process under glibc tcache detection.
9118 #[test]
9119 fn test_xml_free_prop_preserves_dict_interned_attr_name() {
9120 unsafe {
9121 use crate::abi::allocator::xmlMallocZero;
9122 use crate::abi::structs::{_xmlAttr, _xmlNode};
9123 use core::mem::size_of;
9124
9125 let dict = super::xmlDictCreate();
9126 assert!(!dict.is_null());
9127 let doc =
9128 crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9129 assert!(!doc.is_null());
9130 (*doc).dict = dict;
9131 let root = crate::xml::tree::new_node(
9132 core::ptr::null_mut(),
9133 c"root".as_ptr() as *const crate::abi::types::xmlChar,
9134 );
9135 assert!(!root.is_null());
9136 crate::xml::tree::doc_set_root_element(doc, root);
9137
9138 // Intern the attribute name exactly as the dictNames parser does.
9139 let iname = super::xmlDictLookup(
9140 dict,
9141 c"id".as_ptr() as *const crate::abi::types::xmlChar,
9142 -1,
9143 );
9144 assert!(!iname.is_null());
9145
9146 // Build the attribute node with the borrowed dict-interned name
9147 // (mirrors parser_set_prop attribute creation).
9148 let attr = xmlMallocZero(size_of::<_xmlAttr>()) as *mut _xmlAttr;
9149 assert!(!attr.is_null());
9150 (*attr).type_ = crate::abi::types::xmlElementType::XML_ATTRIBUTE_NODE as i32;
9151 (*attr).name = iname as *mut crate::abi::types::xmlChar;
9152 (*attr).parent = root;
9153 (*attr).doc = doc;
9154 (*root).properties = attr;
9155
9156 // PHP SimpleXML unset: xmlUnlinkNode(attr) then xmlFreeProp(attr).
9157 crate::xml::tree::unlink_node(attr as *mut _xmlNode);
9158 crate::abi::exports_tree::xmlFreeProp(attr);
9159
9160 // Teardown: xmlDictFree reaches refcount 0 and frees the interned
9161 // string once. A pre-fix double free aborts here.
9162 crate::xml::tree::free_doc(doc);
9163 }
9164 }
9165
9166 /// Phase 14.3 regression: `xmlNodeListGetString` over a non-text node
9167 /// list must return a NUL-terminated EMPTY string. The pre-fix
9168 /// `xml_strdup(b"")` idiom handed xml_strdup a dangling 0x1 pointer
9169 /// (Rust zero-length byte-string literal), crashing in xml_strlen when
9170 /// SimpleXML string-casts an element whose children produce no text
9171 /// (ext/simplexml 027/028).
9172 ///
9173 /// # Safety
9174 ///
9175 /// - doc/root/person are built and freed exactly once; returned strings
9176 /// are freed with `xmlFreeImpl`.
9177 #[test]
9178 fn test_nodelist_getstring_empty_from_element_chain() {
9179 unsafe {
9180 let doc =
9181 crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9182 assert!(!doc.is_null());
9183 let root = crate::xml::tree::new_node(
9184 core::ptr::null_mut(),
9185 c"people".as_ptr() as *const crate::abi::types::xmlChar,
9186 );
9187 assert!(!root.is_null());
9188 crate::xml::tree::doc_set_root_element(doc, root);
9189 let person = crate::abi::exports_tree::xmlNewTextChild(
9190 root,
9191 core::ptr::null_mut(),
9192 c"person".as_ptr() as *const crate::abi::types::xmlChar,
9193 c"Joe".as_ptr() as *const crate::abi::types::xmlChar,
9194 );
9195 assert!(!person.is_null());
9196 super::xmlSetProp(
9197 person,
9198 c"gender".as_ptr() as *const crate::abi::types::xmlChar,
9199 c"male".as_ptr() as *const crate::abi::types::xmlChar,
9200 );
9201
9202 // Element list head yields an empty string (pre-fix: crash).
9203 let s1 = crate::abi::exports_treedump::xmlNodeListGetString(doc, (*root).children, 1);
9204 assert!(!s1.is_null());
9205 assert_eq!(*s1 as u8, 0);
9206 crate::abi::allocator::xmlFreeImpl(s1 as *mut core::ffi::c_void);
9207
9208 // Text child list yields the element text.
9209 let s2 = crate::abi::exports_treedump::xmlNodeListGetString(doc, (*person).children, 1);
9210 assert!(!s2.is_null());
9211 let b = crate::xml::string::xmlstr_to_bytes(s2);
9212 assert_eq!(b, b"Joe");
9213 crate::abi::allocator::xmlFreeImpl(s2 as *mut core::ffi::c_void);
9214
9215 crate::xml::tree::free_doc(doc);
9216 }
9217 }
9218
9219 /// Phase 14.3 (simplexml S3 / ext/simplexml 008): with no structured
9220 /// handler, a failed XPath compile delivers the message VERBATIM to the
9221 /// generic channel — upstream xpath.c xmlXPathErrFmt sets
9222 /// `channel = xmlGenericError; data = xmlGenericErrorContext`, and
9223 /// xmlVRaiseError calls `channel(data, "%s", to->message)` because the
9224 /// generic channel is NOT one of the parser channels that trigger
9225 /// xmlFormatError's fragment stream (which would prefix "XPath error :").
9226 /// PHP installs a generic handler at request start (php_libxml_issue_
9227 /// warning), so the raw text "Invalid expression\n" must arrive alone;
9228 /// a pre-fix `GenericDelivery::Stream` reached PHP's handler with the
9229 /// fragment prefix and ext/simplexml 008 warned "XPath error : Invalid
9230 /// expression".
9231 ///
9232 /// # Safety
9233 ///
9234 /// - doc/ctxt are created and freed exactly once; `captured` lives on
9235 /// the stack for the duration of the call; the generic handler slot is
9236 /// restored to the default printer before the test ends.
9237 #[test]
9238 fn test_xpath_compile_error_verbatim_to_generic_channel() {
9239 use crate::abi::callbacks::xmlGenericErrorFunc;
9240 use core::ffi::{c_char, c_void};
9241
9242 // Serialized against the handler-slot tests in xml::globals (11.1-X)
9243 // and xml::errors: the generic handler slot is shared global state.
9244 let _guard = crate::xml::globals::ERROR_HANDLER_TEST_LOCK.lock();
9245 unsafe {
9246 let mut captured: Vec<u8> = Vec::new();
9247 let captured_ptr = &mut captured as *mut Vec<u8> as *mut c_void;
9248
9249 unsafe extern "C" fn record(ctx: *mut c_void, msg: *const c_char) {
9250 if msg.is_null() {
9251 return;
9252 }
9253 let out = &mut *(ctx as *mut Vec<u8>);
9254 let bytes = std::ffi::CStr::from_ptr(msg).to_bytes();
9255 out.extend_from_slice(bytes);
9256 }
9257
9258 super::xmlSetGenericErrorFunc(captured_ptr, Some(record as xmlGenericErrorFunc));
9259
9260 let doc =
9261 crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9262 assert!(!doc.is_null());
9263 let ctxt = super::xmlXPathNewContext(doc);
9264 assert!(!ctxt.is_null());
9265 // No structured handler on the context (ctxt->error stays NULL)
9266 // so the generic channel is the delivery target.
9267 (*ctxt).error = None;
9268
9269 let comp = crate::xml::xpath::exports::xmlXPathCtxtCompile(
9270 ctxt,
9271 c"**".as_ptr() as *const crate::abi::types::xmlChar,
9272 );
9273 assert!(comp.is_null(), "`**` must fail to compile");
9274
9275 assert_eq!(
9276 captured, b"Invalid expression\n",
9277 "generic channel must receive the raw message, no \"XPath error : \" prefix"
9278 );
9279
9280 // Restore the generic handler slot to the default printer.
9281 super::xmlSetGenericErrorFunc(core::ptr::null_mut(), None);
9282 super::xmlXPathFreeContext(ctxt);
9283 crate::xml::tree::free_doc(doc);
9284 }
9285 }
9286
9287 /// Phase 14.3 (simplexml S7 / bug63575): node/document copies must NOT
9288 /// carry the source `_private` — upstream xmlStaticCopyNode zeroes the
9289 /// new node and xmlCopyNamespaceList never copies _private. PHP keys its
9290 /// wrapper registrations on `_private` (php_libxml_node_ptr), so a
9291 /// copied subtree that inherits the original's registrations binds the
9292 /// clone to the ORIGINAL document: SimpleXML root-element clone
9293 /// (xmlCopyDoc) then resolved XPath and mutations into the original's
9294 /// tree. The copy must look UNREGISTERED.
9295 ///
9296 /// # Safety
9297 ///
9298 /// - doc/root/marker are created and freed exactly once within the test;
9299 /// pointers are asserted non-NULL before dereference.
9300 #[test]
9301 fn test_copies_do_not_carry_private() {
9302 unsafe {
9303 let doc =
9304 crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9305 assert!(!doc.is_null());
9306 let root = crate::xml::tree::new_node(
9307 core::ptr::null_mut(),
9308 c"a".as_ptr() as *const crate::abi::types::xmlChar,
9309 );
9310 assert!(!root.is_null());
9311 crate::xml::tree::doc_set_root_element(doc, root);
9312
9313 // PHP-style registration marker on the SOURCE node.
9314 let marker: usize = 0x5A5A;
9315 (*root)._private = marker as *mut core::ffi::c_void;
9316
9317 // xmlCopyDoc: the new root must be unregistered.
9318 let cdoc = super::xmlCopyDoc(doc, 1);
9319 assert!(!cdoc.is_null());
9320 let croot = (*cdoc).children;
9321 assert!(!croot.is_null());
9322 assert!(
9323 (*croot)._private.is_null(),
9324 "xmlCopyDoc must not carry the source node _private"
9325 );
9326 assert_eq!(
9327 (*root)._private as usize,
9328 marker,
9329 "source _private is untouched"
9330 );
9331 crate::xml::tree::free_doc(cdoc);
9332
9333 // xmlDocCopyNode into the same doc: the copy must be unregistered.
9334 let copy = crate::abi::exports_treedump::xmlDocCopyNode(root, doc, 1);
9335 assert!(!copy.is_null());
9336 assert!(
9337 (*copy)._private.is_null(),
9338 "xmlDocCopyNode must not carry the source node's _private"
9339 );
9340 // The detached copy owns a duplicated name string: free it
9341 // directly, then the document.
9342 super::xmlFreeNode(copy);
9343 crate::xml::tree::free_doc(doc);
9344 }
9345 }
9346
9347 /// The C-extension-function bridge must expose the invoked function's
9348 /// LOCAL name and namespace URI on `ctxt->context->function` /
9349 /// `functionURI` for the duration of the call, and restore the previous
9350 /// values afterwards (upstream xpath.c xmlXPathCompOpEval, XPATH_OP_
9351 /// FUNCTION). PHP registers ONE trampoline for every custom-namespace
9352 /// XPath function and dispatches to the PHP closure from those two
9353 /// fields — without them the dom/xsl php:function callbacks dereference
9354 /// garbage (SP-14.3.6-dom O1: return_dom_node_from_xpath /
9355 /// registerPhpFunctionNS / gh22077 segv).
9356 ///
9357 /// # Safety
9358 ///
9359 /// - doc/ctxt/result are created and freed exactly once; the callback
9360 /// reads only the two fields the bridge must set.
9361 #[test]
9362 fn test_c_xpath_function_bridge_exposes_function_and_uri() {
9363 unsafe {
9364 use crate::xml::xpath::exports::{xmlXPathNewString, xmlXPathValuePush};
9365 use crate::xml::xpath::parser_context::XmlXPathParserContext;
9366 use std::os::raw::{c_char, c_int};
9367
9368 /// Mirrors PHP's dom_xpath_ext_fetch_intern: read the function
9369 /// identity the invoker set on the context.
9370 unsafe extern "C" fn capture_identity(ctxt: *mut core::ffi::c_void, _nargs: c_int) {
9371 let pc = ctxt as *mut XmlXPathParserContext;
9372 let ctx = (*pc).context;
9373 assert!(!ctx.is_null());
9374 let name = (*ctx).function;
9375 let uri = (*ctx).functionURI;
9376 assert!(!name.is_null());
9377 let name_s = std::ffi::CStr::from_ptr(name as *const c_char)
9378 .to_string_lossy()
9379 .into_owned();
9380 let uri_s = if uri.is_null() {
9381 "(null)".to_string()
9382 } else {
9383 std::ffi::CStr::from_ptr(uri as *const c_char)
9384 .to_string_lossy()
9385 .into_owned()
9386 };
9387 let out = std::ffi::CString::new(format!("{}@{}", name_s, uri_s)).unwrap();
9388 let obj = xmlXPathNewString(out.as_ptr() as *const crate::abi::types::xmlChar);
9389 assert!(!obj.is_null());
9390 assert_eq!(xmlXPathValuePush(ctxt, obj), 0);
9391 }
9392
9393 let doc =
9394 crate::xml::tree::new_doc(c"1.0".as_ptr() as *const crate::abi::types::xmlChar);
9395 assert!(!doc.is_null());
9396 let ctxt = super::xmlXPathNewContext(doc);
9397 assert!(!ctxt.is_null());
9398
9399 super::xmlXPathRegisterNs(
9400 ctxt,
9401 c"t".as_ptr() as *const crate::abi::types::xmlChar,
9402 c"urn:t".as_ptr() as *const crate::abi::types::xmlChar,
9403 );
9404 super::xmlXPathRegisterFuncNS(
9405 ctxt,
9406 c"capture".as_ptr() as *const crate::abi::types::xmlChar,
9407 c"urn:t".as_ptr() as *const crate::abi::types::xmlChar,
9408 Some(capture_identity),
9409 );
9410
9411 let res = super::xmlXPathEvalExpression(
9412 c"t:capture()".as_ptr() as *const crate::abi::types::xmlChar,
9413 ctxt,
9414 );
9415 assert!(!res.is_null());
9416 let s = crate::xml::string::xmlstr_to_bytes((*res).stringval);
9417 assert_eq!(
9418 s, b"capture@urn:t",
9419 "bridge must set context->function (local name) and ->functionURI (ns)"
9420 );
9421 super::xmlXPathFreeObject(res);
9422 super::xmlXPathFreeContext(ctxt);
9423 crate::xml::tree::free_doc(doc);
9424 }
9425 }
9426}