libxml-rs 0.1.0-alpha.36

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; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated function-signature ABI plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions) and the libc default allocator (ALLOCATOR-DEFAULT-001) verified byte-identical; proof-scoped safety commentary (0 unaccounted unsafe sites); residual ledger 79 FIXED / 3 OPEN; 1183 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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
//! Hash table — public xmlHash API (§85 Phase 1).
//!
//! Implements the libxml2 hash table, used for DTD element/attribute tables,
//! XPath function lookup, catalog entries, and more.
//!
//! # UPSTREAM-PARITY
//!
//! The hash table supports:
//! - Single-key, 2-key, and 3-key lookups
//! - Custom deallocator and copier functions
//! - Dictionary-backed keys (for memory efficiency)
//! - Scanning with callback functions
//! - Copying with custom copier
//!
//! # Phase 1 status
//!
//! Complete — all hash table operations are implemented.
//!
//! # Upstream contract
//!
//! Mirrors upstream `hash.c` / `hash.h` (`SRC-LIBXML2-2.15.0-HASH-C`, parity
//! target libxml2 2.15.3 oracle): `xmlHashCreate` / `xmlHashCreateDict` /
//! `xmlHashLookup` / `xmlHashAddEntry` / `xmlHashScan` / `xmlHashCopy` /
//! `xmlHashFree`, including the 1/2/3-key variants and the dict-backed key
//! mode.
//!
//! # Conceptual behavior
//!
//! Implements a chained hash table whose keys are NUL-terminated xmlChar
//! strings (one, two or three of them) with payloads owned per the table
//! deallocator/copier. Two-key tables are used for DTD element/attribute
//! declarations (key order (name,prefix,elem), R-000164) and XPath
//! function lookup; the dictionary-backed variant keeps keys in the dict so
//! the table never frees them.
//!
//! # Ownership & safety invariants
//!
//! The table owns its payloads and frees them through the registered
//! deallocator on `xmlHashFree`/removal; with a copier, `xmlHashCopy`
//! duplicates payloads. In dict mode the keys are borrowed from the dict
//! (never freed by the table). Keys are always copied in; the caller keeps
//! its own strings.
//!
//! # Historical quirks & epochs
//!
//! The multi-key and dict-backed extensions were added in the 2.6
//! validation-era expansion and have been stable across the 2.7.8 → 2.15.3
//! span; the HIST-SURFACE-EPOCH court family (HISTORICAL_SURFACE_EPOCHS.md)
//! fingerprints the API surface per epoch so a future signature change is
//! caught.
//!
//! # Deliberate oddities
//!
//! The 3-key variant (used by the attribute tables) is an upstream
//! historical extension, not part of any spec — it is kept byte-faithful
//! because the DTD lookup order depends on it.
//!
//! # Proving courts
//!
//! HIST-SURFACE-EPOCH fingerprints this module per release epoch; the
//! TREE-001 structural probe (R-000164) exercises the attribute hash key
//! order against the oracle; cargo test runs the unit suites.
//!
//! # Tempting simplifications that would break parity
//!
//! Do not re-key the DTD tables by (elem,name): R-000164 proved the
//! upstream (name,prefix,elem) order is observable. Do not drop the
//! deallocator/copier contract: consumers register custom free/copy
//! functions and observe them firing.

use core::ffi::c_void;
use core::ptr;
use std::os::raw::{c_char, c_int};

use crate::abi::allocator;
use crate::abi::callbacks::xmlHashCopier;
use crate::abi::callbacks::xmlHashDeallocator;
use crate::abi::callbacks::xmlHashScanner;
use crate::abi::callbacks::xmlHashScannerFull;

use crate::abi::types::xmlChar;

// ═══════════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════════

/// Default initial hash table size.
const HASH_INIT_SIZE: usize = 16;

/// Maximum load factor (entries/buckets) before resize.
#[allow(dead_code)]
const MAX_LOAD_FACTOR: f64 = 0.75;

// ═══════════════════════════════════════════════════════════════════════════════
// Internal Types
// ═══════════════════════════════════════════════════════════════════════════════

/// A hash table entry.
#[derive(Debug)]
struct HashEntry {
    /// The key string(s), stored as raw C string pointers.
    key1: *const xmlChar,
    key2: *const xmlChar,
    key3: *const xmlChar,
    /// The value.
    payload: *mut c_void,
}

/// The hash table struct.
#[derive(Debug)]
pub struct HashTable {
    /// Buckets (each is a vector of entries).
    buckets: Vec<Vec<HashEntry>>,
    /// Number of entries.
    count: usize,
    /// Optional deallocator for payloads.
    deallocator: Option<xmlHashDeallocator>,
    /// Optional copier for payloads.
    copier: Option<xmlHashCopier>,
    /// Whether the keys are dictionary-owned (don't free them).
    dict_owned: bool,
}

// ═══════════════════════════════════════════════════════════════════════════════
// String Hashing
// ═══════════════════════════════════════════════════════════════════════════════

/// Simple FNV-1a hash for xmlChar strings.
const fn hash_xml_str(s: *const xmlChar) -> u64 {
    if s.is_null() {
        return 0;
    }
    let mut hash: u64 = 0xcbf29ce484222325;
    let mut i = 0;
    loop {
        // SAFETY: Caller guarantees null-terminated string.
        let c = unsafe { *s.add(i) };
        if c == 0 {
            break;
        }
        hash ^= c as u64;
        hash = hash.wrapping_mul(0x100000001b3);
        i += 1;
    }
    hash
}

/// Compute combined hash for 1-3 keys.
const fn combined_hash(key1: *const xmlChar, key2: *const xmlChar, key3: *const xmlChar) -> u64 {
    let mut h = hash_xml_str(key1);
    h = h.wrapping_mul(31).wrapping_add(hash_xml_str(key2));
    h = h.wrapping_mul(31).wrapping_add(hash_xml_str(key3));
    h
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a new hash table.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlHashTablePtr xmlHashCreate(int size);
/// ```
///
/// Creates a hash table with the given initial size.
/// If size <= 0, uses the default size.
pub fn hash_create(size: c_int) -> *mut HashTable {
    let table = Box::new(HashTable {
        buckets: (0..if size <= 0 {
            HASH_INIT_SIZE
        } else {
            size as usize
        })
            .map(|_| Vec::new())
            .collect(),
        count: 0,
        deallocator: None,
        copier: None,
        dict_owned: false,
    });

    Box::into_raw(table)
}

/// Create a hash table with dictionary-backed keys.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlHashTablePtr xmlHashCreateDict(int size, xmlDictPtr dict);
/// ```
///
/// Creates a hash table where keys are interned in the given dictionary.
/// The dictionary reference is stored but in this implementation, keys
/// are still stored as raw pointers for simplicity.
pub fn hash_create_dict(size: c_int, _dict: *mut c_void) -> *mut HashTable {
    let table = hash_create(size);
    if !table.is_null() {
        unsafe { (*table).dict_owned = true };
    }
    table
}

/// Free a hash table.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlHashFree(xmlHashTablePtr table, xmlHashDeallocator f);
/// ```
///
/// Frees all entries and calls `f` on each payload to free it.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `f` may be NULL (no deallocation of payloads).
pub unsafe fn hash_free(table: *mut HashTable, f: Option<xmlHashDeallocator>) {
    if table.is_null() {
        return;
    }

    let t = unsafe { &mut *table };

    for bucket in t.buckets.iter_mut() {
        for entry in bucket.drain(..) {
            if let Some(dealloc) = f {
                dealloc(entry.payload, entry.key1 as *mut u8);
            }
            if !t.dict_owned {
                if !entry.key1.is_null() {
                    allocator::xmlFreeImpl(entry.key1 as *mut c_void);
                }
                if !entry.key2.is_null() {
                    allocator::xmlFreeImpl(entry.key2 as *mut c_void);
                }
                if !entry.key3.is_null() {
                    allocator::xmlFreeImpl(entry.key3 as *mut c_void);
                }
            }
        }
    }

    drop(Box::from_raw(table));
}

/// Add an entry with a single key.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashAddEntry(xmlHashTablePtr table, const xmlChar *name, void *userdata);
/// ```
///
/// Returns 0 on success, -1 if the key already exists or on failure.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `name` must be a valid null-terminated string.
pub unsafe fn hash_add_entry(
    table: *mut HashTable,
    name: *const xmlChar,
    userdata: *mut c_void,
) -> c_int {
    hash_add_entry3(table, name, ptr::null(), ptr::null(), userdata)
}

/// Add an entry with two keys.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashAddEntry2(xmlHashTablePtr table, const xmlChar *name,
///                      const xmlChar *name2, void *userdata);
/// ```
///
/// # SAFETY
///
/// Same as `hash_add_entry` with an additional key.
pub unsafe fn hash_add_entry2(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    userdata: *mut c_void,
) -> c_int {
    hash_add_entry3(table, name, name2, ptr::null(), userdata)
}

/// Add an entry with three keys.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashAddEntry3(xmlHashTablePtr table, const xmlChar *name,
///                      const xmlChar *name2, const xmlChar *name3,
///                      void *userdata);
/// ```
///
/// Returns 0 on success, -1 if the key already exists or on failure.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable.
/// - `name`, `name2`, `name3` must be valid null-terminated strings or NULL.
pub unsafe fn hash_add_entry3(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
    userdata: *mut c_void,
) -> c_int {
    if table.is_null() {
        return -1;
    }

    let t = unsafe { &mut *table };

    // Check if the key already exists
    if !hash_find_entry(table, name, name2, name3).is_null() {
        return -1;
    }

    let hash = combined_hash(name, name2, name3);
    let bucket_idx = (hash as usize) % t.buckets.len();

    // Copy keys
    let k1 = if name.is_null() {
        ptr::null()
    } else {
        unsafe { allocator::xmlMemStrdupImpl(name as *const c_char) as *const xmlChar }
    };
    let k2 = if name2.is_null() {
        ptr::null()
    } else {
        unsafe { allocator::xmlMemStrdupImpl(name2 as *const c_char) as *const xmlChar }
    };
    let k3 = if name3.is_null() {
        ptr::null()
    } else {
        unsafe { allocator::xmlMemStrdupImpl(name3 as *const c_char) as *const xmlChar }
    };

    t.buckets[bucket_idx].push(HashEntry {
        key1: k1,
        key2: k2,
        key3: k3,
        payload: userdata,
    });
    t.count += 1;

    0
}

/// Update an entry (add or replace).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashUpdateEntry(xmlHashTablePtr table, const xmlChar *name,
///                        void *userdata, xmlHashDeallocator f);
/// ```
///
/// If the key exists, the old payload is deallocated with `f` and replaced.
/// If the key doesn't exist, a new entry is added.
///
/// Returns 0 on success, -1 on failure.
///
/// # SAFETY
///
/// Same as `hash_add_entry` with an additional deallocator.
pub unsafe fn hash_update_entry(
    table: *mut HashTable,
    name: *const xmlChar,
    userdata: *mut c_void,
    f: Option<xmlHashDeallocator>,
) -> c_int {
    hash_update_entry3(table, name, ptr::null(), ptr::null(), userdata, f)
}

/// Update an entry with two keys.
///
/// # SAFETY
///
/// - `table`, `userdata` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `name`, `name2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// - `f` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
pub unsafe fn hash_update_entry2(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    userdata: *mut c_void,
    f: Option<xmlHashDeallocator>,
) -> c_int {
    hash_update_entry3(table, name, name2, ptr::null(), userdata, f)
}

/// Update an entry with three keys.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashUpdateEntry3(xmlHashTablePtr table, const xmlChar *name,
///                         const xmlChar *name2, const xmlChar *name3,
///                         void *userdata, xmlHashDeallocator f);
/// ```
///
/// # SAFETY
///
/// Same as `hash_add_entry3` with an additional deallocator.
pub unsafe fn hash_update_entry3(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
    userdata: *mut c_void,
    f: Option<xmlHashDeallocator>,
) -> c_int {
    if table.is_null() {
        return -1;
    }

    let t = unsafe { &mut *table };

    let hash = combined_hash(name, name2, name3);
    let bucket_idx = (hash as usize) % t.buckets.len();

    // Look for existing entry
    for entry in t.buckets[bucket_idx].iter_mut() {
        if keys_equal(entry.key1, name)
            && keys_equal(entry.key2, name2)
            && keys_equal(entry.key3, name3)
        {
            // Replace payload
            if let Some(dealloc) = f {
                dealloc(entry.payload, entry.key1 as *mut u8);
            }
            entry.payload = userdata;
            return 0;
        }
    }

    // Not found — add new entry
    hash_add_entry3(table, name, name2, name3, userdata)
}

/// Look up an entry by single key.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlHashLookup(xmlHashTablePtr table, const xmlChar *name);
/// ```
///
/// Returns the payload, or NULL if not found.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `name` must be a valid null-terminated string.
pub unsafe fn hash_lookup(table: *mut HashTable, name: *const xmlChar) -> *mut c_void {
    hash_lookup3(table, name, ptr::null(), ptr::null())
}

/// Look up an entry by two keys.
///
/// # SAFETY
///
/// - `table` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `name`, `name2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
pub unsafe fn hash_lookup2(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
) -> *mut c_void {
    hash_lookup3(table, name, name2, ptr::null())
}

/// Look up an entry by three keys.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlHashLookup3(xmlHashTablePtr table, const xmlChar *name,
///                      const xmlChar *name2, const xmlChar *name3);
/// ```
///
/// Returns the payload, or NULL if not found.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `name`, `name2`, `name3` must be valid null-terminated strings or NULL.
pub unsafe fn hash_lookup3(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
) -> *mut c_void {
    hash_find_entry(table, name, name2, name3)
}

/// Internal: find an entry's payload.
///
/// # Safety
///
/// - `table` must be NULL or a valid, initialized `HashTable` that stays
///   alive for the call; `name`, `name2` and `name3` must be NULL or valid
///   NUL-terminated strings readable for the hash/key comparisons.
unsafe fn hash_find_entry(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
) -> *mut c_void {
    if table.is_null() {
        return ptr::null_mut();
    }

    let t = unsafe { &*table };

    let hash = combined_hash(name, name2, name3);
    let bucket_idx = (hash as usize) % t.buckets.len();

    for entry in &t.buckets[bucket_idx] {
        if keys_equal(entry.key1, name)
            && keys_equal(entry.key2, name2)
            && keys_equal(entry.key3, name3)
        {
            return entry.payload;
        }
    }

    ptr::null_mut()
}

/// Get the number of entries in the hash table.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashSize(xmlHashTablePtr table);
/// ```
pub fn hash_size(table: *mut HashTable) -> c_int {
    if table.is_null() {
        return -1;
    }
    unsafe { (*table).count as c_int }
}

/// Remove an entry by single key.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashRemoveEntry(xmlHashTablePtr table, const xmlChar *name,
///                        xmlHashDeallocator f);
/// ```
///
/// Returns 0 on success, -1 if not found.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `name` must be a valid null-terminated string.
/// - `f` may be NULL.
pub unsafe fn hash_remove_entry(
    table: *mut HashTable,
    name: *const xmlChar,
    f: Option<xmlHashDeallocator>,
) -> c_int {
    hash_remove_entry3(table, name, ptr::null(), ptr::null(), f)
}

/// Remove an entry by two keys.
///
/// # SAFETY
///
/// - `table` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `name`, `name2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// - `f` must be a valid callback (or None);
///   the callback is invoked with the documented context pointer and
///   must itself uphold the same pointer invariants.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
pub unsafe fn hash_remove_entry2(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    f: Option<xmlHashDeallocator>,
) -> c_int {
    hash_remove_entry3(table, name, name2, ptr::null(), f)
}

/// Remove an entry by three keys.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlHashRemoveEntry3(xmlHashTablePtr table, const xmlChar *name,
///                         const xmlChar *name2, const xmlChar *name3,
///                         xmlHashDeallocator f);
/// ```
///
/// Returns 0 on success, -1 if not found.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `name`, `name2`, `name3` must be valid null-terminated strings or NULL.
/// - `f` may be NULL.
pub unsafe fn hash_remove_entry3(
    table: *mut HashTable,
    name: *const xmlChar,
    name2: *const xmlChar,
    name3: *const xmlChar,
    f: Option<xmlHashDeallocator>,
) -> c_int {
    if table.is_null() {
        return -1;
    }

    let t = unsafe { &mut *table };

    let hash = combined_hash(name, name2, name3);
    let bucket_idx = (hash as usize) % t.buckets.len();

    let bucket = &mut t.buckets[bucket_idx];
    let pos = bucket.iter().position(|entry| {
        keys_equal(entry.key1, name)
            && keys_equal(entry.key2, name2)
            && keys_equal(entry.key3, name3)
    });

    if let Some(idx) = pos {
        let entry = bucket.remove(idx);
        if let Some(dealloc) = f {
            dealloc(entry.payload, entry.key1 as *mut u8);
        }
        if !t.dict_owned {
            if !entry.key1.is_null() {
                allocator::xmlFreeImpl(entry.key1 as *mut c_void);
            }
            if !entry.key2.is_null() {
                allocator::xmlFreeImpl(entry.key2 as *mut c_void);
            }
            if !entry.key3.is_null() {
                allocator::xmlFreeImpl(entry.key3 as *mut c_void);
            }
        }
        t.count -= 1;
        0
    } else {
        -1
    }
}

/// Scan all entries with a scanner function.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlHashScan(xmlHashTablePtr table, xmlHashScanner f, void *data);
/// ```
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `f` must be a valid function pointer or NULL.
/// - `data` may be NULL.
pub unsafe fn hash_scan(table: *mut HashTable, f: Option<xmlHashScanner>, data: *mut c_void) {
    if table.is_null() || f.is_none() {
        return;
    }
    let f = f.unwrap();

    let t = unsafe { &*table };
    for bucket in &t.buckets {
        for entry in bucket {
            f(entry.payload, data, entry.key1 as *const xmlChar);
        }
    }
}

/// Scan all entries with a full scanner function (includes all keys).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlHashScanFull(xmlHashTablePtr table, xmlHashScannerFull f, void *data);
/// ```
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `f` must be a valid function pointer or NULL.
/// - `data` may be NULL.
pub unsafe fn hash_scan_full(
    table: *mut HashTable,
    f: Option<xmlHashScannerFull>,
    data: *mut c_void,
) {
    if table.is_null() || f.is_none() {
        return;
    }
    let f = f.unwrap();

    let t = unsafe { &*table };
    for bucket in &t.buckets {
        for entry in bucket {
            f(entry.payload, data, entry.key1, entry.key2, entry.key3);
        }
    }
}

/// Copy a hash table.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlHashTablePtr xmlHashCopy(xmlHashTablePtr table, xmlHashCopier f);
/// ```
///
/// Creates a new hash table with copied entries. The `f` function is called
/// for each entry to create a copy of the payload.
///
/// Returns the new hash table, or NULL on failure.
///
/// # SAFETY
///
/// - `table` must be a valid pointer to a HashTable, or NULL.
/// - `f` may be NULL (payloads are copied by pointer).
pub unsafe fn hash_copy(table: *mut HashTable, f: Option<xmlHashCopier>) -> *mut HashTable {
    if table.is_null() {
        return ptr::null_mut();
    }

    let t = unsafe { &*table };
    let new_table = hash_create(t.buckets.len() as c_int);
    if new_table.is_null() {
        return ptr::null_mut();
    }

    let new_t = unsafe { &mut *new_table };
    new_t.deallocator = t.deallocator;
    new_t.copier = t.copier;
    new_t.dict_owned = t.dict_owned;

    for bucket in &t.buckets {
        for entry in bucket {
            let payload = match f {
                Some(copier) => copier(entry.payload, entry.key1 as *const xmlChar),
                None => entry.payload,
            };

            let k1 = if entry.key1.is_null() {
                ptr::null()
            } else {
                allocator::xmlMemStrdupImpl(entry.key1 as *const c_char) as *const xmlChar
            };
            let k2 = if entry.key2.is_null() {
                ptr::null()
            } else {
                allocator::xmlMemStrdupImpl(entry.key2 as *const c_char) as *const xmlChar
            };
            let k3 = if entry.key3.is_null() {
                ptr::null()
            } else {
                allocator::xmlMemStrdupImpl(entry.key3 as *const c_char) as *const xmlChar
            };

            let hash = combined_hash(k1, k2, k3);
            let bucket_idx = (hash as usize) % new_t.buckets.len();

            new_t.buckets[bucket_idx].push(HashEntry {
                key1: k1,
                key2: k2,
                key3: k3,
                payload,
            });
            new_t.count += 1;
        }
    }

    new_table
}

// ═══════════════════════════════════════════════════════════════════════════════
// Helper Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Compare two xmlChar strings for equality (null-safe).
const fn keys_equal(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;
    }
    // Compare byte by byte
    let mut i = 0;
    loop {
        // SAFETY: Both are 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;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    /// Allocate a NUL-terminated xmlChar key buffer with the libxml2 allocator.
    ///
    /// # Safety
    ///
    /// - `s` must be a valid string; the returned pointer is
    ///   allocator-owned and valid for `bytes.len() + 1` bytes, or NULL on
    ///   allocation failure.
    fn c_str(s: &str) -> *const xmlChar {
        let bytes = s.as_bytes();
        let buf = unsafe { allocator::xmlMallocImpl(bytes.len() + 1) as *mut u8 };
        if !buf.is_null() {
            unsafe {
                ptr::copy_nonoverlapping(bytes.as_ptr(), buf, bytes.len());
                *buf.add(bytes.len()) = 0;
            }
        }
        buf as *const xmlChar
    }

    /// Create and free a hash table.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted) and valid until freed with
    ///   `hash_free`, which must be called exactly once.
    #[test]
    fn test_hash_create_free() {
        unsafe {
            let table = hash_create(16);
            assert!(!table.is_null());
            hash_free(table, None);
        }
    }

    /// Add, look up and reject a duplicate key in a hash table.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted); `key` is a valid NUL-terminated
    ///   string allocated by `c_str` and stays valid until `hash_free`;
    ///   `value` points to a stack `c_int` alive for the whole test;
    ///   `hash_free` releases the table exactly once.
    #[test]
    fn test_hash_add_lookup() {
        unsafe {
            let table = hash_create(16);
            let key = c_str("key1");
            let value = &mut 42 as *mut c_int as *mut c_void;

            let result = hash_add_entry(table, key, value);
            assert_eq!(result, 0);

            let found = hash_lookup(table, key);
            assert_eq!(found, value);
            assert_eq!(*(found as *mut c_int), 42);

            // Duplicate key should fail
            let result2 = hash_add_entry(table, key, &mut 99 as *mut c_int as *mut c_void);
            assert_eq!(result2, -1);

            hash_free(table, None);
        }
    }

    /// Looking up a missing key returns NULL.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted); the lookup key is a valid
    ///   NUL-terminated string valid for the call; `hash_free` releases
    ///   the table exactly once.
    #[test]
    fn test_hash_lookup_not_found() {
        unsafe {
            let table = hash_create(16);
            let found = hash_lookup(table, c_str("nonexistent"));
            assert!(found.is_null());
            hash_free(table, None);
        }
    }

    /// Remove an entry and check that a second removal fails.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted); `key` is a valid NUL-terminated
    ///   string valid for the calls; `value` stays alive until `hash_free`
    ///   releases the table exactly once.
    #[test]
    fn test_hash_remove_entry() {
        unsafe {
            let table = hash_create(16);
            let key = c_str("remove_me");
            let value = &mut 42 as *mut c_int as *mut c_void;

            hash_add_entry(table, key, value);
            assert_eq!(hash_size(table), 1);

            let result = hash_remove_entry(table, key, None);
            assert_eq!(result, 0);
            assert_eq!(hash_size(table), 0);

            // Removing again should fail
            let result2 = hash_remove_entry(table, key, None);
            assert_eq!(result2, -1);

            hash_free(table, None);
        }
    }

    /// Update an entry's payload and verify the new value is returned.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted); `key` is a valid NUL-terminated
    ///   string; `val1`/`val2` point to stack `c_int`s alive for the test;
    ///   `hash_free` releases the table exactly once.
    #[test]
    fn test_hash_update_entry() {
        unsafe {
            let table = hash_create(16);
            let key = c_str("update_key");
            let val1 = &mut 1 as *mut c_int as *mut c_void;
            let val2 = &mut 2 as *mut c_int as *mut c_void;

            hash_update_entry(table, key, val1, None);
            assert_eq!(hash_lookup(table, key), val1);

            hash_update_entry(table, key, val2, None);
            assert_eq!(hash_lookup(table, key), val2);

            hash_free(table, None);
        }
    }

    /// Look up an entry keyed by two strings.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted); both key strings are valid
    ///   NUL-terminated strings valid for the calls; `value` is a stack
    ///   `c_int` alive for the test; `hash_free` releases the table
    ///   exactly once.
    #[test]
    fn test_hash_two_key_lookup() {
        unsafe {
            let table = hash_create(16);
            let key1 = c_str("ns");
            let key2 = c_str("local");
            let value = &mut 42 as *mut c_int as *mut c_void;

            hash_add_entry2(table, key1, key2, value);
            let found = hash_lookup2(table, key1, key2);
            assert_eq!(found, value);

            // Wrong second key should not find
            let not_found = hash_lookup2(table, key1, c_str("wrong"));
            assert!(not_found.is_null());

            hash_free(table, None);
        }
    }

    /// Look up an entry keyed by three strings.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted); all three key strings are valid
    ///   NUL-terminated strings valid for the calls; `value` is a stack
    ///   `c_int` alive for the test; `hash_free` releases the table
    ///   exactly once.
    #[test]
    fn test_hash_three_key_lookup() {
        unsafe {
            let table = hash_create(16);
            let k1 = c_str("a");
            let k2 = c_str("b");
            let k3 = c_str("c");
            let value = &mut 42 as *mut c_int as *mut c_void;

            hash_add_entry3(table, k1, k2, k3, value);
            let found = hash_lookup3(table, k1, k2, k3);
            assert_eq!(found, value);

            hash_free(table, None);
        }
    }

    /// Count entries as keys are added.
    ///
    /// # Safety
    ///
    /// - `table` is non-NULL (asserted); each `c_str` key is a valid
    ///   NUL-terminated string valid until `hash_free` releases the table
    ///   exactly once; NULL payloads are accepted.
    #[test]
    fn test_hash_size() {
        unsafe {
            let table = hash_create(16);
            assert_eq!(hash_size(table), 0);

            hash_add_entry(table, c_str("a"), ptr::null_mut());
            assert_eq!(hash_size(table), 1);

            hash_add_entry(table, c_str("b"), ptr::null_mut());
            assert_eq!(hash_size(table), 2);

            hash_add_entry(table, c_str("c"), ptr::null_mut());
            assert_eq!(hash_size(table), 3);

            hash_free(table, None);
        }
    }

    /// NULL table/key arguments must be tolerated without crashing.
    ///
    /// # Safety
    ///
    /// - `hash_lookup`, `hash_size` and `hash_free` handle NULL table
    ///   pointers as documented no-ops; no pointer is dereferenced.
    #[test]
    fn test_hash_null_handling() {
        unsafe {
            assert!(hash_lookup(ptr::null_mut(), ptr::null()).is_null());
            assert_eq!(hash_size(ptr::null_mut()), -1);
            hash_free(ptr::null_mut(), None); // Should not crash
        }
    }
}