libxml-rs 0.1.0-alpha.26

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs correlated to upstream commits; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure (xmlXPath*, xmlTextReader*, xmlTextWriter*, catalogs, serialization, data globals, chvalid, encoding, the full libxslt surface) — parity ledger at 0 missing for both libxml2 and libxslt. 1144 tests passing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! exports_hash — family closure (11.1-I). Filled by workstream.
//!
//! C ABI exports for the libxml2 hash-table and dictionary families:
//! `xmlHashAdd`, `xmlHashAdd2`, `xmlHashAdd3`, `xmlHashCopySafe`,
//! `xmlHashDefaultDeallocator`, `xmlHashQLookup`, `xmlHashQLookup2`,
//! `xmlHashQLookup3`, `xmlHashScan3`, `xmlHashScanFull3` and
//! `xmlDictCleanup`, `xmlDictOwns`, `xmlDictQLookup`, `xmlDictReference`.
//!
//! The public `xmlHashTable` / `xmlDict` types are opaque (`*mut c_void` at
//! the ABI boundary); they are cast to the internal
//! `crate::xml::hash::HashTable` and `crate::xml::dictionary::Dict`.
//!
//! # UPSTREAM-PARITY
//!
//! All semantics follow upstream libxml2 2.15
//! (`oracle/historical/src/libxml2-2.15.0/hash.c` and `dict.c`).

#![allow(
    missing_docs,
    non_snake_case,
    non_camel_case_types,
    non_upper_case_globals
)]
#![allow(clippy::missing_safety_doc)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]

use core::ffi::c_void;
use core::ptr;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use std::collections::{HashMap, HashSet};
use std::os::raw::c_int;

use crate::abi::allocator;
use crate::abi::callbacks::{
    xmlHashCopier, xmlHashDeallocator, xmlHashScanner, xmlHashScannerFull,
};
use crate::abi::types::xmlChar;
use crate::xml::dictionary::{dict_lookup, Dict};
use crate::xml::hash::{
    hash_add_entry3, hash_create, hash_free, hash_lookup3, hash_scan_full, HashTable,
};

// ═══════════════════════════════════════════════════════════════════════════════
// Shared Helpers
// ═══════════════════════════════════════════════════════════════════════════════

/// Byte-wise comparison of two null-terminated xmlChar strings (null-safe).
unsafe fn c_str_eq(a: *const xmlChar, b: *const xmlChar) -> bool {
    if a.is_null() && b.is_null() {
        return true;
    }
    if a.is_null() || b.is_null() {
        return false;
    }
    let mut i = 0usize;
    loop {
        // SAFETY: Both pointers are valid null-terminated strings.
        let ca = unsafe { *a.add(i) };
        let cb = unsafe { *b.add(i) };
        if ca != cb {
            return false;
        }
        if ca == 0 {
            return true;
        }
        i += 1;
    }
}

/// Append the bytes of a null-terminated xmlChar string (excluding the
/// terminator) to a byte vector.
unsafe fn push_c_str(v: &mut Vec<u8>, s: *const xmlChar) {
    if s.is_null() {
        return;
    }
    let mut i = 0usize;
    loop {
        // SAFETY: `s` is a valid null-terminated string.
        let c = unsafe { *s.add(i) };
        if c == 0 {
            break;
        }
        v.push(c);
        i += 1;
    }
}

/// Snapshot of a single hash-table entry collected during a scan.
///
/// The internal hash table's buckets are private, so scans that need to
/// filter entries (or invoke user callbacks afterwards) go through the
/// module's full-scanner API and buffer the entries here.
#[derive(Clone, Copy)]
struct HashEntrySnapshot {
    payload: *mut c_void,
    key1: *const xmlChar,
    key2: *const xmlChar,
    key3: *const xmlChar,
}

/// Full-scanner callback that appends entries to a `Vec<HashEntrySnapshot>`
/// whose pointer is passed via the scanner `data` argument.
unsafe extern "C" fn collect_entry(
    payload: *mut c_void,
    data: *mut c_void,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
) {
    let collected = unsafe { &mut *(data as *mut Vec<HashEntrySnapshot>) };
    collected.push(HashEntrySnapshot {
        payload,
        key1: name,
        key2: name2,
        key3: name3,
    });
}

// ═══════════════════════════════════════════════════════════════════════════════
// xmlHashAdd / xmlHashAdd2 / xmlHashAdd3
// ═══════════════════════════════════════════════════════════════════════════════

/// Shared core for the modern (2.13+) `xmlHashAdd*` family.
///
/// Mirrors upstream `xmlHashUpdateInternal(..., update = 0)`:
/// - `-1` if `hash`/`name` is NULL (or on allocation failure),
/// - `0` if an entry with the key already exists (payload untouched),
/// - `1` on success.
unsafe fn hash_add_impl(
    hash: *mut c_void,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
    userdata: *mut c_void,
) -> c_int {
    if hash.is_null() || name.is_null() {
        return -1;
    }
    let table = hash as *mut HashTable;
    // The internal add_entry3 returns -1 exactly when the key is already
    // present (NULL hash/name were rejected above) and 0 on success.
    if unsafe { hash_add_entry3(table, name, name2, name3, userdata) } == 0 {
        1
    } else {
        0
    }
}

/// Add a hash table entry.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashAdd(xmlHashTable *hash, const xmlChar *name, void *userdata);
/// ```
///
/// Returns 1 on success, 0 if an entry exists and -1 in case of error.
#[no_mangle]
pub unsafe extern "C" fn xmlHashAdd(
    hash: *mut c_void,
    name: *const xmlChar,
    userdata: *mut c_void,
) -> c_int {
    unsafe { hash_add_impl(hash, name, ptr::null(), ptr::null(), userdata) }
}

/// Add a hash table entry with two strings as key.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashAdd2(xmlHashTable *hash, const xmlChar *name,
///                 const xmlChar *name2, void *userdata);
/// ```
///
/// Returns 1 on success, 0 if an entry exists and -1 in case of error.
#[no_mangle]
pub unsafe extern "C" fn xmlHashAdd2(
    hash: *mut c_void,
    name: *const xmlChar,
    name2: *const xmlChar,
    userdata: *mut c_void,
) -> c_int {
    unsafe { hash_add_impl(hash, name, name2, ptr::null(), userdata) }
}

/// Add a hash table entry with three strings as key.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashAdd3(xmlHashTable *hash, const xmlChar *name,
///                 const xmlChar *name2, const xmlChar *name3,
///                 void *userdata);
/// ```
///
/// Returns 1 on success, 0 if an entry exists and -1 in case of error.
#[no_mangle]
pub unsafe extern "C" fn xmlHashAdd3(
    hash: *mut c_void,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
    userdata: *mut c_void,
) -> c_int {
    unsafe { hash_add_impl(hash, name, name2, name3, userdata) }
}

// ═══════════════════════════════════════════════════════════════════════════════
// xmlHashCopySafe
// ═══════════════════════════════════════════════════════════════════════════════

/// Copy a hash table using `copy` to copy payloads; on error the partial
/// table is freed with `dealloc` and NULL is returned.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlHashTable *xmlHashCopySafe(xmlHashTable *hash, xmlHashCopier copy,
///                               xmlHashDeallocator dealloc);
/// ```
///
/// Returns the new table or NULL if a memory allocation failed.
#[no_mangle]
pub unsafe extern "C" fn xmlHashCopySafe(
    hash: *mut c_void,
    copy: Option<xmlHashCopier>,
    dealloc: Option<xmlHashDeallocator>,
) -> *mut c_void {
    if hash.is_null() || copy.is_none() {
        return ptr::null_mut();
    }
    let copy_fn = copy.unwrap();

    // Snapshot every entry first so the copier runs without holding a borrow
    // on the table (the internal buckets are not publicly reachable).
    let mut collected: Vec<HashEntrySnapshot> = Vec::new();
    unsafe {
        hash_scan_full(
            hash as *mut HashTable,
            Some(collect_entry),
            &mut collected as *mut Vec<HashEntrySnapshot> as *mut c_void,
        );
    }

    let new_table = unsafe { hash_create(0) };
    if new_table.is_null() {
        return ptr::null_mut();
    }

    for e in &collected {
        // SAFETY: `copy_fn` is a valid C callback supplied by the caller.
        let copied = unsafe { copy_fn(e.payload, e.key1) };
        if copied.is_null()
            || unsafe { hash_add_entry3(new_table, e.key1, e.key2, e.key3, copied) } != 0
        {
            // Upstream: deallocate the failed copy, then free the partial
            // table (which deallocates every successfully copied payload).
            if let Some(f) = dealloc {
                // SAFETY: `f` is a valid C deallocator supplied by the caller.
                unsafe { f(copied, e.key1 as *mut xmlChar) };
            }
            unsafe { hash_free(new_table, dealloc) };
            return ptr::null_mut();
        }
    }

    new_table as *mut c_void
}

// ═══════════════════════════════════════════════════════════════════════════════
// xmlHashDefaultDeallocator
// ═══════════════════════════════════════════════════════════════════════════════

/// Free a hash table entry with `xmlFree`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlHashDefaultDeallocator(void *entry, const xmlChar *name);
/// ```
#[no_mangle]
pub unsafe extern "C" fn xmlHashDefaultDeallocator(entry: *mut c_void, _name: *const xmlChar) {
    if !entry.is_null() {
        unsafe { allocator::xmlFreeImpl(entry) };
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// xmlHashQLookup / xmlHashQLookup2 / xmlHashQLookup3
// ═══════════════════════════════════════════════════════════════════════════════

/// Find the payload specified by the QNames tuple.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlHashQLookup(xmlHashTable *hash, const xmlChar *prefix,
///                      const xmlChar *name);
/// ```
///
/// The entry key is matched against the concatenation `prefix:name` (the
/// colon is only included when `prefix` is non-NULL); a NULL `prefix` makes
/// this a plain single-key lookup.
///
/// Returns a pointer to the payload or NULL if no entry was found.
#[no_mangle]
pub unsafe extern "C" fn xmlHashQLookup(
    hash: *mut c_void,
    prefix: *const xmlChar,
    name: *const xmlChar,
) -> *mut c_void {
    unsafe {
        qlookup3(
            hash,
            prefix,
            name,
            ptr::null(),
            ptr::null(),
            ptr::null(),
            ptr::null(),
        )
    }
}

/// Find the payload specified by two QNames.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlHashQLookup2(xmlHashTable *hash, const xmlChar *prefix,
///                       const xmlChar *name, const xmlChar *prefix2,
///                       const xmlChar *name2);
/// ```
///
/// Returns a pointer to the payload or NULL if no entry was found.
#[no_mangle]
pub unsafe extern "C" fn xmlHashQLookup2(
    hash: *mut c_void,
    prefix: *const xmlChar,
    name: *const xmlChar,
    prefix2: *const xmlChar,
    name2: *const xmlChar,
) -> *mut c_void {
    unsafe { qlookup3(hash, prefix, name, prefix2, name2, ptr::null(), ptr::null()) }
}

/// Find the payload specified by three QNames.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlHashQLookup3(xmlHashTable *hash, const xmlChar *prefix,
///                       const xmlChar *name, const xmlChar *prefix2,
///                       const xmlChar *name2, const xmlChar *prefix3,
///                       const xmlChar *name3);
/// ```
///
/// Returns a pointer to the payload or NULL if no entry was found.
#[no_mangle]
pub unsafe extern "C" fn xmlHashQLookup3(
    hash: *mut c_void,
    prefix: *const xmlChar,
    name: *const xmlChar,
    prefix2: *const xmlChar,
    name2: *const xmlChar,
    prefix3: *const xmlChar,
    name3: *const xmlChar,
) -> *mut c_void {
    unsafe { qlookup3(hash, prefix, name, prefix2, name2, prefix3, name3) }
}

/// Core QName lookup: each entry key is compared against the `prefix:name`
/// concatenation (prefix omitted when NULL), matching upstream
/// `xmlStrQEqual`/`xmlHashQNameValue` semantics.
unsafe fn qlookup3(
    hash: *mut c_void,
    prefix: *const xmlChar,
    name: *const xmlChar,
    prefix2: *const xmlChar,
    name2: *const xmlChar,
    prefix3: *const xmlChar,
    name3: *const xmlChar,
) -> *mut c_void {
    if hash.is_null() || name.is_null() {
        return ptr::null_mut();
    }
    // Upstream xmlStrQEqual: a NULL local name with a non-NULL prefix can
    // never match any stored key, so the whole lookup fails.
    if (!prefix2.is_null() && name2.is_null()) || (!prefix3.is_null() && name3.is_null()) {
        return ptr::null_mut();
    }

    let table = hash as *mut HashTable;

    // Build the three qualified keys. The buffers are only needed for the
    // duration of the lookup (the internal lookup copies nothing).
    let mut buf1: Vec<u8> = Vec::new();
    if !prefix.is_null() {
        unsafe { push_c_str(&mut buf1, prefix) };
        buf1.push(b':');
    }
    unsafe { push_c_str(&mut buf1, name) };
    buf1.push(0);

    let mut buf2: Vec<u8> = Vec::new();
    let key2: *const xmlChar = if prefix2.is_null() {
        name2
    } else {
        unsafe { push_c_str(&mut buf2, prefix2) };
        buf2.push(b':');
        unsafe { push_c_str(&mut buf2, name2) };
        buf2.push(0);
        buf2.as_ptr() as *const xmlChar
    };

    let mut buf3: Vec<u8> = Vec::new();
    let key3: *const xmlChar = if prefix3.is_null() {
        name3
    } else {
        unsafe { push_c_str(&mut buf3, prefix3) };
        buf3.push(b':');
        unsafe { push_c_str(&mut buf3, name3) };
        buf3.push(0);
        buf3.as_ptr() as *const xmlChar
    };

    unsafe { hash_lookup3(table, buf1.as_ptr() as *const xmlChar, key2, key3) }
}

// ═══════════════════════════════════════════════════════════════════════════════
// xmlHashScan3 / xmlHashScanFull3
// ═══════════════════════════════════════════════════════════════════════════════

/// Collect the entries matching a (`name`, `name2`, `name3`) triple; a NULL
/// key acts as a wildcard. Entries with a NULL payload are skipped, matching
/// upstream `xmlHashScanFull3`.
///
/// The table is fully scanned into a snapshot first, so user callbacks never
/// run while the internal buckets are being iterated.
unsafe fn scan3_collect(
    hash: *mut c_void,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
) -> Vec<HashEntrySnapshot> {
    let mut collected: Vec<HashEntrySnapshot> = Vec::new();
    if hash.is_null() {
        return collected;
    }
    unsafe {
        hash_scan_full(
            hash as *mut HashTable,
            Some(collect_entry),
            &mut collected as *mut Vec<HashEntrySnapshot> as *mut c_void,
        );
    }
    collected.retain(|e| {
        if e.payload.is_null() {
            return false;
        }
        if !name.is_null() && !unsafe { c_str_eq(name, e.key1) } {
            return false;
        }
        if !name2.is_null() && !unsafe { c_str_eq(name2, e.key2) } {
            return false;
        }
        if !name3.is_null() && !unsafe { c_str_eq(name3, e.key3) } {
            return false;
        }
        true
    });
    collected
}

/// Scan the hash `table` and apply `scan` to each value matching the
/// (`name`, `name2`, `name3`) triple. A NULL key matches any value.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlHashScan3(xmlHashTable *hash, const xmlChar *name,
///                   const xmlChar *name2, const xmlChar *name3,
///                   xmlHashScanner scan, void *data);
/// ```
#[no_mangle]
pub unsafe extern "C" fn xmlHashScan3(
    hash: *mut c_void,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
    scan: Option<xmlHashScanner>,
    data: *mut c_void,
) {
    if scan.is_none() {
        return;
    }
    let scan = scan.unwrap();
    let matches = unsafe { scan3_collect(hash, name, name2, name3) };
    for e in &matches {
        // Upstream xmlHashScan3 passes a stub that forwards only key1.
        unsafe { scan(e.payload, data, e.key1) };
    }
}

/// Scan the hash `table` and apply `scan` to each value matching the
/// (`name`, `name2`, `name3`) triple. A NULL key matches any value.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlHashScanFull3(xmlHashTable *hash, const xmlChar *name,
///                       const xmlChar *name2, const xmlChar *name3,
///                       xmlHashScannerFull scan, void *data);
/// ```
#[no_mangle]
pub unsafe extern "C" fn xmlHashScanFull3(
    hash: *mut c_void,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
    scan: Option<xmlHashScannerFull>,
    data: *mut c_void,
) {
    if scan.is_none() {
        return;
    }
    let scan = scan.unwrap();
    let matches = unsafe { scan3_collect(hash, name, name2, name3) };
    for e in &matches {
        unsafe { scan(e.payload, data, e.key1, e.key2, e.key3) };
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Dictionary Exports (xmlDict*)
// ═══════════════════════════════════════════════════════════════════════════════

/// Reference counts tracked for `xmlDictReference`.
///
/// Upstream keeps `ref_counter` inside the `xmlDict` struct; the internal
/// `Dict` has no self-refcount field (its refcounts are per-entry), so the
/// Reference counts for dictionaries (upstream xmlDictReference). The
/// reference count is tracked here in a side table keyed by the opaque dict
/// pointer.
pub static DICT_REFS: Lazy<Mutex<HashMap<usize, u32>>> = Lazy::new(|| Mutex::new(HashMap::new()));

/// Interned string pointers owned by each dictionary, keyed by dict pointer.
///
/// Used by `xmlDictOwns`; upstream checks whether `str` falls inside the
/// dict's string pool, which the internal `Dict` does not track, so pointers
/// returned by `xmlDictQLookup` are recorded here.
static DICT_OWNED: Lazy<Mutex<HashMap<usize, HashSet<usize>>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Record an interned string pointer as owned by `dict` (for `xmlDictOwns`).
fn register_owned(dict: *mut c_void, s: *const xmlChar) {
    if dict.is_null() || s.is_null() {
        return;
    }
    DICT_OWNED
        .lock()
        .entry(dict as usize)
        .or_insert_with(HashSet::new)
        .insert(s as usize);
}

/// Increment the reference counter of a dictionary.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlDictReference(xmlDict *dict);
/// ```
///
/// Returns 0 in case of success and -1 in case of error.
#[no_mangle]
pub unsafe extern "C" fn xmlDictReference(dict: *mut c_void) -> c_int {
    if dict.is_null() {
        return -1;
    }
    *DICT_REFS.lock().entry(dict as usize).or_insert(0) += 1;
    0
}

/// Look up a QName (`prefix:name`) in the dictionary, adding it if not found.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// const xmlChar *xmlDictQLookup(xmlDict *dict, const xmlChar *prefix,
///                               const xmlChar *name);
/// ```
///
/// If `prefix` is NULL this is a plain lookup of `name`. Returns the interned
/// copy of the string or NULL in case of error.
#[no_mangle]
pub unsafe extern "C" fn xmlDictQLookup(
    dict: *mut c_void,
    prefix: *const xmlChar,
    name: *const xmlChar,
) -> *const xmlChar {
    if dict.is_null() || name.is_null() {
        return ptr::null();
    }
    if prefix.is_null() {
        let ret = unsafe { dict_lookup(dict as *mut Dict, name, -1) };
        register_owned(dict, ret);
        return ret;
    }

    // Build "prefix:name", intern it, then drop the temporary buffer.
    let mut qname: Vec<u8> = Vec::new();
    unsafe { push_c_str(&mut qname, prefix) };
    qname.push(b':');
    unsafe { push_c_str(&mut qname, name) };
    qname.push(0);

    let ret = unsafe { dict_lookup(dict as *mut Dict, qname.as_ptr() as *const xmlChar, -1) };
    register_owned(dict, ret);
    ret
}

/// Check if a string is owned by the dictionary.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlDictOwns(xmlDict *dict, const xmlChar *str);
/// ```
///
/// Returns 1 if `str` points into the dictionary's memory, 0 if not, and
/// -1 in case of error (NULL `dict` or `str`).
#[no_mangle]
pub unsafe extern "C" fn xmlDictOwns(dict: *mut c_void, str: *const xmlChar) -> c_int {
    if dict.is_null() || str.is_null() {
        return -1;
    }
    let owned = DICT_OWNED
        .lock()
        .get(&(dict as usize))
        .map_or(false, |set| set.contains(&(str as usize)));
    if owned {
        1
    } else {
        0
    }
}

/// Free the dictionary data.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlDictCleanup(void);
/// ```
///
/// Upstream deprecated this function in 2.13 when the global dictionary was
/// removed; it is a no-op (takes no arguments) in the oracle 2.15 headers.
#[no_mangle]
pub unsafe extern "C" fn xmlDictCleanup() {
    // No-op: there is no global dictionary to clean up (upstream 2.13+).
}