1use std::borrow::Cow;
6
7pub type Attribute<'a> = (&'a str, String);
9
10fn cdata_entity(byte: u8) -> Option<&'static str> {
14 match byte {
15 b'&' => Some("&"),
16 b'<' => Some("<"),
17 b'>' => Some(">"),
18 _ => None,
19 }
20}
21
22fn attribute_entity(byte: u8) -> Option<&'static str> {
25 match byte {
26 b'\'' => Some("'"),
27 b'"' => Some("""),
28 _ => cdata_entity(byte),
29 }
30}
31
32fn 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
40fn 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
59fn 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
70fn 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
85fn 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
104const MAX_INDENT: usize = 64;
106
107#[derive(Debug, Default)]
120pub struct XmlWriter {
121 out: String,
122 tags: Vec<String>,
123 open: bool,
125 data: String,
126}
127
128impl XmlWriter {
129 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 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 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 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 pub fn data(&mut self, text: &str) {
186 self.data.push_str(text);
187 }
188
189 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 pub fn close(&mut self, id: usize) {
211 while self.tags.len() > id {
212 self.end(true);
213 }
214 }
215
216 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 pub fn open_tags(&self) -> &[String] {
227 &self.tags
228 }
229
230 pub fn closes(&self, tag: &str) -> bool {
233 self.tags.last().map(String::as_str) == Some(&*escape_cdata(tag))
234 }
235
236 pub fn take(&mut self) -> String {
238 std::mem::take(&mut self.out)
239 }
240
241 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('&', "&")
255 .replace('<', "<")
256 .replace('>', ">")
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('&', "&")
266 .replace('\'', "'")
267 .replace('"', """)
268 .replace('<', "<")
269 .replace('>', ">");
270 format!("\"{escaped}\"")
271 }
272 };
273 for text in [
274 "",
275 "M 0 0 L 1 1",
276 "a < b & c > d",
277 "&<",
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 <c> -->\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&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"b'c\"");
330 assert_eq!(quoted("x<y"), "\"x<y\"");
331 }
332}