use std::fmt::Write as _;
use crate::error::Rejection;
pub(crate) fn is_xml_char(c: char) -> bool {
matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{FFFD}' | '\u{10000}'..)
}
pub(crate) struct Writer {
out: String,
open: Vec<&'static str>,
tag_open: bool,
error: Option<Rejection>,
}
impl Writer {
pub(crate) fn new() -> Self {
Self {
out: String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#),
open: Vec::new(),
tag_open: false,
error: None,
}
}
fn close_tag(&mut self) {
if self.tag_open {
self.out.push('>');
self.tag_open = false;
}
}
pub(crate) fn start(&mut self, name: &'static str) -> &mut Self {
self.close_tag();
self.out.push('<');
self.out.push_str(name);
self.open.push(name);
self.tag_open = true;
self
}
pub(crate) fn attr(&mut self, name: &str, value: impl std::fmt::Display) -> &mut Self {
debug_assert!(self.tag_open, "attribute outside a start tag");
let value = value.to_string();
if self.error.is_none()
&& let Some(bad) = value.chars().find(|&c| !is_xml_char(c))
{
self.error = Some(
Rejection::schema(
"[XML 1.0 §2.2 Char]",
format!(
"The value contains U+{:04X}, a character XML cannot carry.",
u32::from(bad)
),
)
.at(format!("{}/@{name}", self.open.join("/"))),
);
}
self.out.push(' ');
self.out.push_str(name);
self.out.push_str("=\"");
for c in value.chars() {
match c {
'&' => self.out.push_str("&"),
'<' => self.out.push_str("<"),
'>' => self.out.push_str(">"),
'"' => self.out.push_str("""),
'\t' | '\n' | '\r' => {
let _ = write!(self.out, "&#{};", u32::from(c));
}
c => self.out.push(c),
}
}
self.out.push('"');
self
}
pub(crate) fn opt_attr<T: std::fmt::Display>(
&mut self,
name: &str,
value: Option<&T>,
) -> &mut Self {
if let Some(v) = value {
self.attr(name, v);
}
self
}
pub(crate) fn end(&mut self) -> &mut Self {
let name = self.open.pop().expect("end without start");
if self.tag_open {
self.out.push_str("/>");
self.tag_open = false;
} else {
self.out.push_str("</");
self.out.push_str(name);
self.out.push('>');
}
self
}
pub(crate) fn finish(mut self) -> Result<String, Rejection> {
if let Some(e) = self.error.take() {
return Err(e);
}
while !self.open.is_empty() {
self.end();
}
Ok(self.out)
}
}