1use std::borrow::Cow;
7use std::fmt;
8
9pub const INDENT: &str = " ";
11
12const REPLACEMENT: char = '?';
14
15pub trait AttrValue {
17 fn attr_string(&self) -> Cow<'_, str>;
19}
20
21impl AttrValue for str {
22 fn attr_string(&self) -> Cow<'_, str> {
23 Cow::Borrowed(self)
24 }
25}
26
27impl AttrValue for String {
28 fn attr_string(&self) -> Cow<'_, str> {
29 Cow::Borrowed(self)
30 }
31}
32
33impl AttrValue for Cow<'_, str> {
34 fn attr_string(&self) -> Cow<'_, str> {
35 Cow::Borrowed(self)
36 }
37}
38
39impl AttrValue for bool {
40 fn attr_string(&self) -> Cow<'_, str> {
41 Cow::Borrowed(if *self { "True" } else { "False" })
42 }
43}
44
45impl AttrValue for f64 {
46 fn attr_string(&self) -> Cow<'_, str> {
47 Cow::Owned(crate::py::float_repr(*self))
48 }
49}
50
51impl AttrValue for f32 {
52 fn attr_string(&self) -> Cow<'_, str> {
53 Cow::Owned(crate::py::float_repr(*self as f64))
54 }
55}
56
57macro_rules! int_attr {
58 ($($t:ty),*) => {$(
59 impl AttrValue for $t {
60 fn attr_string(&self) -> Cow<'_, str> {
61 Cow::Owned(self.to_string())
62 }
63 }
64 )*};
65}
66int_attr!(
67 u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize
68);
69
70impl<T: AttrValue + ?Sized> AttrValue for &T {
71 fn attr_string(&self) -> Cow<'_, str> {
72 (**self).attr_string()
73 }
74}
75
76pub type Attrs<'a> = [(&'a str, &'a dyn AttrValue)];
78
79pub struct XmlWriter {
81 out: String,
82 indent_white: String,
83 newline_str: String,
84 indent_level: usize,
85 stack: Vec<String>,
86 need_indent: bool,
87}
88
89impl fmt::Debug for XmlWriter {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.debug_struct("XmlWriter")
92 .field("len", &self.out.len())
93 .field("indent_level", &self.indent_level)
94 .field("stack", &self.stack)
95 .finish()
96 }
97}
98
99impl Default for XmlWriter {
100 fn default() -> Self {
101 Self::new()
102 }
103}
104
105impl XmlWriter {
106 pub fn new() -> Self {
109 Self::with_options(INDENT, "\n")
110 }
111
112 pub fn with_options(indent_white: &str, newline_str: &str) -> Self {
115 let mut w = XmlWriter {
116 out: String::new(),
117 indent_white: indent_white.into(),
118 newline_str: newline_str.into(),
119 indent_level: 0,
120 stack: Vec::new(),
121 need_indent: true,
122 };
123 w.write_raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", true);
124 w.newline();
125 w
126 }
127
128 pub fn indent_white(&self) -> &str {
130 &self.indent_white
131 }
132
133 pub fn indent_level(&self) -> usize {
135 self.indent_level
136 }
137
138 pub fn newline_str(&self) -> &str {
140 &self.newline_str
141 }
142
143 pub fn as_str(&self) -> &str {
145 &self.out
146 }
147
148 pub fn into_string(self) -> String {
150 self.out
151 }
152
153 pub fn write(&mut self, s: &str) {
155 let escaped = escape(s);
156 self.write_raw(&escaped, true);
157 }
158
159 pub fn write_with_indent(&mut self, s: &str, indent: bool) {
161 let escaped = escape(s);
162 self.write_raw(&escaped, indent);
163 }
164
165 pub fn writecdata(&mut self, s: &str) {
167 let s = s.replace("]]>", "]]]]><![CDATA[>");
168 self.write_raw(&format!("<![CDATA[{s}]]>"), true);
169 }
170
171 pub fn write8bit(&mut self, data: &[u8], strip: bool) {
175 let s = escape8bit(data);
176 let s = if strip { s.trim() } else { &s };
177 self.write_raw(s, true);
178 }
179
180 pub fn write_noindent(&mut self, s: &str) {
182 let escaped = escape(s);
183 self.write_raw(&escaped, false);
184 }
185
186 pub fn write_raw(&mut self, data: &str, indent: bool) {
188 if indent && self.need_indent {
189 for _ in 0..self.indent_level {
190 self.out.push_str(&self.indent_white);
191 }
192 self.need_indent = false;
193 }
194 self.out.push_str(data);
195 }
196
197 pub fn newline(&mut self) {
199 self.out.push_str(&self.newline_str);
200 self.need_indent = true;
201 }
202
203 pub fn comment(&mut self, data: &str) {
205 let data = escape(data);
206 let mut lines = data.split('\n');
207 let first = lines.next().unwrap_or_default();
208 self.write_raw(&format!("<!-- {first}"), true);
209 for line in lines {
210 self.newline();
211 self.write_raw(&format!(" {line}"), true);
212 }
213 self.write_raw(" -->", true);
214 }
215
216 pub fn simpletag(&mut self, tag: &str, attrs: &Attrs<'_>) {
219 let data = format!("<{tag}{}/>", stringify_attrs_sorted(attrs));
220 self.write_raw(&data, true);
221 }
222
223 pub fn simpletag_ordered(&mut self, tag: &str, attrs: &Attrs<'_>) {
226 let data = format!("<{tag}{}/>", stringify_attrs(attrs));
227 self.write_raw(&data, true);
228 }
229
230 pub fn begintag(&mut self, tag: &str, attrs: &Attrs<'_>) {
232 let data = format!("<{tag}{}>", stringify_attrs_sorted(attrs));
233 self.open(tag, &data);
234 }
235
236 pub fn begintag_ordered(&mut self, tag: &str, attrs: &Attrs<'_>) {
239 let data = format!("<{tag}{}>", stringify_attrs(attrs));
240 self.open(tag, &data);
241 }
242
243 fn open(&mut self, tag: &str, data: &str) {
244 self.write_raw(data, true);
245 self.stack.push(tag.into());
246 self.indent();
247 }
248
249 pub fn endtag(&mut self, tag: &str) {
256 assert!(
257 self.stack.last().is_some_and(|t| t == tag),
258 "nonmatching endtag: {tag}"
259 );
260 self.stack.pop();
261 self.dedent();
262 self.write_raw(&format!("</{tag}>"), true);
263 }
264
265 pub fn dumphex(&mut self, data: &[u8]) {
268 const LINE_LENGTH: usize = 16;
269 const HEX_LINE_LENGTH: usize = LINE_LENGTH * 2;
270 const CHUNK_SIZE: usize = 8;
271 for chunk in data.chunks(LINE_LENGTH) {
272 let hexline = crate::text_tools::hex_str(chunk);
273 let mut line = String::with_capacity(HEX_LINE_LENGTH + 3);
274 for j in (0..HEX_LINE_LENGTH).step_by(CHUNK_SIZE) {
275 if j > 0 {
276 line.push(' ');
277 }
278 let end = (j + CHUNK_SIZE).min(hexline.len());
279 if j < end {
280 line.push_str(&hexline[j..end]);
281 }
282 }
283 self.write_raw(&line, true);
284 self.newline();
285 }
286 }
287
288 pub fn indent(&mut self) {
290 self.indent_level += 1;
291 }
292
293 pub fn dedent(&mut self) {
295 debug_assert!(self.indent_level > 0);
296 self.indent_level = self.indent_level.saturating_sub(1);
297 }
298}
299
300pub fn stringify_attrs(attrs: &Attrs<'_>) -> String {
302 let mut data = String::new();
303 for (name, value) in attrs {
304 data.push(' ');
305 data.push_str(name);
306 data.push_str("=\"");
307 data.push_str(&escape_attr(&value.attr_string()));
308 data.push('"');
309 }
310 data
311}
312
313pub fn stringify_attrs_sorted(attrs: &Attrs<'_>) -> String {
315 let mut sorted: Vec<_> = attrs.to_vec();
316 sorted.sort_by(|a, b| a.0.cmp(b.0));
317 stringify_attrs(&sorted)
318}
319
320fn is_illegal_xml_char(c: char) -> bool {
321 matches!(c as u32, 0x00..=0x08 | 0x0B | 0x0C | 0x0E..=0x1F | 0xFFFE | 0xFFFF)
322}
323
324pub fn escape(data: &str) -> Cow<'_, str> {
327 if !data
328 .chars()
329 .any(|c| matches!(c, '&' | '<' | '>' | '\r') || is_illegal_xml_char(c))
330 {
331 return Cow::Borrowed(data);
332 }
333 let mut out = String::with_capacity(data.len() + 8);
334 let mut illegal = false;
335 for c in data.chars() {
336 match c {
337 '&' => out.push_str("&"),
338 '<' => out.push_str("<"),
339 '>' => out.push_str(">"),
340 '\r' => out.push_str(" "),
341 c if is_illegal_xml_char(c) => {
342 illegal = true;
343 out.push(REPLACEMENT);
344 }
345 c => out.push(c),
346 }
347 }
348 if illegal {
349 let escaped: String = data
352 .replace('&', "&")
353 .replace('<', "<")
354 .replace('>', ">")
355 .replace('\r', " ");
356 let preview = if escaped.chars().count() > 10 {
357 let head: String = escaped.chars().take(10).collect();
358 let repr = crate::py::str_repr(&head);
359 format!("{}...", &repr[1..repr.len() - 1])
360 } else {
361 crate::py::str_repr(&escaped)
362 };
363 log::warn!(
364 "Illegal XML character(s) found; replacing offending string {} with '{REPLACEMENT}'",
365 crate::py::str_repr(&preview)
366 );
367 }
368 Cow::Owned(out)
369}
370
371pub fn escape_attr(data: &str) -> Cow<'_, str> {
373 match escape(data) {
374 Cow::Borrowed(s) if !s.contains('"') => Cow::Borrowed(s),
375 s => Cow::Owned(s.replace('"', """)),
376 }
377}
378
379pub fn escape8bit(data: &[u8]) -> String {
382 let mut out = String::with_capacity(data.len());
383 for &b in data {
384 if (32..=127).contains(&b) && !matches!(b, b'<' | b'&' | b'>') {
385 out.push(b as char);
386 } else {
387 out.push_str("&#");
388 out.push_str(&b.to_string());
389 out.push(';');
390 }
391 }
392 out
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
400
401 const HEADER: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
402
403 #[test]
404 fn test_comment_escaped() {
405 let mut w = XmlWriter::new();
406 w.comment("This&that are <comments>");
407 assert_eq!(
408 w.as_str(),
409 format!("{HEADER}<!-- This&that are <comments> -->")
410 );
411 }
412
413 #[test]
414 fn test_comment_multiline() {
415 let mut w = XmlWriter::new();
416 w.comment("Hello world\nHow are you?");
417 assert_eq!(
418 w.as_str(),
419 format!("{HEADER}<!-- Hello world\n How are you? -->")
420 );
421 }
422
423 #[test]
424 fn test_encoding_default() {
425 assert_eq!(XmlWriter::new().as_str(), HEADER);
426 }
427
428 #[test]
429 fn test_write() {
430 let mut w = XmlWriter::new();
431 w.write("foo&bar");
432 assert_eq!(w.as_str(), format!("{HEADER}foo&bar"));
433 }
434
435 #[test]
436 fn test_indent_dedent() {
437 let mut w = XmlWriter::new();
438 w.write("foo");
439 w.newline();
440 w.indent();
441 w.write("bar");
442 w.newline();
443 w.dedent();
444 w.write("baz");
445 assert_eq!(w.as_str(), format!("{HEADER}foo\n bar\nbaz"));
446 }
447
448 #[test]
449 fn test_writecdata() {
450 let mut w = XmlWriter::new();
451 w.writecdata("foo&bar");
452 assert_eq!(w.as_str(), format!("{HEADER}<![CDATA[foo&bar]]>"));
453 }
454
455 #[test]
456 fn test_writecdata_split_terminator() {
457 let mut w = XmlWriter::new();
458 w.writecdata("foo]]><tag/>bar");
459 assert_eq!(
460 w.as_str(),
461 format!("{HEADER}<![CDATA[foo]]]]><![CDATA[><tag/>bar]]>")
462 );
463 }
464
465 #[test]
466 fn test_simpletag() {
467 let mut w = XmlWriter::new();
468 w.simpletag("tag", &[("b", &"2"), ("a", &"1")]);
469 assert_eq!(w.as_str(), format!("{HEADER}<tag a=\"1\" b=\"2\"/>"));
470 }
471
472 #[test]
473 fn test_begintag_endtag() {
474 let mut w = XmlWriter::new();
475 w.begintag("tag", &[("attr", &"value")]);
476 w.write("content");
477 w.endtag("tag");
478 assert_eq!(
479 w.as_str(),
480 format!("{HEADER}<tag attr=\"value\">content</tag>")
481 );
482 }
483
484 #[test]
485 fn test_dumphex() {
486 let mut w = XmlWriter::new();
487 w.dumphex(b"Type is a beautiful group of letters, not a group of beautiful letters.");
488 let expected = [
489 "54797065 20697320 61206265 61757469",
490 "66756c20 67726f75 70206f66 206c6574",
491 "74657273 2c206e6f 74206120 67726f75",
492 "70206f66 20626561 75746966 756c206c",
493 "65747465 72732e ",
494 "",
495 ]
496 .join("\n");
497 assert_eq!(w.as_str(), format!("{HEADER}{expected}"));
498 }
499
500 #[test]
501 fn test_stringifyattrs() {
502 assert_eq!(stringify_attrs(&[("attr", &0)]), " attr=\"0\"");
503 assert_eq!(stringify_attrs(&[("attr", &"0")]), " attr=\"0\"");
504 }
505
506 #[test]
507 fn test_carriage_return_escaped() {
508 let mut w = XmlWriter::new();
509 w.write("two lines\r\nseparated by Windows line endings");
510 assert_eq!(
511 w.as_str(),
512 format!("{HEADER}two lines \nseparated by Windows line endings")
513 );
514 }
515
516 #[test]
517 fn test_newlinestr() {
518 let header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
519 for nls in ["\n", "\r\n", "\r", ""] {
520 let mut w = XmlWriter::with_options(INDENT, nls);
521 w.write("hello");
522 w.newline();
523 w.write("world");
524 w.newline();
525 assert_eq!(w.as_str(), format!("{header}{nls}hello{nls}world{nls}"));
526 }
527 }
528
529 #[test]
530 fn illegal_characters() {
531 assert_eq!(escape("a\u{1}b\u{FFFE}"), "a?b?");
532 assert_eq!(escape_attr("\"x\""), ""x"");
533 assert_eq!(escape8bit(b"a<\x00\x7f\x80"), "a<�\x7f€");
534 }
535}