use std::io::Read;
use std::result;
use crate::xml::common::{Position, TextPosition};
pub use self::config::ParserConfig;
pub use self::events::XmlEvent;
use self::parser::PullParser;
mod config;
mod events;
mod lexer;
mod parser;
mod error;
pub use self::error::{Error, ErrorKind};
pub type Outcome<T> = result::Result<T, Error>;
pub struct EventReader<R: Read> {
source: R,
parser: PullParser,
}
impl<R: Read> EventReader<R> {
#[inline]
#[cfg(test)]
pub fn new(source: R) -> EventReader<R> {
EventReader::new_with_config(source, ParserConfig::new())
}
#[inline]
pub fn new_with_config(source: R, config: ParserConfig) -> EventReader<R> {
EventReader {
source,
parser: PullParser::new(config),
}
}
#[inline]
pub fn next_event(&mut self) -> Outcome<XmlEvent> {
self.parser.next(&mut self.source)
}
}
impl<B: Read> Position for EventReader<B> {
#[inline]
fn position(&self) -> TextPosition {
self.parser.position()
}
}
impl<R: Read> IntoIterator for EventReader<R> {
type Item = Outcome<XmlEvent>;
type IntoIter = Events<R>;
fn into_iter(self) -> Events<R> {
Events {
reader: self,
finished: false,
}
}
}
pub struct Events<R: Read> {
reader: EventReader<R>,
finished: bool,
}
impl<R: Read> Events<R> {
#[cfg(test)]
pub fn source_mut(&mut self) -> &mut R {
&mut self.reader.source
}
}
impl<R: Read> Iterator for Events<R> {
type Item = Outcome<XmlEvent>;
#[inline]
fn next(&mut self) -> Option<Outcome<XmlEvent>> {
if self.finished {
None
} else {
let ev = self.reader.next_event();
match ev {
Ok(XmlEvent::EndDocument) | Err(_) => self.finished = true,
_ => {}
}
Some(ev)
}
}
}