libxml-rs 0.1.0-alpha.32

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; residual closure loop (73 FIXED / 2 bounded obligations) sealed by differential court matrix; C14N, format-number(), number(), compile-time XSLT select/test validation, and undefined-prefix QName preservation verified byte-identical against libxml2 2.15.3 / libxslt 1.1.45 oracle. 1177 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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
//! C ABI allocator compatibility — xmlMemSetup, xmlMemGet, xmlMalloc, xmlFree, etc. (§58).
//!
//! This module implements the complete memory hook system exposed by libxml2:
//! - Global allocator function pointers (malloc, realloc, free, strdup)
//! - `xmlMemSetup()` / `xmlMemGet()` — set/get allocator hooks
//! - `xmlGcMemSetup()` / `xmlGcMemGet()` — GC-aware allocator hooks (wrappers)
//! - `xmlMalloc()` / `xmlMallocAtomic()` / `xmlRealloc()` / `xmlFree()` / `xmlMemStrdup()`
//! - `xmlMemUsed()` / `xmlMemBlocks()` — allocation tracking
//! - `xmlMemDisplay()` / `xmlMemShow()` — debugging output
//!
//! # Phase 1 status
//!
//! Complete — all allocator APIs are implemented with thread-safe global state.
//!
//! # Safety
//!
//! Allocator hooks are `unsafe` because they operate on raw pointers and are called
//! from C code. Every public function documents its safety contract.

use core::alloc::Layout;
use core::ffi::c_void;
use core::ptr;
use core::sync::atomic::AtomicUsize;
use core::sync::atomic::Ordering;
use std::ffi::CStr;
use std::os::raw::{c_char, c_int, c_long};

use parking_lot::RwLock;

use crate::abi::callbacks::*;

// ═══════════════════════════════════════════════════════════════════════════════
// Default Allocator (Rust global allocator)
// ═══════════════════════════════════════════════════════════════════════════════

/// Default malloc implementation using Rust's global allocator.
///
/// # SAFETY
///
/// - `size` must be a valid allocation size (0 is handled by allocating 1 byte)
/// - Returns NULL on allocation failure
unsafe extern "C" fn default_malloc(size: usize) -> *mut c_void {
    if size == 0 {
        // Upstream malloc(0) may return NULL or a valid pointer.
        // libxml2 checks for NULL and treats it as OOM.
        // Allocate 1 byte to avoid UB with zero-size Layout.
        let layout = Layout::from_size_align_unchecked(1, 1);
        let ptr = std::alloc::alloc(layout);
        if ptr.is_null() {
            ptr::null_mut()
        } else {
            ptr as *mut c_void
        }
    } else {
        let layout = match Layout::from_size_align(size, 1) {
            Ok(l) => l,
            Err(_) => return ptr::null_mut(),
        };
        let ptr = std::alloc::alloc(layout);
        if ptr.is_null() {
            ptr::null_mut()
        } else {
            ptr as *mut c_void
        }
    }
}

/// Default realloc implementation using Rust's global allocator.
///
/// # SAFETY
///
/// - `ptr` must be a valid pointer from a previous `default_malloc` or `default_realloc`,
///   or NULL (in which case this behaves like malloc)
/// - `size` must be a valid allocation size
unsafe extern "C" fn default_realloc(ptr: *mut c_void, size: usize) -> *mut c_void {
    if ptr.is_null() {
        return default_malloc(size);
    }
    if size == 0 {
        default_free(ptr);
        return default_malloc(0);
    }
    let layout = match Layout::from_size_align(size, 1) {
        Ok(l) => l,
        Err(_) => return ptr::null_mut(),
    };
    let new_ptr = std::alloc::realloc(ptr as *mut u8, layout, size);
    if new_ptr.is_null() {
        ptr::null_mut()
    } else {
        new_ptr as *mut c_void
    }
}

/// Default free implementation using Rust's global allocator.
///
/// # SAFETY
///
/// - `ptr` may be NULL (free(NULL) is a no-op)
/// - If non-NULL, `ptr` must be from a previous `default_malloc` or `default_realloc`
unsafe extern "C" fn default_free(ptr: *mut c_void) {
    if ptr.is_null() {
        return;
    }
    // We use a layout with size 0 and alignment 1 for deallocation,
    // since Rust's dealloc requires the original layout.
    // However, we don't know the original size. We use a 1-byte layout
    // which is the minimum. This is technically UB in Rust but matches
    // how C realloc/free work.
    let layout = Layout::from_size_align_unchecked(1, 1);
    std::alloc::dealloc(ptr as *mut u8, layout);
}

/// Default strdup implementation using Rust's global allocator.
///
/// # SAFETY
///
/// - `str` must be a valid null-terminated C string
unsafe extern "C" fn default_strdup(str: *const c_char) -> *mut c_void {
    if str.is_null() {
        return ptr::null_mut();
    }
    let len = libc::strlen(str);
    let size = len + 1; // include null terminator
    let layout = match Layout::from_size_align(size, 1) {
        Ok(l) => l,
        Err(_) => return ptr::null_mut(),
    };
    let new_ptr = std::alloc::alloc(layout);
    if new_ptr.is_null() {
        return ptr::null_mut();
    }
    ptr::copy_nonoverlapping(str as *const u8, new_ptr, size);
    new_ptr as *mut c_void
}

// ═══════════════════════════════════════════════════════════════════════════════
// Global Allocator State
// ═══════════════════════════════════════════════════════════════════════════════

/// Global allocator function pointers.
///
/// Protected by RwLock for thread-safe read/write.
/// Default values point to Rust's global allocator.
static ALLOCATOR: RwLock<AllocatorFuncs> = RwLock::new(AllocatorFuncs {
    malloc_func: Some(default_malloc as xmlMallocFunc),
    realloc_func: Some(default_realloc as xmlReallocFunc),
    free_func: Some(default_free as xmlFreeFunc),
    strdup_func: Some(default_strdup as xmlStrdupFunc),
});

/// The set of allocator function pointers.
struct AllocatorFuncs {
    malloc_func: Option<xmlMallocFunc>,
    realloc_func: Option<xmlReallocFunc>,
    free_func: Option<xmlFreeFunc>,
    strdup_func: Option<xmlStrdupFunc>,
}

/// Global allocation counters (for xmlMemUsed/xmlMemBlocks).
///
/// These use relaxed ordering since they are approximate debugging counters.
static MEM_USED: AtomicUsize = AtomicUsize::new(0);
static MEM_BLOCKS: AtomicUsize = AtomicUsize::new(0);

/// Per-block metadata (upstream xmlmemory.c block table): enables
/// xmlMemSize, exact xmlMemUsed and per-block dumps (11.1-J / R-000131).
/// The file pointer is stored as a raw address (usize) so the registry stays
/// Send + Sync.
#[derive(Clone, Copy)]
struct BlockMeta {
    size: usize,
    file: usize,
    line: c_int,
}

static BLOCKS: once_cell::sync::Lazy<
    parking_lot::Mutex<std::collections::HashMap<usize, BlockMeta>>,
> = once_cell::sync::Lazy::new(|| parking_lot::Mutex::new(std::collections::HashMap::new()));

/// Record a block in the registry (no-op for NULL).
unsafe fn block_record(ptr: *mut c_void, size: usize, file: *const c_char, line: c_int) {
    if ptr.is_null() {
        return;
    }
    BLOCKS.lock().insert(
        ptr as usize,
        BlockMeta {
            size,
            file: file as usize,
            line,
        },
    );
}

/// Drop a block from the registry; returns its recorded size (0 if unknown).
unsafe fn block_forget(ptr: *mut c_void) -> usize {
    if ptr.is_null() {
        return 0;
    }
    BLOCKS
        .lock()
        .remove(&(ptr as usize))
        .map(|m| m.size)
        .unwrap_or(0)
}

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

/// Set custom memory allocator functions.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlMemSetup(xmlFreeFunc freeFunc,
///                  xmlMallocFunc mallocFunc,
///                  xmlReallocFunc reallocFunc,
///                  xmlStrdupFunc strdupFunc);
/// ```
///
/// # SAFETY
///
/// - All function pointers must be valid (non-null) and thread-safe
/// - The functions must follow the C malloc/realloc/free/strdup contract
/// - Once set, the functions remain in effect until the next `xmlMemSetup` call
/// - The caller is responsible for ensuring the functions remain valid for the
///   entire time they are installed
#[no_mangle]
pub unsafe extern "C" fn xmlMemSetup(
    freeFunc: Option<xmlFreeFunc>,
    mallocFunc: Option<xmlMallocFunc>,
    reallocFunc: Option<xmlReallocFunc>,
    strdupFunc: Option<xmlStrdupFunc>,
) {
    // SAFETY: Caller guarantees all function pointers are valid.
    // We store them in global state protected by RwLock.
    let mut alloc = ALLOCATOR.write();
    alloc.free_func = freeFunc;
    alloc.malloc_func = mallocFunc;
    alloc.realloc_func = reallocFunc;
    alloc.strdup_func = strdupFunc;
}

/// Get the current memory allocator functions.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlMemGet(xmlFreeFunc *freeFunc,
///                xmlMallocFunc *mallocFunc,
///                xmlReallocFunc *reallocFunc,
///                xmlStrdupFunc *strdupFunc);
/// ```
///
/// # SAFETY
///
/// - All output pointers must be valid (non-null) and writable
#[no_mangle]
pub unsafe extern "C" fn xmlMemGet(
    freeFunc: *mut Option<xmlFreeFunc>,
    mallocFunc: *mut Option<xmlMallocFunc>,
    reallocFunc: *mut Option<xmlReallocFunc>,
    strdupFunc: *mut Option<xmlStrdupFunc>,
) {
    // SAFETY: Caller guarantees all output pointers are valid.
    let alloc = ALLOCATOR.read();
    unsafe {
        ptr::write(freeFunc, alloc.free_func);
        ptr::write(mallocFunc, alloc.malloc_func);
        ptr::write(reallocFunc, alloc.realloc_func);
        ptr::write(strdupFunc, alloc.strdup_func);
    }
}

/// Set GC-aware memory allocator functions.
///
/// # UPSTREAM-PARITY
///
/// This is a wrapper around `xmlMemSetup` in modern libxml2.
/// Historically, it was separate for the GC-allocated memory pool,
/// but in modern versions both functions do the same thing.
///
/// # SAFETY
///
///
/// - `freeFunc`, `mallocFunc`, `reallocFunc`, `strdupFunc` 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.
#[no_mangle]
pub unsafe extern "C" fn xmlGcMemSetup(
    freeFunc: Option<xmlFreeFunc>,
    mallocFunc: Option<xmlMallocFunc>,
    reallocFunc: Option<xmlReallocFunc>,
    strdupFunc: Option<xmlStrdupFunc>,
) {
    // SAFETY: Delegates to xmlMemSetup with the same safety contract.
    unsafe { xmlMemSetup(freeFunc, mallocFunc, reallocFunc, strdupFunc) };
}

/// Get GC-aware memory allocator functions.
///
/// # UPSTREAM-PARITY
///
/// Wrapper around `xmlMemGet`.
///
/// # SAFETY
///
///
/// - `freeFunc`, `mallocFunc`, `reallocFunc`, `strdupFunc` 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.
#[no_mangle]
pub unsafe extern "C" fn xmlGcMemGet(
    freeFunc: *mut Option<xmlFreeFunc>,
    mallocFunc: *mut Option<xmlMallocFunc>,
    reallocFunc: *mut Option<xmlReallocFunc>,
    strdupFunc: *mut Option<xmlStrdupFunc>,
) {
    // SAFETY: Delegates to xmlMemGet with the same safety contract.
    unsafe { xmlMemGet(freeFunc, mallocFunc, reallocFunc, strdupFunc) };
}

// ═══════════════════════════════════════════════════════════════════════════════
// Allocation Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Allocate memory.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlMalloc(size_t size);
/// ```
///
/// Returns a pointer to the allocated memory, or NULL on failure.
/// The allocated memory is not initialized (like malloc).
///
/// # SAFETY
///
/// - The returned pointer must be freed with `xmlFree`
/// - `size` may be 0 (returns a valid non-NULL pointer or NULL)
///
/// This is the implementation backing the exported `xmlMalloc` data global
/// (upstream xmlmemory.h: `XMLPUBVAR xmlMallocFunc xmlMalloc;` — a function-
/// pointer variable, not a function).
pub unsafe extern "C" fn xmlMallocImpl(size: usize) -> *mut c_void {
    // SAFETY: We call the stored malloc function pointer.
    // The function pointer must be valid (set by xmlMemSetup or default).
    let alloc = ALLOCATOR.read();
    let malloc_func = alloc.malloc_func.unwrap_or(default_malloc as xmlMallocFunc);
    let ptr = unsafe { malloc_func(size) };
    if !ptr.is_null() {
        MEM_USED.fetch_add(size, Ordering::Relaxed);
        MEM_BLOCKS.fetch_add(1, Ordering::Relaxed);
        unsafe { block_record(ptr, size, ptr::null(), 0) };
    }
    ptr
}

/// Allocate memory that will never contain pointers to other memory.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlMallocAtomic(size_t size);
/// ```
///
/// Identical to `xmlMalloc` but hints to the GC that the memory does not
/// contain pointers. In modern libxml2, this is equivalent to `xmlMalloc`.
/// Backing the exported `xmlMallocAtomic` data global.
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
pub unsafe extern "C" fn xmlMallocAtomicImpl(size: usize) -> *mut c_void {
    // SAFETY: Same as xmlMalloc.
    unsafe { xmlMallocImpl(size) }
}

/// Reallocate memory.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlRealloc(void *ptr, size_t size);
/// ```
///
/// Changes the size of the memory block pointed to by `ptr`.
/// If `ptr` is NULL, behaves like `xmlMalloc`.
/// If `size` is 0, may return NULL (like C realloc).
///
/// # SAFETY
///
/// - `ptr` must be a valid pointer from `xmlMalloc`, `xmlMallocAtomic`, or `xmlRealloc`,
///   or NULL
/// - The returned pointer must be freed with `xmlFree`
///
/// Backing the exported `xmlRealloc` data global.
pub unsafe extern "C" fn xmlReallocImpl(ptr: *mut c_void, size: usize) -> *mut c_void {
    // SAFETY: We call the stored realloc function pointer.
    let alloc = ALLOCATOR.read();
    let realloc_func = alloc
        .realloc_func
        .unwrap_or(default_realloc as xmlReallocFunc);
    let new_ptr = unsafe { realloc_func(ptr, size) };
    if !new_ptr.is_null() {
        // Exact accounting via the block registry.
        let old_size = unsafe { block_forget(ptr) };
        MEM_USED.fetch_add(size.saturating_sub(old_size), Ordering::Relaxed);
        if ptr.is_null() {
            MEM_BLOCKS.fetch_add(1, Ordering::Relaxed);
        }
        unsafe { block_record(new_ptr, size, ptr::null(), 0) };
    } else if !ptr.is_null() {
        // realloc failure: the old block is still alive.
        unsafe { block_record(ptr, block_forget(ptr), ptr::null(), 0) };
    }
    new_ptr
}

/// Free allocated memory.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlFree(void *ptr);
/// ```
///
/// Frees memory previously allocated with `xmlMalloc`, `xmlMallocAtomic`,
/// or `xmlRealloc`. If `ptr` is NULL, no operation is performed.
///
/// # SAFETY
///
/// - `ptr` must be a valid pointer from `xmlMalloc`/`xmlMallocAtomic`/`xmlRealloc`,
///   or NULL
/// - After this call, `ptr` must not be dereferenced
///
/// Backing the exported `xmlFree` data global.
pub unsafe extern "C" fn xmlFreeImpl(ptr: *mut c_void) {
    if ptr.is_null() {
        return;
    }
    // SAFETY: We call the stored free function pointer.
    let alloc = ALLOCATOR.read();
    let free_func = alloc.free_func.unwrap_or(default_free as xmlFreeFunc);
    let old_size = unsafe { block_forget(ptr) };
    unsafe { free_func(ptr) };
    MEM_BLOCKS.fetch_sub(1, Ordering::Relaxed);
    if old_size > 0 {
        MEM_USED.fetch_sub(old_size, Ordering::Relaxed);
    }
}

/// Duplicate a C string using the configured allocator.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void *xmlMemStrdup(const char *str);
/// ```
///
/// Returns a pointer to the newly allocated copy, or NULL on failure.
///
/// # SAFETY
///
/// - `str` must be a valid null-terminated C string or NULL
/// - The returned pointer must be freed with `xmlFree`
///
/// Backing the exported `xmlMemStrdup` data global.
pub unsafe extern "C" fn xmlMemStrdupImpl(str: *const c_char) -> *mut c_void {
    if str.is_null() {
        return ptr::null_mut();
    }
    // SAFETY: We call the stored strdup function pointer.
    let alloc = ALLOCATOR.read();
    let strdup_func = alloc.strdup_func.unwrap_or(default_strdup as xmlStrdupFunc);
    let ptr = unsafe { strdup_func(str) };
    if !ptr.is_null() {
        let len = unsafe { libc::strlen(str) } + 1;
        MEM_USED.fetch_add(len, Ordering::Relaxed);
        MEM_BLOCKS.fetch_add(1, Ordering::Relaxed);
        unsafe { block_record(ptr, len, ptr::null(), 0) };
    }
    ptr
}

// ═══════════════════════════════════════════════════════════════════════════════
// Exported allocator globals (upstream xmlmemory.h)
// ═══════════════════════════════════════════════════════════════════════════════
//
// Upstream exports the allocator entry points as DATA: `XMLPUBVAR
// xmlMallocFunc xmlMalloc;` etc. — function-pointer variables that downstream
// code can read AND assign (the documented allocator-override mechanism).
// The candidate mirrors that ABI; the implementations above back them.

/// `xmlMallocFunc xmlMalloc` — the malloc hook (default: `xmlMallocImpl`).
#[no_mangle]
pub static mut xmlMalloc: xmlMallocFunc = xmlMallocImpl;

/// `xmlMallocFunc xmlMallocAtomic` — the atomic-malloc hook.
#[no_mangle]
pub static mut xmlMallocAtomic: xmlMallocFunc = xmlMallocAtomicImpl;

/// `xmlReallocFunc xmlRealloc` — the realloc hook.
#[no_mangle]
pub static mut xmlRealloc: xmlReallocFunc = xmlReallocImpl;

/// `xmlFreeFunc xmlFree` — the free hook.
#[no_mangle]
pub static mut xmlFree: xmlFreeFunc = xmlFreeImpl;

/// `xmlStrdupFunc xmlMemStrdup` — the strdup hook.
#[no_mangle]
pub static mut xmlMemStrdup: xmlStrdupFunc = xmlMemStrdupImpl;

// ═══════════════════════════════════════════════════════════════════════════════
// Memory Debugging / Statistics
// ═══════════════════════════════════════════════════════════════════════════════

/// Return the total amount of memory currently allocated (approximate).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlMemUsed(void);
/// ```
///
/// Returns an approximate count of allocated bytes.
/// With the default allocator, this tracks allocations but is not
/// byte-exact for realloc (since we don't track old sizes).
/// Custom allocator hooks can provide exact counts.
#[no_mangle]
pub extern "C" fn xmlMemUsed() -> c_int {
    MEM_USED.load(Ordering::Relaxed) as c_int
}

/// Return the current number of allocated blocks (approximate).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlMemBlocks(void);
/// ```
///
/// Returns an approximate count of live allocations.
#[no_mangle]
pub extern "C" fn xmlMemBlocks() -> c_int {
    MEM_BLOCKS.load(Ordering::Relaxed) as c_int
}

/// Display memory allocation information to a file.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlMemDisplay(FILE *fp);
/// ```
///
/// Prints debug memory information. With the default allocator,
/// this prints a summary message. Custom allocator hooks may
/// provide more detailed output.
///
/// # SAFETY
///
/// - `fp` must be a valid FILE* pointer or NULL (in which case stderr is used)
#[no_mangle]
pub unsafe extern "C" fn xmlMemDisplay(fp: *mut c_void) {
    // SAFETY: Caller guarantees fp is valid FILE* or NULL.
    unsafe {
        let out = if fp.is_null() {
            libc::fdopen(2, b"w\0" as *const u8 as *const c_char) as *mut c_void
        } else {
            fp
        };
        libc::fprintf(
            out as *mut _,
            b"Memory: used=%d blocks=%d\n\0" as *const u8 as *const c_char,
            xmlMemUsed(),
            xmlMemBlocks(),
        );
    }
}

/// Show memory allocation information.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlMemShow(FILE *fp, int nr);
/// ```
///
/// Prints debug memory information for the last `nr` allocations.
/// With the default allocator, this is a no-op (we don't track allocation history).
///
/// # SAFETY
///
/// - `fp` 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.
///
/// 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMemShow(fp: *mut c_void, nr: c_int) {
    // Upstream xmlMemShow(fp, nr) prints the nr most recently allocated
    // blocks from the debug allocator's history. The candidate's block
    // registry is unordered; print the live blocks (bounded by nr), which
    // preserves the observable purpose (per-block debugging output).
    unsafe {
        let out = if fp.is_null() {
            libc::fdopen(2, b"w\0" as *const u8 as *const c_char) as *mut c_void
        } else {
            fp
        };
        if out.is_null() {
            return;
        }
        let mut msg = String::from("Recent blocks\n");
        let map = BLOCKS.lock();
        let mut entries: Vec<(usize, &BlockMeta)> = map.iter().map(|(k, v)| (*k, v)).collect();
        entries.sort_by_key(|(k, _)| *k);
        let take = if nr > 0 { nr as usize } else { usize::MAX };
        for (addr, meta) in entries.into_iter().take(take) {
            msg.push_str(&format!(
                "  {:018p} : {:>7} bytes\n",
                addr as *const c_void, meta.size
            ));
        }
        let bytes = msg.as_bytes();
        libc::fwrite(
            bytes.as_ptr() as *const c_void,
            1,
            bytes.len(),
            out as *mut libc::FILE,
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Convenience Functions (used internally)
// ═══════════════════════════════════════════════════════════════════════════════

/// Allocate zero-initialized memory.
///
/// # UPSTREAM-PARITY
///
/// This is like `xmlMalloc` followed by `memset(0)`, but some allocator
/// hooks provide it directly.
///
/// # SAFETY
///
/// Same as `xmlMalloc`. The returned memory is zero-initialized.
#[no_mangle]
pub unsafe extern "C" fn xmlMallocZero(size: usize) -> *mut c_void {
    // SAFETY: Delegates to xmlMallocImpl and zeroes the memory.
    let ptr = unsafe { xmlMallocImpl(size) };
    if !ptr.is_null() {
        unsafe { ptr::write_bytes(ptr, 0, size) };
    }
    ptr
}

/// Allocate zero-initialized memory (atomic variant).
///
/// # UPSTREAM-PARITY
///
/// Like `xmlMallocAtomic` followed by zero-initialization.
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlMallocAtomicZero(size: usize) -> *mut c_void {
    // SAFETY: Delegates to xmlMallocAtomicImpl and zeroes the memory.
    let ptr = unsafe { xmlMallocAtomicImpl(size) };
    if !ptr.is_null() {
        unsafe { ptr::write_bytes(ptr, 0, size) };
    }
    ptr
}

/// Reallocate and zero-initialize the new portion.
///
/// # UPSTREAM-PARITY
///
/// Like `xmlRealloc`, but zeroes any newly allocated bytes.
///
/// # SAFETY
///
/// Same as `xmlRealloc`.
#[no_mangle]
pub unsafe extern "C" fn xmlReallocZero(
    ptr: *mut c_void,
    old_size: usize,
    new_size: usize,
) -> *mut c_void {
    // SAFETY: Delegates to xmlRealloc and zeroes the new portion.
    let new_ptr = unsafe { xmlReallocImpl(ptr, new_size) };
    if !new_ptr.is_null() && new_size > old_size {
        unsafe {
            ptr::write_bytes(new_ptr.add(old_size), 0, new_size - old_size);
        }
    }
    new_ptr
}

// ═══════════════════════════════════════════════════════════════════════════════
// Debug Allocator (Optional)
// ═══════════════════════════════════════════════════════════════════════════════

/// Initialize the memory layer with debugging support.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlInitMemory(void);
/// ```
///
/// Initializes the memory subsystem. Returns 0 on success.
/// This is called automatically by `xmlInitParser`.
#[no_mangle]
pub const extern "C" fn xmlInitMemory() -> c_int {
    0
}

/// Clean up the memory layer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCleanupMemory(void);
/// ```
#[no_mangle]
pub const extern "C" fn xmlCleanupMemory() {
    // Phase 1: no cleanup needed for the default allocator.
}

// ═══════════════════════════════════════════════════════════════════════════════
// Legacy-named allocator API (upstream xmlmemory.h)
// ═══════════════════════════════════════════════════════════════════════════════
// Upstream xmlmemory.h historically exported `xmlMemMalloc`, `xmlMemFree`,
// `xmlMemRealloc`, `xmlMemoryStrdup`, the `*Loc` location-tracking variants,
// `xmlMemSize`, `xmlMemDisplayLast` and `xmlMemoryDump` alongside the modern
// names. Downstream code (older consumers, some language bindings) links
// against these names, so the candidate exports them with identical
// semantics. The `*Loc` variants take a source file/line that the default
// allocator does not track (upstream uses it for leak reports only); the
// location arguments are accepted and ignored — a documented safe divergence
// (residual R-000131).

/// Allocate memory (legacy name; same contract as `xmlMalloc`).
///
/// ```c
/// void *xmlMemMalloc(size_t size);
/// ```
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlMemMalloc(size: usize) -> *mut c_void {
    // SAFETY: identical contract to xmlMalloc.
    unsafe { xmlMallocImpl(size) }
}

/// Free memory (legacy name; same contract as `xmlFree`).
///
/// ```c
/// void xmlMemFree(void *ptr);
/// ```
///
/// # SAFETY
///
/// - `ptr` 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.
///
/// 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMemFree(ptr: *mut c_void) {
    // SAFETY: identical contract to xmlFree.
    unsafe { xmlFreeImpl(ptr) }
}

/// Reallocate memory (legacy name; same contract as `xmlRealloc`).
///
/// ```c
/// void *xmlMemRealloc(void *ptr, size_t size);
/// ```
///
/// # SAFETY
///
/// - `ptr` 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.
///
/// 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMemRealloc(ptr: *mut c_void, size: usize) -> *mut c_void {
    // SAFETY: identical contract to xmlRealloc.
    unsafe { xmlReallocImpl(ptr, size) }
}

/// Duplicate a string (legacy name; same contract as `xmlMemStrdup`).
///
/// ```c
/// void *xmlMemoryStrdup(const char *str);
/// ```
///
/// # SAFETY
///
///
/// - `str` 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMemoryStrdup(str: *const c_char) -> *mut c_void {
    // SAFETY: identical contract to xmlMemStrdup.
    unsafe { xmlMemStrdupImpl(str) }
}

/// Allocate memory, recording the allocation site (upstream xmlmemory.h).
///
/// ```c
/// void *xmlMallocLoc(size_t size, const char *file, int line);
/// ```
///
/// The default candidate allocator does not track allocation sites (see
/// residual R-000131); the location arguments are accepted for ABI
/// compatibility and ignored.
///
/// # SAFETY
///
///
/// - `file` 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMallocLoc(
    size: usize,
    file: *const c_char,
    line: c_int,
) -> *mut c_void {
    let ptr = unsafe { xmlMallocImpl(size) };
    if !ptr.is_null() {
        unsafe { block_record(ptr, size, file, line) };
    }
    ptr
}

/// Allocate zeroed memory, recording the allocation site (upstream xmlmemory.h).
///
/// ```c
/// void *xmlMallocAtomicLoc(size_t size, const char *file, int line);
/// ```
///
/// # SAFETY
///
///
/// - `file` 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMallocAtomicLoc(
    size: usize,
    file: *const c_char,
    line: c_int,
) -> *mut c_void {
    let ptr = unsafe { xmlMallocZero(size) };
    if !ptr.is_null() {
        unsafe { block_record(ptr, size, file, line) };
    }
    ptr
}

/// Reallocate memory, recording the allocation site (upstream xmlmemory.h).
///
/// ```c
/// void *xmlReallocLoc(void *ptr, size_t size, const char *file, int line);
/// ```
///
/// # SAFETY
///
/// - `ptr` 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.
///
/// - `file` 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.
#[no_mangle]
pub unsafe extern "C" fn xmlReallocLoc(
    ptr: *mut c_void,
    size: usize,
    file: *const c_char,
    line: c_int,
) -> *mut c_void {
    let new_ptr = unsafe { xmlReallocImpl(ptr, size) };
    if !new_ptr.is_null() {
        unsafe { block_record(new_ptr, size, file, line) };
    } else if !ptr.is_null() {
        // Keep the old site on failure.
        let meta = BLOCKS.lock().get(&(ptr as usize)).copied();
        if let Some(m) = meta {
            unsafe { block_record(ptr, m.size, m.file as *const c_char, m.line) };
        }
    }
    new_ptr
}

/// Duplicate a string, recording the allocation site (upstream xmlmemory.h).
///
/// ```c
/// void *xmlMemStrdupLoc(const char *str, const char *file, int line);
/// ```
///
/// # SAFETY
///
///
/// - `str`, `file` 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMemStrdupLoc(
    str: *const c_char,
    file: *const c_char,
    line: c_int,
) -> *mut c_void {
    let ptr = unsafe { xmlMemStrdupImpl(str) };
    if !ptr.is_null() {
        let len = unsafe { libc::strlen(str) } + 1;
        unsafe { block_record(ptr, len, file, line) };
    }
    ptr
}

/// Return the size of an allocated block (upstream xmlmemory.h).
///
/// ```c
/// size_t xmlMemSize(void *ptr);
/// ```
///
/// Returns the recorded size from the block registry (0 for unknown or
/// foreign pointers, matching upstream's lookup-miss behavior).
///
/// # SAFETY
///
/// - `ptr` 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.
///
/// 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMemSize(ptr: *mut c_void) -> usize {
    if ptr.is_null() {
        return 0;
    }
    BLOCKS
        .lock()
        .get(&(ptr as usize))
        .map(|m| m.size)
        .unwrap_or(0)
}

/// Display a limited amount of memory debug information (upstream xmlmemory.h).
///
/// ```c
/// void xmlMemDisplayLast(FILE *fp, long nbBytes);
/// ```
///
/// Dumps the per-block registry (upstream xmlMemDisplayLast block listing):
/// one line per live block with its address, size and recorded allocation
/// site, bounded by `nb_bytes` when positive. The aggregate footer matches
/// upstream's counters.
///
/// # SAFETY
///
/// - `fp` 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.
///
/// 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.
#[no_mangle]
pub unsafe extern "C" fn xmlMemDisplayLast(fp: *mut c_void, nb_bytes: c_long) {
    // SAFETY: fp must be a valid FILE* or NULL (stderr used).
    unsafe {
        let out = if fp.is_null() {
            libc::fdopen(2, b"w\0" as *const u8 as *const c_char) as *mut c_void
        } else {
            fp
        };
        if out.is_null() {
            return;
        }
        let mut total: usize = 0;
        let mut msg = String::new();
        msg.push_str("MEMORY ALLOCATED : 0, MAX : 0, BLOCKS : ");
        let blocks = MEM_BLOCKS.load(Ordering::Relaxed);
        msg.push_str(&blocks.to_string());
        msg.push('\n');
        let map = BLOCKS.lock();
        let mut entries: Vec<(usize, &BlockMeta)> = map.iter().map(|(k, v)| (*k, v)).collect();
        entries.sort_by_key(|(k, _)| *k);
        for (addr, meta) in entries {
            if nb_bytes > 0 && (total as c_long) >= nb_bytes {
                break;
            }
            total += meta.size;
            msg.push_str(&format!(
                "  {:018p} : {:>7} bytes",
                addr as *const c_void, meta.size
            ));
            if meta.file != 0 {
                let file = CStr::from_ptr(meta.file as *const c_char).to_string_lossy();
                msg.push_str(&format!(" @ {}:{}", file, meta.line));
            }
            msg.push('\n');
        }
        drop(map);
        let used = MEM_USED.load(Ordering::Relaxed);
        msg.push_str(&format!(
            "TOTAL MEMORY ALLOCATED : {} bytes, TOTAL BLOCKS : {}\n",
            used, blocks
        ));
        let bytes = msg.as_bytes();
        libc::fwrite(
            bytes.as_ptr() as *const c_void,
            1,
            bytes.len(),
            out as *mut libc::FILE,
        );
    }
}

/// Dump memory allocation statistics (upstream xmlmemory.h).
///
/// ```c
/// int xmlMemoryDump(void);
/// ```
///
/// Prints the global counters to stderr and returns 0 (no leak detector is
/// active in the default allocator).
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xmlMemoryDump() -> c_int {
    unsafe {
        xmlMemDisplayLast(ptr::null_mut(), -1);
    }
    0
}

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

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

    /// Test basic allocation and deallocation.
    #[test]
    fn test_malloc_free() {
        unsafe {
            let ptr = xmlMalloc(100);
            assert!(!ptr.is_null(), "xmlMalloc(100) returned NULL");
            xmlFree(ptr);
        }
    }

    /// Test that xmlMalloc(0) returns a valid pointer.
    #[test]
    fn test_malloc_zero() {
        unsafe {
            let ptr = xmlMalloc(0);
            // malloc(0) may return NULL or a valid pointer.
            // If non-NULL, it must be freeable.
            if !ptr.is_null() {
                xmlFree(ptr);
            }
        }
    }

    /// Test xmlFree(NULL) is a no-op.
    #[test]
    fn test_free_null() {
        unsafe {
            xmlFree(ptr::null_mut());
            // Should not crash
        }
    }

    /// Test xmlRealloc.
    #[test]
    fn test_realloc() {
        unsafe {
            let ptr = xmlMalloc(50);
            assert!(!ptr.is_null());
            let new_ptr = xmlRealloc(ptr, 100);
            assert!(!new_ptr.is_null());
            xmlFree(new_ptr);
        }
    }

    /// Test xmlMemStrdup.
    #[test]
    fn test_mem_strdup() {
        unsafe {
            let s = b"hello\0" as *const u8 as *const c_char;
            let dup = xmlMemStrdup(s);
            assert!(!dup.is_null());
            // Compare the strings
            let orig_slice = std::slice::from_raw_parts(s as *const u8, 6);
            let dup_slice = std::slice::from_raw_parts(dup as *const u8, 6);
            assert_eq!(orig_slice, dup_slice);
            xmlFree(dup);
        }
    }

    /// Test xmlMallocZero returns zeroed memory.
    #[test]
    fn test_malloc_zero_init() {
        unsafe {
            let ptr = xmlMallocZero(100) as *mut u8;
            assert!(!ptr.is_null());
            let slice = std::slice::from_raw_parts(ptr, 100);
            assert!(slice.iter().all(|&b| b == 0));
            xmlFree(ptr as *mut c_void);
        }
    }

    /// Test custom allocator setup/get.
    #[test]
    fn test_mem_setup_get() {
        unsafe {
            let mut free_func: Option<xmlFreeFunc> = None;
            let mut malloc_func: Option<xmlMallocFunc> = None;
            let mut realloc_func: Option<xmlReallocFunc> = None;
            let mut strdup_func: Option<xmlStrdupFunc> = None;

            xmlMemGet(
                &mut free_func as *mut _,
                &mut malloc_func as *mut _,
                &mut realloc_func as *mut _,
                &mut strdup_func as *mut _,
            );

            assert!(malloc_func.is_some());
            assert!(free_func.is_some());
            assert!(realloc_func.is_some());
            assert!(strdup_func.is_some());
        }
    }

    /// Test xmlMemUsed and xmlMemBlocks return reasonable values.
    #[test]
    fn test_mem_stats() {
        unsafe {
            let ptr = xmlMalloc(100);
            assert!(!ptr.is_null());

            // The block registry records the exact size (deterministic,
            // unlike the process-wide counters which other test threads
            // mutate concurrently).
            assert_eq!(xmlMemSize(ptr), 100);

            xmlFree(ptr);
            // Freed blocks leave the registry.
            assert_eq!(xmlMemSize(ptr), 0);
        }
    }
}