Skip to main content

pltrs_render/svg/
xml.rs

1//! matplotlib's `XMLWriter`: a streaming XML writer with one space of
2//! indentation per level, empty elements collapsed to `<tag/>` and
3//! attributes without a value left out.
4
5use std::borrow::Cow;
6
7/// An element attribute: name and value.
8pub type Attribute<'a> = (&'a str, String);
9
10/// The entity of a byte of character data, if it has one
11/// (`_escape_cdata`). Every byte escaped is ASCII, which in UTF-8 is never
12/// part of another character, so text can be escaped byte by byte.
13fn cdata_entity(byte: u8) -> Option<&'static str> {
14    match byte {
15        b'&' => Some("&amp;"),
16        b'<' => Some("&lt;"),
17        b'>' => Some("&gt;"),
18        _ => None,
19    }
20}
21
22/// The entity of a byte of an attribute holding both kinds of quotes
23/// (`_quote_escape_attrib`'s last case), if it has one.
24fn attribute_entity(byte: u8) -> Option<&'static str> {
25    match byte {
26        b'\'' => Some("&apos;"),
27        b'"' => Some("&quot;"),
28        _ => cdata_entity(byte),
29    }
30}
31
32/// Whether `text` has a byte `entity` escapes. The bytes are counted
33/// rather than searched for: a loop without an early exit, which the
34/// compiler runs over many bytes at once (a path's data can be megabytes
35/// long, and has none).
36fn needs_escaping(text: &str, entity: impl Fn(u8) -> Option<&'static str>) -> bool {
37    text.bytes().filter(|&byte| entity(byte).is_some()).count() > 0
38}
39
40/// Appends `text` to `out` with every byte `entity` escapes replaced by
41/// its entity, in one pass: what matplotlib's chain of `replace` calls
42/// gives, as no entity contains a character a later one replaces.
43fn push_escaped(out: &mut String, text: &str, entity: impl Fn(u8) -> Option<&'static str> + Copy) {
44    if !needs_escaping(text, entity) {
45        out.push_str(text);
46        return;
47    }
48    let mut copied = 0;
49    for (at, byte) in text.bytes().enumerate() {
50        if let Some(escaped) = entity(byte) {
51            out.push_str(&text[copied..at]);
52            out.push_str(escaped);
53            copied = at + 1;
54        }
55    }
56    out.push_str(&text[copied..]);
57}
58
59/// `_escape_cdata`: the text itself when it has nothing to escape.
60fn escape_cdata(text: &str) -> Cow<'_, str> {
61    if needs_escaping(text, cdata_entity) {
62        let mut escaped = String::with_capacity(text.len() + 16);
63        push_escaped(&mut escaped, text, cdata_entity);
64        Cow::Owned(escaped)
65    } else {
66        Cow::Borrowed(text)
67    }
68}
69
70/// `_escape_comment`: character data escaping plus a space between
71/// consecutive hyphens.
72fn escape_comment(text: &str) -> String {
73    let escaped = escape_cdata(text);
74    let mut out = String::with_capacity(escaped.len());
75    let mut chars = escaped.chars().peekable();
76    while let Some(c) = chars.next() {
77        out.push(c);
78        if c == '-' && chars.peek() == Some(&'-') {
79            out.push(' ');
80        }
81    }
82    out
83}
84
85/// Appends `value` to `out` quoted as `_quote_escape_attrib` quotes it:
86/// in double quotes unless it contains one, then in single quotes, then
87/// fully escaped in double quotes.
88fn push_attribute(out: &mut String, value: &str) {
89    if !value.contains('"') {
90        out.push('"');
91        push_escaped(out, value, cdata_entity);
92        out.push('"');
93    } else if !value.contains('\'') {
94        out.push('\'');
95        push_escaped(out, value, cdata_entity);
96        out.push('\'');
97    } else {
98        out.push('"');
99        push_escaped(out, value, attribute_entity);
100        out.push('"');
101    }
102}
103
104/// The deepest indentation written (matplotlib's 64-space buffer).
105const MAX_INDENT: usize = 64;
106
107/// Writes an XML document into a string, which [`take`](Self::take)
108/// hands out as it grows (matplotlib's `backend_svg.XMLWriter`).
109///
110/// ```
111/// use pltrs_render::XmlWriter;
112/// let mut xml = XmlWriter::new("");
113/// let svg = xml.start("svg", &[("width", "10pt".into())]);
114/// xml.element("title", "a < b", &[]);
115/// xml.close(svg);
116/// assert_eq!(xml.take(), "<svg width=\"10pt\">\n <title>a &lt; b</title>\n</svg>\n");
117/// assert_eq!(xml.take(), "");
118/// ```
119#[derive(Debug, Default)]
120pub struct XmlWriter {
121    out: String,
122    tags: Vec<String>,
123    /// Whether the last start tag still lacks its closing `>`.
124    open: bool,
125    data: String,
126}
127
128impl XmlWriter {
129    /// A writer appending to `prolog`.
130    pub fn new(prolog: &str) -> Self {
131        Self {
132            out: prolog.to_owned(),
133            ..Self::default()
134        }
135    }
136
137    fn indent(&mut self, depth: usize) {
138        self.out
139            .extend(std::iter::repeat_n(' ', depth.min(MAX_INDENT)));
140    }
141
142    /// Finishes a pending start tag and writes buffered character data.
143    fn flush(&mut self, indent: bool) {
144        if self.open {
145            self.out.push_str(if indent { ">\n" } else { ">" });
146            self.open = false;
147        }
148        if !self.data.is_empty() {
149            let data = std::mem::take(&mut self.data);
150            push_escaped(&mut self.out, &data, cdata_entity);
151        }
152    }
153
154    /// Opens an element; returns its depth for [`close`](Self::close).
155    pub fn start(&mut self, tag: &str, attributes: &[Attribute<'_>]) -> usize {
156        self.flush(true);
157        self.data.clear();
158        let tag = escape_cdata(tag).into_owned();
159        self.indent(self.tags.len());
160        self.out.push('<');
161        self.out.push_str(&tag);
162        self.tags.push(tag);
163        for (name, value) in attributes {
164            if !value.is_empty() {
165                self.out.push(' ');
166                push_escaped(&mut self.out, name, cdata_entity);
167                self.out.push('=');
168                push_attribute(&mut self.out, value);
169            }
170        }
171        self.open = true;
172        self.tags.len() - 1
173    }
174
175    /// Writes a comment.
176    pub fn comment(&mut self, text: &str) {
177        self.flush(true);
178        self.indent(self.tags.len());
179        self.out.push_str("<!-- ");
180        self.out.push_str(&escape_comment(text));
181        self.out.push_str(" -->\n");
182    }
183
184    /// Adds character data to the current element.
185    pub fn data(&mut self, text: &str) {
186        self.data.push_str(text);
187    }
188
189    /// Closes the current element; `indent` indents the end tag.
190    pub fn end(&mut self, indent: bool) {
191        let Some(tag) = self.tags.pop() else {
192            return;
193        };
194        if !self.data.is_empty() {
195            self.flush(indent);
196        } else if self.open {
197            self.open = false;
198            self.out.push_str("/>\n");
199            return;
200        }
201        if indent {
202            self.indent(self.tags.len());
203        }
204        self.out.push_str("</");
205        self.out.push_str(&tag);
206        self.out.push_str(">\n");
207    }
208
209    /// Closes every element down to and including depth `id`.
210    pub fn close(&mut self, id: usize) {
211        while self.tags.len() > id {
212            self.end(true);
213        }
214    }
215
216    /// Writes a whole element with optional character data.
217    pub fn element(&mut self, tag: &str, text: &str, attributes: &[Attribute<'_>]) {
218        self.start(tag, attributes);
219        if !text.is_empty() {
220            self.data(text);
221        }
222        self.end(false);
223    }
224
225    /// The open elements, outermost first, as their tags were escaped.
226    pub fn open_tags(&self) -> &[String] {
227        &self.tags
228    }
229
230    /// Whether `tag` names the innermost open element (matplotlib's check
231    /// of `end(tag)`).
232    pub fn closes(&self, tag: &str) -> bool {
233        self.tags.last().map(String::as_str) == Some(&*escape_cdata(tag))
234    }
235
236    /// The text written since the last call, which the writer forgets.
237    pub fn take(&mut self) -> String {
238        std::mem::take(&mut self.out)
239    }
240
241    /// The document written so far.
242    pub(crate) fn into_string(self) -> String {
243        self.out
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn escaping_is_matplotlibs_chain_of_replacements() {
253        let cdata = |text: &str| {
254            text.replace('&', "&amp;")
255                .replace('<', "&lt;")
256                .replace('>', "&gt;")
257        };
258        let quoted = |value: &str| {
259            if !value.contains('"') {
260                format!("\"{}\"", cdata(value))
261            } else if !value.contains('\'') {
262                format!("'{}'", cdata(value))
263            } else {
264                let escaped = value
265                    .replace('&', "&amp;")
266                    .replace('\'', "&apos;")
267                    .replace('"', "&quot;")
268                    .replace('<', "&lt;")
269                    .replace('>', "&gt;");
270                format!("\"{escaped}\"")
271            }
272        };
273        for text in [
274            "",
275            "M 0 0 L 1 1",
276            "a < b & c > d",
277            "&amp;&lt;",
278            "<<>>&&",
279            "é<ü>ß&€",
280            "say \"hi\"",
281            "it's \"both\" & <more>",
282            "'only single'",
283        ] {
284            assert_eq!(escape_cdata(text), cdata(text), "{text:?}");
285            let mut out = String::new();
286            push_attribute(&mut out, text);
287            assert_eq!(out, quoted(text), "{text:?}");
288        }
289        assert!(matches!(escape_cdata("M 0 0 L 1 1"), Cow::Borrowed(_)));
290    }
291
292    #[test]
293    fn writes_like_matplotlib() {
294        let mut w = XmlWriter::new("");
295        let svg = w.start("svg", &[("width", "10pt".into()), ("id", String::new())]);
296        w.start("defs", &[]);
297        w.element("style", "*{a: b}", &[("type", "text/css".into())]);
298        w.end(true);
299        w.start("g", &[]);
300        w.comment("a--b <c>");
301        w.element("path", "", &[("d", "M 0 0 \nz\n".into())]);
302        w.close(svg);
303        assert_eq!(
304            w.into_string(),
305            "<svg width=\"10pt\">\n <defs>\n  <style type=\"text/css\">*{a: b}</style>\n \
306             </defs>\n <g>\n  <!-- a- -b &lt;c&gt; -->\n  <path d=\"M 0 0 \nz\n\"/>\n </g>\n</svg>\n"
307        );
308    }
309
310    #[test]
311    fn end_tags_are_checked_against_the_open_element() {
312        let mut w = XmlWriter::new("");
313        w.start("a&b", &[]);
314        assert!(w.closes("a&b"));
315        assert!(!w.closes("a"));
316        w.end(true);
317        assert!(!w.closes("a&b"));
318        assert_eq!(w.take(), "<a&amp;b/>\n");
319    }
320
321    #[test]
322    fn quotes_attributes() {
323        let quoted = |value: &str| {
324            let mut out = String::new();
325            push_attribute(&mut out, value);
326            out
327        };
328        assert_eq!(quoted("a\"b"), "'a\"b'");
329        assert_eq!(quoted("a\"b'c"), "\"a&quot;b&apos;c\"");
330        assert_eq!(quoted("x<y"), "\"x&lt;y\"");
331    }
332}