libxml-rs 0.1.0-alpha.4

Phase 3: I/O, encoding, URI, catalog, serialization, HTML. Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. 357 tests passing, full encoding subsystem, URI parser, OASIS catalog, HTML parser/serializer, tree serialization, custom I/O buffers.
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
//! SAX callback dispatch — safe wrappers for invoking SAX1 and SAX2 callbacks (§20, §85 Phase 3).
//!
//! Each dispatcher checks whether the corresponding function pointer in the
//! `_xmlSAXHandler` is `Some` (non-NULL). If so, it calls the callback with
//! the provided arguments. If the callback is `None` (NULL), the dispatcher
//! either does nothing (for void callbacks) or returns a safe default value
//! (for callbacks that return a value).
//!
//! # Dispatch priority
//!
//! For `start_element` and `end_element`, the dispatcher prefers the SAX2
//! variant (`startElementNs` / `endElementNs`) when it is set, falling back
//! to the SAX1 variant (`startElement` / `endElement`). This matches the
//! upstream behavior where the parser uses SAX2 callbacks when available.

use crate::abi::callbacks::*;
use crate::abi::constants::XML_SAX2_MAGIC;
use crate::abi::structs::*;
use crate::abi::types::*;
use core::ptr;
use std::os::raw::{c_char, c_int, c_uint, c_void};

/// Safe wrapper around SAX callback dispatch.
pub(crate) struct SaxDispatcher;

#[allow(non_snake_case)]
impl SaxDispatcher {
    /// Dispatch `internalSubset` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `name`, `ext_id`, `sys_id` must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer (typically `_xmlParserCtxt*`).
    #[inline]
    pub unsafe fn internal_subset(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
        ext_id: *const xmlChar,
        sys_id: *const xmlChar,
    ) {
        if let Some(cb) = sax.internalSubset {
            // SAFETY: Caller guarantees the callback signature matches and all
            // pointer arguments satisfy the callback's safety requirements.
            unsafe { cb(ctx, name, ext_id, sys_id) };
        }
    }

    /// Dispatch `isStandalone` callback.
    ///
    /// Returns 1 if standalone="yes", 0 if standalone="no", -1 if not declared.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn is_standalone(sax: &_xmlSAXHandler, ctx: *mut c_void) -> c_int {
        if let Some(cb) = sax.isStandalone {
            // SAFETY: Caller guarantees the callback is safe to call with `ctx`.
            unsafe { cb(ctx) }
        } else {
            -1
        }
    }

    /// Dispatch `hasInternalSubset` callback.
    ///
    /// Returns 1 if the document has an internal subset, 0 otherwise.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn has_internal_subset(sax: &_xmlSAXHandler, ctx: *mut c_void) -> c_int {
        if let Some(cb) = sax.hasInternalSubset {
            // SAFETY: Caller guarantees the callback is safe to call with `ctx`.
            unsafe { cb(ctx) }
        } else {
            0
        }
    }

    /// Dispatch `hasExternalSubset` callback.
    ///
    /// Returns 1 if the document has an external subset, 0 otherwise.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn has_external_subset(sax: &_xmlSAXHandler, ctx: *mut c_void) -> c_int {
        if let Some(cb) = sax.hasExternalSubset {
            // SAFETY: Caller guarantees the callback is safe to call with `ctx`.
            unsafe { cb(ctx) }
        } else {
            0
        }
    }

    /// Dispatch `resolveEntity` callback.
    ///
    /// Returns a pointer to an `_xmlParserInput`, or NULL if not resolved.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `pub_id`, `sys_id` must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn resolve_entity(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        pub_id: *const xmlChar,
        sys_id: *const xmlChar,
    ) -> *mut _xmlParserInput {
        if let Some(cb) = sax.resolveEntity {
            // SAFETY: Caller guarantees the callback signature matches and all
            // pointer arguments satisfy the callback's safety requirements.
            unsafe { cb(ctx, pub_id, sys_id) }
        } else {
            ptr::null_mut()
        }
    }

    /// Dispatch `getEntity` callback.
    ///
    /// Returns a pointer to an `_xmlEntity`, or NULL.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `name` must be a valid null-terminated string.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn get_entity(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
    ) -> *mut _xmlEntity {
        if let Some(cb) = sax.getEntity {
            // SAFETY: Caller guarantees the callback is safe to call.
            unsafe { cb(ctx, name) }
        } else {
            ptr::null_mut()
        }
    }

    /// Dispatch `entityDecl` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn entity_decl(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
        type_: c_int,
        pub_id: *const xmlChar,
        sys_id: *const xmlChar,
        content: *mut xmlChar,
    ) {
        if let Some(cb) = sax.entityDecl {
            // SAFETY: Caller guarantees the callback signature matches.
            unsafe { cb(ctx, name, type_, pub_id, sys_id, content) };
        }
    }

    /// Dispatch `notationDecl` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn notation_decl(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
        pub_id: *const xmlChar,
        sys_id: *const xmlChar,
    ) {
        if let Some(cb) = sax.notationDecl {
            // SAFETY: Caller guarantees the callback signature matches.
            unsafe { cb(ctx, name, pub_id, sys_id) };
        }
    }

    /// Dispatch `attributeDecl` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn attribute_decl(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        elem: *const xmlChar,
        fullname: *const xmlChar,
        type_: c_int,
        def: c_int,
        default_value: *const xmlChar,
        tree: *mut _xmlEnumeration,
    ) {
        if let Some(cb) = sax.attributeDecl {
            // SAFETY: Caller guarantees the callback signature matches.
            unsafe { cb(ctx, elem, fullname, type_, def, default_value, tree) };
        }
    }

    /// Dispatch `elementDecl` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `name` must be a valid null-terminated string.
    /// - `content` must be a valid pointer or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn element_decl(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
        type_: c_int,
        content: *mut _xmlElementContent,
    ) {
        if let Some(cb) = sax.elementDecl {
            // SAFETY: Caller guarantees the callback signature matches.
            unsafe { cb(ctx, name, type_, content) };
        }
    }

    /// Dispatch `unparsedEntityDecl` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn unparsed_entity_decl(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
        pub_id: *const xmlChar,
        sys_id: *const xmlChar,
        notation: *const xmlChar,
    ) {
        if let Some(cb) = sax.unparsedEntityDecl {
            // SAFETY: Caller guarantees the callback signature matches.
            unsafe { cb(ctx, name, pub_id, sys_id, notation) };
        }
    }

    /// Dispatch `setDocumentLocator` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `loc` must be a valid pointer to an `_xmlSAXLocator`.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn set_document_locator(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        loc: *mut _xmlSAXLocator,
    ) {
        if let Some(cb) = sax.setDocumentLocator {
            // SAFETY: Caller guarantees the callback signature matches.
            unsafe { cb(ctx, loc) };
        }
    }

    /// Dispatch `startDocument` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn start_document(sax: &_xmlSAXHandler, ctx: *mut c_void) {
        if let Some(cb) = sax.startDocument {
            // SAFETY: Caller guarantees the callback is safe to call with `ctx`.
            unsafe { cb(ctx) };
        }
    }

    /// Dispatch `endDocument` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn end_document(sax: &_xmlSAXHandler, ctx: *mut c_void) {
        if let Some(cb) = sax.endDocument {
            // SAFETY: Caller guarantees the callback is safe to call with `ctx`.
            unsafe { cb(ctx) };
        }
    }

    /// Dispatch element start, preferring SAX2 (`startElementNs`) over SAX1 (`startElement`).
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ctx` must be a valid context pointer.
    /// - All pointer arguments must satisfy the requirements of whichever callback
    ///   is actually invoked (SAX1 or SAX2).
    #[inline]
    pub unsafe fn start_element(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        localname: *const xmlChar,
        prefix: *const xmlChar,
        URI: *const xmlChar,
        nb_namespaces: c_int,
        namespaces: *mut *const xmlChar,
        nb_attributes: c_int,
        nb_defaulted: c_int,
        attributes: *mut *const xmlChar,
    ) {
        // Prefer SAX2 callback if available.
        if let Some(cb) = sax.startElementNs {
            // SAFETY: Caller guarantees all SAX2 callback arguments are valid.
            unsafe {
                cb(
                    ctx,
                    localname,
                    prefix,
                    URI,
                    nb_namespaces,
                    namespaces,
                    nb_attributes,
                    nb_defaulted,
                    attributes,
                )
            };
        } else if let Some(cb) = sax.startElement {
            // SAX1 fallback: use the element's qualified name.
            // SAX1 callbacks don't receive namespace info, so we only pass the
            // localname as the element name, and NULL for attributes (the caller
            // must convert the SAX2 attribute format to SAX1 format if needed).
            //
            // # UPSTREAM-PARITY
            //
            // In upstream libxml2, the SAX1 fallback in xmlSAX2StartElement
            // reconstructs the qualified name from localname + prefix and
            // converts the attribute array to SAX1 format.
            // SAFETY: Caller guarantees the SAX1 callback arguments are valid.
            unsafe { cb(ctx, localname, ptr::null_mut()) };
        }
    }

    /// Dispatch element end, preferring SAX2 (`endElementNs`) over SAX1 (`endElement`).
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ctx` must be a valid context pointer.
    /// - All pointer arguments must satisfy the requirements of whichever callback
    ///   is actually invoked.
    #[inline]
    pub unsafe fn end_element(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        localname: *const xmlChar,
        prefix: *const xmlChar,
        URI: *const xmlChar,
    ) {
        // Prefer SAX2 callback if available.
        if let Some(cb) = sax.endElementNs {
            // SAFETY: Caller guarantees all SAX2 callback arguments are valid.
            unsafe { cb(ctx, localname, prefix, URI) };
        } else if let Some(cb) = sax.endElement {
            // SAX1 fallback: use the localname as the element name.
            // SAFETY: Caller guarantees the SAX1 callback arguments are valid.
            unsafe { cb(ctx, localname) };
        }
    }

    /// Dispatch `characters` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ch` must be a valid pointer to a buffer of at least `len` bytes.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn characters(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        ch: *const xmlChar,
        len: c_int,
    ) {
        if let Some(cb) = sax.characters {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, ch, len) };
        }
    }

    /// Dispatch `ignorableWhitespace` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `ch` must be a valid pointer to a buffer of at least `len` bytes.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn ignorable_whitespace(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        ch: *const xmlChar,
        len: c_int,
    ) {
        if let Some(cb) = sax.ignorableWhitespace {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, ch, len) };
        }
    }

    /// Dispatch `processingInstruction` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `target` and `data` must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn processing_instruction(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        target: *const xmlChar,
        data: *const xmlChar,
    ) {
        if let Some(cb) = sax.processingInstruction {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, target, data) };
        }
    }

    /// Dispatch `comment` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `value` must be a valid null-terminated string or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn comment(sax: &_xmlSAXHandler, ctx: *mut c_void, value: *const xmlChar) {
        if let Some(cb) = sax.comment {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, value) };
        }
    }

    /// Dispatch `warning` callback (printf-style, variadic at C call site).
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `msg` must be a valid null-terminated C string.
    /// - `ctx` must be a valid context pointer.
    ///
    /// # UPSTREAM-PARITY
    ///
    /// The `...` variadic arguments are not representable in stable Rust's
    /// `extern "C"` function pointer type. The type alias `warningSAXFunc`
    /// only takes `(ctx, msg)` — matching the upstream ABI where the callee
    /// uses `va_list` internally. C callers pass additional variadic arguments
    /// directly on the stack per the platform ABI.
    #[inline]
    pub unsafe fn warning(sax: &_xmlSAXHandler, ctx: *mut c_void, msg: *const c_char) {
        if let Some(cb) = sax.warning {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, msg) };
        }
    }

    /// Dispatch `error` callback (printf-style, variadic at C call site).
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `msg` must be a valid null-terminated C string.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn error(sax: &_xmlSAXHandler, ctx: *mut c_void, msg: *const c_char) {
        if let Some(cb) = sax.error {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, msg) };
        }
    }

    /// Dispatch `fatalError` callback (printf-style, variadic at C call site).
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `msg` must be a valid null-terminated C string.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn fatal_error(sax: &_xmlSAXHandler, ctx: *mut c_void, msg: *const c_char) {
        if let Some(cb) = sax.fatalError {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, msg) };
        }
    }

    /// Dispatch `cdataBlock` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `value` must be a valid pointer to a buffer of at least `len` bytes.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn cdata_block(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        value: *const xmlChar,
        len: c_int,
    ) {
        if let Some(cb) = sax.cdataBlock {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, value, len) };
        }
    }

    /// Dispatch `reference` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `name` must be a valid null-terminated string.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn reference(sax: &_xmlSAXHandler, ctx: *mut c_void, name: *const xmlChar) {
        if let Some(cb) = sax.reference {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, name) };
        }
    }

    /// Dispatch `getParameterEntity` callback.
    ///
    /// Returns a pointer to an `_xmlEntity`, or NULL.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `name` must be a valid null-terminated string.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn get_parameter_entity(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
    ) -> *mut _xmlEntity {
        if let Some(cb) = sax.getParameterEntity {
            // SAFETY: Caller guarantees the callback is safe to call.
            unsafe { cb(ctx, name) }
        } else {
            ptr::null_mut()
        }
    }

    /// Dispatch `externalSubset` callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn external_subset(
        sax: &_xmlSAXHandler,
        ctx: *mut c_void,
        name: *const xmlChar,
        ext_id: *const xmlChar,
        sys_id: *const xmlChar,
    ) {
        if let Some(cb) = sax.externalSubset {
            // SAFETY: Caller guarantees the callback signature matches.
            unsafe { cb(ctx, name, ext_id, sys_id) };
        }
    }

    /// Dispatch `serror` (structured error) callback.
    ///
    /// # SAFETY
    ///
    /// - `sax` must be a valid pointer to an initialized `_xmlSAXHandler`.
    /// - `error` must be a valid pointer to an `_xmlError`.
    /// - `ctx` must be a valid context pointer.
    #[inline]
    pub unsafe fn structured_error(sax: &_xmlSAXHandler, ctx: *mut c_void, error: *mut _xmlError) {
        if let Some(cb) = sax.serror {
            // SAFETY: Caller guarantees the callback arguments are valid.
            unsafe { cb(ctx, error) };
        }
    }
}

/// Initialize a `_xmlSAXHandler` with default SAX2 callback functions.
///
/// This is the Rust equivalent of `xmlSAX2InitDefaultSAXHandler` from upstream
/// libxml2. It sets all callback fields to point to the default SAX2 handlers
/// defined in `super::default::default_sax_handler`, and marks the handler as
/// initialized with `XML_SAX2_MAGIC`.
///
/// # SAFETY
///
/// - `sax` must be a valid pointer to a `_xmlSAXHandler` that can be written to.
/// - The caller is responsible for freeing the handler if needed.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSAX2InitDefaultSAXHandler(xmlSAXHandlerPtr handler, int warning);
/// ```
///
/// Upstream signature includes a `warning` parameter that controls whether
/// warning/error callbacks are set. We ignore it for now and always set them.
#[allow(non_snake_case)]
pub unsafe fn xmlSAX2InitDefaultSAXHandler(sax: *mut _xmlSAXHandler) {
    use super::default::default_sax_handler as dflt;

    if sax.is_null() {
        return;
    }

    // SAFETY: Caller guarantees `sax` is a valid, writable pointer.
    unsafe {
        let h = &mut *sax;
        h.internalSubset = Some(dflt::internalSubset as internalSubsetSAXFunc);
        h.isStandalone = Some(dflt::isStandalone as isStandaloneSAXFunc);
        h.hasInternalSubset = Some(dflt::hasInternalSubset as hasInternalSubsetSAXFunc);
        h.hasExternalSubset = Some(dflt::hasExternalSubset as hasExternalSubsetSAXFunc);
        h.resolveEntity = Some(dflt::resolveEntity as resolveEntitySAXFunc);
        h.getEntity = Some(dflt::getEntity as getEntitySAXFunc);
        h.entityDecl = Some(dflt::entityDecl as entityDeclSAXFunc);
        h.notationDecl = Some(dflt::notationDecl as notationDeclSAXFunc);
        h.attributeDecl = Some(dflt::attributeDecl as attributeDeclSAXFunc);
        h.elementDecl = Some(dflt::elementDecl as elementDeclSAXFunc);
        h.unparsedEntityDecl = Some(dflt::unparsedEntityDecl as unparsedEntityDeclSAXFunc);
        h.setDocumentLocator = Some(dflt::setDocumentLocator as setDocumentLocatorSAXFunc);
        h.startDocument = Some(dflt::startDocument as startDocumentSAXFunc);
        h.endDocument = Some(dflt::endDocument as endDocumentSAXFunc);
        h.startElement = None; // SAX1: not set in SAX2 mode
        h.endElement = None; // SAX1: not set in SAX2 mode
        h.reference = Some(dflt::reference as referenceSAXFunc);
        h.characters = Some(dflt::characters as charactersSAXFunc);
        h.ignorableWhitespace = Some(dflt::ignorableWhitespace as ignorableWhitespaceSAXFunc);
        h.processingInstruction = Some(dflt::processingInstruction as processingInstructionSAXFunc);
        h.comment = Some(dflt::comment as commentSAXFunc);
        h.warning = Some(dflt::warning as warningSAXFunc);
        h.error = Some(dflt::error as errorSAXFunc);
        h.fatalError = Some(dflt::fatalError as fatalErrorSAXFunc);
        h.getParameterEntity = Some(dflt::getParameterEntity as getParameterEntitySAXFunc);
        h.cdataBlock = Some(dflt::cdataBlock as cdataBlockSAXFunc);
        h.externalSubset = Some(dflt::externalSubset as externalSubsetSAXFunc);
        h.initialized = XML_SAX2_MAGIC as c_uint;
        h._private = ptr::null_mut();
        h.startElementNs = Some(dflt::startElementNs as startElementNsSAX2Func);
        h.endElementNs = Some(dflt::endElementNs as endElementNsSAX2Func);
        h.serror = None;
    }
}