use crate::element::{Element, ElementBuilder};
use crate::error::Result;
use std::collections::BTreeMap;
use std::io::Write;
use quick_xml::events::{BytesText, Event};
use quick_xml::Writer as EventWriter;
#[derive(Clone, Debug, Eq)]
pub enum Node {
Element(Element),
Text(String),
}
impl Node {
pub fn as_element(&self) -> Option<&Element> {
match *self {
Node::Element(ref e) => Some(e),
Node::Text(_) => None,
}
}
pub fn as_element_mut(&mut self) -> Option<&mut Element> {
match *self {
Node::Element(ref mut e) => Some(e),
Node::Text(_) => None,
}
}
pub fn into_element(self) -> Option<Element> {
match self {
Node::Element(e) => Some(e),
Node::Text(_) => None,
}
}
pub fn as_text(&self) -> Option<&str> {
match *self {
Node::Element(_) => None,
Node::Text(ref s) => Some(s),
}
}
pub fn as_text_mut(&mut self) -> Option<&mut String> {
match *self {
Node::Element(_) => None,
Node::Text(ref mut s) => Some(s),
}
}
pub fn into_text(self) -> Option<String> {
match self {
Node::Element(_) => None,
Node::Text(s) => Some(s),
}
}
#[doc(hidden)]
pub(crate) fn write_to_inner<W: Write>(
&self,
writer: &mut EventWriter<W>,
prefixes: &mut BTreeMap<Option<String>, String>,
) -> Result<()> {
match *self {
Node::Element(ref elmt) => elmt.write_to_inner(writer, prefixes)?,
Node::Text(ref s) => {
writer.write_event(Event::Text(BytesText::from_plain_str(s)))?;
}
}
Ok(())
}
}
impl<I> From<I> for Node
where
I: Into<Element>,
{
fn from(elm: I) -> Node {
Node::Element(elm.into())
}
}
impl From<String> for Node {
fn from(s: String) -> Node {
Node::Text(s)
}
}
impl<'a> From<&'a str> for Node {
fn from(s: &'a str) -> Node {
Node::Text(s.to_owned())
}
}
impl From<ElementBuilder> for Node {
fn from(builder: ElementBuilder) -> Node {
Node::Element(builder.build())
}
}
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(&Node::Element(ref elem1), &Node::Element(ref elem2)) => elem1 == elem2,
(&Node::Text(ref text1), &Node::Text(ref text2)) => text1 == text2,
_ => false,
}
}
}