use core::iter::FusedIterator;
use core::result;
use crate::common::{Position, TextPosition};
pub use self::config::ParserConfig;
pub use self::config::ParserConfig2;
pub use self::error::{Error, ErrorKind};
pub use self::events::XmlEvent;
use self::parser::PullParser;
mod config;
mod events;
mod lexer;
mod parser;
mod error;
pub type Result<T, E = Error> = result::Result<T, E>;
pub struct EventReader<'a, S: Iterator<Item = &'a u8>> {
source: S,
parser: PullParser,
}
impl<'a, S: Iterator<Item = &'a u8>> EventReader<'a, S> {
#[inline]
pub fn new(source: S) -> EventReader<'a, S> {
EventReader::new_with_config(source, ParserConfig2::new())
}
#[inline]
pub fn new_with_config(source: S, config: impl Into<ParserConfig2>) -> EventReader<'a, S> {
EventReader { source, parser: PullParser::new(config) }
}
#[inline]
pub fn next(&mut self) -> Result<XmlEvent> {
self.parser.next(&mut self.source)
}
#[inline]
pub fn skip(&mut self) -> Result<()> {
let mut depth = 1;
while depth > 0 {
match self.next()? {
XmlEvent::StartElement { .. } => depth += 1,
XmlEvent::EndElement { .. } => depth -= 1,
XmlEvent::EndDocument => return Err(Error {
kind: ErrorKind::UnexpectedEof,
pos: self.parser.position(),
}),
_ => {},
}
}
Ok(())
}
pub fn source(&self) -> &S { &self.source }
pub fn source_mut(&mut self) -> &mut S { &mut self.source }
pub fn into_inner(self) -> S {
self.source
}
}
impl<'a, S: Iterator<Item = &'a u8>> Position for EventReader<'a, S> {
#[inline]
fn position(&self) -> TextPosition {
self.parser.position()
}
}
impl<'a, S: Iterator<Item = &'a u8>> IntoIterator for EventReader<'a, S> {
type Item = Result<XmlEvent>;
type IntoIter = Events<'a, S>;
fn into_iter(self) -> Events<'a, S> {
Events { reader: self, finished: false }
}
}
pub struct Events<'a, S: Iterator<Item = &'a u8>> {
reader: EventReader<'a, S>,
finished: bool,
}
impl<'a, S: Iterator<Item = &'a u8>> Events<'a, S> {
#[inline]
pub fn into_inner(self) -> EventReader<'a, S> {
self.reader
}
pub fn source(&self) -> &S { &self.reader.source }
pub fn source_mut(&mut self) -> &mut S { &mut self.reader.source }
}
impl<'a, S: Iterator<Item = &'a u8>> FusedIterator for Events<'a, S> {
}
impl<'a, S: Iterator<Item = &'a u8>> Iterator for Events<'a, S> {
type Item = Result<XmlEvent>;
#[inline]
fn next(&mut self) -> Option<Result<XmlEvent>> {
if self.finished && !self.reader.parser.is_ignoring_end_of_stream() {
None
} else {
let ev = self.reader.next();
if let Ok(XmlEvent::EndDocument) | Err(_) = ev {
self.finished = true;
}
Some(ev)
}
}
}
impl<'a> EventReader<'a, core::slice::Iter<'a, u8>> {
#[inline]
#[must_use]
pub fn from_str(source: &str) -> EventReader<core::slice::Iter<u8>> {
EventReader::new(source.as_bytes().into_iter())
}
}