anyxml 0.14.0

A fully spec-conformant XML library
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! StAX style XML writer.
//!
//! By writing events in the proper sequence, it is possible to obtain a serialized XML document.
//!
//! Internally, the serialized representation of the written events is also forwarded to the
//! parser to prevent the writing of ill-formed XML.  \
//! If DTD validation is enabled via parser options, the system performs not only well-formedness
//! checks but also validity checks based on the written DTD.
//!
//! To receive all errors, it is necessary to set up an error handler.

use std::{borrow::Cow, io::Write};

use crate::{
    encoding::{Encoder, UTF8Encoder, find_encoder},
    error::XMLError,
    parse::ParseError,
    sax::{
        DefaultSAXHandler, INPUT_CHUNK, ParserConfig, ProgressiveParserSpec, SAXHandler, XMLReader,
    },
    uri::URIString,
};

struct OutputStream<'a> {
    stream: Box<dyn Write + 'a>,
    buffer: Vec<u8>,
    encoder: Box<dyn Encoder>,
}

impl OutputStream<'_> {
    fn write(&mut self, mut data: &str) -> Result<(), XMLError> {
        while !data.is_empty() {
            let (read, write) = self.encoder.encode(data, &mut self.buffer, false)?;
            data = &data[read..];
            self.stream.write_all(&self.buffer[..write])?;
        }
        Ok(())
    }

    fn flush(&mut self) -> Result<(), XMLError> {
        self.stream.flush()?;
        Ok(())
    }
}

impl Default for OutputStream<'_> {
    fn default() -> Self {
        Self {
            stream: Box::new(vec![]),
            buffer: vec![0; INPUT_CHUNK],
            encoder: Box::new(UTF8Encoder),
        }
    }
}

enum State {
    BeforeStart,
    StartDTD,
    InDTD,
    StartElement,
    InContent,
    Finished,
}

/// StAX style XML writer.
///
/// By default, the writer checks the well-formedness constraints of the XML string
/// representation corresponding to the written event.  \
/// By passing a parser configuration to each constructor, it is also possible to perform
/// DTD validation or retrieve external resources.
pub struct XMLStreamWriter<'a, H: SAXHandler = DefaultSAXHandler> {
    stream: OutputStream<'a>,
    checker: XMLReader<ProgressiveParserSpec, H>,
    // QName
    name_stack: Vec<String>,
    // (namespace, prefix, depth)
    ns_stack: Vec<(String, String, usize)>,
    state: State,
    /// If the default namespace is bound and an element with a namespace of NULL is
    /// written as an unqualified name, the meaning changes. Set this flag to `true`
    /// when it is necessary to remove the default namespace to prevent this.
    should_insert_default_namespace: bool,
}

macro_rules! write_tokens {
    ( $self:expr, $( $e:expr ),* ) => {
        $(
            $self.checker.parse_chunk($e.as_bytes(), false)?;
        )*
        $(
            $self.stream.write($e)?;
        )*
    };
}

impl<'a> XMLStreamWriter<'a> {
    /// Constructor for [`XMLStreamWriter`].
    pub fn new(writer: impl Write + 'a, config: Option<ParserConfig>) -> Self {
        let stream = OutputStream {
            stream: Box::new(writer),
            ..Default::default()
        };

        Self {
            stream,
            checker: XMLReader::builder()
                .progressive_parser()
                .set_parser_config(config.unwrap_or_default())
                .build(),
            name_stack: vec![],
            ns_stack: vec![],
            state: State::BeforeStart,
            should_insert_default_namespace: false,
        }
    }
}

impl<'a, H: SAXHandler> XMLStreamWriter<'a, H> {
    /// Constructor for [`XMLStreamWriter`].
    ///
    /// It is possible to pass a custom handler to capture all errors or to sanitize
    /// external resources accessed by write events.
    pub fn with_handler(writer: impl Write + 'a, handler: H, config: Option<ParserConfig>) -> Self {
        let stream = OutputStream {
            stream: Box::new(writer),
            ..Default::default()
        };

        Self {
            stream,
            checker: XMLReader::builder()
                .progressive_parser()
                .set_handler(handler)
                .set_parser_config(config.unwrap_or_default())
                .build(),
            name_stack: vec![],
            ns_stack: vec![],
            state: State::BeforeStart,
            should_insert_default_namespace: false,
        }
    }

    /// Set the base URI of written XML document.
    ///
    /// In some cases, such as when retrieving external resources, it may be necessary
    /// to configure an appropriate base URI.
    pub fn set_base_uri(&mut self, base_uri: impl Into<URIString>) -> Result<(), XMLError> {
        self.checker.set_default_base_uri(base_uri.into())
    }

    /// Write XML declaration.
    ///
    /// The writer changes the encoder based on the specified encoding. If no encoder
    /// corresponding to the specified encoding is registered, an error occurs.
    pub fn write_declaration(
        &mut self,
        version: &str,
        encoding: Option<&str>,
        standalone: Option<bool>,
    ) -> Result<(), XMLError> {
        let encoding = if let Some(encoding) = encoding {
            self.stream.encoder = find_encoder(encoding)
                .ok_or(XMLError::XMLParseError(ParseError::UnsupportedEncoding))?;
            Cow::Owned(format!(" encoding=\"{encoding}\""))
        } else {
            Cow::Borrowed("")
        };
        let standalone =
            standalone.map(|s| format!(" standalone=\"{}\"", if s { "yes" } else { "no" }));
        let standalone = standalone.as_deref().unwrap_or_default();
        write_tokens!(
            self,
            "<?xml version=\"",
            version,
            "\"",
            encoding.as_ref(),
            standalone,
            "?>"
        );
        Ok(())
    }

    /// Write the beginning of DTD.
    pub fn write_start_dtd(
        &mut self,
        name: &str,
        public_id: Option<&str>,
        system_id: Option<&str>,
    ) -> Result<(), XMLError> {
        let system_id = system_id.map(|s| {
            format!(
                " {}\"{s}\"",
                if public_id.is_some() { "" } else { "SYSTEM " }
            )
        });
        let system_id = system_id.as_deref().unwrap_or_default();
        let public_id = public_id.map(|p| format!(" PUBLIC \"{p}\""));
        let public_id = public_id.as_deref().unwrap_or_default();
        write_tokens!(self, "<!DOCTYPE ", name, public_id, system_id);
        self.state = State::StartDTD;
        Ok(())
    }
    /// Write the end of DTD.
    pub fn write_end_dtd(&mut self) -> Result<(), XMLError> {
        if matches!(self.state, State::StartDTD) {
            write_tokens!(self, ">");
        } else {
            write_tokens!(self, "]>");
        }
        Ok(())
    }
    /// Write an element declaration.
    pub fn write_element_decl(&mut self, name: &str, contentspec: &str) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        write_tokens!(self, "<!ELEMENT ", name, " ", contentspec, ">");
        Ok(())
    }
    /// Write an attribute list declaration.
    pub fn write_attribute_decl(
        &mut self,
        element_name: &str,
        attribute_name: &str,
        attribute_type: &str,
        default_decl: &str,
    ) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        write_tokens!(
            self,
            "<!ATTLIST ",
            element_name,
            " ",
            attribute_name,
            " ",
            attribute_type,
            " ",
            default_decl,
            ">"
        );
        Ok(())
    }
    /// Write an internal entity declaration.
    pub fn write_internal_entity_decl(&mut self, name: &str, value: &str) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        write_tokens!(self, "<!ENTITY ", name, " \"", value, "\">");
        Ok(())
    }
    /// Write an external entity declaration.
    pub fn write_external_entity_decl(
        &mut self,
        name: &str,
        public_id: Option<&str>,
        system_id: &str,
    ) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        let system_id = format!(
            " {}\"{system_id}\"",
            if public_id.is_none() { "" } else { "SYSTEM " }
        );
        let public_id = public_id.map(|p| format!(" PUBLIC \"{p}\""));
        let public_id = public_id.as_deref().unwrap();
        write_tokens!(self, "<!ENTITY ", name, public_id, &system_id, ">");
        Ok(())
    }
    /// Write an unparsed entity declaration.
    pub fn write_unparsed_entity_decl(
        &mut self,
        name: &str,
        public_id: Option<&str>,
        system_id: &str,
        notation_name: &str,
    ) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        let system_id = format!(
            " {}\"{system_id}\"",
            if public_id.is_none() { "" } else { "SYSTEM " }
        );
        let public_id = public_id.map(|p| format!(" PUBLIC \"{p}\""));
        let public_id = public_id.as_deref().unwrap();
        write_tokens!(
            self,
            "<!ENTITY ",
            name,
            public_id,
            &system_id,
            " NDATA ",
            notation_name,
            ">"
        );
        Ok(())
    }
    /// Write a notation declaration.
    pub fn write_notation_decl(
        &mut self,
        name: &str,
        public_id: Option<&str>,
        system_id: Option<&str>,
    ) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        let system_id = system_id.map(|system_id| {
            format!(
                " {}\"{system_id}\"",
                if public_id.is_none() { "" } else { "SYSTEM " }
            )
        });
        let system_id = system_id.as_deref().unwrap_or_default();
        let public_id = public_id.map(|p| format!(" PUBLIC \"{p}\""));
        let public_id = public_id.as_deref().unwrap();
        write_tokens!(self, "<!NOTATION ", name, public_id, &system_id, ">");
        Ok(())
    }

    /// Write a start tag.
    pub fn write_start_element(&mut self, qname: &str) -> Result<(), XMLError> {
        self.try_close_start_element()?;
        write_tokens!(self, "<", qname);
        self.name_stack.push(qname.to_owned());
        self.state = State::StartElement;
        Ok(())
    }
    /// Write a start tag.
    ///
    /// Due to implementation limitations, it is not possible to specify a namespace whose
    /// prefix is determined by the namespace declaration of the element the current write
    /// operation is targeting.  \
    /// For example, if using this method to write a document element with a non-null
    /// namespace name, an error will always occur because the prefix bound to the namespace
    /// cannot be determined.  \
    /// To work around this, consider using [`write_start_element`](XMLStreamWriter::write_start_element).
    ///
    /// If a default namespace has already been declared at the time an element with a NULL
    /// namespace is written, the writer automatically writes a default namespace override to
    /// ensure consistency, unless explicitly declared otherwise.
    pub fn write_start_element_ns(
        &mut self,
        namespace_name: Option<&str>,
        local_name: &str,
    ) -> Result<(), XMLError> {
        self.try_close_start_element()?;
        if let Some(namespace_name) = namespace_name {
            let Some(pos) = self.ns_stack.iter().rposition(|s| s.0 == namespace_name) else {
                todo!("raise error")
            };
            if !self.ns_stack[pos].1.is_empty() {
                let qname = format!("{}:{}", self.ns_stack[pos].1, local_name);
                self.write_start_element(&qname)
            } else {
                self.write_start_element(local_name)
            }
        } else {
            self.write_start_element(local_name)?;
            if let Some(pos) = self.checker.namespaces.get("")
                && !pos.namespace_name.is_empty()
            {
                self.should_insert_default_namespace = true;
            }
            Ok(())
        }
    }
    /// Write an end tag.
    pub fn write_end_element(&mut self) -> Result<(), XMLError> {
        self.try_close_start_element()?;
        while self
            .ns_stack
            .pop_if(|l| l.2 == self.name_stack.len())
            .is_some()
        {}
        let qname = self
            .name_stack
            .pop()
            .ok_or(XMLError::XMLParseError(ParseError::InvalidEndTag))?;
        write_tokens!(self, "</", &qname, ">");
        Ok(())
    }
    /// Write an attribute.
    ///
    /// This method can only be used between the time the start tag is written and the time
    /// the element's content is written.
    pub fn write_attribute(&mut self, qname: &str, value: &str) -> Result<(), XMLError> {
        let value = value
            .replace('&', "&amp;")
            .replace('"', "&quot;")
            .replace('<', "&lt;");
        write_tokens!(self, " ", qname, "=\"", &value, "\"");
        Ok(())
    }
    /// Write an attribute.
    ///
    /// This method can only be used between the time the start tag is written and the time
    /// the element's content is written.
    ///
    /// As with the limitations of [`write_start_element_ns`](XMLStreamWriter::write_start_element_ns),
    /// using a namespace whose prefix is not yet bound at the time this method is called will
    /// result in an error.  \
    /// In such cases, please use [`write_attribute`](XMLStreamWriter::write_attribute) instead.
    pub fn write_attribute_ns(
        &mut self,
        namespace_name: Option<&str>,
        local_name: &str,
        value: &str,
    ) -> Result<(), XMLError> {
        let qname = if let Some(namespace_name) = namespace_name {
            let Some(pos) = self.ns_stack.iter().rposition(|s| s.0 == namespace_name) else {
                todo!("raise error")
            };

            if !self.ns_stack[pos].1.is_empty() {
                format!("{}:{}", self.ns_stack[pos].1, local_name)
            } else {
                local_name.to_owned()
            }
        } else {
            local_name.to_owned()
        };
        self.write_attribute(&qname, value)
    }
    /// Write a namespace declaration.
    ///
    /// This method can only be used between the time the start tag is written and the time
    /// the element's content is written.
    pub fn write_namespace_decl(
        &mut self,
        prefix: Option<&str>,
        namespace_name: &str,
    ) -> Result<(), XMLError> {
        if prefix.is_none() && namespace_name.is_empty() {
            self.should_insert_default_namespace = false;
        }
        let local = prefix.map(|p| format!(":{p}"));
        let local = local.as_deref().unwrap_or_default();
        write_tokens!(self, " xmlns", local, "=\"", namespace_name, "\"");
        self.ns_stack.push((
            namespace_name.to_owned(),
            prefix.unwrap_or_default().to_owned(),
            self.name_stack.len(),
        ));
        Ok(())
    }

    /// Write text contents.
    ///
    /// As long as it contains only whitespace, using it outside of document elements does
    /// not result in an error.
    ///
    /// Special characters ("&", "<", ">") contained in `data` are escaped by the writer.  \
    /// Although ">" is a character that does not require escaping, it is escaped because
    /// consecutive method calls can result in the sequence "]]>".
    pub fn write_characters(&mut self, data: &str) -> Result<(), XMLError> {
        self.try_close_start_element()?;
        let data = data
            .replace('&', "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;");
        write_tokens!(self, &data);
        Ok(())
    }
    /// Write a CDATA section.
    pub fn write_cdata(&mut self, data: &str) -> Result<(), XMLError> {
        self.try_close_start_element()?;
        write_tokens!(self, "<![CDATA[", data, "]]>");
        Ok(())
    }

    /// Write a comment.
    pub fn write_comment(&mut self, data: &str) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        self.try_close_start_element()?;
        write_tokens!(self, "<!--", data, "-->");
        Ok(())
    }

    /// Write a processing instruction.
    pub fn write_processing_instruction(
        &mut self,
        target: &str,
        data: Option<&str>,
    ) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        self.try_close_start_element()?;
        let data = data.map(|d| format!(" {d}"));
        let data = data.as_deref().unwrap_or_default();
        write_tokens!(self, "<?", target, data, "?>");
        Ok(())
    }

    /// Write a general entity reference.
    ///
    /// `name` must not contain `&` or `;`.
    pub fn write_general_entity_reference(&mut self, name: &str) -> Result<(), XMLError> {
        self.try_close_start_element()?;
        write_tokens!(self, "&", name, ";");
        Ok(())
    }
    /// Write a parameter entity reference.
    ///
    /// `name` must not contain `%` or `;`.
    pub fn write_parameter_entity_reference(&mut self, name: &str) -> Result<(), XMLError> {
        self.try_start_internal_subset()?;
        write_tokens!(self, "%", name, ";");
        Ok(())
    }

    fn try_start_internal_subset(&mut self) -> Result<(), XMLError> {
        if matches!(self.state, State::StartDTD) {
            write_tokens!(self, " [");
            self.state = State::InDTD;
        }
        Ok(())
    }
    fn try_close_start_element(&mut self) -> Result<(), XMLError> {
        if matches!(self.state, State::StartElement) {
            if self.should_insert_default_namespace {
                self.write_namespace_decl(None, "")?;
            }
            write_tokens!(self, ">");
            self.state = State::InContent;
        }
        Ok(())
    }

    /// Since some documents may require well-formedness checks upon completion,
    /// please call this function only once after all events have been written.
    pub fn flush(&mut self) -> Result<(), XMLError> {
        self.checker.parse_chunk([], true)?;
        self.stream.flush()?;
        self.state = State::Finished;
        Ok(())
    }

    /// Reset all writer context.
    pub fn reset(&mut self) -> Result<(), XMLError> {
        self.stream = OutputStream::default();
        self.checker.reset()?;
        self.name_stack.clear();
        self.ns_stack.clear();
        self.state = State::BeforeStart;
        Ok(())
    }
}

impl<H: SAXHandler> Drop for XMLStreamWriter<'_, H> {
    fn drop(&mut self) {
        self.flush().ok();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn write_declaration_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_declaration("1.0", None, None).unwrap();
        writer.write_start_element("root").unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(ret, r#"<?xml version="1.0"?><root></root>"#);
    }

    #[test]
    fn write_declaration_with_encoding_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer
            .write_declaration("1.0", Some("UTF-8"), None)
            .unwrap();
        writer.write_start_element("root").unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<?xml version="1.0" encoding="UTF-8"?><root></root>"#
        );
    }

    #[test]
    fn write_declaration_with_sa_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer
            .write_declaration("1.0", Some("UTF-8"), Some(true))
            .unwrap();
        writer.write_start_element("root").unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root></root>"#
        );
    }

    #[test]
    fn write_element_withtout_declaration_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_start_element("root").unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(ret, r#"<root></root>"#);
    }

    #[test]
    fn write_attributes_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_declaration("1.0", None, None).unwrap();
        writer.write_start_element("root").unwrap();
        writer.write_attribute("att", "att").unwrap();
        writer.write_attribute("att2", "att2").unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<?xml version="1.0"?><root att="att" att2="att2"></root>"#
        );
    }

    #[test]
    fn write_escaped_attribute_value_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_start_element("root").unwrap();
        writer.write_attribute("att", r#""'&<>"#).unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(ret, r#"<root att="&quot;'&amp;&lt;>"></root>"#);
    }

    #[test]
    fn write_nested_content_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_start_element("root").unwrap();
        writer.write_characters("first").unwrap();
        writer.write_start_element("child").unwrap();
        writer.write_characters("second").unwrap();
        writer.write_characters(" third").unwrap();
        writer.write_end_element().unwrap();
        writer.write_characters("forth").unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(ret, r#"<root>first<child>second third</child>forth</root>"#);
    }

    #[test]
    fn write_escaped_content_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_start_element("root").unwrap();
        writer.write_start_element("child1").unwrap();
        writer.write_characters(r#""'&<>"#).unwrap();
        writer.write_end_element().unwrap();
        writer.write_start_element("child2").unwrap();
        writer.write_characters("]]>").unwrap();
        writer.write_end_element().unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<root><child1>"'&amp;&lt;&gt;</child1><child2>]]&gt;</child2></root>"#
        );
    }

    #[test]
    fn write_cdata_section_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_start_element("root").unwrap();
        writer.write_cdata(r#"normal text"#).unwrap();
        writer.write_cdata(r#""'&<>"#).unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<root><![CDATA[normal text]]><![CDATA["'&<>]]></root>"#
        );
    }

    #[test]
    fn write_nsdecl_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_start_element("ex:root").unwrap();
        writer
            .write_namespace_decl(Some("ex"), "http://example.com/1")
            .unwrap();
        writer
            .write_start_element_ns(Some("http://example.com/1"), "child")
            .unwrap();
        writer.write_end_element().unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<ex:root xmlns:ex="http://example.com/1"><ex:child></ex:child></ex:root>"#
        );
    }

    #[test]
    fn write_default_ns_auto_insertion_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_start_element("root").unwrap();
        writer
            .write_namespace_decl(None, "http://example.com/1")
            .unwrap();
        writer.write_start_element_ns(None, "child").unwrap();
        writer.write_end_element().unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<root xmlns="http://example.com/1"><child xmlns=""></child></root>"#
        );
    }

    #[test]
    fn write_dtd_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer
            .write_start_dtd("root", None, Some("sample.dtd"))
            .unwrap();
        writer
            .write_element_decl("root", "(#PCDATA|child)*")
            .unwrap();
        writer.write_element_decl("child", "EMPTY").unwrap();
        writer
            .write_attribute_decl("root", "att", "NMTOKEN", "#IMPLIED")
            .unwrap();
        writer
            .write_internal_entity_decl("ent", "entity content")
            .unwrap();
        writer.write_end_dtd().unwrap();
        writer.write_start_element("root").unwrap();
        writer.write_attribute("att", "token").unwrap();
        writer.write_start_element("child").unwrap();
        writer.write_end_element().unwrap();
        writer.write_general_entity_reference("ent").unwrap();
        writer.write_end_element().unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<!DOCTYPE root SYSTEM "sample.dtd" [<!ELEMENT root (#PCDATA|child)*><!ELEMENT child EMPTY><!ATTLIST root att NMTOKEN #IMPLIED><!ENTITY ent "entity content">]><root att="token"><child></child>&ent;</root>"#
        );
    }

    #[test]
    fn write_misc_tests() {
        let mut buffer = vec![];
        let mut writer = XMLStreamWriter::new(&mut buffer, None);
        writer.write_comment("comment1").unwrap();
        writer
            .write_processing_instruction("pi1", Some("data1"))
            .unwrap();
        writer.write_start_element("root").unwrap();
        writer.write_comment("comment2").unwrap();
        writer.write_processing_instruction("pi2", None).unwrap();
        writer.write_end_element().unwrap();
        writer.write_comment("comment3").unwrap();
        writer.write_processing_instruction("pi3", None).unwrap();
        writer.flush().unwrap();
        drop(writer);
        let ret = String::from_utf8(buffer).unwrap();
        assert_eq!(
            ret,
            r#"<!--comment1--><?pi1 data1?><root><!--comment2--><?pi2?></root><!--comment3--><?pi3?>"#
        );
    }
}