exml 0.7.3-deprecated

Pure Rust XML library based on libxml2
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
use std::{ffi::c_void, ptr::null_mut};

use crate::{
    globals::{
        GenericErrorContext, get_keep_blanks_default_value, get_line_numbers_default_value,
        get_pedantic_parser_default_value, get_substitute_entities_default_value,
        set_indent_tree_output, set_keep_blanks_default_value, set_line_numbers_default_value,
        set_pedantic_parser_default_value, set_substitute_entities_default_value,
    },
    parser::{XmlSAXHandler, xml_init_parser},
    tree::{XmlDocPtr, XmlDtdPtr, XmlGenericNodePtr, xml_free_doc},
};

/// Parse an XML in-memory document and build a tree.
///
/// Returns the resulting document tree
#[doc(alias = "xmlParseDoc")]
#[deprecated = "Use xmlReadDoc"]
#[cfg(feature = "sax1")]
pub fn xml_parse_doc(cur: &[u8]) -> Option<XmlDocPtr> {
    xml_sax_parse_doc(None, cur, 0)
}

/// Parse an XML file and build a tree. Automatic support for ZLIB/Compress
/// compressed document is provided by default if found at compile-time.
///
/// Returns the resulting document tree if the file was wellformed,
/// NULL otherwise.
#[doc(alias = "xmlParseFile")]
#[deprecated = "Use xmlReadFile"]
#[cfg(feature = "sax1")]
pub fn xml_parse_file(filename: Option<&str>) -> Option<XmlDocPtr> {
    xml_sax_parse_file(None, filename, false)
}

/// Parse an XML in-memory block and build a tree.
///
/// Returns the resulting document tree
#[doc(alias = "xmlParseMemory")]
#[deprecated = "Use xmlReadMemory"]
#[cfg(feature = "sax1")]
pub fn xml_parse_memory(buffer: &[u8]) -> Option<XmlDocPtr> {
    xml_sax_parse_memory(None, buffer, false)
}

/// Set and return the previous value for default entity support.
/// Initially the parser always keep entity references instead of substituting
/// entity values in the output. This function has to be used to change the
/// default parser behavior
/// SAX::substituteEntities() has to be used for changing that on a file by
/// file basis.
///
/// Returns the last value for 0 for no substitution, 1 for substitution.
#[doc(alias = "xmlSubstituteEntitiesDefault")]
#[deprecated = "Use the modern options API with XML_PARSE_NOENT"]
pub fn xml_substitute_entities_default(val: bool) -> bool {
    let old = get_substitute_entities_default_value();

    set_substitute_entities_default_value(val);
    old
}

/// Set and return the previous value for default blanks text nodes support.
/// The 1.x version of the parser used an heuristic to try to detect
/// ignorable white spaces. As a result the SAX callback was generating
/// xmlSAX2IgnorableWhitespace() callbacks instead of characters() one, and when
/// using the DOM output text nodes containing those blanks were not generated.
/// The 2.x and later version will switch to the XML standard way and
/// ignorableWhitespace() are only generated when running the parser in
/// validating mode and when the current element doesn't allow CDATA or
/// mixed content.
/// This function is provided as a way to force the standard behavior
/// on 1.X libs and to switch back to the old mode for compatibility when
/// running 1.X client code on 2.X . Upgrade of 1.X code should be done
/// by using xmlIsBlankNode() commodity function to detect the "empty"
/// nodes generated.
/// This value also affect autogeneration of indentation when saving code
/// if blanks sections are kept, indentation is not generated.
///
/// Returns the last value for 0 for no substitution, 1 for substitution.
#[doc(alias = "xmlKeepBlanksDefault")]
#[deprecated = "Use the modern options API with XML_PARSE_NOBLANKS"]
pub fn xml_keep_blanks_default(val: bool) -> bool {
    let old = get_keep_blanks_default_value();

    set_keep_blanks_default_value(val);
    if !val {
        set_indent_tree_output(1);
    }
    old
}

/// Set and return the previous value for enabling pedantic warnings.
///
/// Returns the last value for 0 for no substitution, 1 for substitution.
#[doc(alias = "xmlPedanticParserDefault")]
#[deprecated = "Use the modern options API with XML_PARSE_PEDANTIC"]
pub fn xml_pedantic_parser_default(val: bool) -> bool {
    let old = get_pedantic_parser_default_value();

    set_pedantic_parser_default_value(val);
    old
}

/// Set and return the previous value for enabling line numbers in elements
/// contents. This may break on old application and is turned off by default.
///
/// Returns the last value for 0 for no substitution, 1 for substitution.
#[doc(alias = "xmlLineNumbersDefault")]
#[deprecated = "The modern options API always enables line numbers"]
pub fn xml_line_numbers_default(val: i32) -> i32 {
    let old = get_line_numbers_default_value();

    set_line_numbers_default_value(val);
    old
}

/// Parse an XML in-memory document and build a tree.
/// In the case the document is not Well Formed, a attempt to build a
/// tree is tried anyway
///
/// Returns the resulting document tree or NULL in case of failure
#[doc(alias = "xmlRecoverDoc")]
#[deprecated = "Use xmlReadDoc with XML_PARSE_RECOVER"]
#[cfg(feature = "sax1")]
pub fn xml_recover_doc(cur: &[u8]) -> Option<XmlDocPtr> {
    xml_sax_parse_doc(None, cur, 1)
}

/// Parse an XML in-memory block and build a tree.
/// In the case the document is not Well Formed, an attempt to
/// build a tree is tried anyway
///
/// Returns the resulting document tree or NULL in case of error
#[doc(alias = "xmlRecoverMemory")]
#[deprecated = "Use xmlReadMemory with XML_PARSE_RECOVER"]
#[cfg(feature = "sax1")]
pub fn xml_recover_memory(buffer: &[u8]) -> Option<XmlDocPtr> {
    xml_sax_parse_memory(None, buffer, true)
}

/// Parse an XML file and build a tree. Automatic support for ZLIB/Compress
/// compressed document is provided by default if found at compile-time.
/// In the case the document is not Well Formed, it attempts to build
/// a tree anyway
///
/// Returns the resulting document tree or NULL in case of failure
#[doc(alias = "xmlRecoverFile")]
#[deprecated = "Use xmlReadFile with XML_PARSE_RECOVER"]
#[cfg(feature = "sax1")]
pub fn xml_recover_file(filename: Option<&str>) -> Option<XmlDocPtr> {
    xml_sax_parse_file(None, filename, true)
}

/// parse an XML file and call the given SAX handler routines.
/// Automatic support for ZLIB/Compress compressed document is provided
///
/// Returns 0 in case of success or a error number otherwise
#[doc(alias = "xmlSAXUserParseFile")]
#[deprecated = "Use xmlNewSAXParserCtxt and xmlCtxtReadFile"]
#[cfg(feature = "sax1")]
pub fn xml_sax_user_parse_file(
    sax: Option<Box<XmlSAXHandler>>,
    user_data: Option<GenericErrorContext>,
    filename: Option<&str>,
) -> i32 {
    use super::XmlParserCtxt;

    let ret: i32;

    let Some(mut ctxt) = XmlParserCtxt::from_filename(filename) else {
        return -1;
    };
    ctxt.sax = sax;
    ctxt.detect_sax2();

    ctxt.user_data = user_data;

    ctxt.parse_document();

    if ctxt.well_formed {
        ret = 0;
    } else if ctxt.err_no != 0 {
        ret = ctxt.err_no;
    } else {
        ret = -1;
    }
    ctxt.sax = None;
    if let Some(my_doc) = ctxt.my_doc.take() {
        unsafe {
            xml_free_doc(my_doc);
        }
    }

    ret
}

/// Parse an XML in-memory buffer and call the given SAX handler routines.
///
/// Returns 0 in case of success or a error number otherwise
#[doc(alias = "xmlSAXUserParseMemory")]
#[deprecated = "Use xmlNewSAXParserCtxt and xmlCtxtReadMemory"]
#[cfg(feature = "sax1")]
pub fn xml_sax_user_parse_memory(
    sax: Option<Box<XmlSAXHandler>>,
    user_data: Option<GenericErrorContext>,
    buffer: &[u8],
) -> i32 {
    use super::XmlParserCtxt;

    let ret: i32;

    xml_init_parser();

    let Some(mut ctxt) = XmlParserCtxt::from_memory(buffer) else {
        return -1;
    };
    ctxt.sax = sax;
    ctxt.detect_sax2();
    ctxt.user_data = user_data;

    ctxt.parse_document();

    if ctxt.well_formed {
        ret = 0;
    } else if ctxt.err_no != 0 {
        ret = ctxt.err_no;
    } else {
        ret = -1;
    }
    ctxt.sax = None;
    if let Some(my_doc) = ctxt.my_doc.take() {
        unsafe {
            xml_free_doc(my_doc);
        }
    }

    ret
}

/// Parse an XML in-memory document and build a tree.
/// It use the given SAX function block to handle the parsing callback.
/// If sax is NULL, fallback to the default DOM tree building routines.
///
/// Returns the resulting document tree
#[doc(alias = "xmlSAXParseDoc")]
#[deprecated = "Use xmlNewSAXParserCtxt and xmlCtxtReadDoc"]
#[cfg(feature = "sax1")]
pub fn xml_sax_parse_doc(
    sax: Option<Box<XmlSAXHandler>>,
    cur: &[u8],
    recovery: i32,
) -> Option<XmlDocPtr> {
    use super::XmlParserCtxt;

    let replaced = sax.is_some();
    let mut oldsax = None;

    let mut ctxt = XmlParserCtxt::from_memory(cur)?;
    if let Some(sax) = sax {
        oldsax = ctxt.sax.replace(sax);
        ctxt.user_data = None;
    }
    ctxt.detect_sax2();
    ctxt.parse_document();
    let ret = if ctxt.well_formed || recovery != 0 {
        ctxt.my_doc
    } else {
        if let Some(my_doc) = ctxt.my_doc.take() {
            unsafe {
                xml_free_doc(my_doc);
            }
        }
        None
    };
    if replaced {
        ctxt.sax = oldsax;
    }

    ret
}

/// Parse an XML in-memory block and use the given SAX function block
/// to handle the parsing callback. If sax is NULL, fallback to the default
/// DOM tree building routines.
///
/// Returns the resulting document tree
#[doc(alias = "xmlSAXParseMemory")]
#[deprecated = "Use xmlNewSAXParserCtxt and xmlCtxtReadMemory"]
#[cfg(feature = "sax1")]
pub fn xml_sax_parse_memory(
    sax: Option<Box<XmlSAXHandler>>,
    buffer: &[u8],
    recovery: bool,
) -> Option<XmlDocPtr> {
    xml_sax_parse_memory_with_data(sax, buffer, recovery, null_mut())
}

/// Parse an XML in-memory block and use the given SAX function block
/// to handle the parsing callback. If sax is NULL, fallback to the default
/// DOM tree building routines.
///
/// User data (c_void *) is stored within the parser context in the
/// context's _private member, so it is available nearly everywhere in libxml
///
/// Returns the resulting document tree
#[doc(alias = "xmlSAXParseMemoryWithData")]
#[deprecated = "Use xmlNewSAXParserCtxt and xmlCtxtReadMemory"]
#[cfg(feature = "sax1")]
pub fn xml_sax_parse_memory_with_data(
    sax: Option<Box<XmlSAXHandler>>,
    buffer: &[u8],
    recovery: bool,
    data: *mut c_void,
) -> Option<XmlDocPtr> {
    use super::XmlParserCtxt;

    let replaced = sax.is_some();

    xml_init_parser();

    let mut ctxt = XmlParserCtxt::from_memory(buffer)?;
    if let Some(sax) = sax {
        ctxt.sax = Some(sax);
    }
    ctxt.detect_sax2();
    if !data.is_null() {
        ctxt._private = data;
    }

    ctxt.recovery = recovery;
    ctxt.parse_document();

    let ret = if ctxt.well_formed || recovery {
        ctxt.my_doc
    } else {
        if let Some(my_doc) = ctxt.my_doc.take() {
            unsafe {
                xml_free_doc(my_doc);
            }
        }
        None
    };
    if replaced {
        ctxt.sax = None;
    }

    ret
}

/// parse an XML file and build a tree. Automatic support for ZLIB/Compress
/// compressed document is provided by default if found at compile-time.
/// It use the given SAX function block to handle the parsing callback.
/// If sax is NULL, fallback to the default DOM tree building routines.
///
/// Returns the resulting document tree
#[doc(alias = "xmlSAXParseFile")]
#[deprecated = "Use xmlNewSAXParserCtxt and xmlCtxtReadFile"]
#[cfg(feature = "sax1")]
pub fn xml_sax_parse_file(
    sax: Option<Box<XmlSAXHandler>>,
    filename: Option<&str>,
    recovery: bool,
) -> Option<XmlDocPtr> {
    xml_sax_parse_file_with_data(sax, filename, recovery, null_mut())
}

/// Parse an XML file and build a tree. Automatic support for ZLIB/Compress
/// compressed document is provided by default if found at compile-time.
/// It use the given SAX function block to handle the parsing callback.
/// If sax is NULL, fallback to the default DOM tree building routines.
///
/// User data (c_void *) is stored within the parser context in the
/// context's _private member, so it is available nearly everywhere in libxml
///
/// Returns the resulting document tree
#[doc(alias = "xmlSAXParseFileWithData")]
#[deprecated = "Use xmlNewSAXParserCtxt and xmlCtxtReadFile"]
#[cfg(feature = "sax1")]
pub fn xml_sax_parse_file_with_data(
    sax: Option<Box<XmlSAXHandler>>,
    filename: Option<&str>,
    recovery: bool,
    data: *mut c_void,
) -> Option<XmlDocPtr> {
    use crate::parser::XmlParserCtxt;

    use crate::io::xml_parser_get_directory;

    let replaced = sax.is_some();

    xml_init_parser();

    let mut ctxt = XmlParserCtxt::from_filename(filename)?;
    if let Some(sax) = sax {
        ctxt.sax = Some(sax);
    }
    ctxt.detect_sax2();
    if !data.is_null() {
        ctxt._private = data;
    }

    if ctxt.directory.is_none() {
        if let Some(filename) = filename {
            if let Some(dir) = xml_parser_get_directory(filename) {
                ctxt.directory = Some(dir.to_string_lossy().into_owned());
            }
        }
    }

    ctxt.recovery = recovery;
    ctxt.parse_document();

    let ret = if ctxt.well_formed || recovery {
        ctxt.my_doc
    } else {
        if let Some(my_doc) = ctxt.my_doc.take() {
            unsafe {
                xml_free_doc(my_doc);
            }
        }
        None
    };
    if replaced {
        ctxt.sax = None;
    }

    ret
}

/// Parse an XML external entity out of context and build a tree.
/// It use the given SAX function block to handle the parsing callback.
/// If sax is NULL, fallback to the default DOM tree building routines.
///
/// ```text
/// [78] extParsedEnt ::= TextDecl? content
/// ```
///
/// This correspond to a "Well Balanced" chunk
///
/// Returns the resulting document tree
#[doc(alias = "xmlSAXParseEntity")]
#[deprecated]
#[cfg(feature = "sax1")]
pub(crate) fn xml_sax_parse_entity(
    sax: Option<Box<XmlSAXHandler>>,
    filename: Option<&str>,
) -> Option<XmlDocPtr> {
    use super::XmlParserCtxt;

    let replaced = sax.is_some();

    let mut ctxt = XmlParserCtxt::from_filename(filename)?;
    if let Some(sax) = sax {
        ctxt.sax = Some(sax);
        ctxt.user_data = None;
    }

    ctxt.parse_ext_parsed_ent();

    let ret = if ctxt.well_formed {
        ctxt.my_doc
    } else {
        if let Some(my_doc) = ctxt.my_doc.take() {
            unsafe {
                xml_free_doc(my_doc);
            }
        }
        None
    };
    if replaced {
        ctxt.sax = None;
    }

    ret
}

/// Parse an XML external entity out of context and build a tree.
///
/// ```text
/// [78] extParsedEnt ::= TextDecl? content
/// ```
///
/// This correspond to a "Well Balanced" chunk
///
/// Returns the resulting document tree
#[doc(alias = "xmlParseEntity")]
#[deprecated]
#[cfg(feature = "sax1")]
pub fn xml_parse_entity(filename: Option<&str>) -> Option<XmlDocPtr> {
    xml_sax_parse_entity(None, filename)
}

/// Load and parse an external subset.
///
/// Returns the resulting xmlDtdPtr or NULL in case of error.
#[doc(alias = "xmlSAXParseDTD")]
#[deprecated]
#[cfg(feature = "libxml_valid")]
pub(crate) fn xml_sax_parse_dtd(
    sax: Option<Box<XmlSAXHandler>>,
    external_id: Option<&str>,
    system_id: Option<&str>,
) -> Option<XmlDtdPtr> {
    use crate::{
        encoding::detect_encoding,
        parser::{XmlParserCtxt, XmlParserOption, xml_err_memory},
        tree::{XmlDocProperties, xml_new_doc, xml_new_dtd},
        uri::canonic_path,
    };

    if external_id.is_none() && system_id.is_none() {
        return None;
    }

    let Ok(mut ctxt) = XmlParserCtxt::new_sax_parser(sax, None) else {
        return None;
    };

    // We are loading a DTD
    ctxt.options |= XmlParserOption::XmlParseDTDLoad as i32;

    // Canonicalise the system ID
    let system_id_canonic = system_id.map(|s| canonic_path(s));

    // Ask the Entity resolver to load the damn thing
    let input = ctxt
        .sax
        .as_deref_mut()
        .and_then(|sax| sax.resolve_entity)
        .and_then(|resolve_entity| {
            resolve_entity(&mut ctxt, external_id, system_id_canonic.as_deref())
        })?;

    // plug some encoding conversion routines here.
    if ctxt.push_input(input).is_err() {
        return None;
    }
    if ctxt.input().unwrap().remainder_len() >= 4 {
        let enc = detect_encoding(&ctxt.content_bytes()[..4]);
        ctxt.switch_encoding(enc);
    }

    if let Some(input) = ctxt.input_mut() {
        if input.filename.is_none() {
            if let Some(canonic) = system_id_canonic {
                input.filename = Some(canonic.into_owned());
            }
        }
        input.line = 1;
        input.col = 1;
        input.base += input.cur;
        input.cur = 0;
    }

    // let's parse that entity knowing it's an external subset.
    ctxt.in_subset = 2;
    ctxt.my_doc = xml_new_doc(Some("1.0"));
    let Some(mut my_doc) = ctxt.my_doc else {
        xml_err_memory(Some(&mut ctxt), Some("New Doc failed"));
        return None;
    };
    my_doc.properties = XmlDocProperties::XmlDocInternal as i32;
    my_doc.ext_subset = xml_new_dtd(ctxt.my_doc, Some("none"), external_id, system_id);
    ctxt.parse_external_subset(external_id, system_id);

    let mut ret = None;
    if let Some(mut my_doc) = ctxt.my_doc.take() {
        if ctxt.well_formed {
            ret = my_doc.ext_subset.take();
            if let Some(mut ret) = ret {
                ret.doc = None;
                let mut tmp = ret.children;
                while let Some(mut now) = tmp {
                    now.set_document(None);
                    tmp = now.next();
                }
            }
        } else {
            ret = None;
        }
        unsafe {
            xml_free_doc(my_doc);
        }
    }

    ret
}

/// Parse a well-balanced chunk of an XML document
/// called by the parser
/// The allowed sequence for the Well Balanced Chunk is the one defined by
/// the content production in the XML grammar:
///
/// `[43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*`
///
/// Returns 0 if the chunk is well balanced, -1 in case of args problem and
/// the parser error code otherwise
#[doc(alias = "xmlParseBalancedChunkMemory")]
#[cfg(feature = "sax1")]
pub unsafe fn xml_parse_balanced_chunk_memory(
    doc: Option<XmlDocPtr>,
    sax: Option<Box<XmlSAXHandler>>,
    user_data: Option<GenericErrorContext>,
    depth: i32,
    string: &str,
    lst: Option<&mut Option<XmlGenericNodePtr>>,
) -> i32 {
    unsafe { xml_parse_balanced_chunk_memory_recover(doc, sax, user_data, depth, string, lst, 0) }
}

/// Parse a well-balanced chunk of an XML document
/// called by the parser
/// The allowed sequence for the Well Balanced Chunk is the one defined by
/// the content production in the XML grammar:
///
/// `[43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*`
///
/// Returns 0 if the chunk is well balanced, -1 in case of args problem and
///    the parser error code otherwise
///
/// In case recover is set to 1, the nodelist will not be empty even if
/// the parsed chunk is not well balanced, assuming the parsing succeeded to
/// some extent.
#[doc(alias = "xmlParseBalancedChunkMemoryRecover")]
#[cfg(feature = "sax1")]
pub unsafe fn xml_parse_balanced_chunk_memory_recover(
    doc: Option<XmlDocPtr>,
    sax: Option<Box<XmlSAXHandler>>,
    user_data: Option<GenericErrorContext>,
    depth: i32,
    string: &str,
    mut lst: Option<&mut Option<XmlGenericNodePtr>>,
    recover: i32,
) -> i32 {
    use crate::{
        error::XmlParserErrors,
        parser::{XmlParserCtxt, XmlParserInputState, XmlParserOption, xml_fatal_err},
        tree::{NodeCommon, XML_XML_NAMESPACE, XmlDocProperties, xml_new_doc, xml_new_doc_node},
    };

    unsafe {
        let replaced = sax.is_some();
        let mut oldsax = None;
        let ret: i32;

        if depth > 40 {
            return XmlParserErrors::XmlErrEntityLoop as i32;
        }

        if let Some(lst) = lst.as_mut() {
            **lst = None;
        }

        let Some(mut ctxt) = XmlParserCtxt::from_memory(string.as_bytes()) else {
            return -1;
        };
        ctxt.user_data = None;
        if let Some(sax) = sax {
            oldsax = ctxt.sax.replace(sax);
            if user_data.is_some() {
                ctxt.user_data = user_data;
            }
        }
        let Some(mut new_doc) = xml_new_doc(Some("1.0")) else {
            return -1;
        };
        new_doc.properties = XmlDocProperties::XmlDocInternal as i32;
        ctxt.use_options_internal(XmlParserOption::XmlParseNoDict as i32, None);
        // doc.is_null() is only supported for historic reasons
        if let Some(doc) = doc {
            new_doc.int_subset = doc.int_subset;
            new_doc.ext_subset = doc.ext_subset;
        }
        let Some(new_root) = xml_new_doc_node(Some(new_doc), None, "pseudoroot", None) else {
            if replaced {
                ctxt.sax = oldsax;
            }
            new_doc.int_subset = None;
            new_doc.ext_subset = None;
            xml_free_doc(new_doc);
            return -1;
        };
        new_doc.add_child(new_root.into());
        ctxt.node_push(new_root);
        // doc.is_null() is only supported for historic reasons
        if let Some(mut doc) = doc {
            ctxt.my_doc = Some(new_doc);
            new_doc.children().unwrap().set_document(Some(doc));
            // Ensure that doc has XML spec namespace
            let d = doc;
            doc.search_ns_by_href(Some(d), XML_XML_NAMESPACE);
            new_doc.old_ns = doc.old_ns;
        } else {
            ctxt.my_doc = Some(new_doc);
        }
        ctxt.instate = XmlParserInputState::XmlParserContent;
        ctxt.input_id = 2;
        ctxt.depth = depth;

        // Doing validity checking on chunk doesn't make sense
        ctxt.validate = false;
        ctxt.loadsubset = 0;
        ctxt.detect_sax2();

        if let Some(mut doc) = doc {
            let content = doc.children.take();
            ctxt.parse_content();
            doc.children = content;
        } else {
            ctxt.parse_content();
        }
        if ctxt.current_byte() == b'<' && ctxt.nth_byte(1) == b'/' {
            xml_fatal_err(&mut ctxt, XmlParserErrors::XmlErrNotWellBalanced, None);
        } else if ctxt.current_byte() != 0 {
            xml_fatal_err(&mut ctxt, XmlParserErrors::XmlErrExtraContent, None);
        }
        if new_doc.children != ctxt.node.map(|node| node.into()) {
            xml_fatal_err(&mut ctxt, XmlParserErrors::XmlErrNotWellBalanced, None);
        }

        if !ctxt.well_formed {
            if ctxt.err_no == 0 {
                ret = 1;
            } else {
                ret = ctxt.err_no;
            }
        } else {
            ret = 0;
        }

        if let Some(lst) = lst {
            if ret == 0 || recover == 1 {
                // Return the newly created nodeset after unlinking it from
                // they pseudo parent.
                let mut cur = new_doc.children().unwrap().children();
                *lst = cur;
                while let Some(mut now) = cur {
                    now.set_doc(doc);
                    now.set_parent(None);
                    cur = now.next();
                }
                new_doc.children().unwrap().set_children(None);
            }
        }

        if replaced {
            ctxt.sax = oldsax;
        }
        new_doc.int_subset = None;
        new_doc.ext_subset = None;
        // This leaks the namespace list if doc.is_null()
        new_doc.old_ns = None;
        xml_free_doc(new_doc);

        ret
    }
}