fastxml 0.8.1

A fast, memory-efficient XML library with XPath and XSD validation support
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
//! SAX-like event streaming for XML processing.
//!
//! This module provides an event-based interface for processing XML
//! that enables single-pass parsing with optional validation.

use std::any::Any;
use std::collections::HashMap;
use std::io::BufRead;
use std::sync::Arc;

use compact_str::CompactString;
use quick_xml::Reader;
use quick_xml::events::Event;

use crate::error::Result;
use crate::namespace::Namespace;
use crate::position::PositionTrackingReader;

/// String interner for reducing memory allocations.
///
/// Caches frequently used strings (element names, prefixes) to avoid
/// repeated allocations for the same string values.
#[derive(Debug, Default)]
struct StringInterner {
    cache: HashMap<Box<str>, Arc<str>>,
}

impl StringInterner {
    fn new() -> Self {
        Self {
            cache: HashMap::new(),
        }
    }

    /// Interns a string, returning a shared reference.
    ///
    /// If the string is already interned, returns the existing Arc.
    /// Otherwise, creates a new Arc and caches it.
    fn intern(&mut self, s: &str) -> Arc<str> {
        if let Some(interned) = self.cache.get(s) {
            Arc::clone(interned)
        } else {
            let arc: Arc<str> = Arc::from(s);
            self.cache.insert(s.into(), Arc::clone(&arc));
            arc
        }
    }

    /// Returns the number of interned strings.
    #[allow(dead_code)]
    fn len(&self) -> usize {
        self.cache.len()
    }
}

/// An XML event for streaming processing.
#[derive(Debug, Clone)]
pub enum XmlEvent {
    /// Start of an element
    StartElement {
        /// Local name of the element (interned)
        name: Arc<str>,
        /// Namespace prefix (interned, if any)
        prefix: Option<Arc<str>>,
        /// Namespace URI (if known)
        namespace: Option<String>,
        /// Attributes as (name, value) pairs (using CompactString to avoid heap allocation for short strings)
        attributes: Vec<(CompactString, CompactString)>,
        /// Namespace declarations on this element
        namespace_decls: Vec<Namespace>,
        /// Line number (1-indexed, if available)
        line: Option<usize>,
        /// Column number (1-indexed, in UTF-8 characters, if available)
        column: Option<usize>,
    },
    /// End of an element
    EndElement {
        /// Local name of the element (interned)
        name: Arc<str>,
        /// Namespace prefix (interned, if any)
        prefix: Option<Arc<str>>,
    },
    /// Text content
    Text(String),
    /// CDATA content
    CData(String),
    /// Comment
    Comment(String),
    /// Processing instruction
    ProcessingInstruction {
        /// Target name
        target: String,
        /// Instruction content
        content: Option<String>,
    },
    /// XML declaration
    Declaration {
        /// XML version
        version: Option<String>,
        /// Document encoding
        encoding: Option<String>,
        /// Standalone declaration
        standalone: Option<bool>,
    },
    /// End of document
    Eof,
}

/// Trait for handling XML events.
///
/// Implement this trait to process XML events during streaming parsing.
/// Multiple handlers can be attached to a single parser.
pub trait XmlEventHandler: Send + Any {
    /// Called for each XML event.
    ///
    /// Return `Ok(())` to continue processing, or an error to stop.
    fn handle(&mut self, event: &XmlEvent) -> Result<()>;

    /// Called when parsing is complete.
    ///
    /// This is called after the final Eof event, allowing handlers
    /// to perform final validation or cleanup.
    fn finish(&mut self) -> Result<()> {
        Ok(())
    }

    /// Returns self as Any for downcasting.
    fn as_any(self: Box<Self>) -> Box<dyn Any>;
}

/// A streaming XML parser that dispatches events to handlers.
pub struct StreamingParser<R: BufRead> {
    reader: Reader<PositionTrackingReader<R>>,
    handlers: Vec<Box<dyn XmlEventHandler>>,
    interner: StringInterner,
}

impl<R: BufRead> StreamingParser<R> {
    /// Creates a new streaming parser from a BufRead source.
    pub fn new(reader: R) -> Self {
        let position_reader = PositionTrackingReader::new(reader);
        let mut xml_reader = Reader::from_reader(position_reader);
        xml_reader.config_mut().trim_text(false);
        xml_reader.config_mut().expand_empty_elements = true;

        Self {
            reader: xml_reader,
            handlers: Vec::new(),
            interner: StringInterner::new(),
        }
    }

    /// Returns the current line number (1-indexed).
    fn current_line(&self) -> usize {
        self.reader.get_ref().line()
    }

    /// Returns the current column number (1-indexed, in UTF-8 characters).
    fn current_column(&self) -> usize {
        self.reader.get_ref().column()
    }

    /// Adds an event handler.
    pub fn add_handler(&mut self, handler: Box<dyn XmlEventHandler>) {
        self.handlers.push(handler);
    }

    /// Takes ownership of all handlers.
    pub fn into_handlers(self) -> Vec<Box<dyn XmlEventHandler>> {
        self.handlers
    }

    /// Parses the document, dispatching events to all handlers.
    pub fn parse(&mut self) -> Result<()> {
        let mut buffer = Vec::with_capacity(8 * 1024);

        loop {
            let event_result = self.reader.read_event_into(&mut buffer);
            let line = self.current_line();
            let column = self.current_column();

            match event_result {
                Ok(Event::Start(ref e)) => {
                    let event = convert_start_event(e, line, column, &mut self.interner)?;
                    self.dispatch_event(&event)?;
                }
                Ok(Event::Empty(ref e)) => {
                    let start_event = convert_start_event(e, line, column, &mut self.interner)?;
                    self.dispatch_event(&start_event)?;

                    // For empty elements, also dispatch end event
                    if let XmlEvent::StartElement {
                        ref name,
                        ref prefix,
                        ..
                    } = start_event
                    {
                        let end_event = XmlEvent::EndElement {
                            name: name.clone(),
                            prefix: prefix.clone(),
                        };
                        self.dispatch_event(&end_event)?;
                    }
                }
                Ok(Event::End(ref e)) => {
                    let name_bytes = e.name().as_ref().to_vec();
                    let full_name = std::str::from_utf8(&name_bytes)?;
                    let (prefix, name) = crate::namespace::split_qname(full_name);
                    let event = XmlEvent::EndElement {
                        name: self.interner.intern(name),
                        prefix: prefix.map(|p| self.interner.intern(p)),
                    };
                    self.dispatch_event(&event)?;
                }
                Ok(Event::Text(ref e)) => {
                    let text = e.unescape().map_err(|e| {
                        crate::parser::error::ParseError::TextDecodeError {
                            message: e.to_string(),
                        }
                    })?;
                    if !text.is_empty() {
                        let event = XmlEvent::Text(text.into_owned());
                        self.dispatch_event(&event)?;
                    }
                }
                Ok(Event::CData(ref e)) => {
                    let text = std::str::from_utf8(e.as_ref())?;
                    let event = XmlEvent::CData(text.to_string());
                    self.dispatch_event(&event)?;
                }
                Ok(Event::Comment(ref e)) => {
                    let text = std::str::from_utf8(e.as_ref())?;
                    let event = XmlEvent::Comment(text.to_string());
                    self.dispatch_event(&event)?;
                }
                Ok(Event::PI(ref e)) => {
                    let content = std::str::from_utf8(e.as_ref())?;
                    let parts: Vec<&str> = content.splitn(2, char::is_whitespace).collect();
                    let target = parts.first().unwrap_or(&"").to_string();
                    let pi_content = parts.get(1).map(|s| s.trim().to_string());
                    let event = XmlEvent::ProcessingInstruction {
                        target,
                        content: pi_content,
                    };
                    self.dispatch_event(&event)?;
                }
                Ok(Event::Decl(ref e)) => {
                    let version = e
                        .version()
                        .ok()
                        .map(|v| String::from_utf8_lossy(v.as_ref()).into_owned());
                    let encoding = e
                        .encoding()
                        .and_then(|r| r.ok())
                        .map(|v| String::from_utf8_lossy(v.as_ref()).into_owned());
                    let standalone = e
                        .standalone()
                        .and_then(|r| r.ok())
                        .map(|v| v.as_ref() == b"yes");
                    let event = XmlEvent::Declaration {
                        version,
                        encoding,
                        standalone,
                    };
                    self.dispatch_event(&event)?;
                }
                Ok(Event::DocType(_)) => {
                    // Skip DOCTYPE
                }
                Ok(Event::Eof) => {
                    let event = XmlEvent::Eof;
                    self.dispatch_event(&event)?;
                    break;
                }
                Err(e) => {
                    return Err(crate::parser::error::ParseError::AtPosition {
                        position: self.reader.get_ref().byte_offset() as u64,
                        message: e.to_string(),
                    }
                    .into());
                }
            }
            buffer.clear();
        }

        // Call finish on all handlers
        for handler in &mut self.handlers {
            handler.finish()?;
        }

        Ok(())
    }

    fn dispatch_event(&mut self, event: &XmlEvent) -> Result<()> {
        for handler in &mut self.handlers {
            handler.handle(event)?;
        }
        Ok(())
    }
}

fn convert_start_event(
    e: &quick_xml::events::BytesStart<'_>,
    line: usize,
    column: usize,
    interner: &mut StringInterner,
) -> Result<XmlEvent> {
    let name_bytes = e.name().as_ref().to_vec();
    let full_name = std::str::from_utf8(&name_bytes)?;
    let (prefix, name) = crate::namespace::split_qname(full_name);

    let mut namespace_decls = Vec::new();
    let mut attributes = Vec::new();

    for attr_result in e.attributes() {
        let attr = attr_result?;
        let key = std::str::from_utf8(attr.key.as_ref())?;
        let value = attr.unescape_value().map_err(|e| {
            crate::parser::error::ParseError::AttributeDecodeError {
                message: e.to_string(),
            }
        })?;

        if key == "xmlns" {
            namespace_decls.push(Namespace::default_ns(value.as_ref()));
        } else if let Some(ns_prefix) = key.strip_prefix("xmlns:") {
            namespace_decls.push(Namespace::new(ns_prefix, value.as_ref()));
        } else {
            attributes.push((
                CompactString::from(key),
                CompactString::from(value.as_ref()),
            ));
        }
    }

    Ok(XmlEvent::StartElement {
        name: interner.intern(name),
        prefix: prefix.map(|p| interner.intern(p)),
        namespace: None, // Would need namespace resolution
        attributes,
        namespace_decls,
        line: Some(line),
        column: Some(column),
    })
}

/// A simple handler that collects all events.
pub struct EventCollector {
    events: Vec<XmlEvent>,
}

impl EventCollector {
    /// Creates a new event collector.
    pub fn new() -> Self {
        Self { events: Vec::new() }
    }

    /// Returns the collected events.
    pub fn events(&self) -> &[XmlEvent] {
        &self.events
    }

    /// Takes ownership of the collected events.
    pub fn into_events(self) -> Vec<XmlEvent> {
        self.events
    }
}

impl Default for EventCollector {
    fn default() -> Self {
        Self::new()
    }
}

impl XmlEventHandler for EventCollector {
    fn handle(&mut self, event: &XmlEvent) -> Result<()> {
        self.events.push(event.clone());
        Ok(())
    }

    fn as_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

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

    #[test]
    fn test_streaming_parser() {
        let xml = r#"<root attr="value"><child>text</child></root>"#;
        let mut parser = StreamingParser::new(xml.as_bytes());

        let collector = EventCollector::new();
        parser.add_handler(Box::new(collector));

        parser.parse().unwrap();

        // Note: we can't access collector after it's been moved into the parser
        // This is a limitation of the current design
    }

    #[test]
    fn test_event_collector() {
        let mut collector = EventCollector::new();

        // Simulate events
        collector
            .handle(&XmlEvent::StartElement {
                name: Arc::from("root"),
                prefix: None,
                namespace: None,
                attributes: vec![],
                namespace_decls: vec![],
                line: Some(1),
                column: Some(1),
            })
            .unwrap();

        collector
            .handle(&XmlEvent::StartElement {
                name: Arc::from("child"),
                prefix: None,
                namespace: None,
                attributes: vec![],
                namespace_decls: vec![],
                line: Some(1),
                column: Some(1),
            })
            .unwrap();

        collector
            .handle(&XmlEvent::EndElement {
                name: Arc::from("child"),
                prefix: None,
            })
            .unwrap();

        collector
            .handle(&XmlEvent::EndElement {
                name: Arc::from("root"),
                prefix: None,
            })
            .unwrap();

        collector.handle(&XmlEvent::Eof).unwrap();

        let events = collector.into_events();
        assert_eq!(events.len(), 5);
    }
}