quick_xml/de/
mod.rs

1//! Serde `Deserializer` module.
2//!
3//! Due to the complexity of the XML standard and the fact that Serde was developed
4//! with JSON in mind, not all Serde concepts apply smoothly to XML. This leads to
5//! that fact that some XML concepts are inexpressible in terms of Serde derives
6//! and may require manual deserialization.
7//!
8//! The most notable restriction is the ability to distinguish between _elements_
9//! and _attributes_, as no other format used by serde has such a conception.
10//!
11//! Due to that the mapping is performed in a best effort manner.
12//!
13//!
14//!
15//! Table of Contents
16//! =================
17//! - [Mapping XML to Rust types](#mapping-xml-to-rust-types)
18//!   - [Basics](#basics)
19//!   - [Optional attributes and elements](#optional-attributes-and-elements)
20//!   - [Choices (`xs:choice` XML Schema type)](#choices-xschoice-xml-schema-type)
21//!   - [Sequences (`xs:all` and `xs:sequence` XML Schema types)](#sequences-xsall-and-xssequence-xml-schema-types)
22//! - [Mapping of `xsi:nil`](#mapping-of-xsinil)
23//! - [Generate Rust types from XML](#generate-rust-types-from-xml)
24//! - [Composition Rules](#composition-rules)
25//! - [Enum Representations](#enum-representations)
26//!   - [Normal enum variant](#normal-enum-variant)
27//!   - [`$text` enum variant](#text-enum-variant)
28//! - [`$text` and `$value` special names](#text-and-value-special-names)
29//!   - [`$text`](#text)
30//!   - [`$value`](#value)
31//!     - [Primitives and sequences of primitives](#primitives-and-sequences-of-primitives)
32//!     - [Structs and sequences of structs](#structs-and-sequences-of-structs)
33//!     - [Enums and sequences of enums](#enums-and-sequences-of-enums)
34//! - [Frequently Used Patterns](#frequently-used-patterns)
35//!   - [`<element>` lists](#element-lists)
36//!   - [Overlapped (Out-of-Order) Elements](#overlapped-out-of-order-elements)
37//!   - [Internally Tagged Enums](#internally-tagged-enums)
38//!
39//!
40//!
41//! Mapping XML to Rust types
42//! =========================
43//!
44//! Type names are never considered when deserializing, so you can name your
45//! types as you wish. Other general rules:
46//! - `struct` field name could be represented in XML only as an attribute name
47//!   or an element name;
48//! - `enum` variant name could be represented in XML only as an attribute name
49//!   or an element name;
50//! - the unit struct, unit type `()` and unit enum variant can be deserialized
51//!   from any valid XML content:
52//!   - attribute and element names;
53//!   - attribute and element values;
54//!   - text or CDATA content (including mixed text and CDATA content).
55//!
56//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
57//!
58//! NOTE: All tests are marked with an `ignore` option, even though they do
59//! compile. This is  because rustdoc marks such blocks with an information
60//! icon unlike `no_run` blocks.
61//!
62//! </div>
63//!
64//! <table>
65//! <thead>
66//! <tr><th colspan="2">
67//!
68//! ## Basics
69//!
70//! </th></tr>
71//! <tr><th>To parse all these XML's...</th><th>...use these Rust type(s)</th></tr>
72//! </thead>
73//! <tbody style="vertical-align:top;">
74//! <tr>
75//! <td>
76//! Content of attributes and text / CDATA content of elements (including mixed
77//! text and CDATA content):
78//!
79//! ```xml
80//! <... ...="content" />
81//! ```
82//! ```xml
83//! <...>content</...>
84//! ```
85//! ```xml
86//! <...><![CDATA[content]]></...>
87//! ```
88//! ```xml
89//! <...>text<![CDATA[cdata]]>text</...>
90//! ```
91//! Mixed text / CDATA content represents one logical string, `"textcdatatext"` in that case.
92//! </td>
93//! <td>
94//!
95//! You can use any type that can be deserialized from an `&str`, for example:
96//! - [`String`] and [`&str`]
97//! - [`Cow<str>`]
98//! - [`u32`], [`f32`] and other numeric types
99//! - `enum`s, like
100//!   ```
101//!   # use pretty_assertions::assert_eq;
102//!   # use serde::Deserialize;
103//!   # #[derive(Debug, PartialEq)]
104//!   #[derive(Deserialize)]
105//!   enum Language {
106//!     Rust,
107//!     Cpp,
108//!     #[serde(other)]
109//!     Other,
110//!   }
111//!   # #[derive(Debug, PartialEq, Deserialize)]
112//!   # struct X { #[serde(rename = "$text")] x: Language }
113//!   # assert_eq!(X { x: Language::Rust  }, quick_xml::de::from_str("<x>Rust</x>").unwrap());
114//!   # assert_eq!(X { x: Language::Cpp   }, quick_xml::de::from_str("<x>C<![CDATA[p]]>p</x>").unwrap());
115//!   # assert_eq!(X { x: Language::Other }, quick_xml::de::from_str("<x><![CDATA[other]]></x>").unwrap());
116//!   ```
117//!
118//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
119//!
120//! NOTE: deserialization to non-owned types (i.e. borrow from the input),
121//! such as `&str`, is possible only if you parse document in the UTF-8
122//! encoding and content does not contain entity references such as `&amp;`,
123//! or character references such as `&#xD;`, as well as text content represented
124//! by one piece of [text] or [CDATA] element.
125//! </div>
126//! <!-- TODO: document an error type returned -->
127//!
128//! [text]: Event::Text
129//! [CDATA]: Event::CData
130//! </td>
131//! </tr>
132//! <!-- 2 ===================================================================================== -->
133//! <tr>
134//! <td>
135//!
136//! Content of attributes and text / CDATA content of elements (including mixed
137//! text and CDATA content), which represents a space-delimited lists, as
138//! specified in the XML Schema specification for [`xs:list`] `simpleType`:
139//!
140//! ```xml
141//! <... ...="element1 element2 ..." />
142//! ```
143//! ```xml
144//! <...>
145//!   element1
146//!   element2
147//!   ...
148//! </...>
149//! ```
150//! ```xml
151//! <...><![CDATA[
152//!   element1
153//!   element2
154//!   ...
155//! ]]></...>
156//! ```
157//!
158//! [`xs:list`]: https://www.w3.org/TR/xmlschema11-2/#list-datatypes
159//! </td>
160//! <td>
161//!
162//! Use any type that deserialized using [`deserialize_seq()`] call, for example:
163//!
164//! ```
165//! type List = Vec<u32>;
166//! ```
167//!
168//! See the next row to learn where in your struct definition you should
169//! use that type.
170//!
171//! According to the XML Schema specification, delimiters for elements is one
172//! or more space (`' '`, `'\r'`, `'\n'`, and `'\t'`) character(s).
173//!
174//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
175//!
176//! NOTE: according to the XML Schema restrictions, you cannot escape those
177//! white-space characters, so list elements will _never_ contain them.
178//! In practice you will usually use `xs:list`s for lists of numbers or enumerated
179//! values which looks like identifiers in many languages, for example, `item`,
180//! `some_item` or `some-item`, so that shouldn't be a problem.
181//!
182//! NOTE: according to the XML Schema specification, list elements can be
183//! delimited only by spaces. Other delimiters (for example, commas) are not
184//! allowed.
185//!
186//! </div>
187//!
188//! [`deserialize_seq()`]: de::Deserializer::deserialize_seq
189//! </td>
190//! </tr>
191//! <!-- 3 ===================================================================================== -->
192//! <tr>
193//! <td>
194//! A typical XML with attributes. The root tag name does not matter:
195//!
196//! ```xml
197//! <any-tag one="..." two="..."/>
198//! ```
199//! </td>
200//! <td>
201//!
202//! A structure where each XML attribute is mapped to a field with a name
203//! starting with `@`. Because Rust identifiers do not permit the `@` character,
204//! you should use the `#[serde(rename = "@...")]` attribute to rename it.
205//! The name of the struct itself does not matter:
206//!
207//! ```
208//! # use serde::Deserialize;
209//! # type T = ();
210//! # type U = ();
211//! // Get both attributes
212//! # #[derive(Debug, PartialEq)]
213//! #[derive(Deserialize)]
214//! struct AnyName {
215//!   #[serde(rename = "@one")]
216//!   one: T,
217//!
218//!   #[serde(rename = "@two")]
219//!   two: U,
220//! }
221//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..." two="..."/>"#).unwrap();
222//! ```
223//! ```
224//! # use serde::Deserialize;
225//! # type T = ();
226//! // Get only the one attribute, ignore the other
227//! # #[derive(Debug, PartialEq)]
228//! #[derive(Deserialize)]
229//! struct AnyName {
230//!   #[serde(rename = "@one")]
231//!   one: T,
232//! }
233//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..." two="..."/>"#).unwrap();
234//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..."/>"#).unwrap();
235//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..."><one>...</one></any-tag>"#).unwrap();
236//! ```
237//! ```
238//! # use serde::Deserialize;
239//! // Ignore all attributes
240//! // You can also use the `()` type (unit type)
241//! # #[derive(Debug, PartialEq)]
242//! #[derive(Deserialize)]
243//! struct AnyName;
244//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..." two="..."/>"#).unwrap();
245//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..."><one>...</one></any-tag>"#).unwrap();
246//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag><one>...</one><two>...</two></any-tag>"#).unwrap();
247//! ```
248//!
249//! All these structs can be used to deserialize from an XML on the
250//! left side depending on amount of information that you want to get.
251//! Of course, you can combine them with elements extractor structs (see below).
252//!
253//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
254//!
255//! NOTE: XML allows you to have an attribute and an element with the same name
256//! inside the one element. quick-xml deals with that by prepending a `@` prefix
257//! to the name of attributes.
258//! </div>
259//! </td>
260//! </tr>
261//! <!-- 4 ===================================================================================== -->
262//! <tr>
263//! <td>
264//! A typical XML with child elements. The root tag name does not matter:
265//!
266//! ```xml
267//! <any-tag>
268//!   <one>...</one>
269//!   <two>...</two>
270//! </any-tag>
271//! ```
272//! </td>
273//! <td>
274//! A structure where each XML child element is mapped to the field.
275//! Each element name becomes a name of field. The name of the struct itself
276//! does not matter:
277//!
278//! ```
279//! # use serde::Deserialize;
280//! # type T = ();
281//! # type U = ();
282//! // Get both elements
283//! # #[derive(Debug, PartialEq)]
284//! #[derive(Deserialize)]
285//! struct AnyName {
286//!   one: T,
287//!   two: U,
288//! }
289//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag><one>...</one><two>...</two></any-tag>"#).unwrap();
290//! #
291//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..." two="..."/>"#).unwrap_err();
292//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..."><two>...</two></any-tag>"#).unwrap_err();
293//! ```
294//! ```
295//! # use serde::Deserialize;
296//! # type T = ();
297//! // Get only the one element, ignore the other
298//! # #[derive(Debug, PartialEq)]
299//! #[derive(Deserialize)]
300//! struct AnyName {
301//!   one: T,
302//! }
303//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag><one>...</one><two>...</two></any-tag>"#).unwrap();
304//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..."><one>...</one></any-tag>"#).unwrap();
305//! ```
306//! ```
307//! # use serde::Deserialize;
308//! // Ignore all elements
309//! // You can also use the `()` type (unit type)
310//! # #[derive(Debug, PartialEq)]
311//! #[derive(Deserialize)]
312//! struct AnyName;
313//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..." two="..."/>"#).unwrap();
314//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag><one>...</one><two>...</two></any-tag>"#).unwrap();
315//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..."><two>...</two></any-tag>"#).unwrap();
316//! # quick_xml::de::from_str::<AnyName>(r#"<any-tag one="..."><one>...</one></any-tag>"#).unwrap();
317//! ```
318//!
319//! All these structs can be used to deserialize from an XML on the
320//! left side depending on amount of information that you want to get.
321//! Of course, you can combine them with attributes extractor structs (see above).
322//!
323//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
324//!
325//! NOTE: XML allows you to have an attribute and an element with the same name
326//! inside the one element. quick-xml deals with that by prepending a `@` prefix
327//! to the name of attributes.
328//! </div>
329//! </td>
330//! </tr>
331//! <!-- 5 ===================================================================================== -->
332//! <tr>
333//! <td>
334//! An XML with an attribute and a child element named equally:
335//!
336//! ```xml
337//! <any-tag field="...">
338//!   <field>...</field>
339//! </any-tag>
340//! ```
341//! </td>
342//! <td>
343//!
344//! You MUST specify `#[serde(rename = "@field")]` on a field that will be used
345//! for an attribute:
346//!
347//! ```
348//! # use pretty_assertions::assert_eq;
349//! # use serde::Deserialize;
350//! # type T = ();
351//! # type U = ();
352//! # #[derive(Debug, PartialEq)]
353//! #[derive(Deserialize)]
354//! struct AnyName {
355//!   #[serde(rename = "@field")]
356//!   attribute: T,
357//!   field: U,
358//! }
359//! # assert_eq!(
360//! #   AnyName { attribute: (), field: () },
361//! #   quick_xml::de::from_str(r#"
362//! #     <any-tag field="...">
363//! #       <field>...</field>
364//! #     </any-tag>
365//! #   "#).unwrap(),
366//! # );
367//! ```
368//! </td>
369//! </tr>
370//! <!-- ======================================================================================= -->
371//! <tr><th colspan="2">
372//!
373//! ## Optional attributes and elements
374//!
375//! </th></tr>
376//! <tr><th>To parse all these XML's...</th><th>...use these Rust type(s)</th></tr>
377//! <!-- 6 ===================================================================================== -->
378//! <tr>
379//! <td>
380//! An optional XML attribute that you want to capture.
381//! The root tag name does not matter:
382//!
383//! ```xml
384//! <any-tag optional="..."/>
385//! ```
386//! ```xml
387//! <any-tag/>
388//! ```
389//! </td>
390//! <td>
391//!
392//! A structure with an optional field, renamed according to the requirements
393//! for attributes:
394//!
395//! ```
396//! # use pretty_assertions::assert_eq;
397//! # use serde::Deserialize;
398//! # type T = ();
399//! # #[derive(Debug, PartialEq)]
400//! #[derive(Deserialize)]
401//! struct AnyName {
402//!   #[serde(rename = "@optional")]
403//!   optional: Option<T>,
404//! }
405//! # assert_eq!(AnyName { optional: Some(()) }, quick_xml::de::from_str(r#"<any-tag optional="..."/>"#).unwrap());
406//! # assert_eq!(AnyName { optional: None     }, quick_xml::de::from_str(r#"<any-tag/>"#).unwrap());
407//! ```
408//! When the XML attribute is present, type `T` will be deserialized from
409//! an attribute value (which is a string). Note, that if `T = String` or other
410//! string type, the empty attribute is mapped to a `Some("")`, whereas `None`
411//! represents the missed attribute:
412//! ```xml
413//! <any-tag optional="..."/><!-- Some("...") -->
414//! <any-tag optional=""/>   <!-- Some("") -->
415//! <any-tag/>               <!-- None -->
416//! ```
417//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
418//!
419//! NOTE: The behaviour is not symmetric by default. `None` will be serialized as
420//! `optional=""`. This behaviour is consistent across serde crates. You should add
421//! `#[serde(skip_serializing_if = "Option::is_none")]` attribute to the field to
422//! skip `None`s.
423//! </div>
424//! </td>
425//! </tr>
426//! <!-- 7 ===================================================================================== -->
427//! <tr>
428//! <td>
429//! An optional XML elements that you want to capture.
430//! The root tag name does not matter:
431//!
432//! ```xml
433//! <any-tag/>
434//!   <optional>...</optional>
435//! </any-tag>
436//! ```
437//! ```xml
438//! <any-tag/>
439//!   <optional/>
440//! </any-tag>
441//! ```
442//! ```xml
443//! <any-tag/>
444//! ```
445//! </td>
446//! <td>
447//!
448//! A structure with an optional field:
449//!
450//! ```
451//! # use pretty_assertions::assert_eq;
452//! # use serde::Deserialize;
453//! # type T = ();
454//! # #[derive(Debug, PartialEq)]
455//! #[derive(Deserialize)]
456//! struct AnyName {
457//!   optional: Option<T>,
458//! }
459//! # assert_eq!(AnyName { optional: Some(()) }, quick_xml::de::from_str(r#"<any-tag><optional>...</optional></any-tag>"#).unwrap());
460//! # assert_eq!(AnyName { optional: None     }, quick_xml::de::from_str(r#"<any-tag/>"#).unwrap());
461//! ```
462//! When the XML element is present, type `T` will be deserialized from an
463//! element (which is a string or a multi-mapping -- i.e. mapping which can have
464//! duplicated keys).
465//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
466//!
467//! NOTE: The behaviour is not symmetric by default. `None` will be serialized as
468//! `<optional/>`. This behaviour is consistent across serde crates. You should add
469//! `#[serde(skip_serializing_if = "Option::is_none")]` attribute to the field to
470//! skip `None`s.
471//!
472//! NOTE: Deserializer will automatically handle a [`xsi:nil`] attribute and set field to `None`.
473//! For more info see [Mapping of `xsi:nil`](#mapping-of-xsinil).
474//! </div>
475//! </td>
476//! </tr>
477//! <!-- ======================================================================================= -->
478//! <tr><th colspan="2">
479//!
480//! ## Choices (`xs:choice` XML Schema type)
481//!
482//! </th></tr>
483//! <tr><th>To parse all these XML's...</th><th>...use these Rust type(s)</th></tr>
484//! <!-- 8 ===================================================================================== -->
485//! <tr>
486//! <td>
487//! An XML with different root tag names, as well as text / CDATA content:
488//!
489//! ```xml
490//! <one field1="...">...</one>
491//! ```
492//! ```xml
493//! <two>
494//!   <field2>...</field2>
495//! </two>
496//! ```
497//! ```xml
498//! Text <![CDATA[or (mixed)
499//! CDATA]]> content
500//! ```
501//! </td>
502//! <td>
503//!
504//! An enum where each variant has the name of a possible root tag. The name of
505//! the enum itself does not matter.
506//!
507//! If you need to get the textual content, mark a variant with `#[serde(rename = "$text")]`.
508//!
509//! All these structs can be used to deserialize from any XML on the
510//! left side depending on amount of information that you want to get:
511//!
512//! ```
513//! # use pretty_assertions::assert_eq;
514//! # use serde::Deserialize;
515//! # type T = ();
516//! # type U = ();
517//! # #[derive(Debug, PartialEq)]
518//! #[derive(Deserialize)]
519//! #[serde(rename_all = "snake_case")]
520//! enum AnyName {
521//!   One { #[serde(rename = "@field1")] field1: T },
522//!   Two { field2: U },
523//!
524//!   /// Use unit variant, if you do not care of a content.
525//!   /// You can use tuple variant if you want to parse
526//!   /// textual content as an xs:list.
527//!   /// Struct variants are will pass a string to the
528//!   /// struct enum variant visitor, which typically
529//!   /// returns Err(Custom)
530//!   #[serde(rename = "$text")]
531//!   Text(String),
532//! }
533//! # assert_eq!(AnyName::One { field1: () }, quick_xml::de::from_str(r#"<one field1="...">...</one>"#).unwrap());
534//! # assert_eq!(AnyName::Two { field2: () }, quick_xml::de::from_str(r#"<two><field2>...</field2></two>"#).unwrap());
535//! # assert_eq!(AnyName::Text("text  cdata ".into()), quick_xml::de::from_str(r#"text <![CDATA[ cdata ]]>"#).unwrap());
536//! ```
537//! ```
538//! # use pretty_assertions::assert_eq;
539//! # use serde::Deserialize;
540//! # type T = ();
541//! # #[derive(Debug, PartialEq)]
542//! #[derive(Deserialize)]
543//! struct Two {
544//!   field2: T,
545//! }
546//! # #[derive(Debug, PartialEq)]
547//! #[derive(Deserialize)]
548//! #[serde(rename_all = "snake_case")]
549//! enum AnyName {
550//!   // `field1` content discarded
551//!   One,
552//!   Two(Two),
553//!   #[serde(rename = "$text")]
554//!   Text,
555//! }
556//! # assert_eq!(AnyName::One,                     quick_xml::de::from_str(r#"<one field1="...">...</one>"#).unwrap());
557//! # assert_eq!(AnyName::Two(Two { field2: () }), quick_xml::de::from_str(r#"<two><field2>...</field2></two>"#).unwrap());
558//! # assert_eq!(AnyName::Text,                    quick_xml::de::from_str(r#"text <![CDATA[ cdata ]]>"#).unwrap());
559//! ```
560//! ```
561//! # use pretty_assertions::assert_eq;
562//! # use serde::Deserialize;
563//! # #[derive(Debug, PartialEq)]
564//! #[derive(Deserialize)]
565//! #[serde(rename_all = "snake_case")]
566//! enum AnyName {
567//!   One,
568//!   // the <two> and textual content will be mapped to this
569//!   #[serde(other)]
570//!   Other,
571//! }
572//! # assert_eq!(AnyName::One,   quick_xml::de::from_str(r#"<one field1="...">...</one>"#).unwrap());
573//! # assert_eq!(AnyName::Other, quick_xml::de::from_str(r#"<two><field2>...</field2></two>"#).unwrap());
574//! # assert_eq!(AnyName::Other, quick_xml::de::from_str(r#"text <![CDATA[ cdata ]]>"#).unwrap());
575//! ```
576//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
577//!
578//! NOTE: You should have variants for all possible tag names in your enum
579//! or have an `#[serde(other)]` variant.
580//! <!-- TODO: document an error type if that requirement is violated -->
581//! </div>
582//! </td>
583//! </tr>
584//! <!-- 9 ===================================================================================== -->
585//! <tr>
586//! <td>
587//!
588//! `<xs:choice>` embedded in the other element, and at the same time you want
589//! to get access to other attributes that can appear in the same container
590//! (`<any-tag>`). Also this case can be described, as if you want to choose
591//! Rust enum variant based on a tag name:
592//!
593//! ```xml
594//! <any-tag field="...">
595//!   <one>...</one>
596//! </any-tag>
597//! ```
598//! ```xml
599//! <any-tag field="...">
600//!   <two>...</two>
601//! </any-tag>
602//! ```
603//! ```xml
604//! <any-tag field="...">
605//!   Text <![CDATA[or (mixed)
606//!   CDATA]]> content
607//! </any-tag>
608//! ```
609//! </td>
610//! <td>
611//!
612//! A structure with a field which type is an `enum`.
613//!
614//! If you need to get a textual content, mark a variant with `#[serde(rename = "$text")]`.
615//!
616//! Names of the enum, struct, and struct field with `Choice` type does not matter:
617//!
618//! ```
619//! # use pretty_assertions::assert_eq;
620//! # use serde::Deserialize;
621//! # type T = ();
622//! # #[derive(Debug, PartialEq)]
623//! #[derive(Deserialize)]
624//! #[serde(rename_all = "snake_case")]
625//! enum Choice {
626//!   One,
627//!   Two,
628//!
629//!   /// Use unit variant, if you do not care of a content.
630//!   /// You can use tuple variant if you want to parse
631//!   /// textual content as an xs:list.
632//!   /// Struct variants are will pass a string to the
633//!   /// struct enum variant visitor, which typically
634//!   /// returns Err(Custom)
635//!   #[serde(rename = "$text")]
636//!   Text(String),
637//! }
638//! # #[derive(Debug, PartialEq)]
639//! #[derive(Deserialize)]
640//! struct AnyName {
641//!   #[serde(rename = "@field")]
642//!   field: T,
643//!
644//!   #[serde(rename = "$value")]
645//!   any_name: Choice,
646//! }
647//! # assert_eq!(
648//! #   AnyName { field: (), any_name: Choice::One },
649//! #   quick_xml::de::from_str(r#"<any-tag field="..."><one>...</one></any-tag>"#).unwrap(),
650//! # );
651//! # assert_eq!(
652//! #   AnyName { field: (), any_name: Choice::Two },
653//! #   quick_xml::de::from_str(r#"<any-tag field="..."><two>...</two></any-tag>"#).unwrap(),
654//! # );
655//! # assert_eq!(
656//! #   AnyName { field: (), any_name: Choice::Text("text  cdata ".into()) },
657//! #   quick_xml::de::from_str(r#"<any-tag field="...">text <![CDATA[ cdata ]]></any-tag>"#).unwrap(),
658//! # );
659//! ```
660//! </td>
661//! </tr>
662//! <!-- 10 ==================================================================================== -->
663//! <tr>
664//! <td>
665//!
666//! `<xs:choice>` embedded in the other element, and at the same time you want
667//! to get access to other elements that can appear in the same container
668//! (`<any-tag>`). Also this case can be described, as if you want to choose
669//! Rust enum variant based on a tag name:
670//!
671//! ```xml
672//! <any-tag>
673//!   <field>...</field>
674//!   <one>...</one>
675//! </any-tag>
676//! ```
677//! ```xml
678//! <any-tag>
679//!   <two>...</two>
680//!   <field>...</field>
681//! </any-tag>
682//! ```
683//! </td>
684//! <td>
685//!
686//! A structure with a field which type is an `enum`.
687//!
688//! Names of the enum, struct, and struct field with `Choice` type does not matter:
689//!
690//! ```
691//! # use pretty_assertions::assert_eq;
692//! # use serde::Deserialize;
693//! # type T = ();
694//! # #[derive(Debug, PartialEq)]
695//! #[derive(Deserialize)]
696//! #[serde(rename_all = "snake_case")]
697//! enum Choice {
698//!   One,
699//!   Two,
700//! }
701//! # #[derive(Debug, PartialEq)]
702//! #[derive(Deserialize)]
703//! struct AnyName {
704//!   field: T,
705//!
706//!   #[serde(rename = "$value")]
707//!   any_name: Choice,
708//! }
709//! # assert_eq!(
710//! #   AnyName { field: (), any_name: Choice::One },
711//! #   quick_xml::de::from_str(r#"<any-tag><field>...</field><one>...</one></any-tag>"#).unwrap(),
712//! # );
713//! # assert_eq!(
714//! #   AnyName { field: (), any_name: Choice::Two },
715//! #   quick_xml::de::from_str(r#"<any-tag><two>...</two><field>...</field></any-tag>"#).unwrap(),
716//! # );
717//! ```
718//!
719//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
720//!
721//! NOTE: if your `Choice` enum would contain an `#[serde(other)]`
722//! variant, element `<field>` will be mapped to the `field` and not to the enum
723//! variant.
724//! </div>
725//!
726//! </td>
727//! </tr>
728//! <!-- 11 ==================================================================================== -->
729//! <tr>
730//! <td>
731//!
732//! `<xs:choice>` encapsulated in other element with a fixed name:
733//!
734//! ```xml
735//! <any-tag field="...">
736//!   <choice>
737//!     <one>...</one>
738//!   </choice>
739//! </any-tag>
740//! ```
741//! ```xml
742//! <any-tag field="...">
743//!   <choice>
744//!     <two>...</two>
745//!   </choice>
746//! </any-tag>
747//! ```
748//! </td>
749//! <td>
750//!
751//! A structure with a field of an intermediate type with one field of `enum` type.
752//! Actually, this example is not necessary, because you can construct it by yourself
753//! using the composition rules that were described above. However the XML construction
754//! described here is very common, so it is shown explicitly.
755//!
756//! Names of the enum and struct does not matter:
757//!
758//! ```
759//! # use pretty_assertions::assert_eq;
760//! # use serde::Deserialize;
761//! # type T = ();
762//! # #[derive(Debug, PartialEq)]
763//! #[derive(Deserialize)]
764//! #[serde(rename_all = "snake_case")]
765//! enum Choice {
766//!   One,
767//!   Two,
768//! }
769//! # #[derive(Debug, PartialEq)]
770//! #[derive(Deserialize)]
771//! struct Holder {
772//!   #[serde(rename = "$value")]
773//!   any_name: Choice,
774//! }
775//! # #[derive(Debug, PartialEq)]
776//! #[derive(Deserialize)]
777//! struct AnyName {
778//!   #[serde(rename = "@field")]
779//!   field: T,
780//!
781//!   choice: Holder,
782//! }
783//! # assert_eq!(
784//! #   AnyName { field: (), choice: Holder { any_name: Choice::One } },
785//! #   quick_xml::de::from_str(r#"<any-tag field="..."><choice><one>...</one></choice></any-tag>"#).unwrap(),
786//! # );
787//! # assert_eq!(
788//! #   AnyName { field: (), choice: Holder { any_name: Choice::Two } },
789//! #   quick_xml::de::from_str(r#"<any-tag field="..."><choice><two>...</two></choice></any-tag>"#).unwrap(),
790//! # );
791//! ```
792//! </td>
793//! </tr>
794//! <!-- 12 ==================================================================================== -->
795//! <tr>
796//! <td>
797//!
798//! `<xs:choice>` encapsulated in other element with a fixed name:
799//!
800//! ```xml
801//! <any-tag>
802//!   <field>...</field>
803//!   <choice>
804//!     <one>...</one>
805//!   </choice>
806//! </any-tag>
807//! ```
808//! ```xml
809//! <any-tag>
810//!   <choice>
811//!     <two>...</two>
812//!   </choice>
813//!   <field>...</field>
814//! </any-tag>
815//! ```
816//! </td>
817//! <td>
818//!
819//! A structure with a field of an intermediate type with one field of `enum` type.
820//! Actually, this example is not necessary, because you can construct it by yourself
821//! using the composition rules that were described above. However the XML construction
822//! described here is very common, so it is shown explicitly.
823//!
824//! Names of the enum and struct does not matter:
825//!
826//! ```
827//! # use pretty_assertions::assert_eq;
828//! # use serde::Deserialize;
829//! # type T = ();
830//! # #[derive(Debug, PartialEq)]
831//! #[derive(Deserialize)]
832//! #[serde(rename_all = "snake_case")]
833//! enum Choice {
834//!   One,
835//!   Two,
836//! }
837//! # #[derive(Debug, PartialEq)]
838//! #[derive(Deserialize)]
839//! struct Holder {
840//!   #[serde(rename = "$value")]
841//!   any_name: Choice,
842//! }
843//! # #[derive(Debug, PartialEq)]
844//! #[derive(Deserialize)]
845//! struct AnyName {
846//!   field: T,
847//!
848//!   choice: Holder,
849//! }
850//! # assert_eq!(
851//! #   AnyName { field: (), choice: Holder { any_name: Choice::One } },
852//! #   quick_xml::de::from_str(r#"<any-tag><field>...</field><choice><one>...</one></choice></any-tag>"#).unwrap(),
853//! # );
854//! # assert_eq!(
855//! #   AnyName { field: (), choice: Holder { any_name: Choice::Two } },
856//! #   quick_xml::de::from_str(r#"<any-tag><choice><two>...</two></choice><field>...</field></any-tag>"#).unwrap(),
857//! # );
858//! ```
859//! </td>
860//! </tr>
861//! <!-- ======================================================================================== -->
862//! <tr><th colspan="2">
863//!
864//! ## Sequences (`xs:all` and `xs:sequence` XML Schema types)
865//!
866//! </th></tr>
867//! <tr><th>To parse all these XML's...</th><th>...use these Rust type(s)</th></tr>
868//! <!-- 13 ==================================================================================== -->
869//! <tr>
870//! <td>
871//! A sequence inside of a tag without a dedicated name:
872//!
873//! ```xml
874//! <any-tag/>
875//! ```
876//! ```xml
877//! <any-tag>
878//!   <item/>
879//! </any-tag>
880//! ```
881//! ```xml
882//! <any-tag>
883//!   <item/>
884//!   <item/>
885//!   <item/>
886//! </any-tag>
887//! ```
888//! </td>
889//! <td>
890//!
891//! A structure with a field which is a sequence type, for example, [`Vec`].
892//! Because XML syntax does not distinguish between empty sequences and missed
893//! elements, we should indicate that on the Rust side, because serde will require
894//! that field `item` exists. You can do that in two possible ways:
895//!
896//! Use the `#[serde(default)]` attribute for a [field] or the entire [struct]:
897//! ```
898//! # use pretty_assertions::assert_eq;
899//! # use serde::Deserialize;
900//! # type Item = ();
901//! # #[derive(Debug, PartialEq)]
902//! #[derive(Deserialize)]
903//! struct AnyName {
904//!   #[serde(default)]
905//!   item: Vec<Item>,
906//! }
907//! # assert_eq!(
908//! #   AnyName { item: vec![] },
909//! #   quick_xml::de::from_str(r#"<any-tag/>"#).unwrap(),
910//! # );
911//! # assert_eq!(
912//! #   AnyName { item: vec![()] },
913//! #   quick_xml::de::from_str(r#"<any-tag><item/></any-tag>"#).unwrap(),
914//! # );
915//! # assert_eq!(
916//! #   AnyName { item: vec![(), (), ()] },
917//! #   quick_xml::de::from_str(r#"<any-tag><item/><item/><item/></any-tag>"#).unwrap(),
918//! # );
919//! ```
920//!
921//! Use the [`Option`]. In that case inner array will always contains at least one
922//! element after deserialization:
923//! ```ignore
924//! # use pretty_assertions::assert_eq;
925//! # use serde::Deserialize;
926//! # type Item = ();
927//! # #[derive(Debug, PartialEq)]
928//! #[derive(Deserialize)]
929//! struct AnyName {
930//!   item: Option<Vec<Item>>,
931//! }
932//! # assert_eq!(
933//! #   AnyName { item: None },
934//! #   quick_xml::de::from_str(r#"<any-tag/>"#).unwrap(),
935//! # );
936//! # assert_eq!(
937//! #   AnyName { item: Some(vec![()]) },
938//! #   quick_xml::de::from_str(r#"<any-tag><item/></any-tag>"#).unwrap(),
939//! # );
940//! # assert_eq!(
941//! #   AnyName { item: Some(vec![(), (), ()]) },
942//! #   quick_xml::de::from_str(r#"<any-tag><item/><item/><item/></any-tag>"#).unwrap(),
943//! # );
944//! ```
945//!
946//! See also [Frequently Used Patterns](#element-lists).
947//!
948//! [field]: https://serde.rs/field-attrs.html#default
949//! [struct]: https://serde.rs/container-attrs.html#default
950//! </td>
951//! </tr>
952//! <!-- 14 ==================================================================================== -->
953//! <tr>
954//! <td>
955//! A sequence with a strict order, probably with mixed content
956//! (text / CDATA and tags):
957//!
958//! ```xml
959//! <one>...</one>
960//! text
961//! <![CDATA[cdata]]>
962//! <two>...</two>
963//! <one>...</one>
964//! ```
965//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
966//!
967//! NOTE: this is just an example for showing mapping. XML does not allow
968//! multiple root tags -- you should wrap the sequence into a tag.
969//! </div>
970//! </td>
971//! <td>
972//!
973//! All elements mapped to the heterogeneous sequential type: tuple or named tuple.
974//! Each element of the tuple should be able to be deserialized from the nested
975//! element content (`...`), except the enum types which would be deserialized
976//! from the full element (`<one>...</one>`), so they could use the element name
977//! to choose the right variant:
978//!
979//! ```
980//! # use pretty_assertions::assert_eq;
981//! # use serde::Deserialize;
982//! # type One = ();
983//! # type Two = ();
984//! # /*
985//! type One = ...;
986//! type Two = ...;
987//! # */
988//! # #[derive(Debug, PartialEq)]
989//! #[derive(Deserialize)]
990//! struct AnyName(One, String, Two, One);
991//! # assert_eq!(
992//! #   AnyName((), "text cdata".into(), (), ()),
993//! #   quick_xml::de::from_str(r#"<one>...</one>text <![CDATA[cdata]]><two>...</two><one>...</one>"#).unwrap(),
994//! # );
995//! ```
996//! ```
997//! # use pretty_assertions::assert_eq;
998//! # use serde::Deserialize;
999//! # #[derive(Debug, PartialEq)]
1000//! #[derive(Deserialize)]
1001//! #[serde(rename_all = "snake_case")]
1002//! enum Choice {
1003//!   One,
1004//! }
1005//! # type Two = ();
1006//! # /*
1007//! type Two = ...;
1008//! # */
1009//! type AnyName = (Choice, String, Two, Choice);
1010//! # assert_eq!(
1011//! #   (Choice::One, "text cdata".to_string(), (), Choice::One),
1012//! #   quick_xml::de::from_str(r#"<one>...</one>text <![CDATA[cdata]]><two>...</two><one>...</one>"#).unwrap(),
1013//! # );
1014//! ```
1015//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
1016//!
1017//! NOTE: consequent text and CDATA nodes are merged into the one text node,
1018//! so you cannot have two adjacent string types in your sequence.
1019//!
1020//! NOTE: In the case that the list might contain tags that are overlapped with
1021//! tags that do not correspond to the list you should add the feature [`overlapped-lists`].
1022//! </div>
1023//! </td>
1024//! </tr>
1025//! <!-- 15 ==================================================================================== -->
1026//! <tr>
1027//! <td>
1028//! A sequence with a non-strict order, probably with a mixed content
1029//! (text / CDATA and tags).
1030//!
1031//! ```xml
1032//! <one>...</one>
1033//! text
1034//! <![CDATA[cdata]]>
1035//! <two>...</two>
1036//! <one>...</one>
1037//! ```
1038//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
1039//!
1040//! NOTE: this is just an example for showing mapping. XML does not allow
1041//! multiple root tags -- you should wrap the sequence into a tag.
1042//! </div>
1043//! </td>
1044//! <td>
1045//! A homogeneous sequence of elements with a fixed or dynamic size:
1046//!
1047//! ```
1048//! # use pretty_assertions::assert_eq;
1049//! # use serde::Deserialize;
1050//! # #[derive(Debug, PartialEq)]
1051//! #[derive(Deserialize)]
1052//! #[serde(rename_all = "snake_case")]
1053//! enum Choice {
1054//!   One,
1055//!   Two,
1056//!   #[serde(other)]
1057//!   Other,
1058//! }
1059//! type AnyName = [Choice; 4];
1060//! # assert_eq!(
1061//! #   [Choice::One, Choice::Other, Choice::Two, Choice::One],
1062//! #   quick_xml::de::from_str::<AnyName>(r#"<one>...</one>text <![CDATA[cdata]]><two>...</two><one>...</one>"#).unwrap(),
1063//! # );
1064//! ```
1065//! ```
1066//! # use pretty_assertions::assert_eq;
1067//! # use serde::Deserialize;
1068//! # #[derive(Debug, PartialEq)]
1069//! #[derive(Deserialize)]
1070//! #[serde(rename_all = "snake_case")]
1071//! enum Choice {
1072//!   One,
1073//!   Two,
1074//!   #[serde(rename = "$text")]
1075//!   Other(String),
1076//! }
1077//! type AnyName = Vec<Choice>;
1078//! # assert_eq!(
1079//! #   vec![
1080//! #     Choice::One,
1081//! #     Choice::Other("text cdata".into()),
1082//! #     Choice::Two,
1083//! #     Choice::One,
1084//! #   ],
1085//! #   quick_xml::de::from_str::<AnyName>(r#"<one>...</one>text <![CDATA[cdata]]><two>...</two><one>...</one>"#).unwrap(),
1086//! # );
1087//! ```
1088//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
1089//!
1090//! NOTE: consequent text and CDATA nodes are merged into the one text node,
1091//! so you cannot have two adjacent string types in your sequence.
1092//! </div>
1093//! </td>
1094//! </tr>
1095//! <!-- 16 ==================================================================================== -->
1096//! <tr>
1097//! <td>
1098//! A sequence with a strict order, probably with a mixed content,
1099//! (text and tags) inside of the other element:
1100//!
1101//! ```xml
1102//! <any-tag attribute="...">
1103//!   <one>...</one>
1104//!   text
1105//!   <![CDATA[cdata]]>
1106//!   <two>...</two>
1107//!   <one>...</one>
1108//! </any-tag>
1109//! ```
1110//! </td>
1111//! <td>
1112//!
1113//! A structure where all child elements mapped to the one field which have
1114//! a heterogeneous sequential type: tuple or named tuple. Each element of the
1115//! tuple should be able to be deserialized from the full element (`<one>...</one>`).
1116//!
1117//! You MUST specify `#[serde(rename = "$value")]` on that field:
1118//!
1119//! ```
1120//! # use pretty_assertions::assert_eq;
1121//! # use serde::Deserialize;
1122//! # type One = ();
1123//! # type Two = ();
1124//! # /*
1125//! type One = ...;
1126//! type Two = ...;
1127//! # */
1128//!
1129//! # #[derive(Debug, PartialEq)]
1130//! #[derive(Deserialize)]
1131//! struct AnyName {
1132//!   #[serde(rename = "@attribute")]
1133//! # attribute: (),
1134//! # /*
1135//!   attribute: ...,
1136//! # */
1137//!   // Does not (yet?) supported by the serde
1138//!   // https://github.com/serde-rs/serde/issues/1905
1139//!   // #[serde(flatten)]
1140//!   #[serde(rename = "$value")]
1141//!   any_name: (One, String, Two, One),
1142//! }
1143//! # assert_eq!(
1144//! #   AnyName { attribute: (), any_name: ((), "text cdata".into(), (), ()) },
1145//! #   quick_xml::de::from_str("\
1146//! #     <any-tag attribute='...'>\
1147//! #       <one>...</one>\
1148//! #       text \
1149//! #       <![CDATA[cdata]]>\
1150//! #       <two>...</two>\
1151//! #       <one>...</one>\
1152//! #     </any-tag>"
1153//! #   ).unwrap(),
1154//! # );
1155//! ```
1156//! ```
1157//! # use pretty_assertions::assert_eq;
1158//! # use serde::Deserialize;
1159//! # type One = ();
1160//! # type Two = ();
1161//! # /*
1162//! type One = ...;
1163//! type Two = ...;
1164//! # */
1165//!
1166//! # #[derive(Debug, PartialEq)]
1167//! #[derive(Deserialize)]
1168//! struct NamedTuple(One, String, Two, One);
1169//!
1170//! # #[derive(Debug, PartialEq)]
1171//! #[derive(Deserialize)]
1172//! struct AnyName {
1173//!   #[serde(rename = "@attribute")]
1174//! # attribute: (),
1175//! # /*
1176//!   attribute: ...,
1177//! # */
1178//!   // Does not (yet?) supported by the serde
1179//!   // https://github.com/serde-rs/serde/issues/1905
1180//!   // #[serde(flatten)]
1181//!   #[serde(rename = "$value")]
1182//!   any_name: NamedTuple,
1183//! }
1184//! # assert_eq!(
1185//! #   AnyName { attribute: (), any_name: NamedTuple((), "text cdata".into(), (), ()) },
1186//! #   quick_xml::de::from_str("\
1187//! #     <any-tag attribute='...'>\
1188//! #       <one>...</one>\
1189//! #       text \
1190//! #       <![CDATA[cdata]]>\
1191//! #       <two>...</two>\
1192//! #       <one>...</one>\
1193//! #     </any-tag>"
1194//! #   ).unwrap(),
1195//! # );
1196//! ```
1197//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
1198//!
1199//! NOTE: consequent text and CDATA nodes are merged into the one text node,
1200//! so you cannot have two adjacent string types in your sequence.
1201//! </div>
1202//! </td>
1203//! </tr>
1204//! <!-- 17 ==================================================================================== -->
1205//! <tr>
1206//! <td>
1207//! A sequence with a non-strict order, probably with a mixed content
1208//! (text / CDATA and tags) inside of the other element:
1209//!
1210//! ```xml
1211//! <any-tag>
1212//!   <one>...</one>
1213//!   text
1214//!   <![CDATA[cdata]]>
1215//!   <two>...</two>
1216//!   <one>...</one>
1217//! </any-tag>
1218//! ```
1219//! </td>
1220//! <td>
1221//!
1222//! A structure where all child elements mapped to the one field which have
1223//! a homogeneous sequential type: array-like container. A container type `T`
1224//! should be able to be deserialized from the nested element content (`...`),
1225//! except if it is an enum type which would be deserialized from the full
1226//! element (`<one>...</one>`).
1227//!
1228//! You MUST specify `#[serde(rename = "$value")]` on that field:
1229//!
1230//! ```
1231//! # use pretty_assertions::assert_eq;
1232//! # use serde::Deserialize;
1233//! # #[derive(Debug, PartialEq)]
1234//! #[derive(Deserialize)]
1235//! #[serde(rename_all = "snake_case")]
1236//! enum Choice {
1237//!   One,
1238//!   Two,
1239//!   #[serde(rename = "$text")]
1240//!   Other(String),
1241//! }
1242//! # #[derive(Debug, PartialEq)]
1243//! #[derive(Deserialize)]
1244//! struct AnyName {
1245//!   #[serde(rename = "@attribute")]
1246//! # attribute: (),
1247//! # /*
1248//!   attribute: ...,
1249//! # */
1250//!   // Does not (yet?) supported by the serde
1251//!   // https://github.com/serde-rs/serde/issues/1905
1252//!   // #[serde(flatten)]
1253//!   #[serde(rename = "$value")]
1254//!   any_name: [Choice; 4],
1255//! }
1256//! # assert_eq!(
1257//! #   AnyName { attribute: (), any_name: [
1258//! #     Choice::One,
1259//! #     Choice::Other("text cdata".into()),
1260//! #     Choice::Two,
1261//! #     Choice::One,
1262//! #   ] },
1263//! #   quick_xml::de::from_str("\
1264//! #     <any-tag attribute='...'>\
1265//! #       <one>...</one>\
1266//! #       text \
1267//! #       <![CDATA[cdata]]>\
1268//! #       <two>...</two>\
1269//! #       <one>...</one>\
1270//! #     </any-tag>"
1271//! #   ).unwrap(),
1272//! # );
1273//! ```
1274//! ```
1275//! # use pretty_assertions::assert_eq;
1276//! # use serde::Deserialize;
1277//! # #[derive(Debug, PartialEq)]
1278//! #[derive(Deserialize)]
1279//! #[serde(rename_all = "snake_case")]
1280//! enum Choice {
1281//!   One,
1282//!   Two,
1283//!   #[serde(rename = "$text")]
1284//!   Other(String),
1285//! }
1286//! # #[derive(Debug, PartialEq)]
1287//! #[derive(Deserialize)]
1288//! struct AnyName {
1289//!   #[serde(rename = "@attribute")]
1290//! # attribute: (),
1291//! # /*
1292//!   attribute: ...,
1293//! # */
1294//!   // Does not (yet?) supported by the serde
1295//!   // https://github.com/serde-rs/serde/issues/1905
1296//!   // #[serde(flatten)]
1297//!   #[serde(rename = "$value")]
1298//!   any_name: Vec<Choice>,
1299//! }
1300//! # assert_eq!(
1301//! #   AnyName { attribute: (), any_name: vec![
1302//! #     Choice::One,
1303//! #     Choice::Other("text cdata".into()),
1304//! #     Choice::Two,
1305//! #     Choice::One,
1306//! #   ] },
1307//! #   quick_xml::de::from_str("\
1308//! #     <any-tag attribute='...'>\
1309//! #       <one>...</one>\
1310//! #       text \
1311//! #       <![CDATA[cdata]]>\
1312//! #       <two>...</two>\
1313//! #       <one>...</one>\
1314//! #     </any-tag>"
1315//! #   ).unwrap(),
1316//! # );
1317//! ```
1318//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
1319//!
1320//! NOTE: consequent text and CDATA nodes are merged into the one text node,
1321//! so you cannot have two adjacent string types in your sequence.
1322//! </div>
1323//! </td>
1324//! </tr>
1325//! </tbody>
1326//! </table>
1327//!
1328//!
1329//! Mapping of `xsi:nil`
1330//! ====================
1331//!
1332//! quick-xml supports handling of [`xsi:nil`] special attribute. When field of optional
1333//! type is mapped to the XML element which have `xsi:nil="true"` set, or if that attribute
1334//! is placed on parent XML element, the deserializer will call [`Visitor::visit_none`]
1335//! and skip XML element corresponding to a field.
1336//!
1337//! Examples:
1338//!
1339//! ```
1340//! # use pretty_assertions::assert_eq;
1341//! # use serde::Deserialize;
1342//! #[derive(Deserialize, Debug, PartialEq)]
1343//! struct TypeWithOptionalField {
1344//!   element: Option<String>,
1345//! }
1346//!
1347//! assert_eq!(
1348//!   TypeWithOptionalField {
1349//!     element: None,
1350//!   },
1351//!   quick_xml::de::from_str("
1352//!     <any-tag xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
1353//!       <element xsi:nil='true'>Content is skiped because of xsi:nil='true'</element>
1354//!     </any-tag>
1355//!   ").unwrap(),
1356//! );
1357//! ```
1358//!
1359//! You can capture attributes from the optional type, because ` xsi:nil="true"` elements can have
1360//! attributes:
1361//! ```
1362//! # use pretty_assertions::assert_eq;
1363//! # use serde::Deserialize;
1364//! #[derive(Deserialize, Debug, PartialEq)]
1365//! struct TypeWithOptionalField {
1366//!   #[serde(rename = "@attribute")]
1367//!   attribute: usize,
1368//!
1369//!   element: Option<String>,
1370//!   non_optional: String,
1371//! }
1372//!
1373//! assert_eq!(
1374//!   TypeWithOptionalField {
1375//!     attribute: 42,
1376//!     element: None,
1377//!     non_optional: "Note, that non-optional fields will be deserialized as usual".to_string(),
1378//!   },
1379//!   quick_xml::de::from_str("
1380//!     <any-tag attribute='42' xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
1381//!       <element>Content is skiped because of xsi:nil='true'</element>
1382//!       <non_optional>Note, that non-optional fields will be deserialized as usual</non_optional>
1383//!     </any-tag>
1384//!   ").unwrap(),
1385//! );
1386//! ```
1387//!
1388//! Generate Rust types from XML
1389//! ============================
1390//!
1391//! To speed up the creation of Rust types that represent a given XML file you can
1392//! use the [xml_schema_generator](https://github.com/Thomblin/xml_schema_generator).
1393//! It provides a standalone binary and a Rust library that parses one or more XML files
1394//! and generates a collection of structs that are compatible with quick_xml::de.
1395//!
1396//!
1397//!
1398//! Composition Rules
1399//! =================
1400//!
1401//! The XML format is very different from other formats supported by `serde`.
1402//! One such difference it is how data in the serialized form is related to
1403//! the Rust type. Usually each byte in the data can be associated only with
1404//! one field in the data structure. However, XML is an exception.
1405//!
1406//! For example, took this XML:
1407//!
1408//! ```xml
1409//! <any>
1410//!   <key attr="value"/>
1411//! </any>
1412//! ```
1413//!
1414//! and try to deserialize it to the struct `AnyName`:
1415//!
1416//! ```no_run
1417//! # use serde::Deserialize;
1418//! #[derive(Deserialize)]
1419//! struct AnyName { // AnyName calls `deserialize_struct` on `<any><key attr="value"/></any>`
1420//!                  //                         Used data:          ^^^^^^^^^^^^^^^^^^^
1421//!   key: Inner,    // Inner   calls `deserialize_struct` on `<key attr="value"/>`
1422//!                  //                         Used data:          ^^^^^^^^^^^^
1423//! }
1424//! #[derive(Deserialize)]
1425//! struct Inner {
1426//!   #[serde(rename = "@attr")]
1427//!   attr: String,  // String  calls `deserialize_string` on `value`
1428//!                  //                         Used data:     ^^^^^
1429//! }
1430//! ```
1431//!
1432//! Comments shows what methods of a [`Deserializer`] called by each struct
1433//! `deserialize` method and which input their seen. **Used data** shows, what
1434//! content is actually used for deserializing. As you see, name of the inner
1435//! `<key>` tag used both as a map key / outer struct field name and as part
1436//! of the inner struct (although _value_ of the tag, i.e. `key` is not used
1437//! by it).
1438//!
1439//!
1440//!
1441//! Enum Representations
1442//! ====================
1443//!
1444//! `quick-xml` represents enums differently in normal fields, `$text` fields and
1445//! `$value` fields. A normal representation is compatible with serde's adjacent
1446//! and internal tags feature -- tag for adjacently and internally tagged enums
1447//! are serialized using [`Serializer::serialize_unit_variant`] and deserialized
1448//! using [`Deserializer::deserialize_enum`].
1449//!
1450//! Use those simple rules to remember, how enum would be represented in XML:
1451//! - In `$value` field the representation is always the same as top-level representation;
1452//! - In `$text` field the representation is always the same as in normal field,
1453//!   but surrounding tags with field name are removed;
1454//! - In normal field the representation is always contains a tag with a field name.
1455//!
1456//! Normal enum variant
1457//! -------------------
1458//!
1459//! To model an `xs:choice` XML construct use `$value` field.
1460//! To model a top-level `xs:choice` just use the enum type.
1461//!
1462//! |Kind   |Top-level and in `$value` field          |In normal field      |In `$text` field     |
1463//! |-------|-----------------------------------------|---------------------|---------------------|
1464//! |Unit   |`<Unit/>`                                |`<field>Unit</field>`|`Unit`               |
1465//! |Newtype|`<Newtype>42</Newtype>`                  |Err(Custom) [^0]     |Err(Custom) [^0]     |
1466//! |Tuple  |`<Tuple>42</Tuple><Tuple>answer</Tuple>` |Err(Custom) [^0]     |Err(Custom) [^0]     |
1467//! |Struct |`<Struct><q>42</q><a>answer</a></Struct>`|Err(Custom) [^0]     |Err(Custom) [^0]     |
1468//!
1469//! `$text` enum variant
1470//! --------------------
1471//!
1472//! |Kind   |Top-level and in `$value` field          |In normal field      |In `$text` field     |
1473//! |-------|-----------------------------------------|---------------------|---------------------|
1474//! |Unit   |_(empty)_                                |`<field/>`           |_(empty)_            |
1475//! |Newtype|`42`                                     |Err(Custom) [^0] [^1]|Err(Custom) [^0] [^2]|
1476//! |Tuple  |`42 answer`                              |Err(Custom) [^0] [^3]|Err(Custom) [^0] [^4]|
1477//! |Struct |Err(Custom) [^0]                         |Err(Custom) [^0]     |Err(Custom) [^0]     |
1478//!
1479//! [^0]: Error is returned by the deserialized type. In case of derived implementation a `Custom`
1480//!       error will be returned, but custom deserialize implementation can successfully deserialize
1481//!       value from a string which will be passed to it.
1482//!
1483//! [^1]: If this serialize as `<field>42</field>` then it will be ambiguity during deserialization,
1484//!       because it clash with `Unit` representation in normal field.
1485//!
1486//! [^2]: If this serialize as `42` then it will be ambiguity during deserialization,
1487//!       because it clash with `Unit` representation in `$text` field.
1488//!
1489//! [^3]: If this serialize as `<field>42 answer</field>` then it will be ambiguity during deserialization,
1490//!       because it clash with `Unit` representation in normal field.
1491//!
1492//! [^4]: If this serialize as `42 answer` then it will be ambiguity during deserialization,
1493//!       because it clash with `Unit` representation in `$text` field.
1494//!
1495//!
1496//!
1497//! `$text` and `$value` special names
1498//! ==================================
1499//!
1500//! quick-xml supports two special names for fields -- `$text` and `$value`.
1501//! Although they may seem the same, there is a distinction. Two different
1502//! names is required mostly for serialization, because quick-xml should know
1503//! how you want to serialize certain constructs, which could be represented
1504//! through XML in multiple different ways.
1505//!
1506//! The only difference is in how complex types and sequences are serialized.
1507//! If you doubt which one you should select, begin with [`$value`](#value).
1508//!
1509//! If you have both `$text` and `$value` in you struct, then text events will be
1510//! mapped to the `$text` field:
1511//!
1512//! ```
1513//! # use serde::Deserialize;
1514//! # use quick_xml::de::from_str;
1515//! #[derive(Deserialize, PartialEq, Debug)]
1516//! struct TextAndValue {
1517//!     #[serde(rename = "$text")]
1518//!     text: Option<String>,
1519//!
1520//!     #[serde(rename = "$value")]
1521//!     value: Option<String>,
1522//! }
1523//!
1524//! let object: TextAndValue = from_str("<AnyName>text <![CDATA[and CDATA]]></AnyName>").unwrap();
1525//! assert_eq!(object, TextAndValue {
1526//!     text: Some("text and CDATA".to_string()),
1527//!     value: None,
1528//! });
1529//! ```
1530//!
1531//! ## `$text`
1532//! `$text` is used when you want to write your XML as a text or a CDATA content.
1533//! More formally, field with that name represents simple type definition with
1534//! `{variety} = atomic` or `{variety} = union` whose basic members are all atomic,
1535//! as described in the [specification].
1536//!
1537//! As a result, not all types of such fields can be serialized. Only serialization
1538//! of following types are supported:
1539//! - all primitive types (strings, numbers, booleans)
1540//! - unit variants of enumerations (serializes to a name of a variant)
1541//! - newtypes (delegates serialization to inner type)
1542//! - [`Option`] of above (`None` serializes to nothing)
1543//! - sequences (including tuples and tuple variants of enumerations) of above,
1544//!   excluding `None` and empty string elements (because it will not be possible
1545//!   to deserialize them back). The elements are separated by space(s)
1546//! - unit type `()` and unit structs (serializes to nothing)
1547//!
1548//! Complex types, such as structs and maps, are not supported in this field.
1549//! If you want them, you should use `$value`.
1550//!
1551//! Sequences serialized to a space-delimited string, that is why only certain
1552//! types are allowed in this mode:
1553//!
1554//! ```
1555//! # use serde::{Deserialize, Serialize};
1556//! # use quick_xml::de::from_str;
1557//! # use quick_xml::se::to_string;
1558//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1559//! struct AnyName {
1560//!     #[serde(rename = "$text")]
1561//!     field: Vec<usize>,
1562//! }
1563//!
1564//! let obj = AnyName { field: vec![1, 2, 3] };
1565//! let xml = to_string(&obj).unwrap();
1566//! assert_eq!(xml, "<AnyName>1 2 3</AnyName>");
1567//!
1568//! let object: AnyName = from_str(&xml).unwrap();
1569//! assert_eq!(object, obj);
1570//! ```
1571//!
1572//! ## `$value`
1573//! <div style="background:rgba(120,145,255,0.45);padding:0.75em;">
1574//!
1575//! NOTE: a name `#content` would better explain the purpose of that field,
1576//! but `$value` is used for compatibility with other XML serde crates, which
1577//! uses that name. This will allow you to switch XML crates more smoothly if required.
1578//! </div>
1579//!
1580//! The representation of primitive types in `$value` does not differ from their
1581//! representation in `$text` fields. The difference is how sequences are serialized
1582//! and deserialized. `$value` serializes each sequence item as a separate XML element.
1583//! How the name of the XML element is chosen depends on the field's type. For
1584//! `enum`s, the variant name is used. For `struct`s, the name of the `struct`
1585//! is used.
1586//!
1587//! During deserialization, if the `$value` field is an enum, then the variant's
1588//! name is matched against. That's **not** the case with structs, however, since
1589//! `serde` does not expose type names of nested fields. This does mean that **any**
1590//! type could be deserialized into a `$value` struct-type field, so long as the
1591//! struct's fields have compatible types (or are captured as text by `String`
1592//! or similar-behaving types). This can be handy when using generic types in fields
1593//! where one knows in advance what to expect. If you do not know what to expect,
1594//! however, prefer an enum with all possible variants.
1595//!
1596//! Unit structs and unit type `()` serialize to nothing and can be deserialized
1597//! from any content.
1598//!
1599//! Serialization and deserialization of `$value` field performed as usual, except
1600//! that name for an XML element will be given by the serialized type, instead of
1601//! field. The latter allow to serialize enumerated types, where variant is encoded
1602//! as a tag name, and, so, represent an XSD `xs:choice` schema by the Rust `enum`.
1603//!
1604//! In the example below, field will be serialized as `<field/>`, because elements
1605//! get their names from the field name. It cannot be deserialized, because `Enum`
1606//! expects elements `<A/>`, `<B/>` or `<C/>`, but `AnyName` looked only for `<field/>`:
1607//!
1608//! ```
1609//! # use serde::{Deserialize, Serialize};
1610//! # use pretty_assertions::assert_eq;
1611//! # #[derive(PartialEq, Debug)]
1612//! #[derive(Deserialize, Serialize)]
1613//! enum Enum { A, B, C }
1614//!
1615//! # #[derive(PartialEq, Debug)]
1616//! #[derive(Deserialize, Serialize)]
1617//! struct AnyName {
1618//!     // <field>A</field>, <field>B</field>, or <field>C</field>
1619//!     field: Enum,
1620//! }
1621//! # assert_eq!(
1622//! #     quick_xml::se::to_string(&AnyName { field: Enum::A }).unwrap(),
1623//! #     "<AnyName><field>A</field></AnyName>",
1624//! # );
1625//! # assert_eq!(
1626//! #     AnyName { field: Enum::B },
1627//! #     quick_xml::de::from_str("<root><field>B</field></root>").unwrap(),
1628//! # );
1629//! ```
1630//!
1631//! If you rename field to `$value`, then `field` would be serialized as `<A/>`,
1632//! `<B/>` or `<C/>`, depending on the its content. It is also possible to
1633//! deserialize it from the same elements:
1634//!
1635//! ```
1636//! # use serde::{Deserialize, Serialize};
1637//! # use pretty_assertions::assert_eq;
1638//! # #[derive(Deserialize, Serialize, PartialEq, Debug)]
1639//! # enum Enum { A, B, C }
1640//! #
1641//! # #[derive(PartialEq, Debug)]
1642//! #[derive(Deserialize, Serialize)]
1643//! struct AnyName {
1644//!     // <A/>, <B/> or <C/>
1645//!     #[serde(rename = "$value")]
1646//!     field: Enum,
1647//! }
1648//! # assert_eq!(
1649//! #     quick_xml::se::to_string(&AnyName { field: Enum::A }).unwrap(),
1650//! #     "<AnyName><A/></AnyName>",
1651//! # );
1652//! # assert_eq!(
1653//! #     AnyName { field: Enum::B },
1654//! #     quick_xml::de::from_str("<root><B/></root>").unwrap(),
1655//! # );
1656//! ```
1657//!
1658//! The next example demonstrates how generic types can be used in conjunction
1659//! with `$value`-named fields to allow the reuse of wrapping structs. A common
1660//! example use case for this feature is SOAP messages, which can be commmonly
1661//! found wrapped around `<soapenv:Envelope> ... </soapenv:Envelope>`.
1662//!
1663//! ```rust
1664//! # use pretty_assertions::assert_eq;
1665//! # use quick_xml::de::from_str;
1666//! # use quick_xml::se::to_string;
1667//! # use serde::{Deserialize, Serialize};
1668//! #
1669//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1670//! struct Envelope<T> {
1671//!     body: Body<T>,
1672//! }
1673//!
1674//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1675//! struct Body<T> {
1676//!     #[serde(rename = "$value")]
1677//!     inner: T,
1678//! }
1679//!
1680//! #[derive(Serialize, PartialEq, Debug)]
1681//! struct Example {
1682//!     a: i32,
1683//! }
1684//!
1685//! assert_eq!(
1686//!     to_string(&Envelope { body: Body { inner: Example { a: 42 } } }).unwrap(),
1687//!     // Notice how `inner` is not present in the XML
1688//!     "<Envelope><body><Example><a>42</a></Example></body></Envelope>",
1689//! );
1690//!
1691//! #[derive(Deserialize, PartialEq, Debug)]
1692//! struct AnotherExample {
1693//!     a: i32,
1694//! }
1695//!
1696//! assert_eq!(
1697//!     // Notice that tag the name does nothing for struct in `$value` field
1698//!     Envelope { body: Body { inner: AnotherExample { a: 42 } } },
1699//!     from_str("<Envelope><body><Example><a>42</a></Example></body></Envelope>").unwrap(),
1700//! );
1701//! ```
1702//!
1703//! ### Primitives and sequences of primitives
1704//!
1705//! Sequences serialized to a list of elements. Note, that types that does not
1706//! produce their own tag (i. e. primitives) will produce [`SeError::Unsupported`]
1707//! if they contains more that one element, because such sequence cannot be
1708//! deserialized to the same value:
1709//!
1710//! ```
1711//! # use serde::{Deserialize, Serialize};
1712//! # use pretty_assertions::assert_eq;
1713//! # use quick_xml::de::from_str;
1714//! # use quick_xml::se::to_string;
1715//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1716//! struct AnyName {
1717//!     #[serde(rename = "$value")]
1718//!     field: Vec<usize>,
1719//! }
1720//!
1721//! let obj = AnyName { field: vec![1, 2, 3] };
1722//! // If this object were serialized, it would be represented as "<AnyName>123</AnyName>"
1723//! to_string(&obj).unwrap_err();
1724//!
1725//! let object: AnyName = from_str("<AnyName>123</AnyName>").unwrap();
1726//! assert_eq!(object, AnyName { field: vec![123] });
1727//!
1728//! // `1 2 3` is mapped to a single `usize` element
1729//! // It is impossible to deserialize list of primitives to such field
1730//! from_str::<AnyName>("<AnyName>1 2 3</AnyName>").unwrap_err();
1731//! ```
1732//!
1733//! A particular case of that example is a string `$value` field, which probably
1734//! would be a most used example of that attribute:
1735//!
1736//! ```
1737//! # use serde::{Deserialize, Serialize};
1738//! # use pretty_assertions::assert_eq;
1739//! # use quick_xml::de::from_str;
1740//! # use quick_xml::se::to_string;
1741//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1742//! struct AnyName {
1743//!     #[serde(rename = "$value")]
1744//!     field: String,
1745//! }
1746//!
1747//! let obj = AnyName { field: "content".to_string() };
1748//! let xml = to_string(&obj).unwrap();
1749//! assert_eq!(xml, "<AnyName>content</AnyName>");
1750//! ```
1751//!
1752//! ### Structs and sequences of structs
1753//!
1754//! Note, that structures do not have a serializable name as well (name of the
1755//! type is never used), so it is impossible to serialize non-unit struct or
1756//! sequence of non-unit structs in `$value` field. (sequences of) unit structs
1757//! are serialized as empty string, because units itself serializing
1758//! to nothing:
1759//!
1760//! ```
1761//! # use serde::{Deserialize, Serialize};
1762//! # use pretty_assertions::assert_eq;
1763//! # use quick_xml::de::from_str;
1764//! # use quick_xml::se::to_string;
1765//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1766//! struct Unit;
1767//!
1768//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1769//! struct AnyName {
1770//!     // #[serde(default)] is required to deserialization of empty lists
1771//!     // This is a general note, not related to $value
1772//!     #[serde(rename = "$value", default)]
1773//!     field: Vec<Unit>,
1774//! }
1775//!
1776//! let obj = AnyName { field: vec![Unit, Unit, Unit] };
1777//! let xml = to_string(&obj).unwrap();
1778//! assert_eq!(xml, "<AnyName/>");
1779//!
1780//! let object: AnyName = from_str("<AnyName/>").unwrap();
1781//! assert_eq!(object, AnyName { field: vec![] });
1782//!
1783//! let object: AnyName = from_str("<AnyName></AnyName>").unwrap();
1784//! assert_eq!(object, AnyName { field: vec![] });
1785//!
1786//! let object: AnyName = from_str("<AnyName><A/><B/><C/></AnyName>").unwrap();
1787//! assert_eq!(object, AnyName { field: vec![Unit, Unit, Unit] });
1788//! ```
1789//!
1790//! ### Enums and sequences of enums
1791//!
1792//! Enumerations uses the variant name as an element name:
1793//!
1794//! ```
1795//! # use serde::{Deserialize, Serialize};
1796//! # use pretty_assertions::assert_eq;
1797//! # use quick_xml::de::from_str;
1798//! # use quick_xml::se::to_string;
1799//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1800//! struct AnyName {
1801//!     #[serde(rename = "$value")]
1802//!     field: Vec<Enum>,
1803//! }
1804//!
1805//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1806//! enum Enum { A, B, C }
1807//!
1808//! let obj = AnyName { field: vec![Enum::A, Enum::B, Enum::C] };
1809//! let xml = to_string(&obj).unwrap();
1810//! assert_eq!(
1811//!     xml,
1812//!     "<AnyName>\
1813//!         <A/>\
1814//!         <B/>\
1815//!         <C/>\
1816//!      </AnyName>"
1817//! );
1818//!
1819//! let object: AnyName = from_str(&xml).unwrap();
1820//! assert_eq!(object, obj);
1821//! ```
1822//!
1823//!
1824//!
1825//! Frequently Used Patterns
1826//! ========================
1827//!
1828//! Some XML constructs used so frequent, that it is worth to document the recommended
1829//! way to represent them in the Rust. The sections below describes them.
1830//!
1831//! `<element>` lists
1832//! -----------------
1833//! Many XML formats wrap lists of elements in the additional container,
1834//! although this is not required by the XML rules:
1835//!
1836//! ```xml
1837//! <root>
1838//!   <field1/>
1839//!   <field2/>
1840//!   <list><!-- Container -->
1841//!     <element/>
1842//!     <element/>
1843//!     <element/>
1844//!   </list>
1845//!   <field3/>
1846//! </root>
1847//! ```
1848//! In this case, there is a great desire to describe this XML in this way:
1849//! ```
1850//! /// Represents <element/>
1851//! type Element = ();
1852//!
1853//! /// Represents <root>...</root>
1854//! struct AnyName {
1855//!     // Incorrect
1856//!     list: Vec<Element>,
1857//! }
1858//! ```
1859//! This will not work, because potentially `<list>` element can have attributes
1860//! and other elements inside. You should define the struct for the `<list>`
1861//! explicitly, as you do that in the XSD for that XML:
1862//! ```
1863//! /// Represents <element/>
1864//! type Element = ();
1865//!
1866//! /// Represents <root>...</root>
1867//! struct AnyName {
1868//!     // Correct
1869//!     list: List,
1870//! }
1871//! /// Represents <list>...</list>
1872//! struct List {
1873//!     element: Vec<Element>,
1874//! }
1875//! ```
1876//!
1877//! If you want to simplify your API, you could write a simple function for unwrapping
1878//! inner list and apply it via [`deserialize_with`]:
1879//!
1880//! ```
1881//! # use pretty_assertions::assert_eq;
1882//! use quick_xml::de::from_str;
1883//! use serde::{Deserialize, Deserializer};
1884//!
1885//! /// Represents <element/>
1886//! type Element = ();
1887//!
1888//! /// Represents <root>...</root>
1889//! #[derive(Deserialize, Debug, PartialEq)]
1890//! struct AnyName {
1891//!     #[serde(deserialize_with = "unwrap_list")]
1892//!     list: Vec<Element>,
1893//! }
1894//!
1895//! fn unwrap_list<'de, D>(deserializer: D) -> Result<Vec<Element>, D::Error>
1896//! where
1897//!     D: Deserializer<'de>,
1898//! {
1899//!     /// Represents <list>...</list>
1900//!     #[derive(Deserialize)]
1901//!     struct List {
1902//!         // default allows empty list
1903//!         #[serde(default)]
1904//!         element: Vec<Element>,
1905//!     }
1906//!     Ok(List::deserialize(deserializer)?.element)
1907//! }
1908//!
1909//! assert_eq!(
1910//!     AnyName { list: vec![(), (), ()] },
1911//!     from_str("
1912//!         <root>
1913//!           <list>
1914//!             <element/>
1915//!             <element/>
1916//!             <element/>
1917//!           </list>
1918//!         </root>
1919//!     ").unwrap(),
1920//! );
1921//! ```
1922//!
1923//! Instead of writing such functions manually, you also could try <https://lib.rs/crates/serde-query>.
1924//!
1925//! Overlapped (Out-of-Order) Elements
1926//! ----------------------------------
1927//! In the case that the list might contain tags that are overlapped with
1928//! tags that do not correspond to the list (this is a usual case in XML
1929//! documents) like this:
1930//! ```xml
1931//! <any-name>
1932//!   <item/>
1933//!   <another-item/>
1934//!   <item/>
1935//!   <item/>
1936//! </any-name>
1937//! ```
1938//! you should enable the [`overlapped-lists`] feature to make it possible
1939//! to deserialize this to:
1940//! ```no_run
1941//! # use serde::Deserialize;
1942//! #[derive(Deserialize)]
1943//! #[serde(rename_all = "kebab-case")]
1944//! struct AnyName {
1945//!     item: Vec<()>,
1946//!     another_item: (),
1947//! }
1948//! ```
1949//!
1950//!
1951//! Internally Tagged Enums
1952//! -----------------------
1953//! [Tagged enums] are currently not supported because of an issue in the Serde
1954//! design (see [serde#1183] and [quick-xml#586]) and missing optimizations in
1955//! Serde which could be useful for XML parsing ([serde#1495]). This can be worked
1956//! around by manually implementing deserialize with `#[serde(deserialize_with = "func")]`
1957//! or implementing [`Deserialize`], but this can get very tedious very fast for
1958//! files with large amounts of tagged enums. To help with this issue quick-xml
1959//! provides a macro [`impl_deserialize_for_internally_tagged_enum!`]. See the
1960//! macro documentation for details.
1961//!
1962//!
1963//! [`overlapped-lists`]: ../index.html#overlapped-lists
1964//! [specification]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition
1965//! [`deserialize_with`]: https://serde.rs/field-attrs.html#deserialize_with
1966//! [`xsi:nil`]: https://www.w3.org/TR/xmlschema-1/#xsi_nil
1967//! [`Serializer::serialize_unit_variant`]: serde::Serializer::serialize_unit_variant
1968//! [`Deserializer::deserialize_enum`]: serde::Deserializer::deserialize_enum
1969//! [`SeError::Unsupported`]: crate::errors::serialize::SeError::Unsupported
1970//! [Tagged enums]: https://serde.rs/enum-representations.html#internally-tagged
1971//! [serde#1183]: https://github.com/serde-rs/serde/issues/1183
1972//! [serde#1495]: https://github.com/serde-rs/serde/issues/1495
1973//! [quick-xml#586]: https://github.com/tafia/quick-xml/issues/586
1974//! [`impl_deserialize_for_internally_tagged_enum!`]: crate::impl_deserialize_for_internally_tagged_enum
1975
1976// Macros should be defined before the modules that using them
1977// Also, macros should be imported before using them
1978use serde::serde_if_integer128;
1979
1980macro_rules! deserialize_num {
1981    ($deserialize:ident => $visit:ident, $($mut:tt)?) => {
1982        fn $deserialize<V>($($mut)? self, visitor: V) -> Result<V::Value, DeError>
1983        where
1984            V: Visitor<'de>,
1985        {
1986            // No need to unescape because valid integer representations cannot be escaped
1987            let text = self.read_string()?;
1988            match text.parse() {
1989                Ok(number) => visitor.$visit(number),
1990                Err(_) => match text {
1991                    Cow::Borrowed(t) => visitor.visit_str(t),
1992                    Cow::Owned(t) => visitor.visit_string(t),
1993                }
1994            }
1995        }
1996    };
1997}
1998
1999/// Implement deserialization methods for scalar types, such as numbers, strings,
2000/// byte arrays, booleans and identifiers.
2001macro_rules! deserialize_primitives {
2002    ($($mut:tt)?) => {
2003        deserialize_num!(deserialize_i8 => visit_i8, $($mut)?);
2004        deserialize_num!(deserialize_i16 => visit_i16, $($mut)?);
2005        deserialize_num!(deserialize_i32 => visit_i32, $($mut)?);
2006        deserialize_num!(deserialize_i64 => visit_i64, $($mut)?);
2007
2008        deserialize_num!(deserialize_u8 => visit_u8, $($mut)?);
2009        deserialize_num!(deserialize_u16 => visit_u16, $($mut)?);
2010        deserialize_num!(deserialize_u32 => visit_u32, $($mut)?);
2011        deserialize_num!(deserialize_u64 => visit_u64, $($mut)?);
2012
2013        serde_if_integer128! {
2014            deserialize_num!(deserialize_i128 => visit_i128, $($mut)?);
2015            deserialize_num!(deserialize_u128 => visit_u128, $($mut)?);
2016        }
2017
2018        deserialize_num!(deserialize_f32 => visit_f32, $($mut)?);
2019        deserialize_num!(deserialize_f64 => visit_f64, $($mut)?);
2020
2021        fn deserialize_bool<V>($($mut)? self, visitor: V) -> Result<V::Value, DeError>
2022        where
2023            V: Visitor<'de>,
2024        {
2025            let text = match self.read_string()? {
2026                Cow::Borrowed(s) => CowRef::Input(s),
2027                Cow::Owned(s) => CowRef::Owned(s),
2028            };
2029            text.deserialize_bool(visitor)
2030        }
2031
2032        /// Character represented as [strings](#method.deserialize_str).
2033        #[inline]
2034        fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, DeError>
2035        where
2036            V: Visitor<'de>,
2037        {
2038            self.deserialize_str(visitor)
2039        }
2040
2041        fn deserialize_str<V>($($mut)? self, visitor: V) -> Result<V::Value, DeError>
2042        where
2043            V: Visitor<'de>,
2044        {
2045            let text = self.read_string()?;
2046            match text {
2047                Cow::Borrowed(string) => visitor.visit_borrowed_str(string),
2048                Cow::Owned(string) => visitor.visit_string(string),
2049            }
2050        }
2051
2052        /// Representation of owned strings the same as [non-owned](#method.deserialize_str).
2053        #[inline]
2054        fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, DeError>
2055        where
2056            V: Visitor<'de>,
2057        {
2058            self.deserialize_str(visitor)
2059        }
2060
2061        /// Forwards deserialization to the [`deserialize_any`](#method.deserialize_any).
2062        #[inline]
2063        fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, DeError>
2064        where
2065            V: Visitor<'de>,
2066        {
2067            self.deserialize_any(visitor)
2068        }
2069
2070        /// Forwards deserialization to the [`deserialize_bytes`](#method.deserialize_bytes).
2071        #[inline]
2072        fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, DeError>
2073        where
2074            V: Visitor<'de>,
2075        {
2076            self.deserialize_bytes(visitor)
2077        }
2078
2079        /// Representation of the named units the same as [unnamed units](#method.deserialize_unit).
2080        #[inline]
2081        fn deserialize_unit_struct<V>(
2082            self,
2083            _name: &'static str,
2084            visitor: V,
2085        ) -> Result<V::Value, DeError>
2086        where
2087            V: Visitor<'de>,
2088        {
2089            self.deserialize_unit(visitor)
2090        }
2091
2092        /// Representation of tuples the same as [sequences](#method.deserialize_seq).
2093        #[inline]
2094        fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, DeError>
2095        where
2096            V: Visitor<'de>,
2097        {
2098            self.deserialize_seq(visitor)
2099        }
2100
2101        /// Representation of named tuples the same as [unnamed tuples](#method.deserialize_tuple).
2102        #[inline]
2103        fn deserialize_tuple_struct<V>(
2104            self,
2105            _name: &'static str,
2106            len: usize,
2107            visitor: V,
2108        ) -> Result<V::Value, DeError>
2109        where
2110            V: Visitor<'de>,
2111        {
2112            self.deserialize_tuple(len, visitor)
2113        }
2114
2115        /// Forwards deserialization to the [`deserialize_struct`](#method.deserialize_struct)
2116        /// with empty name and fields.
2117        #[inline]
2118        fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, DeError>
2119        where
2120            V: Visitor<'de>,
2121        {
2122            self.deserialize_struct("", &[], visitor)
2123        }
2124
2125        /// Identifiers represented as [strings](#method.deserialize_str).
2126        #[inline]
2127        fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, DeError>
2128        where
2129            V: Visitor<'de>,
2130        {
2131            self.deserialize_str(visitor)
2132        }
2133
2134        /// Forwards deserialization to the [`deserialize_unit`](#method.deserialize_unit).
2135        #[inline]
2136        fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, DeError>
2137        where
2138            V: Visitor<'de>,
2139        {
2140            self.deserialize_unit(visitor)
2141        }
2142    };
2143}
2144
2145mod attributes;
2146mod key;
2147mod map;
2148mod resolver;
2149mod simple_type;
2150mod text;
2151mod var;
2152
2153pub use self::attributes::AttributesDeserializer;
2154pub use self::resolver::{EntityResolver, PredefinedEntityResolver};
2155pub use self::simple_type::SimpleTypeDeserializer;
2156pub use crate::errors::serialize::DeError;
2157
2158use crate::{
2159    de::map::ElementMapAccess,
2160    encoding::Decoder,
2161    errors::Error,
2162    escape::{parse_number, EscapeError},
2163    events::{BytesCData, BytesEnd, BytesRef, BytesStart, BytesText, Event},
2164    name::QName,
2165    reader::NsReader,
2166    utils::CowRef,
2167};
2168use serde::de::{
2169    self, Deserialize, DeserializeOwned, DeserializeSeed, IntoDeserializer, SeqAccess, Visitor,
2170};
2171use std::borrow::Cow;
2172#[cfg(feature = "overlapped-lists")]
2173use std::collections::VecDeque;
2174use std::io::BufRead;
2175use std::mem::replace;
2176#[cfg(feature = "overlapped-lists")]
2177use std::num::NonZeroUsize;
2178use std::ops::{Deref, Range};
2179
2180/// Data represented by a text node or a CDATA node. XML markup is not expected
2181pub(crate) const TEXT_KEY: &str = "$text";
2182/// Data represented by any XML markup inside
2183pub(crate) const VALUE_KEY: &str = "$value";
2184
2185/// A function to check whether the character is a whitespace (blank, new line, carriage return or tab).
2186#[inline]
2187const fn is_non_whitespace(ch: char) -> bool {
2188    !matches!(ch, ' ' | '\r' | '\n' | '\t')
2189}
2190
2191/// Decoded and concatenated content of consequent [`Text`] and [`CData`]
2192/// events. _Consequent_ means that events should follow each other or be
2193/// delimited only by (any count of) [`Comment`] or [`PI`] events.
2194///
2195/// Internally text is stored in `Cow<str>`. Cloning of text is cheap while it
2196/// is borrowed and makes copies of data when it is owned.
2197///
2198/// [`Text`]: Event::Text
2199/// [`CData`]: Event::CData
2200/// [`Comment`]: Event::Comment
2201/// [`PI`]: Event::PI
2202#[derive(Clone, Debug, PartialEq, Eq)]
2203pub struct Text<'a> {
2204    /// Untrimmed text after concatenating content of all
2205    /// [`Text`] and [`CData`] events
2206    ///
2207    /// [`Text`]: Event::Text
2208    /// [`CData`]: Event::CData
2209    text: Cow<'a, str>,
2210    /// A range into `text` which contains data after trimming
2211    content: Range<usize>,
2212}
2213
2214impl<'a> Text<'a> {
2215    fn new(text: Cow<'a, str>) -> Self {
2216        let start = text.find(is_non_whitespace).unwrap_or(0);
2217        let end = text.rfind(is_non_whitespace).map_or(0, |i| i + 1);
2218
2219        let content = if start >= end { 0..0 } else { start..end };
2220
2221        Self { text, content }
2222    }
2223
2224    /// Returns text without leading and trailing whitespaces as [defined] by XML specification.
2225    ///
2226    /// If you want to only check if text contains only whitespaces, use [`is_blank`](Self::is_blank),
2227    /// which will not allocate.
2228    ///
2229    /// # Example
2230    ///
2231    /// ```
2232    /// # use quick_xml::de::Text;
2233    /// # use pretty_assertions::assert_eq;
2234    /// #
2235    /// let text = Text::from("");
2236    /// assert_eq!(text.trimmed(), "");
2237    ///
2238    /// let text = Text::from(" \r\n\t ");
2239    /// assert_eq!(text.trimmed(), "");
2240    ///
2241    /// let text = Text::from("  some useful text  ");
2242    /// assert_eq!(text.trimmed(), "some useful text");
2243    /// ```
2244    ///
2245    /// [defined]: https://www.w3.org/TR/xml11/#NT-S
2246    pub fn trimmed(&self) -> Cow<'a, str> {
2247        match self.text {
2248            Cow::Borrowed(text) => Cow::Borrowed(&text[self.content.clone()]),
2249            Cow::Owned(ref text) => Cow::Owned(text[self.content.clone()].to_string()),
2250        }
2251    }
2252
2253    /// Returns `true` if text is empty or contains only whitespaces as [defined] by XML specification.
2254    ///
2255    /// # Example
2256    ///
2257    /// ```
2258    /// # use quick_xml::de::Text;
2259    /// # use pretty_assertions::assert_eq;
2260    /// #
2261    /// let text = Text::from("");
2262    /// assert_eq!(text.is_blank(), true);
2263    ///
2264    /// let text = Text::from(" \r\n\t ");
2265    /// assert_eq!(text.is_blank(), true);
2266    ///
2267    /// let text = Text::from("  some useful text  ");
2268    /// assert_eq!(text.is_blank(), false);
2269    /// ```
2270    ///
2271    /// [defined]: https://www.w3.org/TR/xml11/#NT-S
2272    pub fn is_blank(&self) -> bool {
2273        self.content.is_empty()
2274    }
2275}
2276
2277impl<'a> Deref for Text<'a> {
2278    type Target = str;
2279
2280    #[inline]
2281    fn deref(&self) -> &Self::Target {
2282        self.text.deref()
2283    }
2284}
2285
2286impl<'a> From<&'a str> for Text<'a> {
2287    #[inline]
2288    fn from(text: &'a str) -> Self {
2289        Self::new(Cow::Borrowed(text))
2290    }
2291}
2292
2293impl<'a> From<String> for Text<'a> {
2294    #[inline]
2295    fn from(text: String) -> Self {
2296        Self::new(Cow::Owned(text))
2297    }
2298}
2299
2300impl<'a> From<Cow<'a, str>> for Text<'a> {
2301    #[inline]
2302    fn from(text: Cow<'a, str>) -> Self {
2303        Self::new(text)
2304    }
2305}
2306
2307////////////////////////////////////////////////////////////////////////////////////////////////////
2308
2309/// Simplified event which contains only these variants that used by deserializer
2310#[derive(Clone, Debug, PartialEq, Eq)]
2311pub enum DeEvent<'a> {
2312    /// Start tag (with attributes) `<tag attr="value">`.
2313    Start(BytesStart<'a>),
2314    /// End tag `</tag>`.
2315    End(BytesEnd<'a>),
2316    /// Decoded and concatenated content of consequent [`Text`] and [`CData`]
2317    /// events. _Consequent_ means that events should follow each other or be
2318    /// delimited only by (any count of) [`Comment`] or [`PI`] events.
2319    ///
2320    /// [`Text`]: Event::Text
2321    /// [`CData`]: Event::CData
2322    /// [`Comment`]: Event::Comment
2323    /// [`PI`]: Event::PI
2324    Text(Text<'a>),
2325    /// End of XML document.
2326    Eof,
2327}
2328
2329////////////////////////////////////////////////////////////////////////////////////////////////////
2330
2331/// Simplified event which contains only these variants that used by deserializer,
2332/// but [`Text`] events not yet fully processed.
2333///
2334/// [`Text`] events should be trimmed if they does not surrounded by the other
2335/// [`Text`] or [`CData`] events. This event contains intermediate state of [`Text`]
2336/// event, where they are trimmed from the start, but not from the end. To trim
2337/// end spaces we should lookahead by one deserializer event (i. e. skip all
2338/// comments and processing instructions).
2339///
2340/// [`Text`]: Event::Text
2341/// [`CData`]: Event::CData
2342#[derive(Clone, Debug, PartialEq, Eq)]
2343pub enum PayloadEvent<'a> {
2344    /// Start tag (with attributes) `<tag attr="value">`.
2345    Start(BytesStart<'a>),
2346    /// End tag `</tag>`.
2347    End(BytesEnd<'a>),
2348    /// Escaped character data between tags.
2349    Text(BytesText<'a>),
2350    /// Unescaped character data stored in `<![CDATA[...]]>`.
2351    CData(BytesCData<'a>),
2352    /// Document type definition data (DTD) stored in `<!DOCTYPE ...>`.
2353    DocType(BytesText<'a>),
2354    /// Reference `&ref;` in the textual data.
2355    GeneralRef(BytesRef<'a>),
2356    /// End of XML document.
2357    Eof,
2358}
2359
2360impl<'a> PayloadEvent<'a> {
2361    /// Ensures that all data is owned to extend the object's lifetime if necessary.
2362    #[inline]
2363    fn into_owned(self) -> PayloadEvent<'static> {
2364        match self {
2365            PayloadEvent::Start(e) => PayloadEvent::Start(e.into_owned()),
2366            PayloadEvent::End(e) => PayloadEvent::End(e.into_owned()),
2367            PayloadEvent::Text(e) => PayloadEvent::Text(e.into_owned()),
2368            PayloadEvent::CData(e) => PayloadEvent::CData(e.into_owned()),
2369            PayloadEvent::DocType(e) => PayloadEvent::DocType(e.into_owned()),
2370            PayloadEvent::GeneralRef(e) => PayloadEvent::GeneralRef(e.into_owned()),
2371            PayloadEvent::Eof => PayloadEvent::Eof,
2372        }
2373    }
2374}
2375
2376/// An intermediate reader that consumes [`PayloadEvent`]s and produces final [`DeEvent`]s.
2377/// [`PayloadEvent::Text`] events, that followed by any event except
2378/// [`PayloadEvent::Text`] or [`PayloadEvent::CData`], are trimmed from the end.
2379struct XmlReader<'i, R: XmlRead<'i>, E: EntityResolver = PredefinedEntityResolver> {
2380    /// A source of low-level XML events
2381    reader: R,
2382    /// Intermediate event, that could be returned by the next call to `next()`.
2383    /// If that is the `Text` event then leading spaces already trimmed, but
2384    /// trailing spaces is not. Before the event will be returned, trimming of
2385    /// the spaces could be necessary
2386    lookahead: Result<PayloadEvent<'i>, DeError>,
2387
2388    /// Used to resolve unknown entities that would otherwise cause the parser
2389    /// to return an [`EscapeError::UnrecognizedEntity`] error.
2390    ///
2391    /// [`EscapeError::UnrecognizedEntity`]: crate::escape::EscapeError::UnrecognizedEntity
2392    entity_resolver: E,
2393}
2394
2395impl<'i, R: XmlRead<'i>, E: EntityResolver> XmlReader<'i, R, E> {
2396    fn new(mut reader: R, entity_resolver: E) -> Self {
2397        // Lookahead by one event immediately, so we do not need to check in the
2398        // loop if we need lookahead or not
2399        let lookahead = reader.next();
2400
2401        Self {
2402            reader,
2403            lookahead,
2404            entity_resolver,
2405        }
2406    }
2407
2408    /// Returns `true` if all events was consumed
2409    const fn is_empty(&self) -> bool {
2410        matches!(self.lookahead, Ok(PayloadEvent::Eof))
2411    }
2412
2413    /// Read next event and put it in lookahead, return the current lookahead
2414    #[inline(always)]
2415    fn next_impl(&mut self) -> Result<PayloadEvent<'i>, DeError> {
2416        replace(&mut self.lookahead, self.reader.next())
2417    }
2418
2419    /// Returns `true` when next event is not a text event in any form.
2420    #[inline(always)]
2421    const fn current_event_is_last_text(&self) -> bool {
2422        // If next event is a text or CDATA, we should not trim trailing spaces
2423        !matches!(
2424            self.lookahead,
2425            Ok(PayloadEvent::Text(_)) | Ok(PayloadEvent::CData(_) | PayloadEvent::GeneralRef(_))
2426        )
2427    }
2428
2429    /// Read all consequent [`Text`] and [`CData`] events until non-text event
2430    /// occurs. Content of all events would be appended to `result` and returned
2431    /// as [`DeEvent::Text`].
2432    ///
2433    /// [`Text`]: PayloadEvent::Text
2434    /// [`CData`]: PayloadEvent::CData
2435    fn drain_text(&mut self, mut result: Cow<'i, str>) -> Result<DeEvent<'i>, DeError> {
2436        loop {
2437            if self.current_event_is_last_text() {
2438                break;
2439            }
2440
2441            match self.next_impl()? {
2442                PayloadEvent::Text(e) => result.to_mut().push_str(&e.xml_content()?),
2443                PayloadEvent::CData(e) => result.to_mut().push_str(&e.xml_content()?),
2444                PayloadEvent::GeneralRef(e) => self.resolve_reference(result.to_mut(), e)?,
2445
2446                // SAFETY: current_event_is_last_text checks that event is Text, CData or GeneralRef
2447                _ => unreachable!("Only `Text`, `CData` or `GeneralRef` events can come here"),
2448            }
2449        }
2450        Ok(DeEvent::Text(Text::new(result)))
2451    }
2452
2453    /// Return an input-borrowing event.
2454    fn next(&mut self) -> Result<DeEvent<'i>, DeError> {
2455        loop {
2456            return match self.next_impl()? {
2457                PayloadEvent::Start(e) => Ok(DeEvent::Start(e)),
2458                PayloadEvent::End(e) => Ok(DeEvent::End(e)),
2459                PayloadEvent::Text(e) => self.drain_text(e.xml_content()?),
2460                PayloadEvent::CData(e) => self.drain_text(e.xml_content()?),
2461                PayloadEvent::DocType(e) => {
2462                    self.entity_resolver
2463                        .capture(e)
2464                        .map_err(|err| DeError::Custom(format!("cannot parse DTD: {}", err)))?;
2465                    continue;
2466                }
2467                PayloadEvent::GeneralRef(e) => {
2468                    let mut text = String::new();
2469                    self.resolve_reference(&mut text, e)?;
2470                    self.drain_text(text.into())
2471                }
2472                PayloadEvent::Eof => Ok(DeEvent::Eof),
2473            };
2474        }
2475    }
2476
2477    fn resolve_reference(&mut self, result: &mut String, event: BytesRef) -> Result<(), DeError> {
2478        let len = event.len();
2479        let reference = self.decoder().decode(&event)?;
2480
2481        if let Some(num) = reference.strip_prefix('#') {
2482            let codepoint = parse_number(num).map_err(EscapeError::InvalidCharRef)?;
2483            result.push_str(codepoint.encode_utf8(&mut [0u8; 4]));
2484            return Ok(());
2485        }
2486        if let Some(value) = self.entity_resolver.resolve(reference.as_ref()) {
2487            result.push_str(value);
2488            return Ok(());
2489        }
2490        Err(EscapeError::UnrecognizedEntity(0..len, reference.to_string()).into())
2491    }
2492
2493    #[inline]
2494    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
2495        match self.lookahead {
2496            // We pre-read event with the same name that is required to be skipped.
2497            // First call of `read_to_end` will end out pre-read event, the second
2498            // will consume other events
2499            Ok(PayloadEvent::Start(ref e)) if e.name() == name => {
2500                let result1 = self.reader.read_to_end(name);
2501                let result2 = self.reader.read_to_end(name);
2502
2503                // In case of error `next_impl` returns `Eof`
2504                let _ = self.next_impl();
2505                result1?;
2506                result2?;
2507            }
2508            // We pre-read event with the same name that is required to be skipped.
2509            // Because this is end event, we already consume the whole tree, so
2510            // nothing to do, just update lookahead
2511            Ok(PayloadEvent::End(ref e)) if e.name() == name => {
2512                let _ = self.next_impl();
2513            }
2514            Ok(_) => {
2515                let result = self.reader.read_to_end(name);
2516
2517                // In case of error `next_impl` returns `Eof`
2518                let _ = self.next_impl();
2519                result?;
2520            }
2521            // Read next lookahead event, unpack error from the current lookahead
2522            Err(_) => {
2523                self.next_impl()?;
2524            }
2525        }
2526        Ok(())
2527    }
2528
2529    #[inline]
2530    fn decoder(&self) -> Decoder {
2531        self.reader.decoder()
2532    }
2533}
2534
2535////////////////////////////////////////////////////////////////////////////////////////////////////
2536
2537/// Deserialize an instance of type `T` from a string of XML text.
2538pub fn from_str<'de, T>(s: &'de str) -> Result<T, DeError>
2539where
2540    T: Deserialize<'de>,
2541{
2542    let mut de = Deserializer::from_str(s);
2543    T::deserialize(&mut de)
2544}
2545
2546/// Deserialize from a reader. This method will do internal copies of data
2547/// read from `reader`. If you want have a `&str` input and want to borrow
2548/// as much as possible, use [`from_str`].
2549pub fn from_reader<R, T>(reader: R) -> Result<T, DeError>
2550where
2551    R: BufRead,
2552    T: DeserializeOwned,
2553{
2554    let mut de = Deserializer::from_reader(reader);
2555    T::deserialize(&mut de)
2556}
2557
2558////////////////////////////////////////////////////////////////////////////////////////////////////
2559
2560/// A structure that deserializes XML into Rust values.
2561pub struct Deserializer<'de, R, E: EntityResolver = PredefinedEntityResolver>
2562where
2563    R: XmlRead<'de>,
2564{
2565    /// An XML reader that streams events into this deserializer
2566    reader: XmlReader<'de, R, E>,
2567
2568    /// When deserializing sequences sometimes we have to skip unwanted events.
2569    /// That events should be stored and then replayed. This is a replay buffer,
2570    /// that streams events while not empty. When it exhausted, events will
2571    /// requested from [`Self::reader`].
2572    #[cfg(feature = "overlapped-lists")]
2573    read: VecDeque<DeEvent<'de>>,
2574    /// When deserializing sequences sometimes we have to skip events, because XML
2575    /// is tolerant to elements order and even if in the XSD order is strictly
2576    /// specified (using `xs:sequence`) most of XML parsers allows order violations.
2577    /// That means, that elements, forming a sequence, could be overlapped with
2578    /// other elements, do not related to that sequence.
2579    ///
2580    /// In order to support this, deserializer will scan events and skip unwanted
2581    /// events, store them here. After call [`Self::start_replay()`] all events
2582    /// moved from this to [`Self::read`].
2583    #[cfg(feature = "overlapped-lists")]
2584    write: VecDeque<DeEvent<'de>>,
2585    /// Maximum number of events that can be skipped when processing sequences
2586    /// that occur out-of-order. This field is used to prevent potential
2587    /// denial-of-service (DoS) attacks which could cause infinite memory
2588    /// consumption when parsing a very large amount of XML into a sequence field.
2589    #[cfg(feature = "overlapped-lists")]
2590    limit: Option<NonZeroUsize>,
2591
2592    #[cfg(not(feature = "overlapped-lists"))]
2593    peek: Option<DeEvent<'de>>,
2594
2595    /// Buffer to store attribute name as a field name exposed to serde consumers
2596    key_buf: String,
2597}
2598
2599impl<'de, R, E> Deserializer<'de, R, E>
2600where
2601    R: XmlRead<'de>,
2602    E: EntityResolver,
2603{
2604    /// Create an XML deserializer from one of the possible quick_xml input sources.
2605    ///
2606    /// Typically it is more convenient to use one of these methods instead:
2607    ///
2608    ///  - [`Deserializer::from_str`]
2609    ///  - [`Deserializer::from_reader`]
2610    fn new(reader: R, entity_resolver: E) -> Self {
2611        Self {
2612            reader: XmlReader::new(reader, entity_resolver),
2613
2614            #[cfg(feature = "overlapped-lists")]
2615            read: VecDeque::new(),
2616            #[cfg(feature = "overlapped-lists")]
2617            write: VecDeque::new(),
2618            #[cfg(feature = "overlapped-lists")]
2619            limit: None,
2620
2621            #[cfg(not(feature = "overlapped-lists"))]
2622            peek: None,
2623
2624            key_buf: String::new(),
2625        }
2626    }
2627
2628    /// Returns `true` if all events was consumed.
2629    pub fn is_empty(&self) -> bool {
2630        #[cfg(feature = "overlapped-lists")]
2631        let event = self.read.front();
2632
2633        #[cfg(not(feature = "overlapped-lists"))]
2634        let event = self.peek.as_ref();
2635
2636        match event {
2637            None | Some(DeEvent::Eof) => self.reader.is_empty(),
2638            _ => false,
2639        }
2640    }
2641
2642    /// Returns the underlying XML reader.
2643    ///
2644    /// ```
2645    /// # use pretty_assertions::assert_eq;
2646    /// use serde::Deserialize;
2647    /// use quick_xml::de::Deserializer;
2648    /// use quick_xml::NsReader;
2649    ///
2650    /// #[derive(Deserialize)]
2651    /// struct SomeStruct {
2652    ///     field1: String,
2653    ///     field2: String,
2654    /// }
2655    ///
2656    /// // Try to deserialize from broken XML
2657    /// let mut de = Deserializer::from_str(
2658    ///     "<SomeStruct><field1><field2></SomeStruct>"
2659    /// //   0                           ^= 28        ^= 41
2660    /// );
2661    ///
2662    /// let err = SomeStruct::deserialize(&mut de);
2663    /// assert!(err.is_err());
2664    ///
2665    /// let reader: &NsReader<_> = de.get_ref().get_ref();
2666    ///
2667    /// assert_eq!(reader.error_position(), 28);
2668    /// assert_eq!(reader.buffer_position(), 41);
2669    /// ```
2670    pub const fn get_ref(&self) -> &R {
2671        &self.reader.reader
2672    }
2673
2674    /// Set the maximum number of events that could be skipped during deserialization
2675    /// of sequences.
2676    ///
2677    /// If `<element>` contains more than specified nested elements, `$text` or
2678    /// CDATA nodes, then [`DeError::TooManyEvents`] will be returned during
2679    /// deserialization of sequence field (any type that uses [`deserialize_seq`]
2680    /// for the deserialization, for example, `Vec<T>`).
2681    ///
2682    /// This method can be used to prevent a [DoS] attack and infinite memory
2683    /// consumption when parsing a very large XML to a sequence field.
2684    ///
2685    /// It is strongly recommended to set limit to some value when you parse data
2686    /// from untrusted sources. You should choose a value that your typical XMLs
2687    /// can have _between_ different elements that corresponds to the same sequence.
2688    ///
2689    /// # Examples
2690    ///
2691    /// Let's imagine, that we deserialize such structure:
2692    /// ```
2693    /// struct List {
2694    ///   item: Vec<()>,
2695    /// }
2696    /// ```
2697    ///
2698    /// The XML that we try to parse look like this:
2699    /// ```xml
2700    /// <any-name>
2701    ///   <item/>
2702    ///   <!-- Bufferization starts at this point -->
2703    ///   <another-item>
2704    ///     <some-element>with text</some-element>
2705    ///     <yet-another-element/>
2706    ///   </another-item>
2707    ///   <!-- Buffer will be emptied at this point; 7 events were buffered -->
2708    ///   <item/>
2709    ///   <!-- There is nothing to buffer, because elements follows each other -->
2710    ///   <item/>
2711    /// </any-name>
2712    /// ```
2713    ///
2714    /// There, when we deserialize the `item` field, we need to buffer 7 events,
2715    /// before we can deserialize the second `<item/>`:
2716    ///
2717    /// - `<another-item>`
2718    /// - `<some-element>`
2719    /// - `$text(with text)`
2720    /// - `</some-element>`
2721    /// - `<yet-another-element/>` (virtual start event)
2722    /// - `<yet-another-element/>` (virtual end event)
2723    /// - `</another-item>`
2724    ///
2725    /// Note, that `<yet-another-element/>` internally represented as 2 events:
2726    /// one for the start tag and one for the end tag. In the future this can be
2727    /// eliminated, but for now we use [auto-expanding feature] of a reader,
2728    /// because this simplifies deserializer code.
2729    ///
2730    /// [`deserialize_seq`]: serde::Deserializer::deserialize_seq
2731    /// [DoS]: https://en.wikipedia.org/wiki/Denial-of-service_attack
2732    /// [auto-expanding feature]: crate::reader::Config::expand_empty_elements
2733    #[cfg(feature = "overlapped-lists")]
2734    pub fn event_buffer_size(&mut self, limit: Option<NonZeroUsize>) -> &mut Self {
2735        self.limit = limit;
2736        self
2737    }
2738
2739    #[cfg(feature = "overlapped-lists")]
2740    fn peek(&mut self) -> Result<&DeEvent<'de>, DeError> {
2741        if self.read.is_empty() {
2742            self.read.push_front(self.reader.next()?);
2743        }
2744        if let Some(event) = self.read.front() {
2745            return Ok(event);
2746        }
2747        // SAFETY: `self.read` was filled in the code above.
2748        // NOTE: Can be replaced with `unsafe { std::hint::unreachable_unchecked() }`
2749        // if unsafe code will be allowed
2750        unreachable!()
2751    }
2752    #[cfg(not(feature = "overlapped-lists"))]
2753    fn peek(&mut self) -> Result<&DeEvent<'de>, DeError> {
2754        match &mut self.peek {
2755            Some(event) => Ok(event),
2756            empty_peek @ None => Ok(empty_peek.insert(self.reader.next()?)),
2757        }
2758    }
2759
2760    #[inline]
2761    fn last_peeked(&self) -> &DeEvent<'de> {
2762        #[cfg(feature = "overlapped-lists")]
2763        {
2764            self.read
2765                .front()
2766                .expect("`Deserializer::peek()` should be called")
2767        }
2768        #[cfg(not(feature = "overlapped-lists"))]
2769        {
2770            self.peek
2771                .as_ref()
2772                .expect("`Deserializer::peek()` should be called")
2773        }
2774    }
2775
2776    fn next(&mut self) -> Result<DeEvent<'de>, DeError> {
2777        // Replay skipped or peeked events
2778        #[cfg(feature = "overlapped-lists")]
2779        if let Some(event) = self.read.pop_front() {
2780            return Ok(event);
2781        }
2782        #[cfg(not(feature = "overlapped-lists"))]
2783        if let Some(e) = self.peek.take() {
2784            return Ok(e);
2785        }
2786        self.reader.next()
2787    }
2788
2789    fn skip_whitespaces(&mut self) -> Result<(), DeError> {
2790        loop {
2791            match self.peek()? {
2792                DeEvent::Text(e) if e.is_blank() => {
2793                    self.next()?;
2794                }
2795                _ => break,
2796            }
2797        }
2798        Ok(())
2799    }
2800
2801    /// Returns the mark after which all events, skipped by [`Self::skip()`] call,
2802    /// should be replayed after calling [`Self::start_replay()`].
2803    #[cfg(feature = "overlapped-lists")]
2804    #[inline]
2805    #[must_use = "returned checkpoint should be used in `start_replay`"]
2806    fn skip_checkpoint(&self) -> usize {
2807        self.write.len()
2808    }
2809
2810    /// Extracts XML tree of events from and stores them in the skipped events
2811    /// buffer from which they can be retrieved later. You MUST call
2812    /// [`Self::start_replay()`] after calling this to give access to the skipped
2813    /// events and release internal buffers.
2814    #[cfg(feature = "overlapped-lists")]
2815    fn skip(&mut self) -> Result<(), DeError> {
2816        let event = self.next()?;
2817        self.skip_event(event)?;
2818        match self.write.back() {
2819            // Skip all subtree, if we skip a start event
2820            Some(DeEvent::Start(e)) => {
2821                let end = e.name().as_ref().to_owned();
2822                let mut depth = 0;
2823                loop {
2824                    let event = self.next()?;
2825                    match event {
2826                        DeEvent::Start(ref e) if e.name().as_ref() == end => {
2827                            self.skip_event(event)?;
2828                            depth += 1;
2829                        }
2830                        DeEvent::End(ref e) if e.name().as_ref() == end => {
2831                            self.skip_event(event)?;
2832                            if depth == 0 {
2833                                break;
2834                            }
2835                            depth -= 1;
2836                        }
2837                        DeEvent::Eof => {
2838                            self.skip_event(event)?;
2839                            break;
2840                        }
2841                        _ => self.skip_event(event)?,
2842                    }
2843                }
2844            }
2845            _ => (),
2846        }
2847        Ok(())
2848    }
2849
2850    #[cfg(feature = "overlapped-lists")]
2851    #[inline]
2852    fn skip_event(&mut self, event: DeEvent<'de>) -> Result<(), DeError> {
2853        if let Some(max) = self.limit {
2854            if self.write.len() >= max.get() {
2855                return Err(DeError::TooManyEvents(max));
2856            }
2857        }
2858        self.write.push_back(event);
2859        Ok(())
2860    }
2861
2862    /// Moves buffered events, skipped after given `checkpoint` from [`Self::write`]
2863    /// skip buffer to [`Self::read`] buffer.
2864    ///
2865    /// After calling this method, [`Self::peek()`] and [`Self::next()`] starts
2866    /// return events that was skipped previously by calling [`Self::skip()`],
2867    /// and only when all that events will be consumed, the deserializer starts
2868    /// to drain events from underlying reader.
2869    ///
2870    /// This method MUST be called if any number of [`Self::skip()`] was called
2871    /// after [`Self::new()`] or `start_replay()` or you'll lost events.
2872    #[cfg(feature = "overlapped-lists")]
2873    fn start_replay(&mut self, checkpoint: usize) {
2874        if checkpoint == 0 {
2875            self.write.append(&mut self.read);
2876            std::mem::swap(&mut self.read, &mut self.write);
2877        } else {
2878            let mut read = self.write.split_off(checkpoint);
2879            read.append(&mut self.read);
2880            self.read = read;
2881        }
2882    }
2883
2884    #[inline]
2885    fn read_string(&mut self) -> Result<Cow<'de, str>, DeError> {
2886        self.read_string_impl(true)
2887    }
2888
2889    /// Consumes consequent [`Text`] and [`CData`] (both a referred below as a _text_)
2890    /// events, merge them into one string. If there are no such events, returns
2891    /// an empty string.
2892    ///
2893    /// If `allow_start` is `false`, then only text events are consumed, for other
2894    /// events an error is returned (see table below).
2895    ///
2896    /// If `allow_start` is `true`, then two or three events are expected:
2897    /// - [`DeEvent::Start`];
2898    /// - _(optional)_ [`DeEvent::Text`] which content is returned;
2899    /// - [`DeEvent::End`]. If text event was missed, an empty string is returned.
2900    ///
2901    /// Corresponding events are consumed.
2902    ///
2903    /// # Handling events
2904    ///
2905    /// The table below shows how events is handled by this method:
2906    ///
2907    /// |Event             |XML                        |Handling
2908    /// |------------------|---------------------------|----------------------------------------
2909    /// |[`DeEvent::Start`]|`<tag>...</tag>`           |if `allow_start == true`, result determined by the second table, otherwise emits [`UnexpectedStart("tag")`](DeError::UnexpectedStart)
2910    /// |[`DeEvent::End`]  |`</any-tag>`               |This is impossible situation, the method will panic if it happens
2911    /// |[`DeEvent::Text`] |`text content` or `<![CDATA[cdata content]]>` (probably mixed)|Returns event content unchanged
2912    /// |[`DeEvent::Eof`]  |                           |Emits [`UnexpectedEof`](DeError::UnexpectedEof)
2913    ///
2914    /// Second event, consumed if [`DeEvent::Start`] was received and `allow_start == true`:
2915    ///
2916    /// |Event             |XML                        |Handling
2917    /// |------------------|---------------------------|----------------------------------------------------------------------------------
2918    /// |[`DeEvent::Start`]|`<any-tag>...</any-tag>`   |Emits [`UnexpectedStart("any-tag")`](DeError::UnexpectedStart)
2919    /// |[`DeEvent::End`]  |`</tag>`                   |Returns an empty slice. The reader guarantee that tag will match the open one
2920    /// |[`DeEvent::Text`] |`text content` or `<![CDATA[cdata content]]>` (probably mixed)|Returns event content unchanged, expects the `</tag>` after that
2921    /// |[`DeEvent::Eof`]  |                           |Emits [`InvalidXml(IllFormed(MissingEndTag))`](DeError::InvalidXml)
2922    ///
2923    /// [`Text`]: Event::Text
2924    /// [`CData`]: Event::CData
2925    fn read_string_impl(&mut self, allow_start: bool) -> Result<Cow<'de, str>, DeError> {
2926        match self.next()? {
2927            DeEvent::Text(e) => Ok(e.text),
2928            // allow one nested level
2929            DeEvent::Start(e) if allow_start => self.read_text(e.name()),
2930            DeEvent::Start(e) => Err(DeError::UnexpectedStart(e.name().as_ref().to_owned())),
2931            // SAFETY: The reader is guaranteed that we don't have unmatched tags
2932            // If we here, then our deserializer has a bug
2933            DeEvent::End(e) => unreachable!("{:?}", e),
2934            DeEvent::Eof => Err(DeError::UnexpectedEof),
2935        }
2936    }
2937    /// Consumes one [`DeEvent::Text`] event and ensures that it is followed by the
2938    /// [`DeEvent::End`] event.
2939    ///
2940    /// # Parameters
2941    /// - `name`: name of a tag opened before reading text. The corresponding end tag
2942    ///   should present in input just after the text
2943    fn read_text(&mut self, name: QName) -> Result<Cow<'de, str>, DeError> {
2944        match self.next()? {
2945            DeEvent::Text(e) => match self.next()? {
2946                // The matching tag name is guaranteed by the reader
2947                DeEvent::End(_) => Ok(e.text),
2948                // SAFETY: Cannot be two consequent Text events, they would be merged into one
2949                DeEvent::Text(_) => unreachable!(),
2950                DeEvent::Start(e) => Err(DeError::UnexpectedStart(e.name().as_ref().to_owned())),
2951                DeEvent::Eof => Err(Error::missed_end(name, self.reader.decoder()).into()),
2952            },
2953            // We can get End event in case of `<tag></tag>` or `<tag/>` input
2954            // Return empty text in that case
2955            // The matching tag name is guaranteed by the reader
2956            DeEvent::End(_) => Ok("".into()),
2957            DeEvent::Start(s) => Err(DeError::UnexpectedStart(s.name().as_ref().to_owned())),
2958            DeEvent::Eof => Err(Error::missed_end(name, self.reader.decoder()).into()),
2959        }
2960    }
2961
2962    /// Drops all events until event with [name](BytesEnd::name()) `name` won't be
2963    /// dropped. This method should be called after [`Self::next()`]
2964    #[cfg(feature = "overlapped-lists")]
2965    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
2966        let mut depth = 0;
2967        loop {
2968            match self.read.pop_front() {
2969                Some(DeEvent::Start(e)) if e.name() == name => {
2970                    depth += 1;
2971                }
2972                Some(DeEvent::End(e)) if e.name() == name => {
2973                    if depth == 0 {
2974                        break;
2975                    }
2976                    depth -= 1;
2977                }
2978
2979                // Drop all other skipped events
2980                Some(_) => continue,
2981
2982                // If we do not have skipped events, use effective reading that will
2983                // not allocate memory for events
2984                None => {
2985                    // We should close all opened tags, because we could buffer
2986                    // Start events, but not the corresponding End events. So we
2987                    // keep reading events until we exit all nested tags.
2988                    // `read_to_end()` will return an error if an Eof was encountered
2989                    // preliminary (in case of malformed XML).
2990                    //
2991                    // <tag><tag></tag></tag>
2992                    // ^^^^^^^^^^             - buffered in `self.read`, when `self.read_to_end()` is called, depth = 2
2993                    //           ^^^^^^       - read by the first call of `self.reader.read_to_end()`
2994                    //                 ^^^^^^ - read by the second call of `self.reader.read_to_end()`
2995                    loop {
2996                        self.reader.read_to_end(name)?;
2997                        if depth == 0 {
2998                            break;
2999                        }
3000                        depth -= 1;
3001                    }
3002                    break;
3003                }
3004            }
3005        }
3006        Ok(())
3007    }
3008    #[cfg(not(feature = "overlapped-lists"))]
3009    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
3010        // First one might be in self.peek
3011        match self.next()? {
3012            DeEvent::Start(e) => self.reader.read_to_end(e.name())?,
3013            DeEvent::End(e) if e.name() == name => return Ok(()),
3014            _ => (),
3015        }
3016        self.reader.read_to_end(name)
3017    }
3018
3019    fn skip_next_tree(&mut self) -> Result<(), DeError> {
3020        let DeEvent::Start(start) = self.next()? else {
3021            unreachable!("Only call this if the next event is a start event")
3022        };
3023        let name = start.name();
3024        self.read_to_end(name)
3025    }
3026
3027    /// Method for testing Deserializer implementation. Checks that all events was consumed during
3028    /// deserialization. Panics if the next event will not be [`DeEvent::Eof`].
3029    #[doc(hidden)]
3030    #[track_caller]
3031    pub fn check_eof_reached(&mut self) {
3032        // Deserializer may not consume trailing spaces, that is normal
3033        self.skip_whitespaces().expect("cannot skip whitespaces");
3034        let event = self.peek().expect("cannot peek event");
3035        assert_eq!(
3036            *event,
3037            DeEvent::Eof,
3038            "the whole XML document should be consumed, expected `Eof`",
3039        );
3040    }
3041}
3042
3043impl<'de> Deserializer<'de, SliceReader<'de>> {
3044    /// Create a new deserializer that will borrow data from the specified string.
3045    ///
3046    /// Deserializer created with this method will not resolve custom entities.
3047    #[allow(clippy::should_implement_trait)]
3048    pub fn from_str(source: &'de str) -> Self {
3049        Self::from_str_with_resolver(source, PredefinedEntityResolver)
3050    }
3051
3052    /// Create a new deserializer that will borrow data from the specified preconfigured
3053    /// reader.
3054    ///
3055    /// Deserializer created with this method will not resolve custom entities.
3056    ///
3057    /// Note, that config option [`Config::expand_empty_elements`] will be set to `true`.
3058    ///
3059    /// # Example
3060    ///
3061    /// ```
3062    /// # use pretty_assertions::assert_eq;
3063    /// # use quick_xml::de::Deserializer;
3064    /// # use quick_xml::NsReader;
3065    /// # use serde::Deserialize;
3066    /// #
3067    /// #[derive(Deserialize, PartialEq, Debug)]
3068    /// struct Object<'a> {
3069    ///     tag: &'a str,
3070    /// }
3071    ///
3072    /// let mut reader = NsReader::from_str("<xml><tag>    test    </tag></xml>");
3073    ///
3074    /// let mut de = Deserializer::borrowing(reader.clone());
3075    /// let obj = Object::deserialize(&mut de).unwrap();
3076    /// assert_eq!(obj, Object { tag: "    test    " });
3077    ///
3078    /// reader.config_mut().trim_text(true);
3079    ///
3080    /// let mut de = Deserializer::borrowing(reader);
3081    /// let obj = Object::deserialize(&mut de).unwrap();
3082    /// assert_eq!(obj, Object { tag: "test" });
3083    /// ```
3084    ///
3085    /// [`Config::expand_empty_elements`]: crate::reader::Config::expand_empty_elements
3086    #[inline]
3087    pub fn borrowing(reader: NsReader<&'de [u8]>) -> Self {
3088        Self::borrowing_with_resolver(reader, PredefinedEntityResolver)
3089    }
3090}
3091
3092impl<'de, E> Deserializer<'de, SliceReader<'de>, E>
3093where
3094    E: EntityResolver,
3095{
3096    /// Create a new deserializer that will borrow data from the specified string
3097    /// and use the specified entity resolver.
3098    pub fn from_str_with_resolver(source: &'de str, entity_resolver: E) -> Self {
3099        Self::borrowing_with_resolver(NsReader::from_str(source), entity_resolver)
3100    }
3101
3102    /// Create a new deserializer that will borrow data from the specified preconfigured
3103    /// reader and use the specified entity resolver.
3104    ///
3105    /// Note, that config option [`Config::expand_empty_elements`] will be set to `true`.
3106    ///
3107    /// [`Config::expand_empty_elements`]: crate::reader::Config::expand_empty_elements
3108    pub fn borrowing_with_resolver(mut reader: NsReader<&'de [u8]>, entity_resolver: E) -> Self {
3109        let config = reader.config_mut();
3110        config.expand_empty_elements = true;
3111
3112        Self::new(SliceReader { reader }, entity_resolver)
3113    }
3114}
3115
3116impl<'de, R> Deserializer<'de, IoReader<R>>
3117where
3118    R: BufRead,
3119{
3120    /// Create a new deserializer that will copy data from the specified reader
3121    /// into internal buffer.
3122    ///
3123    /// If you already have a string use [`Self::from_str`] instead, because it
3124    /// will borrow instead of copy. If you have `&[u8]` which is known to represent
3125    /// UTF-8, you can decode it first before using [`from_str`].
3126    ///
3127    /// Deserializer created with this method will not resolve custom entities.
3128    pub fn from_reader(reader: R) -> Self {
3129        Self::with_resolver(reader, PredefinedEntityResolver)
3130    }
3131
3132    /// Create a new deserializer that will copy data from the specified preconfigured
3133    /// reader into internal buffer.
3134    ///
3135    /// Deserializer created with this method will not resolve custom entities.
3136    ///
3137    /// Note, that config option [`Config::expand_empty_elements`] will be set to `true`.
3138    ///
3139    /// # Example
3140    ///
3141    /// ```
3142    /// # use pretty_assertions::assert_eq;
3143    /// # use quick_xml::de::Deserializer;
3144    /// # use quick_xml::NsReader;
3145    /// # use serde::Deserialize;
3146    /// #
3147    /// #[derive(Deserialize, PartialEq, Debug)]
3148    /// struct Object {
3149    ///     tag: String,
3150    /// }
3151    ///
3152    /// let mut reader = NsReader::from_str("<xml><tag>    test    </tag></xml>");
3153    ///
3154    /// let mut de = Deserializer::buffering(reader.clone());
3155    /// let obj = Object::deserialize(&mut de).unwrap();
3156    /// assert_eq!(obj, Object { tag: "    test    ".to_string() });
3157    ///
3158    /// reader.config_mut().trim_text(true);
3159    ///
3160    /// let mut de = Deserializer::buffering(reader);
3161    /// let obj = Object::deserialize(&mut de).unwrap();
3162    /// assert_eq!(obj, Object { tag: "test".to_string() });
3163    /// ```
3164    ///
3165    /// [`Config::expand_empty_elements`]: crate::reader::Config::expand_empty_elements
3166    #[inline]
3167    pub fn buffering(reader: NsReader<R>) -> Self {
3168        Self::buffering_with_resolver(reader, PredefinedEntityResolver)
3169    }
3170}
3171
3172impl<'de, R, E> Deserializer<'de, IoReader<R>, E>
3173where
3174    R: BufRead,
3175    E: EntityResolver,
3176{
3177    /// Create a new deserializer that will copy data from the specified reader
3178    /// into internal buffer and use the specified entity resolver.
3179    ///
3180    /// If you already have a string use [`Self::from_str`] instead, because it
3181    /// will borrow instead of copy. If you have `&[u8]` which is known to represent
3182    /// UTF-8, you can decode it first before using [`from_str`].
3183    pub fn with_resolver(reader: R, entity_resolver: E) -> Self {
3184        let mut reader = NsReader::from_reader(reader);
3185        let config = reader.config_mut();
3186        config.expand_empty_elements = true;
3187
3188        Self::new(
3189            IoReader {
3190                reader,
3191                buf: Vec::new(),
3192            },
3193            entity_resolver,
3194        )
3195    }
3196
3197    /// Create new deserializer that will copy data from the specified preconfigured reader
3198    /// into internal buffer and use the specified entity resolver.
3199    ///
3200    /// Note, that config option [`Config::expand_empty_elements`] will be set to `true`.
3201    ///
3202    /// [`Config::expand_empty_elements`]: crate::reader::Config::expand_empty_elements
3203    pub fn buffering_with_resolver(mut reader: NsReader<R>, entity_resolver: E) -> Self {
3204        let config = reader.config_mut();
3205        config.expand_empty_elements = true;
3206
3207        Self::new(
3208            IoReader {
3209                reader,
3210                buf: Vec::new(),
3211            },
3212            entity_resolver,
3213        )
3214    }
3215}
3216
3217impl<'de, 'a, R, E> de::Deserializer<'de> for &'a mut Deserializer<'de, R, E>
3218where
3219    R: XmlRead<'de>,
3220    E: EntityResolver,
3221{
3222    type Error = DeError;
3223
3224    deserialize_primitives!();
3225
3226    fn deserialize_struct<V>(
3227        self,
3228        _name: &'static str,
3229        fields: &'static [&'static str],
3230        visitor: V,
3231    ) -> Result<V::Value, DeError>
3232    where
3233        V: Visitor<'de>,
3234    {
3235        // When document is pretty-printed there could be whitespaces before the root element
3236        self.skip_whitespaces()?;
3237        match self.next()? {
3238            DeEvent::Start(e) => visitor.visit_map(ElementMapAccess::new(self, e, fields)?),
3239            // SAFETY: The reader is guaranteed that we don't have unmatched tags
3240            // If we here, then our deserializer has a bug
3241            DeEvent::End(e) => unreachable!("{:?}", e),
3242            // Deserializer methods are only hints, if deserializer could not satisfy
3243            // request, it should return the data that it has. It is responsibility
3244            // of a Visitor to return an error if it does not understand the data
3245            DeEvent::Text(e) => match e.text {
3246                Cow::Borrowed(s) => visitor.visit_borrowed_str(s),
3247                Cow::Owned(s) => visitor.visit_string(s),
3248            },
3249            DeEvent::Eof => Err(DeError::UnexpectedEof),
3250        }
3251    }
3252
3253    /// Unit represented in XML as a `xs:element` or text/CDATA content.
3254    /// Any content inside `xs:element` is ignored and skipped.
3255    ///
3256    /// Produces unit struct from any of following inputs:
3257    /// - any `<tag ...>...</tag>`
3258    /// - any `<tag .../>`
3259    /// - any consequent text / CDATA content (can consist of several parts
3260    ///   delimited by comments and processing instructions)
3261    ///
3262    /// # Events handling
3263    ///
3264    /// |Event             |XML                        |Handling
3265    /// |------------------|---------------------------|-------------------------------------------
3266    /// |[`DeEvent::Start`]|`<tag>...</tag>`           |Calls `visitor.visit_unit()`, consumes all events up to and including corresponding `End` event
3267    /// |[`DeEvent::End`]  |`</tag>`                   |This is impossible situation, the method will panic if it happens
3268    /// |[`DeEvent::Text`] |`text content` or `<![CDATA[cdata content]]>` (probably mixed)|Calls `visitor.visit_unit()`. The content is ignored
3269    /// |[`DeEvent::Eof`]  |                           |Emits [`UnexpectedEof`](DeError::UnexpectedEof)
3270    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, DeError>
3271    where
3272        V: Visitor<'de>,
3273    {
3274        match self.next()? {
3275            DeEvent::Start(s) => {
3276                self.read_to_end(s.name())?;
3277                visitor.visit_unit()
3278            }
3279            DeEvent::Text(_) => visitor.visit_unit(),
3280            // SAFETY: The reader is guaranteed that we don't have unmatched tags
3281            // If we here, then our deserializer has a bug
3282            DeEvent::End(e) => unreachable!("{:?}", e),
3283            DeEvent::Eof => Err(DeError::UnexpectedEof),
3284        }
3285    }
3286
3287    /// Forwards deserialization of the inner type. Always calls [`Visitor::visit_newtype_struct`]
3288    /// with the same deserializer.
3289    fn deserialize_newtype_struct<V>(
3290        self,
3291        _name: &'static str,
3292        visitor: V,
3293    ) -> Result<V::Value, DeError>
3294    where
3295        V: Visitor<'de>,
3296    {
3297        visitor.visit_newtype_struct(self)
3298    }
3299
3300    fn deserialize_enum<V>(
3301        self,
3302        _name: &'static str,
3303        _variants: &'static [&'static str],
3304        visitor: V,
3305    ) -> Result<V::Value, DeError>
3306    where
3307        V: Visitor<'de>,
3308    {
3309        // When document is pretty-printed there could be whitespaces before the root element
3310        // which represents the enum variant
3311        // Checked by `top_level::list_of_enum` test in serde-de-seq
3312        self.skip_whitespaces()?;
3313        visitor.visit_enum(var::EnumAccess::new(self))
3314    }
3315
3316    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, DeError>
3317    where
3318        V: Visitor<'de>,
3319    {
3320        visitor.visit_seq(self)
3321    }
3322
3323    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, DeError>
3324    where
3325        V: Visitor<'de>,
3326    {
3327        // We cannot use result of `peek()` directly because of borrow checker
3328        let _ = self.peek()?;
3329        match self.last_peeked() {
3330            DeEvent::Text(t) if t.is_empty() => visitor.visit_none(),
3331            DeEvent::Eof => visitor.visit_none(),
3332            // if the `xsi:nil` attribute is set to true we got a none value
3333            DeEvent::Start(start) if self.reader.reader.has_nil_attr(&start) => {
3334                self.skip_next_tree()?;
3335                visitor.visit_none()
3336            }
3337            _ => visitor.visit_some(self),
3338        }
3339    }
3340
3341    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, DeError>
3342    where
3343        V: Visitor<'de>,
3344    {
3345        match self.peek()? {
3346            DeEvent::Text(_) => self.deserialize_str(visitor),
3347            _ => self.deserialize_map(visitor),
3348        }
3349    }
3350}
3351
3352/// An accessor to sequence elements forming a value for top-level sequence of XML
3353/// elements.
3354///
3355/// Technically, multiple top-level elements violates XML rule of only one top-level
3356/// element, but we consider this as several concatenated XML documents.
3357impl<'de, 'a, R, E> SeqAccess<'de> for &'a mut Deserializer<'de, R, E>
3358where
3359    R: XmlRead<'de>,
3360    E: EntityResolver,
3361{
3362    type Error = DeError;
3363
3364    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
3365    where
3366        T: DeserializeSeed<'de>,
3367    {
3368        // When document is pretty-printed there could be whitespaces before, between
3369        // and after root elements. We cannot defer decision if we need to skip spaces
3370        // or not: if we have a sequence of type that does not accept blank text, it
3371        // will need to return something and it can return only error. For example,
3372        // it can be enum without `$text` variant
3373        // Checked by `top_level::list_of_enum` test in serde-de-seq
3374        self.skip_whitespaces()?;
3375        match self.peek()? {
3376            DeEvent::Eof => Ok(None),
3377
3378            // Start(tag), End(tag), Text
3379            _ => seed.deserialize(&mut **self).map(Some),
3380        }
3381    }
3382}
3383
3384impl<'de, 'a, R, E> IntoDeserializer<'de, DeError> for &'a mut Deserializer<'de, R, E>
3385where
3386    R: XmlRead<'de>,
3387    E: EntityResolver,
3388{
3389    type Deserializer = Self;
3390
3391    #[inline]
3392    fn into_deserializer(self) -> Self {
3393        self
3394    }
3395}
3396
3397////////////////////////////////////////////////////////////////////////////////////////////////////
3398
3399/// Converts raw reader's event into a payload event.
3400/// Returns `None`, if event should be skipped.
3401#[inline(always)]
3402fn skip_uninterested<'a>(event: Event<'a>) -> Option<PayloadEvent<'a>> {
3403    let event = match event {
3404        Event::DocType(e) => PayloadEvent::DocType(e),
3405        Event::Start(e) => PayloadEvent::Start(e),
3406        Event::End(e) => PayloadEvent::End(e),
3407        Event::Eof => PayloadEvent::Eof,
3408
3409        // Do not trim next text event after Text, CDATA or reference event
3410        Event::CData(e) => PayloadEvent::CData(e),
3411        Event::Text(e) => PayloadEvent::Text(e),
3412        Event::GeneralRef(e) => PayloadEvent::GeneralRef(e),
3413
3414        _ => return None,
3415    };
3416    Some(event)
3417}
3418
3419////////////////////////////////////////////////////////////////////////////////////////////////////
3420
3421/// Trait used by the deserializer for iterating over input. This is manually
3422/// "specialized" for iterating over `&[u8]`.
3423///
3424/// You do not need to implement this trait, it is needed to abstract from
3425/// [borrowing](SliceReader) and [copying](IoReader) data sources and reuse code in
3426/// deserializer
3427pub trait XmlRead<'i> {
3428    /// Return an input-borrowing event.
3429    fn next(&mut self) -> Result<PayloadEvent<'i>, DeError>;
3430
3431    /// Skips until end element is found. Unlike `next()` it will not allocate
3432    /// when it cannot satisfy the lifetime.
3433    fn read_to_end(&mut self, name: QName) -> Result<(), DeError>;
3434
3435    /// A copy of the reader's decoder used to decode strings.
3436    fn decoder(&self) -> Decoder;
3437
3438    /// Checks if the `start` tag has a [`xsi:nil`] attribute. This method ignores
3439    /// any errors in attributes.
3440    ///
3441    /// [`xsi:nil`]: https://www.w3.org/TR/xmlschema-1/#xsi_nil
3442    fn has_nil_attr(&self, start: &BytesStart) -> bool;
3443}
3444
3445/// XML input source that reads from a std::io input stream.
3446///
3447/// You cannot create it, it is created automatically when you call
3448/// [`Deserializer::from_reader`]
3449pub struct IoReader<R: BufRead> {
3450    reader: NsReader<R>,
3451    buf: Vec<u8>,
3452}
3453
3454impl<R: BufRead> IoReader<R> {
3455    /// Returns the underlying XML reader.
3456    ///
3457    /// ```
3458    /// # use pretty_assertions::assert_eq;
3459    /// use serde::Deserialize;
3460    /// use std::io::Cursor;
3461    /// use quick_xml::de::Deserializer;
3462    /// use quick_xml::NsReader;
3463    ///
3464    /// #[derive(Deserialize)]
3465    /// struct SomeStruct {
3466    ///     field1: String,
3467    ///     field2: String,
3468    /// }
3469    ///
3470    /// // Try to deserialize from broken XML
3471    /// let mut de = Deserializer::from_reader(Cursor::new(
3472    ///     "<SomeStruct><field1><field2></SomeStruct>"
3473    /// //   0                           ^= 28        ^= 41
3474    /// ));
3475    ///
3476    /// let err = SomeStruct::deserialize(&mut de);
3477    /// assert!(err.is_err());
3478    ///
3479    /// let reader: &NsReader<Cursor<&str>> = de.get_ref().get_ref();
3480    ///
3481    /// assert_eq!(reader.error_position(), 28);
3482    /// assert_eq!(reader.buffer_position(), 41);
3483    /// ```
3484    pub const fn get_ref(&self) -> &NsReader<R> {
3485        &self.reader
3486    }
3487}
3488
3489impl<'i, R: BufRead> XmlRead<'i> for IoReader<R> {
3490    fn next(&mut self) -> Result<PayloadEvent<'static>, DeError> {
3491        loop {
3492            self.buf.clear();
3493
3494            let event = self.reader.read_event_into(&mut self.buf)?;
3495            if let Some(event) = skip_uninterested(event) {
3496                return Ok(event.into_owned());
3497            }
3498        }
3499    }
3500
3501    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
3502        match self.reader.read_to_end_into(name, &mut self.buf) {
3503            Err(e) => Err(e.into()),
3504            Ok(_) => Ok(()),
3505        }
3506    }
3507
3508    fn decoder(&self) -> Decoder {
3509        self.reader.decoder()
3510    }
3511
3512    fn has_nil_attr(&self, start: &BytesStart) -> bool {
3513        start.attributes().has_nil(&self.reader)
3514    }
3515}
3516
3517/// XML input source that reads from a slice of bytes and can borrow from it.
3518///
3519/// You cannot create it, it is created automatically when you call
3520/// [`Deserializer::from_str`].
3521pub struct SliceReader<'de> {
3522    reader: NsReader<&'de [u8]>,
3523}
3524
3525impl<'de> SliceReader<'de> {
3526    /// Returns the underlying XML reader.
3527    ///
3528    /// ```
3529    /// # use pretty_assertions::assert_eq;
3530    /// use serde::Deserialize;
3531    /// use quick_xml::de::Deserializer;
3532    /// use quick_xml::NsReader;
3533    ///
3534    /// #[derive(Deserialize)]
3535    /// struct SomeStruct {
3536    ///     field1: String,
3537    ///     field2: String,
3538    /// }
3539    ///
3540    /// // Try to deserialize from broken XML
3541    /// let mut de = Deserializer::from_str(
3542    ///     "<SomeStruct><field1><field2></SomeStruct>"
3543    /// //   0                           ^= 28        ^= 41
3544    /// );
3545    ///
3546    /// let err = SomeStruct::deserialize(&mut de);
3547    /// assert!(err.is_err());
3548    ///
3549    /// let reader: &NsReader<&[u8]> = de.get_ref().get_ref();
3550    ///
3551    /// assert_eq!(reader.error_position(), 28);
3552    /// assert_eq!(reader.buffer_position(), 41);
3553    /// ```
3554    pub const fn get_ref(&self) -> &NsReader<&'de [u8]> {
3555        &self.reader
3556    }
3557}
3558
3559impl<'de> XmlRead<'de> for SliceReader<'de> {
3560    fn next(&mut self) -> Result<PayloadEvent<'de>, DeError> {
3561        loop {
3562            let event = self.reader.read_event()?;
3563            if let Some(event) = skip_uninterested(event) {
3564                return Ok(event);
3565            }
3566        }
3567    }
3568
3569    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
3570        match self.reader.read_to_end(name) {
3571            Err(e) => Err(e.into()),
3572            Ok(_) => Ok(()),
3573        }
3574    }
3575
3576    fn decoder(&self) -> Decoder {
3577        self.reader.decoder()
3578    }
3579
3580    fn has_nil_attr(&self, start: &BytesStart) -> bool {
3581        start.attributes().has_nil(&self.reader)
3582    }
3583}
3584
3585#[cfg(test)]
3586mod tests {
3587    use super::*;
3588    use crate::errors::IllFormedError;
3589    use pretty_assertions::assert_eq;
3590
3591    fn make_de<'de>(source: &'de str) -> Deserializer<'de, SliceReader<'de>> {
3592        dbg!(source);
3593        Deserializer::from_str(source)
3594    }
3595
3596    #[cfg(feature = "overlapped-lists")]
3597    mod skip {
3598        use super::*;
3599        use crate::de::DeEvent::*;
3600        use crate::events::BytesEnd;
3601        use pretty_assertions::assert_eq;
3602
3603        /// Checks that `peek()` and `read()` behaves correctly after `skip()`
3604        #[test]
3605        fn read_and_peek() {
3606            let mut de = make_de(
3607                "\
3608                <root>\
3609                    <inner>\
3610                        text\
3611                        <inner/>\
3612                    </inner>\
3613                    <next/>\
3614                    <target/>\
3615                </root>\
3616                ",
3617            );
3618
3619            // Initial conditions - both are empty
3620            assert_eq!(de.read, vec![]);
3621            assert_eq!(de.write, vec![]);
3622
3623            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
3624            assert_eq!(de.peek().unwrap(), &Start(BytesStart::new("inner")));
3625
3626            // Mark that start_replay() should begin replay from this point
3627            let checkpoint = de.skip_checkpoint();
3628            assert_eq!(checkpoint, 0);
3629
3630            // Should skip first <inner> tree
3631            de.skip().unwrap();
3632            assert_eq!(de.read, vec![]);
3633            assert_eq!(
3634                de.write,
3635                vec![
3636                    Start(BytesStart::new("inner")),
3637                    Text("text".into()),
3638                    Start(BytesStart::new("inner")),
3639                    End(BytesEnd::new("inner")),
3640                    End(BytesEnd::new("inner")),
3641                ]
3642            );
3643
3644            // Consume <next/>. Now unconsumed XML looks like:
3645            //
3646            //   <inner>
3647            //     text
3648            //     <inner/>
3649            //   </inner>
3650            //   <target/>
3651            // </root>
3652            assert_eq!(de.next().unwrap(), Start(BytesStart::new("next")));
3653            assert_eq!(de.next().unwrap(), End(BytesEnd::new("next")));
3654
3655            // We finish writing. Next call to `next()` should start replay that messages:
3656            //
3657            //   <inner>
3658            //     text
3659            //     <inner/>
3660            //   </inner>
3661            //
3662            // and after that stream that messages:
3663            //
3664            //   <target/>
3665            // </root>
3666            de.start_replay(checkpoint);
3667            assert_eq!(
3668                de.read,
3669                vec![
3670                    Start(BytesStart::new("inner")),
3671                    Text("text".into()),
3672                    Start(BytesStart::new("inner")),
3673                    End(BytesEnd::new("inner")),
3674                    End(BytesEnd::new("inner")),
3675                ]
3676            );
3677            assert_eq!(de.write, vec![]);
3678            assert_eq!(de.next().unwrap(), Start(BytesStart::new("inner")));
3679
3680            // Mark that start_replay() should begin replay from this point
3681            let checkpoint = de.skip_checkpoint();
3682            assert_eq!(checkpoint, 0);
3683
3684            // Skip `$text` node and consume <inner/> after it
3685            de.skip().unwrap();
3686            assert_eq!(
3687                de.read,
3688                vec![
3689                    Start(BytesStart::new("inner")),
3690                    End(BytesEnd::new("inner")),
3691                    End(BytesEnd::new("inner")),
3692                ]
3693            );
3694            assert_eq!(
3695                de.write,
3696                vec![
3697                    // This comment here to keep the same formatting of both arrays
3698                    // otherwise rustfmt suggest one-line it
3699                    Text("text".into()),
3700                ]
3701            );
3702
3703            assert_eq!(de.next().unwrap(), Start(BytesStart::new("inner")));
3704            assert_eq!(de.next().unwrap(), End(BytesEnd::new("inner")));
3705
3706            // We finish writing. Next call to `next()` should start replay messages:
3707            //
3708            //     text
3709            //   </inner>
3710            //
3711            // and after that stream that messages:
3712            //
3713            //   <target/>
3714            // </root>
3715            de.start_replay(checkpoint);
3716            assert_eq!(
3717                de.read,
3718                vec![
3719                    // This comment here to keep the same formatting as others
3720                    // otherwise rustfmt suggest one-line it
3721                    Text("text".into()),
3722                    End(BytesEnd::new("inner")),
3723                ]
3724            );
3725            assert_eq!(de.write, vec![]);
3726            assert_eq!(de.next().unwrap(), Text("text".into()));
3727            assert_eq!(de.next().unwrap(), End(BytesEnd::new("inner")));
3728            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target")));
3729            assert_eq!(de.next().unwrap(), End(BytesEnd::new("target")));
3730            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
3731            assert_eq!(de.next().unwrap(), Eof);
3732        }
3733
3734        /// Checks that `read_to_end()` behaves correctly after `skip()`
3735        #[test]
3736        fn read_to_end() {
3737            let mut de = make_de(
3738                "\
3739                <root>\
3740                    <skip>\
3741                        text\
3742                        <skip/>\
3743                    </skip>\
3744                    <target>\
3745                        <target/>\
3746                    </target>\
3747                </root>\
3748                ",
3749            );
3750
3751            // Initial conditions - both are empty
3752            assert_eq!(de.read, vec![]);
3753            assert_eq!(de.write, vec![]);
3754
3755            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
3756
3757            // Mark that start_replay() should begin replay from this point
3758            let checkpoint = de.skip_checkpoint();
3759            assert_eq!(checkpoint, 0);
3760
3761            // Skip the <skip> tree
3762            de.skip().unwrap();
3763            assert_eq!(de.read, vec![]);
3764            assert_eq!(
3765                de.write,
3766                vec![
3767                    Start(BytesStart::new("skip")),
3768                    Text("text".into()),
3769                    Start(BytesStart::new("skip")),
3770                    End(BytesEnd::new("skip")),
3771                    End(BytesEnd::new("skip")),
3772                ]
3773            );
3774
3775            // Drop all events that represents <target> tree. Now unconsumed XML looks like:
3776            //
3777            //   <skip>
3778            //     text
3779            //     <skip/>
3780            //   </skip>
3781            // </root>
3782            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target")));
3783            de.read_to_end(QName(b"target")).unwrap();
3784            assert_eq!(de.read, vec![]);
3785            assert_eq!(
3786                de.write,
3787                vec![
3788                    Start(BytesStart::new("skip")),
3789                    Text("text".into()),
3790                    Start(BytesStart::new("skip")),
3791                    End(BytesEnd::new("skip")),
3792                    End(BytesEnd::new("skip")),
3793                ]
3794            );
3795
3796            // We finish writing. Next call to `next()` should start replay that messages:
3797            //
3798            //   <skip>
3799            //     text
3800            //     <skip/>
3801            //   </skip>
3802            //
3803            // and after that stream that messages:
3804            //
3805            // </root>
3806            de.start_replay(checkpoint);
3807            assert_eq!(
3808                de.read,
3809                vec![
3810                    Start(BytesStart::new("skip")),
3811                    Text("text".into()),
3812                    Start(BytesStart::new("skip")),
3813                    End(BytesEnd::new("skip")),
3814                    End(BytesEnd::new("skip")),
3815                ]
3816            );
3817            assert_eq!(de.write, vec![]);
3818
3819            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skip")));
3820            de.read_to_end(QName(b"skip")).unwrap();
3821
3822            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
3823            assert_eq!(de.next().unwrap(), Eof);
3824        }
3825
3826        /// Checks that replay replayes only part of events
3827        /// Test for https://github.com/tafia/quick-xml/issues/435
3828        #[test]
3829        fn partial_replay() {
3830            let mut de = make_de(
3831                "\
3832                <root>\
3833                    <skipped-1/>\
3834                    <skipped-2/>\
3835                    <inner>\
3836                        <skipped-3/>\
3837                        <skipped-4/>\
3838                        <target-2/>\
3839                    </inner>\
3840                    <target-1/>\
3841                </root>\
3842                ",
3843            );
3844
3845            // Initial conditions - both are empty
3846            assert_eq!(de.read, vec![]);
3847            assert_eq!(de.write, vec![]);
3848
3849            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
3850
3851            // start_replay() should start replay from this point
3852            let checkpoint1 = de.skip_checkpoint();
3853            assert_eq!(checkpoint1, 0);
3854
3855            // Should skip first and second <skipped-N/> elements
3856            de.skip().unwrap(); // skipped-1
3857            de.skip().unwrap(); // skipped-2
3858            assert_eq!(de.read, vec![]);
3859            assert_eq!(
3860                de.write,
3861                vec![
3862                    Start(BytesStart::new("skipped-1")),
3863                    End(BytesEnd::new("skipped-1")),
3864                    Start(BytesStart::new("skipped-2")),
3865                    End(BytesEnd::new("skipped-2")),
3866                ]
3867            );
3868
3869            ////////////////////////////////////////////////////////////////////////////////////////
3870
3871            assert_eq!(de.next().unwrap(), Start(BytesStart::new("inner")));
3872            assert_eq!(de.peek().unwrap(), &Start(BytesStart::new("skipped-3")));
3873            assert_eq!(
3874                de.read,
3875                vec![
3876                    // This comment here to keep the same formatting of both arrays
3877                    // otherwise rustfmt suggest one-line it
3878                    Start(BytesStart::new("skipped-3")),
3879                ]
3880            );
3881            assert_eq!(
3882                de.write,
3883                vec![
3884                    Start(BytesStart::new("skipped-1")),
3885                    End(BytesEnd::new("skipped-1")),
3886                    Start(BytesStart::new("skipped-2")),
3887                    End(BytesEnd::new("skipped-2")),
3888                ]
3889            );
3890
3891            // start_replay() should start replay from this point
3892            let checkpoint2 = de.skip_checkpoint();
3893            assert_eq!(checkpoint2, 4);
3894
3895            // Should skip third and forth <skipped-N/> elements
3896            de.skip().unwrap(); // skipped-3
3897            de.skip().unwrap(); // skipped-4
3898            assert_eq!(de.read, vec![]);
3899            assert_eq!(
3900                de.write,
3901                vec![
3902                    // checkpoint 1
3903                    Start(BytesStart::new("skipped-1")),
3904                    End(BytesEnd::new("skipped-1")),
3905                    Start(BytesStart::new("skipped-2")),
3906                    End(BytesEnd::new("skipped-2")),
3907                    // checkpoint 2
3908                    Start(BytesStart::new("skipped-3")),
3909                    End(BytesEnd::new("skipped-3")),
3910                    Start(BytesStart::new("skipped-4")),
3911                    End(BytesEnd::new("skipped-4")),
3912                ]
3913            );
3914            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target-2")));
3915            assert_eq!(de.next().unwrap(), End(BytesEnd::new("target-2")));
3916            assert_eq!(de.peek().unwrap(), &End(BytesEnd::new("inner")));
3917            assert_eq!(
3918                de.read,
3919                vec![
3920                    // This comment here to keep the same formatting of both arrays
3921                    // otherwise rustfmt suggest one-line it
3922                    End(BytesEnd::new("inner")),
3923                ]
3924            );
3925            assert_eq!(
3926                de.write,
3927                vec![
3928                    // checkpoint 1
3929                    Start(BytesStart::new("skipped-1")),
3930                    End(BytesEnd::new("skipped-1")),
3931                    Start(BytesStart::new("skipped-2")),
3932                    End(BytesEnd::new("skipped-2")),
3933                    // checkpoint 2
3934                    Start(BytesStart::new("skipped-3")),
3935                    End(BytesEnd::new("skipped-3")),
3936                    Start(BytesStart::new("skipped-4")),
3937                    End(BytesEnd::new("skipped-4")),
3938                ]
3939            );
3940
3941            // Start replay events from checkpoint 2
3942            de.start_replay(checkpoint2);
3943            assert_eq!(
3944                de.read,
3945                vec![
3946                    Start(BytesStart::new("skipped-3")),
3947                    End(BytesEnd::new("skipped-3")),
3948                    Start(BytesStart::new("skipped-4")),
3949                    End(BytesEnd::new("skipped-4")),
3950                    End(BytesEnd::new("inner")),
3951                ]
3952            );
3953            assert_eq!(
3954                de.write,
3955                vec![
3956                    Start(BytesStart::new("skipped-1")),
3957                    End(BytesEnd::new("skipped-1")),
3958                    Start(BytesStart::new("skipped-2")),
3959                    End(BytesEnd::new("skipped-2")),
3960                ]
3961            );
3962
3963            // Replayed events
3964            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-3")));
3965            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-3")));
3966            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-4")));
3967            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-4")));
3968
3969            assert_eq!(de.next().unwrap(), End(BytesEnd::new("inner")));
3970            assert_eq!(de.read, vec![]);
3971            assert_eq!(
3972                de.write,
3973                vec![
3974                    Start(BytesStart::new("skipped-1")),
3975                    End(BytesEnd::new("skipped-1")),
3976                    Start(BytesStart::new("skipped-2")),
3977                    End(BytesEnd::new("skipped-2")),
3978                ]
3979            );
3980
3981            ////////////////////////////////////////////////////////////////////////////////////////
3982
3983            // New events
3984            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target-1")));
3985            assert_eq!(de.next().unwrap(), End(BytesEnd::new("target-1")));
3986
3987            assert_eq!(de.read, vec![]);
3988            assert_eq!(
3989                de.write,
3990                vec![
3991                    Start(BytesStart::new("skipped-1")),
3992                    End(BytesEnd::new("skipped-1")),
3993                    Start(BytesStart::new("skipped-2")),
3994                    End(BytesEnd::new("skipped-2")),
3995                ]
3996            );
3997
3998            // Start replay events from checkpoint 1
3999            de.start_replay(checkpoint1);
4000            assert_eq!(
4001                de.read,
4002                vec![
4003                    Start(BytesStart::new("skipped-1")),
4004                    End(BytesEnd::new("skipped-1")),
4005                    Start(BytesStart::new("skipped-2")),
4006                    End(BytesEnd::new("skipped-2")),
4007                ]
4008            );
4009            assert_eq!(de.write, vec![]);
4010
4011            // Replayed events
4012            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-1")));
4013            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-1")));
4014            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-2")));
4015            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-2")));
4016
4017            assert_eq!(de.read, vec![]);
4018            assert_eq!(de.write, vec![]);
4019
4020            // New events
4021            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
4022            assert_eq!(de.next().unwrap(), Eof);
4023        }
4024
4025        /// Checks that limiting buffer size works correctly
4026        #[test]
4027        fn limit() {
4028            use serde::Deserialize;
4029
4030            #[derive(Debug, Deserialize)]
4031            #[allow(unused)]
4032            struct List {
4033                item: Vec<()>,
4034            }
4035
4036            let mut de = make_de(
4037                "\
4038                <any-name>\
4039                    <item/>\
4040                    <another-item>\
4041                        <some-element>with text</some-element>\
4042                        <yet-another-element/>\
4043                    </another-item>\
4044                    <item/>\
4045                    <item/>\
4046                </any-name>\
4047                ",
4048            );
4049            de.event_buffer_size(NonZeroUsize::new(3));
4050
4051            match List::deserialize(&mut de) {
4052                Err(DeError::TooManyEvents(count)) => assert_eq!(count.get(), 3),
4053                e => panic!("Expected `Err(TooManyEvents(3))`, but got `{:?}`", e),
4054            }
4055        }
4056
4057        /// Without handling Eof in `skip` this test failed with memory allocation
4058        #[test]
4059        fn invalid_xml() {
4060            use crate::de::DeEvent::*;
4061
4062            let mut de = make_de("<root>");
4063
4064            // Cache all events
4065            let checkpoint = de.skip_checkpoint();
4066            de.skip().unwrap();
4067            de.start_replay(checkpoint);
4068            assert_eq!(de.read, vec![Start(BytesStart::new("root")), Eof]);
4069        }
4070    }
4071
4072    mod read_to_end {
4073        use super::*;
4074        use crate::de::DeEvent::*;
4075        use pretty_assertions::assert_eq;
4076
4077        #[test]
4078        fn complex() {
4079            let mut de = make_de(
4080                r#"
4081                <root>
4082                    <tag a="1"><tag>text</tag>content</tag>
4083                    <tag a="2"><![CDATA[cdata content]]></tag>
4084                    <self-closed/>
4085                </root>
4086                "#,
4087            );
4088
4089            assert_eq!(de.next().unwrap(), Text("\n                ".into()));
4090            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
4091
4092            assert_eq!(de.next().unwrap(), Text("\n                    ".into()));
4093            assert_eq!(
4094                de.next().unwrap(),
4095                Start(BytesStart::from_content(r#"tag a="1""#, 3))
4096            );
4097            assert_eq!(de.read_to_end(QName(b"tag")).unwrap(), ());
4098
4099            assert_eq!(de.next().unwrap(), Text("\n                    ".into()));
4100            assert_eq!(
4101                de.next().unwrap(),
4102                Start(BytesStart::from_content(r#"tag a="2""#, 3))
4103            );
4104            assert_eq!(de.next().unwrap(), Text("cdata content".into()));
4105            assert_eq!(de.next().unwrap(), End(BytesEnd::new("tag")));
4106
4107            assert_eq!(de.next().unwrap(), Text("\n                    ".into()));
4108            assert_eq!(de.next().unwrap(), Start(BytesStart::new("self-closed")));
4109            assert_eq!(de.read_to_end(QName(b"self-closed")).unwrap(), ());
4110
4111            assert_eq!(de.next().unwrap(), Text("\n                ".into()));
4112            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
4113            assert_eq!(de.next().unwrap(), Text("\n                ".into()));
4114            assert_eq!(de.next().unwrap(), Eof);
4115        }
4116
4117        #[test]
4118        fn invalid_xml1() {
4119            let mut de = make_de("<tag><tag></tag>");
4120
4121            assert_eq!(de.next().unwrap(), Start(BytesStart::new("tag")));
4122            assert_eq!(de.peek().unwrap(), &Start(BytesStart::new("tag")));
4123
4124            match de.read_to_end(QName(b"tag")) {
4125                Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4126                    assert_eq!(cause, IllFormedError::MissingEndTag("tag".into()))
4127                }
4128                x => panic!(
4129                    "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4130                    x
4131                ),
4132            }
4133            assert_eq!(de.next().unwrap(), Eof);
4134        }
4135
4136        #[test]
4137        fn invalid_xml2() {
4138            let mut de = make_de("<tag><![CDATA[]]><tag></tag>");
4139
4140            assert_eq!(de.next().unwrap(), Start(BytesStart::new("tag")));
4141            assert_eq!(de.peek().unwrap(), &Text("".into()));
4142
4143            match de.read_to_end(QName(b"tag")) {
4144                Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4145                    assert_eq!(cause, IllFormedError::MissingEndTag("tag".into()))
4146                }
4147                x => panic!(
4148                    "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4149                    x
4150                ),
4151            }
4152            assert_eq!(de.next().unwrap(), Eof);
4153        }
4154    }
4155
4156    #[test]
4157    fn borrowing_reader_parity() {
4158        let s = r#"
4159            <item name="hello" source="world.rs">Some text</item>
4160            <item2/>
4161            <item3 value="world" />
4162        "#;
4163
4164        let mut reader1 = IoReader {
4165            reader: NsReader::from_reader(s.as_bytes()),
4166            buf: Vec::new(),
4167        };
4168        let mut reader2 = SliceReader {
4169            reader: NsReader::from_str(s),
4170        };
4171
4172        loop {
4173            let event1 = reader1.next().unwrap();
4174            let event2 = reader2.next().unwrap();
4175
4176            if let (PayloadEvent::Eof, PayloadEvent::Eof) = (&event1, &event2) {
4177                break;
4178            }
4179
4180            assert_eq!(event1, event2);
4181        }
4182    }
4183
4184    #[test]
4185    fn borrowing_reader_events() {
4186        let s = r#"
4187            <item name="hello" source="world.rs">Some text</item>
4188            <item2></item2>
4189            <item3/>
4190            <item4 value="world" />
4191        "#;
4192
4193        let mut reader = SliceReader {
4194            reader: NsReader::from_str(s),
4195        };
4196
4197        let config = reader.reader.config_mut();
4198        config.expand_empty_elements = true;
4199
4200        let mut events = Vec::new();
4201
4202        loop {
4203            let event = reader.next().unwrap();
4204            if let PayloadEvent::Eof = event {
4205                break;
4206            }
4207            events.push(event);
4208        }
4209
4210        use crate::de::PayloadEvent::*;
4211
4212        assert_eq!(
4213            events,
4214            vec![
4215                Text(BytesText::from_escaped("\n            ")),
4216                Start(BytesStart::from_content(
4217                    r#"item name="hello" source="world.rs""#,
4218                    4
4219                )),
4220                Text(BytesText::from_escaped("Some text")),
4221                End(BytesEnd::new("item")),
4222                Text(BytesText::from_escaped("\n            ")),
4223                Start(BytesStart::from_content("item2", 5)),
4224                End(BytesEnd::new("item2")),
4225                Text(BytesText::from_escaped("\n            ")),
4226                Start(BytesStart::from_content("item3", 5)),
4227                End(BytesEnd::new("item3")),
4228                Text(BytesText::from_escaped("\n            ")),
4229                Start(BytesStart::from_content(r#"item4 value="world" "#, 5)),
4230                End(BytesEnd::new("item4")),
4231                Text(BytesText::from_escaped("\n        ")),
4232            ]
4233        )
4234    }
4235
4236    /// Ensures, that [`Deserializer::read_string()`] never can get an `End` event,
4237    /// because parser reports error early
4238    #[test]
4239    fn read_string() {
4240        match from_str::<String>(r#"</root>"#) {
4241            Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4242                assert_eq!(cause, IllFormedError::UnmatchedEndTag("root".into()));
4243            }
4244            x => panic!(
4245                "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4246                x
4247            ),
4248        }
4249
4250        let s: String = from_str(r#"<root></root>"#).unwrap();
4251        assert_eq!(s, "");
4252
4253        match from_str::<String>(r#"<root></other>"#) {
4254            Err(DeError::InvalidXml(Error::IllFormed(cause))) => assert_eq!(
4255                cause,
4256                IllFormedError::MismatchedEndTag {
4257                    expected: "root".into(),
4258                    found: "other".into(),
4259                }
4260            ),
4261            x => panic!("Expected `Err(InvalidXml(IllFormed(_))`, but got `{:?}`", x),
4262        }
4263    }
4264
4265    /// Tests for https://github.com/tafia/quick-xml/issues/474.
4266    ///
4267    /// That tests ensures that comments and processed instructions is ignored
4268    /// and can split one logical string in pieces.
4269    mod merge_text {
4270        use super::*;
4271        use pretty_assertions::assert_eq;
4272
4273        #[test]
4274        fn text() {
4275            let mut de = make_de("text");
4276            assert_eq!(de.next().unwrap(), DeEvent::Text("text".into()));
4277        }
4278
4279        #[test]
4280        fn cdata() {
4281            let mut de = make_de("<![CDATA[cdata]]>");
4282            assert_eq!(de.next().unwrap(), DeEvent::Text("cdata".into()));
4283        }
4284
4285        #[test]
4286        fn text_and_cdata() {
4287            let mut de = make_de("text and <![CDATA[cdata]]>");
4288            assert_eq!(de.next().unwrap(), DeEvent::Text("text and cdata".into()));
4289        }
4290
4291        #[test]
4292        fn text_and_empty_cdata() {
4293            let mut de = make_de("text and <![CDATA[]]>");
4294            assert_eq!(de.next().unwrap(), DeEvent::Text("text and ".into()));
4295        }
4296
4297        #[test]
4298        fn cdata_and_text() {
4299            let mut de = make_de("<![CDATA[cdata]]> and text");
4300            assert_eq!(de.next().unwrap(), DeEvent::Text("cdata and text".into()));
4301        }
4302
4303        #[test]
4304        fn empty_cdata_and_text() {
4305            let mut de = make_de("<![CDATA[]]> and text");
4306            assert_eq!(de.next().unwrap(), DeEvent::Text(" and text".into()));
4307        }
4308
4309        #[test]
4310        fn cdata_and_cdata() {
4311            let mut de = make_de(
4312                "\
4313                    <![CDATA[cdata]]]]>\
4314                    <![CDATA[>cdata]]>\
4315                ",
4316            );
4317            assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4318        }
4319
4320        mod comment_between {
4321            use super::*;
4322            use pretty_assertions::assert_eq;
4323
4324            #[test]
4325            fn text() {
4326                let mut de = make_de(
4327                    "\
4328                        text \
4329                        <!--comment 1--><!--comment 2--> \
4330                        text\
4331                    ",
4332                );
4333                assert_eq!(de.next().unwrap(), DeEvent::Text("text  text".into()));
4334            }
4335
4336            #[test]
4337            fn cdata() {
4338                let mut de = make_de(
4339                    "\
4340                        <![CDATA[cdata]]]]>\
4341                        <!--comment 1--><!--comment 2-->\
4342                        <![CDATA[>cdata]]>\
4343                    ",
4344                );
4345                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4346            }
4347
4348            #[test]
4349            fn text_and_cdata() {
4350                let mut de = make_de(
4351                    "\
4352                        text \
4353                        <!--comment 1--><!--comment 2-->\
4354                        <![CDATA[ cdata]]>\
4355                    ",
4356                );
4357                assert_eq!(de.next().unwrap(), DeEvent::Text("text  cdata".into()));
4358            }
4359
4360            #[test]
4361            fn text_and_empty_cdata() {
4362                let mut de = make_de(
4363                    "\
4364                        text \
4365                        <!--comment 1--><!--comment 2-->\
4366                        <![CDATA[]]>\
4367                    ",
4368                );
4369                assert_eq!(de.next().unwrap(), DeEvent::Text("text ".into()));
4370            }
4371
4372            #[test]
4373            fn cdata_and_text() {
4374                let mut de = make_de(
4375                    "\
4376                        <![CDATA[cdata ]]>\
4377                        <!--comment 1--><!--comment 2--> \
4378                        text \
4379                    ",
4380                );
4381                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata  text ".into()));
4382            }
4383
4384            #[test]
4385            fn empty_cdata_and_text() {
4386                let mut de = make_de(
4387                    "\
4388                        <![CDATA[]]>\
4389                        <!--comment 1--><!--comment 2--> \
4390                        text \
4391                    ",
4392                );
4393                assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4394            }
4395
4396            #[test]
4397            fn cdata_and_cdata() {
4398                let mut de = make_de(
4399                    "\
4400                        <![CDATA[cdata]]]>\
4401                        <!--comment 1--><!--comment 2-->\
4402                        <![CDATA[]>cdata]]>\
4403                    ",
4404                );
4405                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4406            }
4407        }
4408
4409        mod pi_between {
4410            use super::*;
4411            use pretty_assertions::assert_eq;
4412
4413            #[test]
4414            fn text() {
4415                let mut de = make_de(
4416                    "\
4417                        text \
4418                        <?pi 1?><?pi 2?> \
4419                        text\
4420                    ",
4421                );
4422                assert_eq!(de.next().unwrap(), DeEvent::Text("text  text".into()));
4423            }
4424
4425            #[test]
4426            fn cdata() {
4427                let mut de = make_de(
4428                    "\
4429                        <![CDATA[cdata]]]]>\
4430                        <?pi 1?><?pi 2?>\
4431                        <![CDATA[>cdata]]>\
4432                    ",
4433                );
4434                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4435            }
4436
4437            #[test]
4438            fn text_and_cdata() {
4439                let mut de = make_de(
4440                    "\
4441                        text \
4442                        <?pi 1?><?pi 2?>\
4443                        <![CDATA[ cdata]]>\
4444                    ",
4445                );
4446                assert_eq!(de.next().unwrap(), DeEvent::Text("text  cdata".into()));
4447            }
4448
4449            #[test]
4450            fn text_and_empty_cdata() {
4451                let mut de = make_de(
4452                    "\
4453                        text \
4454                        <?pi 1?><?pi 2?>\
4455                        <![CDATA[]]>\
4456                    ",
4457                );
4458                assert_eq!(de.next().unwrap(), DeEvent::Text("text ".into()));
4459            }
4460
4461            #[test]
4462            fn cdata_and_text() {
4463                let mut de = make_de(
4464                    "\
4465                        <![CDATA[cdata ]]>\
4466                        <?pi 1?><?pi 2?> \
4467                        text \
4468                    ",
4469                );
4470                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata  text ".into()));
4471            }
4472
4473            #[test]
4474            fn empty_cdata_and_text() {
4475                let mut de = make_de(
4476                    "\
4477                        <![CDATA[]]>\
4478                        <?pi 1?><?pi 2?> \
4479                        text \
4480                    ",
4481                );
4482                assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4483            }
4484
4485            #[test]
4486            fn cdata_and_cdata() {
4487                let mut de = make_de(
4488                    "\
4489                        <![CDATA[cdata]]]>\
4490                        <?pi 1?><?pi 2?>\
4491                        <![CDATA[]>cdata]]>\
4492                    ",
4493                );
4494                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4495            }
4496        }
4497    }
4498
4499    /// Tests for https://github.com/tafia/quick-xml/issues/474.
4500    ///
4501    /// This tests ensures that any combination of payload data is processed
4502    /// as expected.
4503    mod triples {
4504        use super::*;
4505        use pretty_assertions::assert_eq;
4506
4507        mod start {
4508            use super::*;
4509
4510            /// <tag1><tag2>...
4511            mod start {
4512                use super::*;
4513                use pretty_assertions::assert_eq;
4514
4515                #[test]
4516                fn start() {
4517                    let mut de = make_de("<tag1><tag2><tag3>");
4518                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4519                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4520                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag3")));
4521                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4522                }
4523
4524                /// Not matching end tag will result to error
4525                #[test]
4526                fn end() {
4527                    let mut de = make_de("<tag1><tag2></tag2>");
4528                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4529                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4530                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag2")));
4531                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4532                }
4533
4534                #[test]
4535                fn text() {
4536                    let mut de = make_de("<tag1><tag2> text ");
4537                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4538                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4539                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4540                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4541                }
4542
4543                #[test]
4544                fn cdata() {
4545                    let mut de = make_de("<tag1><tag2><![CDATA[ cdata ]]>");
4546                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4547                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4548                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4549                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4550                }
4551
4552                #[test]
4553                fn eof() {
4554                    let mut de = make_de("<tag1><tag2>");
4555                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4556                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4557                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4558                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4559                }
4560            }
4561
4562            /// <tag></tag>...
4563            mod end {
4564                use super::*;
4565                use pretty_assertions::assert_eq;
4566
4567                #[test]
4568                fn start() {
4569                    let mut de = make_de("<tag></tag><tag2>");
4570                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4571                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4572                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4573                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4574                }
4575
4576                #[test]
4577                fn end() {
4578                    let mut de = make_de("<tag></tag></tag2>");
4579                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4580                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4581                    match de.next() {
4582                        Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4583                            assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag2".into()));
4584                        }
4585                        x => panic!(
4586                            "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4587                            x
4588                        ),
4589                    }
4590                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4591                }
4592
4593                #[test]
4594                fn text() {
4595                    let mut de = make_de("<tag></tag> text ");
4596                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4597                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4598                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4599                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4600                }
4601
4602                #[test]
4603                fn cdata() {
4604                    let mut de = make_de("<tag></tag><![CDATA[ cdata ]]>");
4605                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4606                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4607                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4608                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4609                }
4610
4611                #[test]
4612                fn eof() {
4613                    let mut de = make_de("<tag></tag>");
4614                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4615                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4616                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4617                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4618                }
4619            }
4620
4621            /// <tag> text ...
4622            mod text {
4623                use super::*;
4624                use pretty_assertions::assert_eq;
4625
4626                #[test]
4627                fn start() {
4628                    let mut de = make_de("<tag> text <tag2>");
4629                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4630                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4631                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4632                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4633                }
4634
4635                #[test]
4636                fn end() {
4637                    let mut de = make_de("<tag> text </tag>");
4638                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4639                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4640                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4641                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4642                }
4643
4644                // start::text::text has no difference from start::text
4645
4646                #[test]
4647                fn cdata() {
4648                    let mut de = make_de("<tag> text <![CDATA[ cdata ]]>");
4649                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4650                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4651                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4652                }
4653
4654                #[test]
4655                fn eof() {
4656                    let mut de = make_de("<tag> text ");
4657                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4658                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4659                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4660                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4661                }
4662            }
4663
4664            /// <tag><![CDATA[ cdata ]]>...
4665            mod cdata {
4666                use super::*;
4667                use pretty_assertions::assert_eq;
4668
4669                #[test]
4670                fn start() {
4671                    let mut de = make_de("<tag><![CDATA[ cdata ]]><tag2>");
4672                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4673                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4674                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4675                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4676                }
4677
4678                #[test]
4679                fn end() {
4680                    let mut de = make_de("<tag><![CDATA[ cdata ]]></tag>");
4681                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4682                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4683                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4684                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4685                }
4686
4687                #[test]
4688                fn text() {
4689                    let mut de = make_de("<tag><![CDATA[ cdata ]]> text ");
4690                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4691                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  text ".into()));
4692                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4693                }
4694
4695                #[test]
4696                fn cdata() {
4697                    let mut de = make_de("<tag><![CDATA[ cdata ]]><![CDATA[ cdata2 ]]>");
4698                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4699                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
4700                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4701                }
4702
4703                #[test]
4704                fn eof() {
4705                    let mut de = make_de("<tag><![CDATA[ cdata ]]>");
4706                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4707                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4708                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4709                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4710                }
4711            }
4712        }
4713
4714        /// Start from End event will always generate an error
4715        #[test]
4716        fn end() {
4717            let mut de = make_de("</tag>");
4718            match de.next() {
4719                Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4720                    assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4721                }
4722                x => panic!(
4723                    "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4724                    x
4725                ),
4726            }
4727            assert_eq!(de.next().unwrap(), DeEvent::Eof);
4728        }
4729
4730        mod text {
4731            use super::*;
4732            use pretty_assertions::assert_eq;
4733
4734            mod start {
4735                use super::*;
4736                use pretty_assertions::assert_eq;
4737
4738                #[test]
4739                fn start() {
4740                    let mut de = make_de(" text <tag1><tag2>");
4741                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4742                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4743                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4744                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4745                }
4746
4747                /// Not matching end tag will result in error
4748                #[test]
4749                fn end() {
4750                    let mut de = make_de(" text <tag></tag>");
4751                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4752                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4753                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4754                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4755                }
4756
4757                #[test]
4758                fn text() {
4759                    let mut de = make_de(" text <tag> text2 ");
4760                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4761                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4762                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text2 ".into()));
4763                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4764                }
4765
4766                #[test]
4767                fn cdata() {
4768                    let mut de = make_de(" text <tag><![CDATA[ cdata ]]>");
4769                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4770                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4771                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4772                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4773                }
4774
4775                #[test]
4776                fn eof() {
4777                    let mut de = make_de(" text <tag>");
4778                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4779                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4780                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4781                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4782                }
4783            }
4784
4785            /// End event without corresponding start event will always generate an error
4786            #[test]
4787            fn end() {
4788                let mut de = make_de(" text </tag>");
4789                assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4790                match de.next() {
4791                    Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4792                        assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4793                    }
4794                    x => panic!(
4795                        "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4796                        x
4797                    ),
4798                }
4799                assert_eq!(de.next().unwrap(), DeEvent::Eof);
4800            }
4801
4802            // text::text::something is equivalent to text::something
4803
4804            mod cdata {
4805                use super::*;
4806                use pretty_assertions::assert_eq;
4807
4808                #[test]
4809                fn start() {
4810                    let mut de = make_de(" text <![CDATA[ cdata ]]><tag>");
4811                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4812                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4813                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4814                }
4815
4816                #[test]
4817                fn end() {
4818                    let mut de = make_de(" text <![CDATA[ cdata ]]></tag>");
4819                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4820                    match de.next() {
4821                        Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4822                            assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4823                        }
4824                        x => panic!(
4825                            "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4826                            x
4827                        ),
4828                    }
4829                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4830                }
4831
4832                #[test]
4833                fn text() {
4834                    let mut de = make_de(" text <![CDATA[ cdata ]]> text2 ");
4835                    assert_eq!(
4836                        de.next().unwrap(),
4837                        DeEvent::Text(" text  cdata  text2 ".into())
4838                    );
4839                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4840                }
4841
4842                #[test]
4843                fn cdata() {
4844                    let mut de = make_de(" text <![CDATA[ cdata ]]><![CDATA[ cdata2 ]]>");
4845                    assert_eq!(
4846                        de.next().unwrap(),
4847                        DeEvent::Text(" text  cdata  cdata2 ".into())
4848                    );
4849                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4850                }
4851
4852                #[test]
4853                fn eof() {
4854                    let mut de = make_de(" text <![CDATA[ cdata ]]>");
4855                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4856                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4857                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4858                }
4859            }
4860        }
4861
4862        mod cdata {
4863            use super::*;
4864            use pretty_assertions::assert_eq;
4865
4866            mod start {
4867                use super::*;
4868                use pretty_assertions::assert_eq;
4869
4870                #[test]
4871                fn start() {
4872                    let mut de = make_de("<![CDATA[ cdata ]]><tag1><tag2>");
4873                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4874                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4875                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4876                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4877                }
4878
4879                /// Not matching end tag will result in error
4880                #[test]
4881                fn end() {
4882                    let mut de = make_de("<![CDATA[ cdata ]]><tag></tag>");
4883                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4884                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4885                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4886                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4887                }
4888
4889                #[test]
4890                fn text() {
4891                    let mut de = make_de("<![CDATA[ cdata ]]><tag> text ");
4892                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4893                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4894                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4895                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4896                }
4897
4898                #[test]
4899                fn cdata() {
4900                    let mut de = make_de("<![CDATA[ cdata ]]><tag><![CDATA[ cdata2 ]]>");
4901                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4902                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4903                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata2 ".into()));
4904                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4905                }
4906
4907                #[test]
4908                fn eof() {
4909                    let mut de = make_de("<![CDATA[ cdata ]]><tag>");
4910                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4911                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4912                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4913                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4914                }
4915            }
4916
4917            /// End event without corresponding start event will always generate an error
4918            #[test]
4919            fn end() {
4920                let mut de = make_de("<![CDATA[ cdata ]]></tag>");
4921                assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4922                match de.next() {
4923                    Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4924                        assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4925                    }
4926                    x => panic!(
4927                        "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4928                        x
4929                    ),
4930                }
4931                assert_eq!(de.next().unwrap(), DeEvent::Eof);
4932            }
4933
4934            mod text {
4935                use super::*;
4936                use pretty_assertions::assert_eq;
4937
4938                #[test]
4939                fn start() {
4940                    let mut de = make_de("<![CDATA[ cdata ]]> text <tag>");
4941                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  text ".into()));
4942                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4943                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4944                }
4945
4946                #[test]
4947                fn end() {
4948                    let mut de = make_de("<![CDATA[ cdata ]]> text </tag>");
4949                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  text ".into()));
4950                    match de.next() {
4951                        Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4952                            assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4953                        }
4954                        x => panic!(
4955                            "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4956                            x
4957                        ),
4958                    }
4959                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4960                }
4961
4962                // cdata::text::text is equivalent to cdata::text
4963
4964                #[test]
4965                fn cdata() {
4966                    let mut de = make_de("<![CDATA[ cdata ]]> text <![CDATA[ cdata2 ]]>");
4967                    assert_eq!(
4968                        de.next().unwrap(),
4969                        DeEvent::Text(" cdata  text  cdata2 ".into())
4970                    );
4971                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4972                }
4973
4974                #[test]
4975                fn eof() {
4976                    let mut de = make_de("<![CDATA[ cdata ]]> text ");
4977                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  text ".into()));
4978                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4979                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4980                }
4981            }
4982
4983            mod cdata {
4984                use super::*;
4985                use pretty_assertions::assert_eq;
4986
4987                #[test]
4988                fn start() {
4989                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]><tag>");
4990                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
4991                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4992                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4993                }
4994
4995                #[test]
4996                fn end() {
4997                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]></tag>");
4998                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
4999                    match de.next() {
5000                        Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
5001                            assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
5002                        }
5003                        x => panic!(
5004                            "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
5005                            x
5006                        ),
5007                    }
5008                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
5009                }
5010
5011                #[test]
5012                fn text() {
5013                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]> text ");
5014                    assert_eq!(
5015                        de.next().unwrap(),
5016                        DeEvent::Text(" cdata  cdata2  text ".into())
5017                    );
5018                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
5019                }
5020
5021                #[test]
5022                fn cdata() {
5023                    let mut de =
5024                        make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]><![CDATA[ cdata3 ]]>");
5025                    assert_eq!(
5026                        de.next().unwrap(),
5027                        DeEvent::Text(" cdata  cdata2  cdata3 ".into())
5028                    );
5029                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
5030                }
5031
5032                #[test]
5033                fn eof() {
5034                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]>");
5035                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
5036                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
5037                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
5038                }
5039            }
5040        }
5041    }
5042}