use std::borrow::Cow;
pub type Attribute<'a> = (&'a str, String);
fn cdata_entity(byte: u8) -> Option<&'static str> {
match byte {
b'&' => Some("&"),
b'<' => Some("<"),
b'>' => Some(">"),
_ => None,
}
}
fn attribute_entity(byte: u8) -> Option<&'static str> {
match byte {
b'\'' => Some("'"),
b'"' => Some("""),
_ => cdata_entity(byte),
}
}
fn needs_escaping(text: &str, entity: impl Fn(u8) -> Option<&'static str>) -> bool {
text.bytes().filter(|&byte| entity(byte).is_some()).count() > 0
}
fn push_escaped(out: &mut String, text: &str, entity: impl Fn(u8) -> Option<&'static str> + Copy) {
if !needs_escaping(text, entity) {
out.push_str(text);
return;
}
let mut copied = 0;
for (at, byte) in text.bytes().enumerate() {
if let Some(escaped) = entity(byte) {
out.push_str(&text[copied..at]);
out.push_str(escaped);
copied = at + 1;
}
}
out.push_str(&text[copied..]);
}
fn escape_cdata(text: &str) -> Cow<'_, str> {
if needs_escaping(text, cdata_entity) {
let mut escaped = String::with_capacity(text.len() + 16);
push_escaped(&mut escaped, text, cdata_entity);
Cow::Owned(escaped)
} else {
Cow::Borrowed(text)
}
}
fn escape_comment(text: &str) -> String {
let escaped = escape_cdata(text);
let mut out = String::with_capacity(escaped.len());
let mut chars = escaped.chars().peekable();
while let Some(c) = chars.next() {
out.push(c);
if c == '-' && chars.peek() == Some(&'-') {
out.push(' ');
}
}
out
}
fn push_attribute(out: &mut String, value: &str) {
if !value.contains('"') {
out.push('"');
push_escaped(out, value, cdata_entity);
out.push('"');
} else if !value.contains('\'') {
out.push('\'');
push_escaped(out, value, cdata_entity);
out.push('\'');
} else {
out.push('"');
push_escaped(out, value, attribute_entity);
out.push('"');
}
}
const MAX_INDENT: usize = 64;
#[derive(Debug, Default)]
pub struct XmlWriter {
out: String,
tags: Vec<String>,
open: bool,
data: String,
}
impl XmlWriter {
pub fn new(prolog: &str) -> Self {
Self {
out: prolog.to_owned(),
..Self::default()
}
}
fn indent(&mut self, depth: usize) {
self.out
.extend(std::iter::repeat_n(' ', depth.min(MAX_INDENT)));
}
fn flush(&mut self, indent: bool) {
if self.open {
self.out.push_str(if indent { ">\n" } else { ">" });
self.open = false;
}
if !self.data.is_empty() {
let data = std::mem::take(&mut self.data);
push_escaped(&mut self.out, &data, cdata_entity);
}
}
pub fn start(&mut self, tag: &str, attributes: &[Attribute<'_>]) -> usize {
self.flush(true);
self.data.clear();
let tag = escape_cdata(tag).into_owned();
self.indent(self.tags.len());
self.out.push('<');
self.out.push_str(&tag);
self.tags.push(tag);
for (name, value) in attributes {
if !value.is_empty() {
self.out.push(' ');
push_escaped(&mut self.out, name, cdata_entity);
self.out.push('=');
push_attribute(&mut self.out, value);
}
}
self.open = true;
self.tags.len() - 1
}
pub fn comment(&mut self, text: &str) {
self.flush(true);
self.indent(self.tags.len());
self.out.push_str("<!-- ");
self.out.push_str(&escape_comment(text));
self.out.push_str(" -->\n");
}
pub fn data(&mut self, text: &str) {
self.data.push_str(text);
}
pub fn end(&mut self, indent: bool) {
let Some(tag) = self.tags.pop() else {
return;
};
if !self.data.is_empty() {
self.flush(indent);
} else if self.open {
self.open = false;
self.out.push_str("/>\n");
return;
}
if indent {
self.indent(self.tags.len());
}
self.out.push_str("</");
self.out.push_str(&tag);
self.out.push_str(">\n");
}
pub fn close(&mut self, id: usize) {
while self.tags.len() > id {
self.end(true);
}
}
pub fn element(&mut self, tag: &str, text: &str, attributes: &[Attribute<'_>]) {
self.start(tag, attributes);
if !text.is_empty() {
self.data(text);
}
self.end(false);
}
pub fn open_tags(&self) -> &[String] {
&self.tags
}
pub fn closes(&self, tag: &str) -> bool {
self.tags.last().map(String::as_str) == Some(&*escape_cdata(tag))
}
pub fn take(&mut self) -> String {
std::mem::take(&mut self.out)
}
pub(crate) fn into_string(self) -> String {
self.out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escaping_is_matplotlibs_chain_of_replacements() {
let cdata = |text: &str| {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
};
let quoted = |value: &str| {
if !value.contains('"') {
format!("\"{}\"", cdata(value))
} else if !value.contains('\'') {
format!("'{}'", cdata(value))
} else {
let escaped = value
.replace('&', "&")
.replace('\'', "'")
.replace('"', """)
.replace('<', "<")
.replace('>', ">");
format!("\"{escaped}\"")
}
};
for text in [
"",
"M 0 0 L 1 1",
"a < b & c > d",
"&<",
"<<>>&&",
"é<ü>ß&€",
"say \"hi\"",
"it's \"both\" & <more>",
"'only single'",
] {
assert_eq!(escape_cdata(text), cdata(text), "{text:?}");
let mut out = String::new();
push_attribute(&mut out, text);
assert_eq!(out, quoted(text), "{text:?}");
}
assert!(matches!(escape_cdata("M 0 0 L 1 1"), Cow::Borrowed(_)));
}
#[test]
fn writes_like_matplotlib() {
let mut w = XmlWriter::new("");
let svg = w.start("svg", &[("width", "10pt".into()), ("id", String::new())]);
w.start("defs", &[]);
w.element("style", "*{a: b}", &[("type", "text/css".into())]);
w.end(true);
w.start("g", &[]);
w.comment("a--b <c>");
w.element("path", "", &[("d", "M 0 0 \nz\n".into())]);
w.close(svg);
assert_eq!(
w.into_string(),
"<svg width=\"10pt\">\n <defs>\n <style type=\"text/css\">*{a: b}</style>\n \
</defs>\n <g>\n <!-- a- -b <c> -->\n <path d=\"M 0 0 \nz\n\"/>\n </g>\n</svg>\n"
);
}
#[test]
fn end_tags_are_checked_against_the_open_element() {
let mut w = XmlWriter::new("");
w.start("a&b", &[]);
assert!(w.closes("a&b"));
assert!(!w.closes("a"));
w.end(true);
assert!(!w.closes("a&b"));
assert_eq!(w.take(), "<a&b/>\n");
}
#[test]
fn quotes_attributes() {
let quoted = |value: &str| {
let mut out = String::new();
push_attribute(&mut out, value);
out
};
assert_eq!(quoted("a\"b"), "'a\"b'");
assert_eq!(quoted("a\"b'c"), "\"a"b'c\"");
assert_eq!(quoted("x<y"), "\"x<y\"");
}
}