exml 0.7.2

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
use std::{ptr::fn_addr_eq, str::from_utf8_unchecked};

use crate::{
    chvalid::XmlCharValid,
    error::XmlParserErrors,
    parser::{
        XML_MAX_HUGE_LENGTH, XML_MAX_TEXT_LENGTH, XML_PARSER_BIG_BUFFER_SIZE, XmlParserCtxt,
        XmlParserInputState, XmlParserOption, xml_fatal_err, xml_fatal_err_msg,
        xml_fatal_err_msg_int, xml_fatal_err_msg_str,
    },
    tree::{NodeCommon, XmlElementType},
    valid::xml_is_mixed_element,
};

impl XmlParserCtxt<'_> {
    /// Is this a sequence of blank chars that one can ignore ?
    ///
    /// Returns 1 if ignorable 0 otherwise.
    #[doc(alias = "areBlanks")]
    fn are_blanks(&mut self, s: &str, blank_chars: bool) -> bool {
        // Don't spend time trying to differentiate them, the same callback is used !
        if self.sax.as_deref().is_none_or(|sax| {
            (sax.ignorable_whitespace.is_none() && sax.characters.is_none())
                || sax
                    .ignorable_whitespace
                    .zip(sax.characters)
                    .is_some_and(|(l, r)| fn_addr_eq(l, r))
        }) {
            return false;
        }

        // Check for xml:space value.
        if self.space() == 1 || self.space() == -2 {
            return false;
        }

        // Check that the string is made of blanks
        if !blank_chars && s.chars().any(|c| !c.is_xml_blank_char()) {
            return false;
        }

        // Look if the element is mixed content in the DTD if available
        let Some(context_node) = self.node else {
            return false;
        };
        if let Some(my_doc) = self.my_doc {
            let ret = xml_is_mixed_element(my_doc, &context_node.name().unwrap());
            if ret == 0 {
                return true;
            }
            if ret == 1 {
                return false;
            }
        }

        // Otherwise, heuristic :-\
        if !matches!(self.current_byte(), b'<' | 0xD) {
            return false;
        }
        if context_node.children().is_none() && self.content_bytes().starts_with(b"</") {
            // index out of bound may occur at this `nth_byte` ??? It may be necessary to fix.
            return false;
        }

        if let Some(last_child) = context_node.get_last_child() {
            if last_child.is_text_node()
                || context_node
                    .children()
                    .filter(|c| c.is_text_node())
                    .is_some()
            {
                return false;
            }
        } else if context_node.element_type() != XmlElementType::XmlElementNode
            && context_node.content.is_some()
        {
            return false;
        }
        true
    }

    /// Always makes progress if the first char isn't '<' or '&'.
    ///
    /// parse a CharData section.this is the fallback function
    /// of xmlParseCharData() when the parsing requires handling
    /// of non-ASCII characters.
    #[doc(alias = "xmlParseCharDataComplex")]
    fn parse_char_data_complex(&mut self, partial: i32) {
        let mut buf = String::with_capacity(XML_PARSER_BIG_BUFFER_SIZE + 5);
        let mut cur = self.current_char();
        // test also done in xmlCurrentChar()
        while let Some(nc) = cur.filter(|&cur| cur != '<' && cur != '&' && cur.is_xml_char()) {
            if nc == ']' && self.nth_byte(1) == b']' && self.nth_byte(2) == b'>' {
                xml_fatal_err(self, XmlParserErrors::XmlErrMisplacedCDATAEnd, None);
            }
            buf.push(nc);
            // move current position before possible calling of (*self.sax).characters
            self.advance_with_line_handling(nc.len_utf8());
            if buf.len() >= XML_PARSER_BIG_BUFFER_SIZE {
                // OK the segment is to be consumed as chars.
                if !self.disable_sax {
                    let blank = self.are_blanks(&buf, false);
                    if let Some(sax) = self.sax.as_deref_mut() {
                        if blank {
                            if let Some(ignorable_whitespace) = sax.ignorable_whitespace {
                                ignorable_whitespace(self, &buf);
                            }
                        } else {
                            if let Some(characters) = sax.characters {
                                characters(self, &buf);
                            }
                            let sax = self.sax.as_deref_mut().unwrap();
                            if (sax.ignorable_whitespace.is_some() || sax.characters.is_some())
                                && sax
                                    .ignorable_whitespace
                                    .zip(sax.characters)
                                    .is_none_or(|(l, r)| !fn_addr_eq(l, r))
                                && self.space() == -1
                            {
                                *self.space_mut() = -2;
                            }
                        }
                    }
                }
                buf.clear();
                // something really bad happened in the SAX callback
                if !matches!(self.instate, XmlParserInputState::XmlParserContent) {
                    return;
                }
                self.shrink();
            }
            cur = self.current_char();
        }
        if matches!(self.instate, XmlParserInputState::XmlParserEOF) {
            return;
        }
        if !buf.is_empty() {
            // OK the segment is to be consumed as chars.
            if !self.disable_sax {
                let blank = self.are_blanks(&buf, false);
                if let Some(sax) = self.sax.as_deref_mut() {
                    if blank {
                        if let Some(ignorable_whitespace) = sax.ignorable_whitespace {
                            ignorable_whitespace(self, &buf);
                        }
                    } else {
                        if let Some(characters) = sax.characters {
                            characters(self, &buf);
                        }
                        let sax = self.sax.as_deref_mut().unwrap();
                        if (sax.ignorable_whitespace.is_some() || sax.characters.is_some())
                            && sax
                                .ignorable_whitespace
                                .zip(sax.characters)
                                .is_none_or(|(l, r)| !fn_addr_eq(l, r))
                            && self.space() == -1
                        {
                            *self.space_mut() = -2;
                        }
                    }
                }
            }
        }
        // cur == 0 can mean
        //
        // - xmlParserInputState::XmlParserEOF or memory error. This is checked above.
        // - An actual 0 character.
        // - End of buffer.
        // - An incomplete UTF-8 sequence. This is allowed if partial is set.
        if !self.content_bytes().is_empty() {
            if cur.is_none_or(|cur| cur == '\0') && self.current_byte() != 0 {
                if partial == 0 {
                    xml_fatal_err_msg_int!(
                        self,
                        XmlParserErrors::XmlErrInvalidChar,
                        format!(
                            "Incomplete UTF-8 sequence starting with {:02X}\n",
                            self.current_byte()
                        )
                        .as_str(),
                        self.current_byte() as i32
                    );
                    self.advance_with_line_handling(1);
                }
            } else if !matches!(cur, Some('<' | '&')) {
                // Generate the error and skip the offending character
                let c = cur.unwrap_or('\0');
                xml_fatal_err_msg_int!(
                    self,
                    XmlParserErrors::XmlErrInvalidChar,
                    format!("PCDATA invalid Char value {}\n", c as i32).as_str(),
                    c as i32
                );
                self.advance_with_line_handling(cur.map_or(0, |c| c.len_utf8()));
            }
        }
    }

    /// Parse character data. Always makes progress if the first char isn't '<' or '&'.
    ///
    /// The right angle bracket (>) may be represented using the string "&gt;",
    /// and must, for compatibility, be escaped using "&gt;" or a character
    /// reference when it appears in the string "]]>" in content, when that
    /// string is not marking the end of a CDATA section.
    ///
    /// ````text
    /// [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
    /// ```
    #[doc(alias = "xmlParseCharDataInternal")]
    pub(crate) fn parse_char_data_internal(&mut self, partial: i32) {
        // used for the test in the inner loop of the char data testing
        // &    : start reference
        // <    : start tag
        // ]    : end CDATA section
        const TEST_CHAR_DATA: [u8; 256] = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x00, 0x27, 0x28, 0x29,
            0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
            0x38, 0x39, 0x3A, 0x3B, 0x00, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
            0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53,
            0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x00, 0x5E, 0x5F, 0x60, 0x61,
            0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
            0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D,
            0x7E, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];

        self.grow();
        // Accelerated common case where input don't need to be
        // modified before passing it to the handler.
        let mut input = self.content_bytes();
        let mut line = self.input().unwrap().line;
        let mut col = self.input().unwrap().col;
        let mut buf = String::new();
        while matches!(input.first(), Some(&b'\n' | &b'\t' | &(0x20..=0x7F))) {
            while matches!(input.first(), Some(&b' ' | &b'\n')) {
                let spaces = input.iter().position(|&b| b != b' ').unwrap_or(input.len());
                col += spaces as i32;
                input = &input[spaces..];
                let lines = input
                    .iter()
                    .position(|&b| b != b'\n')
                    .unwrap_or(input.len());
                if lines != 0 {
                    line += lines as i32;
                    col = 1;
                    input = &input[lines..];
                }
            }

            if input.first() == Some(&b'<') {
                let len = self.content_bytes().len() - input.len();
                if len > 0 {
                    buf.clear();
                    unsafe {
                        // # Safety
                        // `self.content_bytes()[..len]` contains only ASCII characters.
                        // Therefore, UTF-8 validation won't be failed.
                        buf.push_str(from_utf8_unchecked(&self.content_bytes()[..len]));
                    }

                    // commit consumed bytes for SAX interface
                    let input = self.input_mut().unwrap();
                    input.cur += len;
                    input.line = line;
                    input.col = col;

                    let blank = self.are_blanks(&buf, true);

                    if let Some(sax) = self.sax.as_deref_mut().filter(|sax| {
                        (sax.ignorable_whitespace.is_some() || sax.characters.is_some())
                            && sax
                                .ignorable_whitespace
                                .zip(sax.characters)
                                .is_none_or(|(l, r)| !fn_addr_eq(l, r))
                    }) {
                        if blank {
                            if let Some(ignorable_whitespace) = sax.ignorable_whitespace {
                                ignorable_whitespace(self, &buf);
                            }
                        } else {
                            if let Some(characters) = sax.characters {
                                characters(self, &buf);
                            }
                            if self.space() == -1 {
                                *self.space_mut() = -2;
                            }
                        }
                    } else if let Some(characters) =
                        self.sax.as_deref_mut().and_then(|sax| sax.characters)
                    {
                        characters(self, &buf);
                    }
                }
                return;
            }

            while input
                .first()
                .filter(|&&b| TEST_CHAR_DATA[b as usize] != 0 || matches!(b, 0xA | b']'))
                .is_some()
            {
                let chars = input
                    .iter()
                    .position(|&b| TEST_CHAR_DATA[b as usize] == 0)
                    .unwrap_or(input.len());
                col += chars as i32;
                input = &input[chars..];

                let lines = input.iter().position(|&b| b != 0xA).unwrap_or(input.len());
                if lines != 0 {
                    line += lines as i32;
                    col = 1;
                    input = &input[lines..];
                }

                if let Some(rem) = input.strip_prefix(b"]") {
                    // "]]>" must not be contained in CharData
                    if rem.starts_with(b"]>") {
                        // commit consumed bytes before raise an error
                        let diff = self.content_bytes().len() - input.len();
                        let input = self.input_mut().unwrap();
                        input.line = line;
                        input.col = col;
                        input.cur += diff;
                        xml_fatal_err(self, XmlParserErrors::XmlErrMisplacedCDATAEnd, None);
                        if !matches!(self.instate, XmlParserInputState::XmlParserEOF) {
                            // if the parser input state is not EOF,
                            // consume the head of ']'.
                            self.input_mut().unwrap().cur += 1;
                        }
                        return;
                    }
                    col += 1;
                    input = rem;
                }
            }

            let len = self.content_bytes().len() - input.len();
            if len > 0 {
                buf.clear();
                unsafe {
                    // # Safety
                    // `self.content_bytes()[..len]` contains only ASCII characters.
                    // Therefore, UTF-8 validation won't be failed.
                    buf.push_str(from_utf8_unchecked(&self.content_bytes()[..len]));
                }

                // commit consumed bytes for SAX interface
                let input_mut = self.input_mut().unwrap();
                input_mut.cur += len;
                input_mut.line = line;
                input_mut.col = col;

                let blank = self.are_blanks(&buf, false);

                if let Some(sax) = self.sax.as_deref_mut().filter(|sax| {
                    (sax.ignorable_whitespace.is_some() || sax.characters.is_some())
                        && sax
                            .ignorable_whitespace
                            .zip(sax.characters)
                            .is_none_or(|(l, r)| !fn_addr_eq(l, r))
                }) {
                    if blank {
                        if let Some(ignorable_whitespace) = sax.ignorable_whitespace {
                            ignorable_whitespace(self, &buf);
                        }
                    } else {
                        if let Some(characters) = sax.characters {
                            characters(self, &buf);
                        }
                        if self.space() == -1 {
                            *self.space_mut() = -2;
                        }
                    }
                } else if let Some(characters) =
                    self.sax.as_deref_mut().and_then(|sax| sax.characters)
                {
                    characters(self, &buf);
                }

                // refresh input buffer
                input = self.content_bytes();
            }

            // Replace "\r\n" to "\n" and skip
            if input.starts_with(b"\r\n") {
                line += 1;
                col = 1;
                // To skip '\r', `+1` is needed.
                let diff = self.content_bytes().len() - input.len() + 1;
                // At this point, `content_bytes` will start with '\n' ('\r' is skipped)
                self.input_mut().unwrap().cur += diff;
                // and skip '\n' at the head of `content_bytes`.
                input = &self.content_bytes()[1..];
                continue;
            }

            // At this point, the buffer is already committed,
            // so commit only line and col
            self.input_mut().unwrap().line = line;
            self.input_mut().unwrap().col = col;

            if matches!(self.content_bytes().first(), Some(&(b'<' | b'&'))) {
                return;
            }

            self.shrink();
            self.grow();
            if matches!(self.instate, XmlParserInputState::XmlParserEOF) {
                return;
            }

            // refresh input buffer
            input = self.content_bytes();
        }

        let len = self.content_bytes().len() - input.len();
        self.input_mut().unwrap().cur += len;
        self.input_mut().unwrap().line = line;
        self.input_mut().unwrap().col = col;
        self.parse_char_data_complex(partial);
    }

    /// Parse escaped pure raw content. Always consumes '<!['.
    ///
    /// ```text
    /// [18] CDSect ::= CDStart CData CDEnd
    /// [19] CDStart ::= '<![CDATA['
    /// [20] Data ::= (Char* - (Char* ']]>' Char*))
    /// [21] CDEnd ::= ']]>'
    /// ```
    #[doc(alias = "xmlParseCDSect")]
    pub(crate) fn parse_cdsect(&mut self) {
        let max_length = if self.options & XmlParserOption::XmlParseHuge as i32 != 0 {
            XML_MAX_HUGE_LENGTH
        } else {
            XML_MAX_TEXT_LENGTH
        };

        if !self.content_bytes().starts_with(b"<![CDATA[") {
            return;
        }
        self.advance(9);

        self.instate = XmlParserInputState::XmlParserCDATASection;
        let Some(mut r) = self.current_char().filter(|&r| r.is_xml_char()) else {
            xml_fatal_err(self, XmlParserErrors::XmlErrCDATANotFinished, None);
            if !matches!(self.instate, XmlParserInputState::XmlParserEOF) {
                self.instate = XmlParserInputState::XmlParserContent;
            }
            return;
        };
        self.advance_with_line_handling(r.len_utf8());
        let Some(mut s) = self.current_char().filter(|&s| s.is_xml_char()) else {
            xml_fatal_err(self, XmlParserErrors::XmlErrCDATANotFinished, None);
            if !matches!(self.instate, XmlParserInputState::XmlParserEOF) {
                self.instate = XmlParserInputState::XmlParserContent;
            }
            return;
        };
        self.advance_with_line_handling(s.len_utf8());
        let mut cur = self.current_char();
        let mut buf = String::new();
        while let Some(nc) =
            cur.filter(|&cur| cur.is_xml_char() && (r != ']' || s != ']' || cur != '>'))
        {
            buf.push(r);
            if buf.len() > max_length {
                xml_fatal_err_msg(
                    self,
                    XmlParserErrors::XmlErrCDATANotFinished,
                    "CData section too big found\n",
                );
                if !matches!(self.instate, XmlParserInputState::XmlParserEOF) {
                    self.instate = XmlParserInputState::XmlParserContent;
                }
                return;
            }
            r = s;
            s = nc;
            self.advance_with_line_handling(nc.len_utf8());
            cur = self.current_char();
        }
        if matches!(self.instate, XmlParserInputState::XmlParserEOF) {
            return;
        }
        if cur != Some('>') {
            xml_fatal_err_msg_str!(
                self,
                XmlParserErrors::XmlErrCDATANotFinished,
                "CData section not finished\n{}\n",
                buf
            );
            // goto out;
            if !matches!(self.instate, XmlParserInputState::XmlParserEOF) {
                self.instate = XmlParserInputState::XmlParserContent;
            }
            return;
        }
        self.advance_with_line_handling(cur.map_or(0, |c| c.len_utf8()));

        // OK the buffer is to be consumed as cdata.
        if !self.disable_sax {
            if let Some(sax) = self.sax.as_deref_mut() {
                if let Some(cdata) = sax.cdata_block {
                    cdata(self, &buf);
                } else if let Some(characters) = sax.characters {
                    characters(self, &buf);
                }
            }
        }

        // out:
        if !matches!(self.instate, XmlParserInputState::XmlParserEOF) {
            self.instate = XmlParserInputState::XmlParserContent;
        }
    }
}