Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// Copyright © 2025 Stephan Kunz
// Copyright © before 2025 Piotr Zolnierek

use std::fmt;
use std::io::{self, Write};

pub type Result = io::Result<()>;

/// The XmlWriter himself
pub struct XmlWriter<'a, W: Write> {
    /// element stack
    /// `bool` indicates element having children
    stack: Vec<(&'a str, bool)>,
    /// namespace stack
    ns_stack: Vec<Option<&'a str>>,
    writer: Box<W>,
    /// An XML namespace that all elements will be part of, unless `None`
    namespace: Option<&'a str>,
    /// If `true` it will
    /// - indent all opening elements
    /// - put closing elements into own line
    /// - elements without children are self-closing
    very_pretty: bool,
    /// if `true` current elem is open
    opened: bool,
    /// newline indicator
    newline: bool,
    /// if `true` current elem has children
    children: bool,
    /// if `true` current elem has only text_content
    text_content: bool,
}

impl<'a, W: Write> fmt::Debug for XmlWriter<'a, W> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Ok(write!(
            f,
            "XmlWriter {{ stack: {:?}, opened: {} }}",
            self.stack, self.opened
        )?)
    }
}

impl<'a, W: Write> XmlWriter<'a, W> {
    /// Create a new writer with `compact` output
    pub fn compact_mode(writer: W) -> XmlWriter<'a, W> {
        XmlWriter {
            stack: Vec::new(),
            ns_stack: Vec::new(),
            writer: Box::new(writer),
            namespace: None,
            very_pretty: false,
            opened: false,
            newline: false,
            children: false,
            text_content: false,
        }
    }

    /// Create a new writer with `pretty` output
    pub fn pretty_mode(writer: W) -> XmlWriter<'a, W> {
        XmlWriter {
            stack: Vec::new(),
            ns_stack: Vec::new(),
            writer: Box::new(writer),
            namespace: None,
            very_pretty: true,
            opened: false,
            newline: false,
            children: false,
            text_content: false,
        }
    }

    /// Switch to `compact` mode
    pub fn set_compact_mode(&mut self) {
        self.very_pretty = false;
    }

    /// Switch to `pretty` mode
    pub fn set_pretty_mode(&mut self) {
        self.very_pretty = true;
    }

    /// Get the namespace
    pub fn namespace(&self) -> Option<&'a str> {
        self.namespace
    }

    /// Set the namespace
    pub fn set_namespace(&mut self, namespace: &'a str) {
        self.namespace = Some(namespace);
    }

    /// Remove/Unset the namespace
    pub fn unset_namespace(&mut self) {
        self.namespace = None;
    }

    /// Write the DTD
    pub fn dtd(&mut self, encoding: &str) -> Result {
        self.write("<?xml version=\"1.0\" encoding=\"")?;
        self.write(encoding)?;
        self.write("\" ?>\n")
    }

    fn indent(&mut self) -> Result {
        let indent = self.stack.len();
        if self.very_pretty {
            if self.newline {
                self.write("\n")?;
            } else {
                self.newline = true;
            }
            for _ in 0..indent {
                self.write("  ")?;
            }
        }
        Ok(())
    }

    /// Write a namespace prefix for the current element,
    /// if there is one set
    fn ns_prefix(&mut self, namespace: Option<&'a str>) -> Result {
        if let Some(ns) = namespace {
            self.write(ns)?;
            self.write(":")?;
        }
        Ok(())
    }

    /// Writes namespace declarations (xmlns:xx) into the currently open element
    pub fn ns_decl(&mut self, ns_map: &Vec<(Option<&'a str>, &'a str)>) -> Result {
        if !self.opened {
            panic!(
                "Attempted to write namespace decl to elem, when no elem was opened, stack {:?}",
                self.stack
            );
        }

        for item in ns_map {
            let name = match item.0 {
                Some(pre) => "xmlns:".to_string() + pre,
                None => "xmlns".to_string(),
            };
            self.attr(&name, item.1)?;
        }
        Ok(())
    }

    /// Write a self-closing element like <br/>
    pub fn elem(&mut self, name: &str) -> Result {
        self.close_elem()?;
        self.indent()?;
        self.write("<")?;
        let ns = self.namespace;
        self.ns_prefix(ns)?;
        self.write(name)?;
        self.write("/>")
    }

    /// Write an element with inlined text content (escaped)
    pub fn elem_text(&mut self, name: &str, text: &str) -> Result {
        self.close_elem()?;
        self.indent()?;
        self.write("<")?;
        let ns = self.namespace;
        self.ns_prefix(ns)?;
        self.write(name)?;
        self.write(">")?;

        self.escape(text, false)?;

        self.write("</")?;
        self.write(name)?;
        self.write(">")
    }

    /// Begin an elem, make sure name contains only allowed chars
    pub fn begin_elem(&mut self, name: &'a str) -> Result {
        self.children = true;
        self.close_elem()?;
        // change previous elem to having children
        if let Some(mut previous) = self.stack.pop() {
            previous.1 = true;
            self.stack.push(previous);
        }
        self.indent()?;
        self.stack.push((name, false));
        self.ns_stack.push(self.namespace);
        self.write("<")?;
        self.opened = true;
        self.children = false;
        // stderr().write_fmt(format_args!("\nbegin {}", name));
        let ns = self.namespace;
        self.ns_prefix(ns)?;
        self.write(name)
    }

    /// Close an elem if open, do nothing otherwise
    fn close_elem(&mut self) -> Result {
        if self.opened {
            if self.very_pretty && !self.children {
                self.write("/>")?;
            } else {
                self.write(">")?;
            }
            self.opened = false;
        }
        Ok(())
    }

    /// End and elem
    pub fn end_elem(&mut self) -> Result {
        self.close_elem()?;
        let ns = self.ns_stack.pop().unwrap_or_else(
            || panic!("Attempted to close namespaced element without corresponding open namespace, stack {:?}", self.ns_stack)
        );
        match self.stack.pop() {
            Some((name, children)) => {
                if self.very_pretty {
                    // elem without children have been self-closed
                    if !children {
                        return Ok(());
                    }
                    if !self.text_content {
                        self.indent()?;
                    }
                    self.text_content = false;
                }
                self.write("</")?;
                self.ns_prefix(ns)?;
                self.write(name)?;
                self.write(">")?;
                Ok(())
            }
            None => panic!(
                "Attempted to close an elem, when none was open, stack {:?}",
                self.stack
            ),
        }
    }

    /// Begin an empty elem
    pub fn empty_elem(&mut self, name: &'a str) -> Result {
        self.children = true;
        self.close_elem()?;
        // change previous elem to having children
        if let Some(mut previous) = self.stack.pop() {
            previous.1 = true;
            self.stack.push(previous);
        }
        self.children = false;
        self.indent()?;
        self.write("<")?;
        let ns = self.namespace;
        self.ns_prefix(ns)?;
        self.write(name)?;
        self.write("/>")
    }

    /// Write an attr, make sure name and value contain only allowed chars.
    /// For an escaping version use `attr_esc`
    pub fn attr(&mut self, name: &str, value: &str) -> Result {
        if !self.opened {
            panic!(
                "Attempted to write attr to elem, when no elem was opened, stack {:?}",
                self.stack
            );
        }
        self.write(" ")?;
        self.write(name)?;
        self.write("=\"")?;
        self.write(value)?;
        self.write("\"")
    }

    /// Write an attr, make sure name contains only allowed chars
    pub fn attr_esc(&mut self, name: &str, value: &str) -> Result {
        if !self.opened {
            panic!(
                "Attempted to write attr to elem, when no elem was opened, stack {:?}",
                self.stack
            );
        }
        self.write(" ")?;
        self.escape(name, true)?;
        self.write("=\"")?;
        self.escape(value, false)?;
        self.write("\"")
    }

    /// Escape identifiers or text
    fn escape(&mut self, text: &str, ident: bool) -> Result {
        for c in text.chars() {
            match c {
                '"' => self.write("&quot;")?,
                '\'' => self.write("&apos;")?,
                '&' => self.write("&amp;")?,
                '<' => self.write("&lt;")?,
                '>' => self.write("&gt;")?,
                '\\' if ident => self.write("\\\\")?,
                _ => self.write_slice(c.encode_utf8(&mut [0; 4]).as_bytes())?,
            };
        }
        Ok(())
    }

    /// Write a text content, escapes the text automatically
    pub fn text(&mut self, text: &str) -> Result {
        self.children = true;
        self.close_elem()?;
        // change previous elem to having children
        if let Some(mut previous) = self.stack.pop() {
            previous.1 = true;
            self.stack.push(previous);
        }
        self.children = false;
        self.text_content = true;
        self.escape(text, false)
    }

    /// Raw write, no escaping, no safety net, use at own risk
    pub fn write(&mut self, text: &str) -> Result {
        self.writer.write_all(text.as_bytes())?;
        Ok(())
    }

    /// Raw write, no escaping, no safety net, use at own risk
    fn write_slice(&mut self, slice: &[u8]) -> Result {
        self.writer.write_all(slice)?;
        Ok(())
    }

    /// Write a CDATA
    pub fn cdata(&mut self, cdata: &str) -> Result {
        self.children = true;
        self.close_elem()?;
        // change previous elem to having children
        if let Some(mut previous) = self.stack.pop() {
            previous.1 = true;
            self.stack.push(previous);
        }
        if self.very_pretty {
            self.indent()?;
        }
        self.children = false;
        self.write("<![CDATA[")?;
        self.write(cdata)?;
        self.write("]]>")
    }

    /// Write a comment
    pub fn comment(&mut self, comment: &str) -> Result {
        self.children = true;
        self.close_elem()?;
        // change previous elem to having children
        if let Some(mut previous) = self.stack.pop() {
            previous.1 = true;
            self.stack.push(previous);
        }
        self.indent()?;
        self.children = false;
        self.write("<!-- ")?;
        self.escape(comment, false)?;
        self.write(" -->")
    }

    /// Close all open elems
    pub fn close(&mut self) -> Result {
        for _ in 0..self.stack.len() {
            self.end_elem()?;
        }
        Ok(())
    }

    /// Flush the underlying Writer
    pub fn flush(&mut self) -> Result {
        self.writer.flush()
    }

    /// Consume the XmlWriter and return the inner Writer
    pub fn into_inner(self) -> W {
        *self.writer
    }
}

#[allow(unused_must_use)]
#[cfg(test)]
mod tests {
    use super::XmlWriter;
    use std::str;

    fn create_xml(
        writer: &mut XmlWriter<'_, Vec<u8>>,
        nsmap: &Vec<(Option<&'static str>, &'static str)>,
    ) {
        writer.begin_elem("OTDS");
        writer.ns_decl(nsmap);
        writer.comment("nice to see you");
        writer.namespace = Some("st");
        writer.empty_elem("success");
        writer.begin_elem("node");
        writer.attr_esc("name", "\"123\"");
        writer.attr("id", "abc");
        writer.attr("'unescaped'", "\"123\""); // this WILL generate invalid xml
        writer.text("'text'");
        writer.end_elem();
        writer.namespace = None;
        writer.begin_elem("stuff");
        writer.cdata("blablab");
        // xml.end_elem();
        // xml.end_elem();
        writer.close();
        writer.flush();
    }

    #[test]
    fn compact() {
        let nsmap = vec![
            (None, "http://localhost/"),
            (Some("st"), "http://127.0.0.1/"),
        ];
        let mut writer = XmlWriter::compact_mode(Vec::new());

        create_xml(&mut writer, &nsmap);

        let actual = writer.into_inner();
        println!("{}", str::from_utf8(&actual).unwrap());
        assert_eq!(
            str::from_utf8(&actual).unwrap(),
            "<OTDS xmlns=\"http://localhost/\" xmlns:st=\"http://127.0.0.1/\"><!-- nice to see you --><st:success/><st:node name=\"&quot;123&quot;\" id=\"abc\" \'unescaped\'=\"\"123\"\">&apos;text&apos;</st:node><stuff><![CDATA[blablab]]></stuff></OTDS>"
        );
    }

    #[test]
    fn pretty() {
        let nsmap = vec![
            (None, "http://localhost/"),
            (Some("st"), "http://127.0.0.1/"),
        ];
        let mut writer = XmlWriter::pretty_mode(Vec::new());

        create_xml(&mut writer, &nsmap);

        let actual = writer.into_inner();
        println!("{}", str::from_utf8(&actual).unwrap());
        assert_eq!(
            str::from_utf8(&actual).unwrap(),
            "<OTDS xmlns=\"http://localhost/\" xmlns:st=\"http://127.0.0.1/\">\n  <!-- nice to see you -->\n  <st:success/>\n  <st:node name=\"&quot;123&quot;\" id=\"abc\" \'unescaped\'=\"\"123\"\">&apos;text&apos;</st:node>\n  <stuff>\n    <![CDATA[blablab]]>\n  </stuff>\n</OTDS>"
        );
    }

    #[test]
    fn comment() {
        let mut xml = XmlWriter::pretty_mode(Vec::new());
        xml.comment("comment");

        let actual = xml.into_inner();
        assert_eq!(str::from_utf8(&actual).unwrap(), "<!-- comment -->");

        let mut xml = XmlWriter::compact_mode(Vec::new());
        xml.comment("comment");

        let actual = xml.into_inner();
        assert_eq!(str::from_utf8(&actual).unwrap(), "<!-- comment -->");
    }
}