use std::borrow::Cow;
use crate::xml::attribute::Attribute;
use crate::xml::common::XmlVersion;
use crate::xml::name::Name;
use crate::xml::namespace::Namespace;
#[derive(Debug)]
pub enum XmlEvent<'a> {
StartDocument {
version: XmlVersion,
encoding: Option<&'a str>,
standalone: Option<bool>,
},
#[cfg(test)]
ProcessingInstruction {
name: &'a str,
data: Option<&'a str>,
},
StartElement {
name: Name<'a>,
attributes: Cow<'a, [Attribute<'a>]>,
namespace: Cow<'a, Namespace>,
},
EndElement {
name: Option<Name<'a>>,
},
#[cfg(test)]
Comment(&'a str),
Characters(&'a str),
}
impl<'a> XmlEvent<'a> {
#[inline]
#[cfg(test)]
pub fn start_element<S>(name: S) -> StartElementBuilder<'a>
where
S: Into<Name<'a>>,
{
StartElementBuilder {
name: name.into(),
attributes: Vec::new(),
namespace: Namespace::empty(),
}
}
#[inline]
#[cfg(test)]
pub fn end_element() -> EndElementBuilder<'a> {
EndElementBuilder { name: None }
}
#[inline]
#[cfg(test)]
pub fn characters(data: &'a str) -> XmlEvent<'a> {
XmlEvent::Characters(data)
}
#[inline]
#[cfg(test)]
pub fn comment(data: &'a str) -> XmlEvent<'a> {
XmlEvent::Comment(data)
}
}
impl<'a> From<&'a str> for XmlEvent<'a> {
#[inline]
fn from(s: &'a str) -> XmlEvent<'a> {
XmlEvent::Characters(s)
}
}
pub struct EndElementBuilder<'a> {
name: Option<Name<'a>>,
}
impl<'a> From<EndElementBuilder<'a>> for XmlEvent<'a> {
fn from(b: EndElementBuilder<'a>) -> XmlEvent<'a> {
XmlEvent::EndElement { name: b.name }
}
}
pub struct StartElementBuilder<'a> {
name: Name<'a>,
attributes: Vec<Attribute<'a>>,
namespace: Namespace,
}
impl<'a> StartElementBuilder<'a> {
#[inline]
#[cfg(test)]
pub fn attr<N>(mut self, name: N, value: &'a str) -> StartElementBuilder<'a>
where
N: Into<Name<'a>>,
{
self.attributes.push(Attribute::new(name.into(), value));
self
}
#[inline]
#[cfg(test)]
pub fn ns<S1, S2>(mut self, prefix: S1, uri: S2) -> StartElementBuilder<'a>
where
S1: Into<String>,
S2: Into<String>,
{
self.namespace.put(prefix, uri);
self
}
}
impl<'a> From<StartElementBuilder<'a>> for XmlEvent<'a> {
#[inline]
fn from(b: StartElementBuilder<'a>) -> XmlEvent<'a> {
XmlEvent::StartElement {
name: b.name,
attributes: Cow::Owned(b.attributes),
namespace: Cow::Owned(b.namespace),
}
}
}