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//! Representation of primitive types in `$value` does not differ from their
1581//! representation in `$text` field. The difference is how sequences are serialized.
1582//! `$value` serializes each sequence item as a separate XML element. The name
1583//! of that element is taken from serialized type, and because only `enum`s provide
1584//! such name (their variant name), only they should be used for such fields.
1585//!
1586//! `$value` fields does not support `struct` types with fields, the serialization
1587//! of such types would end with an `Err(Unsupported)`. Unit structs and unit
1588//! type `()` serializing to nothing and can be deserialized from any content.
1589//!
1590//! Serialization and deserialization of `$value` field performed as usual, except
1591//! that name for an XML element will be given by the serialized type, instead of
1592//! field. The latter allow to serialize enumerated types, where variant is encoded
1593//! as a tag name, and, so, represent an XSD `xs:choice` schema by the Rust `enum`.
1594//!
1595//! In the example below, field will be serialized as `<field/>`, because elements
1596//! get their names from the field name. It cannot be deserialized, because `Enum`
1597//! expects elements `<A/>`, `<B/>` or `<C/>`, but `AnyName` looked only for `<field/>`:
1598//!
1599//! ```
1600//! # use serde::{Deserialize, Serialize};
1601//! # use pretty_assertions::assert_eq;
1602//! # #[derive(PartialEq, Debug)]
1603//! #[derive(Deserialize, Serialize)]
1604//! enum Enum { A, B, C }
1605//!
1606//! # #[derive(PartialEq, Debug)]
1607//! #[derive(Deserialize, Serialize)]
1608//! struct AnyName {
1609//!     // <field>A</field>, <field>B</field>, or <field>C</field>
1610//!     field: Enum,
1611//! }
1612//! # assert_eq!(
1613//! #     quick_xml::se::to_string(&AnyName { field: Enum::A }).unwrap(),
1614//! #     "<AnyName><field>A</field></AnyName>",
1615//! # );
1616//! # assert_eq!(
1617//! #     AnyName { field: Enum::B },
1618//! #     quick_xml::de::from_str("<root><field>B</field></root>").unwrap(),
1619//! # );
1620//! ```
1621//!
1622//! If you rename field to `$value`, then `field` would be serialized as `<A/>`,
1623//! `<B/>` or `<C/>`, depending on the its content. It is also possible to
1624//! deserialize it from the same elements:
1625//!
1626//! ```
1627//! # use serde::{Deserialize, Serialize};
1628//! # use pretty_assertions::assert_eq;
1629//! # #[derive(Deserialize, Serialize, PartialEq, Debug)]
1630//! # enum Enum { A, B, C }
1631//! #
1632//! # #[derive(PartialEq, Debug)]
1633//! #[derive(Deserialize, Serialize)]
1634//! struct AnyName {
1635//!     // <A/>, <B/> or <C/>
1636//!     #[serde(rename = "$value")]
1637//!     field: Enum,
1638//! }
1639//! # assert_eq!(
1640//! #     quick_xml::se::to_string(&AnyName { field: Enum::A }).unwrap(),
1641//! #     "<AnyName><A/></AnyName>",
1642//! # );
1643//! # assert_eq!(
1644//! #     AnyName { field: Enum::B },
1645//! #     quick_xml::de::from_str("<root><B/></root>").unwrap(),
1646//! # );
1647//! ```
1648//!
1649//! ### Primitives and sequences of primitives
1650//!
1651//! Sequences serialized to a list of elements. Note, that types that does not
1652//! produce their own tag (i. e. primitives) will produce [`SeError::Unsupported`]
1653//! if they contains more that one element, because such sequence cannot be
1654//! deserialized to the same value:
1655//!
1656//! ```
1657//! # use serde::{Deserialize, Serialize};
1658//! # use pretty_assertions::assert_eq;
1659//! # use quick_xml::de::from_str;
1660//! # use quick_xml::se::to_string;
1661//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1662//! struct AnyName {
1663//!     #[serde(rename = "$value")]
1664//!     field: Vec<usize>,
1665//! }
1666//!
1667//! let obj = AnyName { field: vec![1, 2, 3] };
1668//! // If this object were serialized, it would be represented as "<AnyName>123</AnyName>"
1669//! to_string(&obj).unwrap_err();
1670//!
1671//! let object: AnyName = from_str("<AnyName>123</AnyName>").unwrap();
1672//! assert_eq!(object, AnyName { field: vec![123] });
1673//!
1674//! // `1 2 3` is mapped to a single `usize` element
1675//! // It is impossible to deserialize list of primitives to such field
1676//! from_str::<AnyName>("<AnyName>1 2 3</AnyName>").unwrap_err();
1677//! ```
1678//!
1679//! A particular case of that example is a string `$value` field, which probably
1680//! would be a most used example of that attribute:
1681//!
1682//! ```
1683//! # use serde::{Deserialize, Serialize};
1684//! # use pretty_assertions::assert_eq;
1685//! # use quick_xml::de::from_str;
1686//! # use quick_xml::se::to_string;
1687//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1688//! struct AnyName {
1689//!     #[serde(rename = "$value")]
1690//!     field: String,
1691//! }
1692//!
1693//! let obj = AnyName { field: "content".to_string() };
1694//! let xml = to_string(&obj).unwrap();
1695//! assert_eq!(xml, "<AnyName>content</AnyName>");
1696//! ```
1697//!
1698//! ### Structs and sequences of structs
1699//!
1700//! Note, that structures do not have a serializable name as well (name of the
1701//! type is never used), so it is impossible to serialize non-unit struct or
1702//! sequence of non-unit structs in `$value` field. (sequences of) unit structs
1703//! are serialized as empty string, because units itself serializing
1704//! to nothing:
1705//!
1706//! ```
1707//! # use serde::{Deserialize, Serialize};
1708//! # use pretty_assertions::assert_eq;
1709//! # use quick_xml::de::from_str;
1710//! # use quick_xml::se::to_string;
1711//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1712//! struct Unit;
1713//!
1714//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1715//! struct AnyName {
1716//!     // #[serde(default)] is required to deserialization of empty lists
1717//!     // This is a general note, not related to $value
1718//!     #[serde(rename = "$value", default)]
1719//!     field: Vec<Unit>,
1720//! }
1721//!
1722//! let obj = AnyName { field: vec![Unit, Unit, Unit] };
1723//! let xml = to_string(&obj).unwrap();
1724//! assert_eq!(xml, "<AnyName/>");
1725//!
1726//! let object: AnyName = from_str("<AnyName/>").unwrap();
1727//! assert_eq!(object, AnyName { field: vec![] });
1728//!
1729//! let object: AnyName = from_str("<AnyName></AnyName>").unwrap();
1730//! assert_eq!(object, AnyName { field: vec![] });
1731//!
1732//! let object: AnyName = from_str("<AnyName><A/><B/><C/></AnyName>").unwrap();
1733//! assert_eq!(object, AnyName { field: vec![Unit, Unit, Unit] });
1734//! ```
1735//!
1736//! ### Enums and sequences of enums
1737//!
1738//! Enumerations uses the variant name as an element name:
1739//!
1740//! ```
1741//! # use serde::{Deserialize, Serialize};
1742//! # use pretty_assertions::assert_eq;
1743//! # use quick_xml::de::from_str;
1744//! # use quick_xml::se::to_string;
1745//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1746//! struct AnyName {
1747//!     #[serde(rename = "$value")]
1748//!     field: Vec<Enum>,
1749//! }
1750//!
1751//! #[derive(Deserialize, Serialize, PartialEq, Debug)]
1752//! enum Enum { A, B, C }
1753//!
1754//! let obj = AnyName { field: vec![Enum::A, Enum::B, Enum::C] };
1755//! let xml = to_string(&obj).unwrap();
1756//! assert_eq!(
1757//!     xml,
1758//!     "<AnyName>\
1759//!         <A/>\
1760//!         <B/>\
1761//!         <C/>\
1762//!      </AnyName>"
1763//! );
1764//!
1765//! let object: AnyName = from_str(&xml).unwrap();
1766//! assert_eq!(object, obj);
1767//! ```
1768//!
1769//!
1770//!
1771//! Frequently Used Patterns
1772//! ========================
1773//!
1774//! Some XML constructs used so frequent, that it is worth to document the recommended
1775//! way to represent them in the Rust. The sections below describes them.
1776//!
1777//! `<element>` lists
1778//! -----------------
1779//! Many XML formats wrap lists of elements in the additional container,
1780//! although this is not required by the XML rules:
1781//!
1782//! ```xml
1783//! <root>
1784//!   <field1/>
1785//!   <field2/>
1786//!   <list><!-- Container -->
1787//!     <element/>
1788//!     <element/>
1789//!     <element/>
1790//!   </list>
1791//!   <field3/>
1792//! </root>
1793//! ```
1794//! In this case, there is a great desire to describe this XML in this way:
1795//! ```
1796//! /// Represents <element/>
1797//! type Element = ();
1798//!
1799//! /// Represents <root>...</root>
1800//! struct AnyName {
1801//!     // Incorrect
1802//!     list: Vec<Element>,
1803//! }
1804//! ```
1805//! This will not work, because potentially `<list>` element can have attributes
1806//! and other elements inside. You should define the struct for the `<list>`
1807//! explicitly, as you do that in the XSD for that XML:
1808//! ```
1809//! /// Represents <element/>
1810//! type Element = ();
1811//!
1812//! /// Represents <root>...</root>
1813//! struct AnyName {
1814//!     // Correct
1815//!     list: List,
1816//! }
1817//! /// Represents <list>...</list>
1818//! struct List {
1819//!     element: Vec<Element>,
1820//! }
1821//! ```
1822//!
1823//! If you want to simplify your API, you could write a simple function for unwrapping
1824//! inner list and apply it via [`deserialize_with`]:
1825//!
1826//! ```
1827//! # use pretty_assertions::assert_eq;
1828//! use quick_xml::de::from_str;
1829//! use serde::{Deserialize, Deserializer};
1830//!
1831//! /// Represents <element/>
1832//! type Element = ();
1833//!
1834//! /// Represents <root>...</root>
1835//! #[derive(Deserialize, Debug, PartialEq)]
1836//! struct AnyName {
1837//!     #[serde(deserialize_with = "unwrap_list")]
1838//!     list: Vec<Element>,
1839//! }
1840//!
1841//! fn unwrap_list<'de, D>(deserializer: D) -> Result<Vec<Element>, D::Error>
1842//! where
1843//!     D: Deserializer<'de>,
1844//! {
1845//!     /// Represents <list>...</list>
1846//!     #[derive(Deserialize)]
1847//!     struct List {
1848//!         // default allows empty list
1849//!         #[serde(default)]
1850//!         element: Vec<Element>,
1851//!     }
1852//!     Ok(List::deserialize(deserializer)?.element)
1853//! }
1854//!
1855//! assert_eq!(
1856//!     AnyName { list: vec![(), (), ()] },
1857//!     from_str("
1858//!         <root>
1859//!           <list>
1860//!             <element/>
1861//!             <element/>
1862//!             <element/>
1863//!           </list>
1864//!         </root>
1865//!     ").unwrap(),
1866//! );
1867//! ```
1868//!
1869//! Instead of writing such functions manually, you also could try <https://lib.rs/crates/serde-query>.
1870//!
1871//! Overlapped (Out-of-Order) Elements
1872//! ----------------------------------
1873//! In the case that the list might contain tags that are overlapped with
1874//! tags that do not correspond to the list (this is a usual case in XML
1875//! documents) like this:
1876//! ```xml
1877//! <any-name>
1878//!   <item/>
1879//!   <another-item/>
1880//!   <item/>
1881//!   <item/>
1882//! </any-name>
1883//! ```
1884//! you should enable the [`overlapped-lists`] feature to make it possible
1885//! to deserialize this to:
1886//! ```no_run
1887//! # use serde::Deserialize;
1888//! #[derive(Deserialize)]
1889//! #[serde(rename_all = "kebab-case")]
1890//! struct AnyName {
1891//!     item: Vec<()>,
1892//!     another_item: (),
1893//! }
1894//! ```
1895//!
1896//!
1897//! Internally Tagged Enums
1898//! -----------------------
1899//! [Tagged enums] are currently not supported because of an issue in the Serde
1900//! design (see [serde#1183] and [quick-xml#586]) and missing optimizations in
1901//! Serde which could be useful for XML parsing ([serde#1495]). This can be worked
1902//! around by manually implementing deserialize with `#[serde(deserialize_with = "func")]`
1903//! or implementing [`Deserialize`], but this can get very tedious very fast for
1904//! files with large amounts of tagged enums. To help with this issue quick-xml
1905//! provides a macro [`impl_deserialize_for_internally_tagged_enum!`]. See the
1906//! macro documentation for details.
1907//!
1908//!
1909//! [`overlapped-lists`]: ../index.html#overlapped-lists
1910//! [specification]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition
1911//! [`deserialize_with`]: https://serde.rs/field-attrs.html#deserialize_with
1912//! [`xsi:nil`]: https://www.w3.org/TR/xmlschema-1/#xsi_nil
1913//! [`Serializer::serialize_unit_variant`]: serde::Serializer::serialize_unit_variant
1914//! [`Deserializer::deserialize_enum`]: serde::Deserializer::deserialize_enum
1915//! [`SeError::Unsupported`]: crate::errors::serialize::SeError::Unsupported
1916//! [Tagged enums]: https://serde.rs/enum-representations.html#internally-tagged
1917//! [serde#1183]: https://github.com/serde-rs/serde/issues/1183
1918//! [serde#1495]: https://github.com/serde-rs/serde/issues/1495
1919//! [quick-xml#586]: https://github.com/tafia/quick-xml/issues/586
1920//! [`impl_deserialize_for_internally_tagged_enum!`]: crate::impl_deserialize_for_internally_tagged_enum
1921
1922// Macros should be defined before the modules that using them
1923// Also, macros should be imported before using them
1924use serde::serde_if_integer128;
1925
1926macro_rules! deserialize_num {
1927    ($deserialize:ident => $visit:ident, $($mut:tt)?) => {
1928        fn $deserialize<V>($($mut)? self, visitor: V) -> Result<V::Value, DeError>
1929        where
1930            V: Visitor<'de>,
1931        {
1932            // No need to unescape because valid integer representations cannot be escaped
1933            let text = self.read_string()?;
1934            match text.parse() {
1935                Ok(number) => visitor.$visit(number),
1936                Err(_) => match text {
1937                    Cow::Borrowed(t) => visitor.visit_str(t),
1938                    Cow::Owned(t) => visitor.visit_string(t),
1939                }
1940            }
1941        }
1942    };
1943}
1944
1945/// Implement deserialization methods for scalar types, such as numbers, strings,
1946/// byte arrays, booleans and identifiers.
1947macro_rules! deserialize_primitives {
1948    ($($mut:tt)?) => {
1949        deserialize_num!(deserialize_i8 => visit_i8, $($mut)?);
1950        deserialize_num!(deserialize_i16 => visit_i16, $($mut)?);
1951        deserialize_num!(deserialize_i32 => visit_i32, $($mut)?);
1952        deserialize_num!(deserialize_i64 => visit_i64, $($mut)?);
1953
1954        deserialize_num!(deserialize_u8 => visit_u8, $($mut)?);
1955        deserialize_num!(deserialize_u16 => visit_u16, $($mut)?);
1956        deserialize_num!(deserialize_u32 => visit_u32, $($mut)?);
1957        deserialize_num!(deserialize_u64 => visit_u64, $($mut)?);
1958
1959        serde_if_integer128! {
1960            deserialize_num!(deserialize_i128 => visit_i128, $($mut)?);
1961            deserialize_num!(deserialize_u128 => visit_u128, $($mut)?);
1962        }
1963
1964        deserialize_num!(deserialize_f32 => visit_f32, $($mut)?);
1965        deserialize_num!(deserialize_f64 => visit_f64, $($mut)?);
1966
1967        fn deserialize_bool<V>($($mut)? self, visitor: V) -> Result<V::Value, DeError>
1968        where
1969            V: Visitor<'de>,
1970        {
1971            let text = match self.read_string()? {
1972                Cow::Borrowed(s) => CowRef::Input(s),
1973                Cow::Owned(s) => CowRef::Owned(s),
1974            };
1975            text.deserialize_bool(visitor)
1976        }
1977
1978        /// Character represented as [strings](#method.deserialize_str).
1979        #[inline]
1980        fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, DeError>
1981        where
1982            V: Visitor<'de>,
1983        {
1984            self.deserialize_str(visitor)
1985        }
1986
1987        fn deserialize_str<V>($($mut)? self, visitor: V) -> Result<V::Value, DeError>
1988        where
1989            V: Visitor<'de>,
1990        {
1991            let text = self.read_string()?;
1992            match text {
1993                Cow::Borrowed(string) => visitor.visit_borrowed_str(string),
1994                Cow::Owned(string) => visitor.visit_string(string),
1995            }
1996        }
1997
1998        /// Representation of owned strings the same as [non-owned](#method.deserialize_str).
1999        #[inline]
2000        fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, DeError>
2001        where
2002            V: Visitor<'de>,
2003        {
2004            self.deserialize_str(visitor)
2005        }
2006
2007        /// Forwards deserialization to the [`deserialize_any`](#method.deserialize_any).
2008        #[inline]
2009        fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, DeError>
2010        where
2011            V: Visitor<'de>,
2012        {
2013            self.deserialize_any(visitor)
2014        }
2015
2016        /// Forwards deserialization to the [`deserialize_bytes`](#method.deserialize_bytes).
2017        #[inline]
2018        fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, DeError>
2019        where
2020            V: Visitor<'de>,
2021        {
2022            self.deserialize_bytes(visitor)
2023        }
2024
2025        /// Representation of the named units the same as [unnamed units](#method.deserialize_unit).
2026        #[inline]
2027        fn deserialize_unit_struct<V>(
2028            self,
2029            _name: &'static str,
2030            visitor: V,
2031        ) -> Result<V::Value, DeError>
2032        where
2033            V: Visitor<'de>,
2034        {
2035            self.deserialize_unit(visitor)
2036        }
2037
2038        /// Representation of tuples the same as [sequences](#method.deserialize_seq).
2039        #[inline]
2040        fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, DeError>
2041        where
2042            V: Visitor<'de>,
2043        {
2044            self.deserialize_seq(visitor)
2045        }
2046
2047        /// Representation of named tuples the same as [unnamed tuples](#method.deserialize_tuple).
2048        #[inline]
2049        fn deserialize_tuple_struct<V>(
2050            self,
2051            _name: &'static str,
2052            len: usize,
2053            visitor: V,
2054        ) -> Result<V::Value, DeError>
2055        where
2056            V: Visitor<'de>,
2057        {
2058            self.deserialize_tuple(len, visitor)
2059        }
2060
2061        /// Forwards deserialization to the [`deserialize_struct`](#method.deserialize_struct)
2062        /// with empty name and fields.
2063        #[inline]
2064        fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, DeError>
2065        where
2066            V: Visitor<'de>,
2067        {
2068            self.deserialize_struct("", &[], visitor)
2069        }
2070
2071        /// Identifiers represented as [strings](#method.deserialize_str).
2072        #[inline]
2073        fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, DeError>
2074        where
2075            V: Visitor<'de>,
2076        {
2077            self.deserialize_str(visitor)
2078        }
2079
2080        /// Forwards deserialization to the [`deserialize_unit`](#method.deserialize_unit).
2081        #[inline]
2082        fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, DeError>
2083        where
2084            V: Visitor<'de>,
2085        {
2086            self.deserialize_unit(visitor)
2087        }
2088    };
2089}
2090
2091mod attributes;
2092mod key;
2093mod map;
2094mod resolver;
2095mod simple_type;
2096mod text;
2097mod var;
2098
2099pub use self::attributes::AttributesDeserializer;
2100pub use self::resolver::{EntityResolver, PredefinedEntityResolver};
2101pub use self::simple_type::SimpleTypeDeserializer;
2102pub use crate::errors::serialize::DeError;
2103
2104use crate::{
2105    de::map::ElementMapAccess,
2106    encoding::Decoder,
2107    errors::Error,
2108    escape::{parse_number, EscapeError},
2109    events::{BytesCData, BytesEnd, BytesRef, BytesStart, BytesText, Event},
2110    name::QName,
2111    reader::NsReader,
2112    utils::CowRef,
2113};
2114use serde::de::{
2115    self, Deserialize, DeserializeOwned, DeserializeSeed, IntoDeserializer, SeqAccess, Visitor,
2116};
2117use std::borrow::Cow;
2118#[cfg(feature = "overlapped-lists")]
2119use std::collections::VecDeque;
2120use std::io::BufRead;
2121use std::mem::replace;
2122#[cfg(feature = "overlapped-lists")]
2123use std::num::NonZeroUsize;
2124use std::ops::{Deref, Range};
2125
2126/// Data represented by a text node or a CDATA node. XML markup is not expected
2127pub(crate) const TEXT_KEY: &str = "$text";
2128/// Data represented by any XML markup inside
2129pub(crate) const VALUE_KEY: &str = "$value";
2130
2131/// A function to check whether the character is a whitespace (blank, new line, carriage return or tab).
2132#[inline]
2133const fn is_non_whitespace(ch: char) -> bool {
2134    !matches!(ch, ' ' | '\r' | '\n' | '\t')
2135}
2136
2137/// Decoded and concatenated content of consequent [`Text`] and [`CData`]
2138/// events. _Consequent_ means that events should follow each other or be
2139/// delimited only by (any count of) [`Comment`] or [`PI`] events.
2140///
2141/// Internally text is stored in `Cow<str>`. Cloning of text is cheap while it
2142/// is borrowed and makes copies of data when it is owned.
2143///
2144/// [`Text`]: Event::Text
2145/// [`CData`]: Event::CData
2146/// [`Comment`]: Event::Comment
2147/// [`PI`]: Event::PI
2148#[derive(Clone, Debug, PartialEq, Eq)]
2149pub struct Text<'a> {
2150    /// Untrimmed text after concatenating content of all
2151    /// [`Text`] and [`CData`] events
2152    ///
2153    /// [`Text`]: Event::Text
2154    /// [`CData`]: Event::CData
2155    text: Cow<'a, str>,
2156    /// A range into `text` which contains data after trimming
2157    content: Range<usize>,
2158}
2159
2160impl<'a> Text<'a> {
2161    fn new(text: Cow<'a, str>) -> Self {
2162        let start = text.find(is_non_whitespace).unwrap_or(0);
2163        let end = text.rfind(is_non_whitespace).map_or(0, |i| i + 1);
2164
2165        let content = if start >= end { 0..0 } else { start..end };
2166
2167        Self { text, content }
2168    }
2169
2170    /// Returns text without leading and trailing whitespaces as [defined] by XML specification.
2171    ///
2172    /// If you want to only check if text contains only whitespaces, use [`is_blank`](Self::is_blank),
2173    /// which will not allocate.
2174    ///
2175    /// # Example
2176    ///
2177    /// ```
2178    /// # use quick_xml::de::Text;
2179    /// # use pretty_assertions::assert_eq;
2180    /// #
2181    /// let text = Text::from("");
2182    /// assert_eq!(text.trimmed(), "");
2183    ///
2184    /// let text = Text::from(" \r\n\t ");
2185    /// assert_eq!(text.trimmed(), "");
2186    ///
2187    /// let text = Text::from("  some useful text  ");
2188    /// assert_eq!(text.trimmed(), "some useful text");
2189    /// ```
2190    ///
2191    /// [defined]: https://www.w3.org/TR/xml11/#NT-S
2192    pub fn trimmed(&self) -> Cow<'a, str> {
2193        match self.text {
2194            Cow::Borrowed(text) => Cow::Borrowed(&text[self.content.clone()]),
2195            Cow::Owned(ref text) => Cow::Owned(text[self.content.clone()].to_string()),
2196        }
2197    }
2198
2199    /// Returns `true` if text is empty or contains only whitespaces as [defined] by XML specification.
2200    ///
2201    /// # Example
2202    ///
2203    /// ```
2204    /// # use quick_xml::de::Text;
2205    /// # use pretty_assertions::assert_eq;
2206    /// #
2207    /// let text = Text::from("");
2208    /// assert_eq!(text.is_blank(), true);
2209    ///
2210    /// let text = Text::from(" \r\n\t ");
2211    /// assert_eq!(text.is_blank(), true);
2212    ///
2213    /// let text = Text::from("  some useful text  ");
2214    /// assert_eq!(text.is_blank(), false);
2215    /// ```
2216    ///
2217    /// [defined]: https://www.w3.org/TR/xml11/#NT-S
2218    pub fn is_blank(&self) -> bool {
2219        self.content.is_empty()
2220    }
2221}
2222
2223impl<'a> Deref for Text<'a> {
2224    type Target = str;
2225
2226    #[inline]
2227    fn deref(&self) -> &Self::Target {
2228        self.text.deref()
2229    }
2230}
2231
2232impl<'a> From<&'a str> for Text<'a> {
2233    #[inline]
2234    fn from(text: &'a str) -> Self {
2235        Self::new(Cow::Borrowed(text))
2236    }
2237}
2238
2239impl<'a> From<String> for Text<'a> {
2240    #[inline]
2241    fn from(text: String) -> Self {
2242        Self::new(Cow::Owned(text))
2243    }
2244}
2245
2246impl<'a> From<Cow<'a, str>> for Text<'a> {
2247    #[inline]
2248    fn from(text: Cow<'a, str>) -> Self {
2249        Self::new(text)
2250    }
2251}
2252
2253////////////////////////////////////////////////////////////////////////////////////////////////////
2254
2255/// Simplified event which contains only these variants that used by deserializer
2256#[derive(Clone, Debug, PartialEq, Eq)]
2257pub enum DeEvent<'a> {
2258    /// Start tag (with attributes) `<tag attr="value">`.
2259    Start(BytesStart<'a>),
2260    /// End tag `</tag>`.
2261    End(BytesEnd<'a>),
2262    /// Decoded and concatenated content of consequent [`Text`] and [`CData`]
2263    /// events. _Consequent_ means that events should follow each other or be
2264    /// delimited only by (any count of) [`Comment`] or [`PI`] events.
2265    ///
2266    /// [`Text`]: Event::Text
2267    /// [`CData`]: Event::CData
2268    /// [`Comment`]: Event::Comment
2269    /// [`PI`]: Event::PI
2270    Text(Text<'a>),
2271    /// End of XML document.
2272    Eof,
2273}
2274
2275////////////////////////////////////////////////////////////////////////////////////////////////////
2276
2277/// Simplified event which contains only these variants that used by deserializer,
2278/// but [`Text`] events not yet fully processed.
2279///
2280/// [`Text`] events should be trimmed if they does not surrounded by the other
2281/// [`Text`] or [`CData`] events. This event contains intermediate state of [`Text`]
2282/// event, where they are trimmed from the start, but not from the end. To trim
2283/// end spaces we should lookahead by one deserializer event (i. e. skip all
2284/// comments and processing instructions).
2285///
2286/// [`Text`]: Event::Text
2287/// [`CData`]: Event::CData
2288#[derive(Clone, Debug, PartialEq, Eq)]
2289pub enum PayloadEvent<'a> {
2290    /// Start tag (with attributes) `<tag attr="value">`.
2291    Start(BytesStart<'a>),
2292    /// End tag `</tag>`.
2293    End(BytesEnd<'a>),
2294    /// Escaped character data between tags.
2295    Text(BytesText<'a>),
2296    /// Unescaped character data stored in `<![CDATA[...]]>`.
2297    CData(BytesCData<'a>),
2298    /// Document type definition data (DTD) stored in `<!DOCTYPE ...>`.
2299    DocType(BytesText<'a>),
2300    /// Reference `&ref;` in the textual data.
2301    GeneralRef(BytesRef<'a>),
2302    /// End of XML document.
2303    Eof,
2304}
2305
2306impl<'a> PayloadEvent<'a> {
2307    /// Ensures that all data is owned to extend the object's lifetime if necessary.
2308    #[inline]
2309    fn into_owned(self) -> PayloadEvent<'static> {
2310        match self {
2311            PayloadEvent::Start(e) => PayloadEvent::Start(e.into_owned()),
2312            PayloadEvent::End(e) => PayloadEvent::End(e.into_owned()),
2313            PayloadEvent::Text(e) => PayloadEvent::Text(e.into_owned()),
2314            PayloadEvent::CData(e) => PayloadEvent::CData(e.into_owned()),
2315            PayloadEvent::DocType(e) => PayloadEvent::DocType(e.into_owned()),
2316            PayloadEvent::GeneralRef(e) => PayloadEvent::GeneralRef(e.into_owned()),
2317            PayloadEvent::Eof => PayloadEvent::Eof,
2318        }
2319    }
2320}
2321
2322/// An intermediate reader that consumes [`PayloadEvent`]s and produces final [`DeEvent`]s.
2323/// [`PayloadEvent::Text`] events, that followed by any event except
2324/// [`PayloadEvent::Text`] or [`PayloadEvent::CData`], are trimmed from the end.
2325struct XmlReader<'i, R: XmlRead<'i>, E: EntityResolver = PredefinedEntityResolver> {
2326    /// A source of low-level XML events
2327    reader: R,
2328    /// Intermediate event, that could be returned by the next call to `next()`.
2329    /// If that is the `Text` event then leading spaces already trimmed, but
2330    /// trailing spaces is not. Before the event will be returned, trimming of
2331    /// the spaces could be necessary
2332    lookahead: Result<PayloadEvent<'i>, DeError>,
2333
2334    /// Used to resolve unknown entities that would otherwise cause the parser
2335    /// to return an [`EscapeError::UnrecognizedEntity`] error.
2336    ///
2337    /// [`EscapeError::UnrecognizedEntity`]: crate::escape::EscapeError::UnrecognizedEntity
2338    entity_resolver: E,
2339}
2340
2341impl<'i, R: XmlRead<'i>, E: EntityResolver> XmlReader<'i, R, E> {
2342    fn new(mut reader: R, entity_resolver: E) -> Self {
2343        // Lookahead by one event immediately, so we do not need to check in the
2344        // loop if we need lookahead or not
2345        let lookahead = reader.next();
2346
2347        Self {
2348            reader,
2349            lookahead,
2350            entity_resolver,
2351        }
2352    }
2353
2354    /// Returns `true` if all events was consumed
2355    const fn is_empty(&self) -> bool {
2356        matches!(self.lookahead, Ok(PayloadEvent::Eof))
2357    }
2358
2359    /// Read next event and put it in lookahead, return the current lookahead
2360    #[inline(always)]
2361    fn next_impl(&mut self) -> Result<PayloadEvent<'i>, DeError> {
2362        replace(&mut self.lookahead, self.reader.next())
2363    }
2364
2365    /// Returns `true` when next event is not a text event in any form.
2366    #[inline(always)]
2367    const fn current_event_is_last_text(&self) -> bool {
2368        // If next event is a text or CDATA, we should not trim trailing spaces
2369        !matches!(
2370            self.lookahead,
2371            Ok(PayloadEvent::Text(_)) | Ok(PayloadEvent::CData(_) | PayloadEvent::GeneralRef(_))
2372        )
2373    }
2374
2375    /// Read all consequent [`Text`] and [`CData`] events until non-text event
2376    /// occurs. Content of all events would be appended to `result` and returned
2377    /// as [`DeEvent::Text`].
2378    ///
2379    /// [`Text`]: PayloadEvent::Text
2380    /// [`CData`]: PayloadEvent::CData
2381    fn drain_text(&mut self, mut result: Cow<'i, str>) -> Result<DeEvent<'i>, DeError> {
2382        loop {
2383            if self.current_event_is_last_text() {
2384                break;
2385            }
2386
2387            match self.next_impl()? {
2388                PayloadEvent::Text(e) => result.to_mut().push_str(&e.decode()?),
2389                PayloadEvent::CData(e) => result.to_mut().push_str(&e.decode()?),
2390                PayloadEvent::GeneralRef(e) => self.resolve_reference(result.to_mut(), e)?,
2391
2392                // SAFETY: current_event_is_last_text checks that event is Text, CData or GeneralRef
2393                _ => unreachable!("Only `Text`, `CData` or `GeneralRef` events can come here"),
2394            }
2395        }
2396        Ok(DeEvent::Text(Text::new(result)))
2397    }
2398
2399    /// Return an input-borrowing event.
2400    fn next(&mut self) -> Result<DeEvent<'i>, DeError> {
2401        loop {
2402            return match self.next_impl()? {
2403                PayloadEvent::Start(e) => Ok(DeEvent::Start(e)),
2404                PayloadEvent::End(e) => Ok(DeEvent::End(e)),
2405                PayloadEvent::Text(e) => self.drain_text(e.decode()?),
2406                PayloadEvent::CData(e) => self.drain_text(e.decode()?),
2407                PayloadEvent::DocType(e) => {
2408                    self.entity_resolver
2409                        .capture(e)
2410                        .map_err(|err| DeError::Custom(format!("cannot parse DTD: {}", err)))?;
2411                    continue;
2412                }
2413                PayloadEvent::GeneralRef(e) => {
2414                    let mut text = String::new();
2415                    self.resolve_reference(&mut text, e)?;
2416                    self.drain_text(text.into())
2417                }
2418                PayloadEvent::Eof => Ok(DeEvent::Eof),
2419            };
2420        }
2421    }
2422
2423    fn resolve_reference(&mut self, result: &mut String, event: BytesRef) -> Result<(), DeError> {
2424        let len = event.len();
2425        let reference = self.decoder().decode(&event)?;
2426
2427        if let Some(num) = reference.strip_prefix('#') {
2428            let codepoint = parse_number(num).map_err(EscapeError::InvalidCharRef)?;
2429            result.push_str(codepoint.encode_utf8(&mut [0u8; 4]));
2430            return Ok(());
2431        }
2432        if let Some(value) = self.entity_resolver.resolve(reference.as_ref()) {
2433            result.push_str(value);
2434            return Ok(());
2435        }
2436        Err(EscapeError::UnrecognizedEntity(0..len, reference.to_string()).into())
2437    }
2438
2439    #[inline]
2440    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
2441        match self.lookahead {
2442            // We pre-read event with the same name that is required to be skipped.
2443            // First call of `read_to_end` will end out pre-read event, the second
2444            // will consume other events
2445            Ok(PayloadEvent::Start(ref e)) if e.name() == name => {
2446                let result1 = self.reader.read_to_end(name);
2447                let result2 = self.reader.read_to_end(name);
2448
2449                // In case of error `next_impl` returns `Eof`
2450                let _ = self.next_impl();
2451                result1?;
2452                result2?;
2453            }
2454            // We pre-read event with the same name that is required to be skipped.
2455            // Because this is end event, we already consume the whole tree, so
2456            // nothing to do, just update lookahead
2457            Ok(PayloadEvent::End(ref e)) if e.name() == name => {
2458                let _ = self.next_impl();
2459            }
2460            Ok(_) => {
2461                let result = self.reader.read_to_end(name);
2462
2463                // In case of error `next_impl` returns `Eof`
2464                let _ = self.next_impl();
2465                result?;
2466            }
2467            // Read next lookahead event, unpack error from the current lookahead
2468            Err(_) => {
2469                self.next_impl()?;
2470            }
2471        }
2472        Ok(())
2473    }
2474
2475    #[inline]
2476    fn decoder(&self) -> Decoder {
2477        self.reader.decoder()
2478    }
2479}
2480
2481////////////////////////////////////////////////////////////////////////////////////////////////////
2482
2483/// Deserialize an instance of type `T` from a string of XML text.
2484pub fn from_str<'de, T>(s: &'de str) -> Result<T, DeError>
2485where
2486    T: Deserialize<'de>,
2487{
2488    let mut de = Deserializer::from_str(s);
2489    T::deserialize(&mut de)
2490}
2491
2492/// Deserialize from a reader. This method will do internal copies of data
2493/// read from `reader`. If you want have a `&str` input and want to borrow
2494/// as much as possible, use [`from_str`].
2495pub fn from_reader<R, T>(reader: R) -> Result<T, DeError>
2496where
2497    R: BufRead,
2498    T: DeserializeOwned,
2499{
2500    let mut de = Deserializer::from_reader(reader);
2501    T::deserialize(&mut de)
2502}
2503
2504////////////////////////////////////////////////////////////////////////////////////////////////////
2505
2506/// A structure that deserializes XML into Rust values.
2507pub struct Deserializer<'de, R, E: EntityResolver = PredefinedEntityResolver>
2508where
2509    R: XmlRead<'de>,
2510{
2511    /// An XML reader that streams events into this deserializer
2512    reader: XmlReader<'de, R, E>,
2513
2514    /// When deserializing sequences sometimes we have to skip unwanted events.
2515    /// That events should be stored and then replayed. This is a replay buffer,
2516    /// that streams events while not empty. When it exhausted, events will
2517    /// requested from [`Self::reader`].
2518    #[cfg(feature = "overlapped-lists")]
2519    read: VecDeque<DeEvent<'de>>,
2520    /// When deserializing sequences sometimes we have to skip events, because XML
2521    /// is tolerant to elements order and even if in the XSD order is strictly
2522    /// specified (using `xs:sequence`) most of XML parsers allows order violations.
2523    /// That means, that elements, forming a sequence, could be overlapped with
2524    /// other elements, do not related to that sequence.
2525    ///
2526    /// In order to support this, deserializer will scan events and skip unwanted
2527    /// events, store them here. After call [`Self::start_replay()`] all events
2528    /// moved from this to [`Self::read`].
2529    #[cfg(feature = "overlapped-lists")]
2530    write: VecDeque<DeEvent<'de>>,
2531    /// Maximum number of events that can be skipped when processing sequences
2532    /// that occur out-of-order. This field is used to prevent potential
2533    /// denial-of-service (DoS) attacks which could cause infinite memory
2534    /// consumption when parsing a very large amount of XML into a sequence field.
2535    #[cfg(feature = "overlapped-lists")]
2536    limit: Option<NonZeroUsize>,
2537
2538    #[cfg(not(feature = "overlapped-lists"))]
2539    peek: Option<DeEvent<'de>>,
2540
2541    /// Buffer to store attribute name as a field name exposed to serde consumers
2542    key_buf: String,
2543}
2544
2545impl<'de, R, E> Deserializer<'de, R, E>
2546where
2547    R: XmlRead<'de>,
2548    E: EntityResolver,
2549{
2550    /// Create an XML deserializer from one of the possible quick_xml input sources.
2551    ///
2552    /// Typically it is more convenient to use one of these methods instead:
2553    ///
2554    ///  - [`Deserializer::from_str`]
2555    ///  - [`Deserializer::from_reader`]
2556    fn new(reader: R, entity_resolver: E) -> Self {
2557        Self {
2558            reader: XmlReader::new(reader, entity_resolver),
2559
2560            #[cfg(feature = "overlapped-lists")]
2561            read: VecDeque::new(),
2562            #[cfg(feature = "overlapped-lists")]
2563            write: VecDeque::new(),
2564            #[cfg(feature = "overlapped-lists")]
2565            limit: None,
2566
2567            #[cfg(not(feature = "overlapped-lists"))]
2568            peek: None,
2569
2570            key_buf: String::new(),
2571        }
2572    }
2573
2574    /// Returns `true` if all events was consumed.
2575    pub fn is_empty(&self) -> bool {
2576        #[cfg(feature = "overlapped-lists")]
2577        let event = self.read.front();
2578
2579        #[cfg(not(feature = "overlapped-lists"))]
2580        let event = self.peek.as_ref();
2581
2582        match event {
2583            None | Some(DeEvent::Eof) => self.reader.is_empty(),
2584            _ => false,
2585        }
2586    }
2587
2588    /// Returns the underlying XML reader.
2589    ///
2590    /// ```
2591    /// # use pretty_assertions::assert_eq;
2592    /// use serde::Deserialize;
2593    /// use quick_xml::de::Deserializer;
2594    /// use quick_xml::NsReader;
2595    ///
2596    /// #[derive(Deserialize)]
2597    /// struct SomeStruct {
2598    ///     field1: String,
2599    ///     field2: String,
2600    /// }
2601    ///
2602    /// // Try to deserialize from broken XML
2603    /// let mut de = Deserializer::from_str(
2604    ///     "<SomeStruct><field1><field2></SomeStruct>"
2605    /// //   0                           ^= 28        ^= 41
2606    /// );
2607    ///
2608    /// let err = SomeStruct::deserialize(&mut de);
2609    /// assert!(err.is_err());
2610    ///
2611    /// let reader: &NsReader<_> = de.get_ref().get_ref();
2612    ///
2613    /// assert_eq!(reader.error_position(), 28);
2614    /// assert_eq!(reader.buffer_position(), 41);
2615    /// ```
2616    pub const fn get_ref(&self) -> &R {
2617        &self.reader.reader
2618    }
2619
2620    /// Set the maximum number of events that could be skipped during deserialization
2621    /// of sequences.
2622    ///
2623    /// If `<element>` contains more than specified nested elements, `$text` or
2624    /// CDATA nodes, then [`DeError::TooManyEvents`] will be returned during
2625    /// deserialization of sequence field (any type that uses [`deserialize_seq`]
2626    /// for the deserialization, for example, `Vec<T>`).
2627    ///
2628    /// This method can be used to prevent a [DoS] attack and infinite memory
2629    /// consumption when parsing a very large XML to a sequence field.
2630    ///
2631    /// It is strongly recommended to set limit to some value when you parse data
2632    /// from untrusted sources. You should choose a value that your typical XMLs
2633    /// can have _between_ different elements that corresponds to the same sequence.
2634    ///
2635    /// # Examples
2636    ///
2637    /// Let's imagine, that we deserialize such structure:
2638    /// ```
2639    /// struct List {
2640    ///   item: Vec<()>,
2641    /// }
2642    /// ```
2643    ///
2644    /// The XML that we try to parse look like this:
2645    /// ```xml
2646    /// <any-name>
2647    ///   <item/>
2648    ///   <!-- Bufferization starts at this point -->
2649    ///   <another-item>
2650    ///     <some-element>with text</some-element>
2651    ///     <yet-another-element/>
2652    ///   </another-item>
2653    ///   <!-- Buffer will be emptied at this point; 7 events were buffered -->
2654    ///   <item/>
2655    ///   <!-- There is nothing to buffer, because elements follows each other -->
2656    ///   <item/>
2657    /// </any-name>
2658    /// ```
2659    ///
2660    /// There, when we deserialize the `item` field, we need to buffer 7 events,
2661    /// before we can deserialize the second `<item/>`:
2662    ///
2663    /// - `<another-item>`
2664    /// - `<some-element>`
2665    /// - `$text(with text)`
2666    /// - `</some-element>`
2667    /// - `<yet-another-element/>` (virtual start event)
2668    /// - `<yet-another-element/>` (virtual end event)
2669    /// - `</another-item>`
2670    ///
2671    /// Note, that `<yet-another-element/>` internally represented as 2 events:
2672    /// one for the start tag and one for the end tag. In the future this can be
2673    /// eliminated, but for now we use [auto-expanding feature] of a reader,
2674    /// because this simplifies deserializer code.
2675    ///
2676    /// [`deserialize_seq`]: serde::Deserializer::deserialize_seq
2677    /// [DoS]: https://en.wikipedia.org/wiki/Denial-of-service_attack
2678    /// [auto-expanding feature]: crate::reader::Config::expand_empty_elements
2679    #[cfg(feature = "overlapped-lists")]
2680    pub fn event_buffer_size(&mut self, limit: Option<NonZeroUsize>) -> &mut Self {
2681        self.limit = limit;
2682        self
2683    }
2684
2685    #[cfg(feature = "overlapped-lists")]
2686    fn peek(&mut self) -> Result<&DeEvent<'de>, DeError> {
2687        if self.read.is_empty() {
2688            self.read.push_front(self.reader.next()?);
2689        }
2690        if let Some(event) = self.read.front() {
2691            return Ok(event);
2692        }
2693        // SAFETY: `self.read` was filled in the code above.
2694        // NOTE: Can be replaced with `unsafe { std::hint::unreachable_unchecked() }`
2695        // if unsafe code will be allowed
2696        unreachable!()
2697    }
2698    #[cfg(not(feature = "overlapped-lists"))]
2699    fn peek(&mut self) -> Result<&DeEvent<'de>, DeError> {
2700        match &mut self.peek {
2701            Some(event) => Ok(event),
2702            empty_peek @ None => Ok(empty_peek.insert(self.reader.next()?)),
2703        }
2704    }
2705
2706    #[inline]
2707    fn last_peeked(&self) -> &DeEvent<'de> {
2708        #[cfg(feature = "overlapped-lists")]
2709        {
2710            self.read
2711                .front()
2712                .expect("`Deserializer::peek()` should be called")
2713        }
2714        #[cfg(not(feature = "overlapped-lists"))]
2715        {
2716            self.peek
2717                .as_ref()
2718                .expect("`Deserializer::peek()` should be called")
2719        }
2720    }
2721
2722    fn next(&mut self) -> Result<DeEvent<'de>, DeError> {
2723        // Replay skipped or peeked events
2724        #[cfg(feature = "overlapped-lists")]
2725        if let Some(event) = self.read.pop_front() {
2726            return Ok(event);
2727        }
2728        #[cfg(not(feature = "overlapped-lists"))]
2729        if let Some(e) = self.peek.take() {
2730            return Ok(e);
2731        }
2732        self.reader.next()
2733    }
2734
2735    fn skip_whitespaces(&mut self) -> Result<(), DeError> {
2736        loop {
2737            match self.peek()? {
2738                DeEvent::Text(e) if e.is_blank() => {
2739                    self.next()?;
2740                }
2741                _ => break,
2742            }
2743        }
2744        Ok(())
2745    }
2746
2747    /// Returns the mark after which all events, skipped by [`Self::skip()`] call,
2748    /// should be replayed after calling [`Self::start_replay()`].
2749    #[cfg(feature = "overlapped-lists")]
2750    #[inline]
2751    #[must_use = "returned checkpoint should be used in `start_replay`"]
2752    fn skip_checkpoint(&self) -> usize {
2753        self.write.len()
2754    }
2755
2756    /// Extracts XML tree of events from and stores them in the skipped events
2757    /// buffer from which they can be retrieved later. You MUST call
2758    /// [`Self::start_replay()`] after calling this to give access to the skipped
2759    /// events and release internal buffers.
2760    #[cfg(feature = "overlapped-lists")]
2761    fn skip(&mut self) -> Result<(), DeError> {
2762        let event = self.next()?;
2763        self.skip_event(event)?;
2764        match self.write.back() {
2765            // Skip all subtree, if we skip a start event
2766            Some(DeEvent::Start(e)) => {
2767                let end = e.name().as_ref().to_owned();
2768                let mut depth = 0;
2769                loop {
2770                    let event = self.next()?;
2771                    match event {
2772                        DeEvent::Start(ref e) if e.name().as_ref() == end => {
2773                            self.skip_event(event)?;
2774                            depth += 1;
2775                        }
2776                        DeEvent::End(ref e) if e.name().as_ref() == end => {
2777                            self.skip_event(event)?;
2778                            if depth == 0 {
2779                                break;
2780                            }
2781                            depth -= 1;
2782                        }
2783                        DeEvent::Eof => {
2784                            self.skip_event(event)?;
2785                            break;
2786                        }
2787                        _ => self.skip_event(event)?,
2788                    }
2789                }
2790            }
2791            _ => (),
2792        }
2793        Ok(())
2794    }
2795
2796    #[cfg(feature = "overlapped-lists")]
2797    #[inline]
2798    fn skip_event(&mut self, event: DeEvent<'de>) -> Result<(), DeError> {
2799        if let Some(max) = self.limit {
2800            if self.write.len() >= max.get() {
2801                return Err(DeError::TooManyEvents(max));
2802            }
2803        }
2804        self.write.push_back(event);
2805        Ok(())
2806    }
2807
2808    /// Moves buffered events, skipped after given `checkpoint` from [`Self::write`]
2809    /// skip buffer to [`Self::read`] buffer.
2810    ///
2811    /// After calling this method, [`Self::peek()`] and [`Self::next()`] starts
2812    /// return events that was skipped previously by calling [`Self::skip()`],
2813    /// and only when all that events will be consumed, the deserializer starts
2814    /// to drain events from underlying reader.
2815    ///
2816    /// This method MUST be called if any number of [`Self::skip()`] was called
2817    /// after [`Self::new()`] or `start_replay()` or you'll lost events.
2818    #[cfg(feature = "overlapped-lists")]
2819    fn start_replay(&mut self, checkpoint: usize) {
2820        if checkpoint == 0 {
2821            self.write.append(&mut self.read);
2822            std::mem::swap(&mut self.read, &mut self.write);
2823        } else {
2824            let mut read = self.write.split_off(checkpoint);
2825            read.append(&mut self.read);
2826            self.read = read;
2827        }
2828    }
2829
2830    #[inline]
2831    fn read_string(&mut self) -> Result<Cow<'de, str>, DeError> {
2832        self.read_string_impl(true)
2833    }
2834
2835    /// Consumes consequent [`Text`] and [`CData`] (both a referred below as a _text_)
2836    /// events, merge them into one string. If there are no such events, returns
2837    /// an empty string.
2838    ///
2839    /// If `allow_start` is `false`, then only text events are consumed, for other
2840    /// events an error is returned (see table below).
2841    ///
2842    /// If `allow_start` is `true`, then two or three events are expected:
2843    /// - [`DeEvent::Start`];
2844    /// - _(optional)_ [`DeEvent::Text`] which content is returned;
2845    /// - [`DeEvent::End`]. If text event was missed, an empty string is returned.
2846    ///
2847    /// Corresponding events are consumed.
2848    ///
2849    /// # Handling events
2850    ///
2851    /// The table below shows how events is handled by this method:
2852    ///
2853    /// |Event             |XML                        |Handling
2854    /// |------------------|---------------------------|----------------------------------------
2855    /// |[`DeEvent::Start`]|`<tag>...</tag>`           |if `allow_start == true`, result determined by the second table, otherwise emits [`UnexpectedStart("tag")`](DeError::UnexpectedStart)
2856    /// |[`DeEvent::End`]  |`</any-tag>`               |This is impossible situation, the method will panic if it happens
2857    /// |[`DeEvent::Text`] |`text content` or `<![CDATA[cdata content]]>` (probably mixed)|Returns event content unchanged
2858    /// |[`DeEvent::Eof`]  |                           |Emits [`UnexpectedEof`](DeError::UnexpectedEof)
2859    ///
2860    /// Second event, consumed if [`DeEvent::Start`] was received and `allow_start == true`:
2861    ///
2862    /// |Event             |XML                        |Handling
2863    /// |------------------|---------------------------|----------------------------------------------------------------------------------
2864    /// |[`DeEvent::Start`]|`<any-tag>...</any-tag>`   |Emits [`UnexpectedStart("any-tag")`](DeError::UnexpectedStart)
2865    /// |[`DeEvent::End`]  |`</tag>`                   |Returns an empty slice. The reader guarantee that tag will match the open one
2866    /// |[`DeEvent::Text`] |`text content` or `<![CDATA[cdata content]]>` (probably mixed)|Returns event content unchanged, expects the `</tag>` after that
2867    /// |[`DeEvent::Eof`]  |                           |Emits [`InvalidXml(IllFormed(MissingEndTag))`](DeError::InvalidXml)
2868    ///
2869    /// [`Text`]: Event::Text
2870    /// [`CData`]: Event::CData
2871    fn read_string_impl(&mut self, allow_start: bool) -> Result<Cow<'de, str>, DeError> {
2872        match self.next()? {
2873            DeEvent::Text(e) => Ok(e.text),
2874            // allow one nested level
2875            DeEvent::Start(e) if allow_start => self.read_text(e.name()),
2876            DeEvent::Start(e) => Err(DeError::UnexpectedStart(e.name().as_ref().to_owned())),
2877            // SAFETY: The reader is guaranteed that we don't have unmatched tags
2878            // If we here, then our deserializer has a bug
2879            DeEvent::End(e) => unreachable!("{:?}", e),
2880            DeEvent::Eof => Err(DeError::UnexpectedEof),
2881        }
2882    }
2883    /// Consumes one [`DeEvent::Text`] event and ensures that it is followed by the
2884    /// [`DeEvent::End`] event.
2885    ///
2886    /// # Parameters
2887    /// - `name`: name of a tag opened before reading text. The corresponding end tag
2888    ///   should present in input just after the text
2889    fn read_text(&mut self, name: QName) -> Result<Cow<'de, str>, DeError> {
2890        match self.next()? {
2891            DeEvent::Text(e) => match self.next()? {
2892                // The matching tag name is guaranteed by the reader
2893                DeEvent::End(_) => Ok(e.text),
2894                // SAFETY: Cannot be two consequent Text events, they would be merged into one
2895                DeEvent::Text(_) => unreachable!(),
2896                DeEvent::Start(e) => Err(DeError::UnexpectedStart(e.name().as_ref().to_owned())),
2897                DeEvent::Eof => Err(Error::missed_end(name, self.reader.decoder()).into()),
2898            },
2899            // We can get End event in case of `<tag></tag>` or `<tag/>` input
2900            // Return empty text in that case
2901            // The matching tag name is guaranteed by the reader
2902            DeEvent::End(_) => Ok("".into()),
2903            DeEvent::Start(s) => Err(DeError::UnexpectedStart(s.name().as_ref().to_owned())),
2904            DeEvent::Eof => Err(Error::missed_end(name, self.reader.decoder()).into()),
2905        }
2906    }
2907
2908    /// Drops all events until event with [name](BytesEnd::name()) `name` won't be
2909    /// dropped. This method should be called after [`Self::next()`]
2910    #[cfg(feature = "overlapped-lists")]
2911    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
2912        let mut depth = 0;
2913        loop {
2914            match self.read.pop_front() {
2915                Some(DeEvent::Start(e)) if e.name() == name => {
2916                    depth += 1;
2917                }
2918                Some(DeEvent::End(e)) if e.name() == name => {
2919                    if depth == 0 {
2920                        break;
2921                    }
2922                    depth -= 1;
2923                }
2924
2925                // Drop all other skipped events
2926                Some(_) => continue,
2927
2928                // If we do not have skipped events, use effective reading that will
2929                // not allocate memory for events
2930                None => {
2931                    // We should close all opened tags, because we could buffer
2932                    // Start events, but not the corresponding End events. So we
2933                    // keep reading events until we exit all nested tags.
2934                    // `read_to_end()` will return an error if an Eof was encountered
2935                    // preliminary (in case of malformed XML).
2936                    //
2937                    // <tag><tag></tag></tag>
2938                    // ^^^^^^^^^^             - buffered in `self.read`, when `self.read_to_end()` is called, depth = 2
2939                    //           ^^^^^^       - read by the first call of `self.reader.read_to_end()`
2940                    //                 ^^^^^^ - read by the second call of `self.reader.read_to_end()`
2941                    loop {
2942                        self.reader.read_to_end(name)?;
2943                        if depth == 0 {
2944                            break;
2945                        }
2946                        depth -= 1;
2947                    }
2948                    break;
2949                }
2950            }
2951        }
2952        Ok(())
2953    }
2954    #[cfg(not(feature = "overlapped-lists"))]
2955    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
2956        // First one might be in self.peek
2957        match self.next()? {
2958            DeEvent::Start(e) => self.reader.read_to_end(e.name())?,
2959            DeEvent::End(e) if e.name() == name => return Ok(()),
2960            _ => (),
2961        }
2962        self.reader.read_to_end(name)
2963    }
2964
2965    fn skip_next_tree(&mut self) -> Result<(), DeError> {
2966        let DeEvent::Start(start) = self.next()? else {
2967            unreachable!("Only call this if the next event is a start event")
2968        };
2969        let name = start.name();
2970        self.read_to_end(name)
2971    }
2972
2973    /// Method for testing Deserializer implementation. Checks that all events was consumed during
2974    /// deserialization. Panics if the next event will not be [`DeEvent::Eof`].
2975    #[doc(hidden)]
2976    #[track_caller]
2977    pub fn check_eof_reached(&mut self) {
2978        // Deserializer may not consume trailing spaces, that is normal
2979        self.skip_whitespaces().expect("cannot skip whitespaces");
2980        let event = self.peek().expect("cannot peek event");
2981        assert_eq!(
2982            *event,
2983            DeEvent::Eof,
2984            "the whole XML document should be consumed, expected `Eof`",
2985        );
2986    }
2987}
2988
2989impl<'de> Deserializer<'de, SliceReader<'de>> {
2990    /// Create new deserializer that will borrow data from the specified string.
2991    ///
2992    /// Deserializer created with this method will not resolve custom entities.
2993    #[allow(clippy::should_implement_trait)]
2994    pub fn from_str(source: &'de str) -> Self {
2995        Self::from_str_with_resolver(source, PredefinedEntityResolver)
2996    }
2997}
2998
2999impl<'de, E> Deserializer<'de, SliceReader<'de>, E>
3000where
3001    E: EntityResolver,
3002{
3003    /// Create new deserializer that will borrow data from the specified string
3004    /// and use specified entity resolver.
3005    pub fn from_str_with_resolver(source: &'de str, entity_resolver: E) -> Self {
3006        let mut reader = NsReader::from_str(source);
3007        let config = reader.config_mut();
3008        config.expand_empty_elements = true;
3009
3010        Self::new(SliceReader { reader }, entity_resolver)
3011    }
3012}
3013
3014impl<'de, R> Deserializer<'de, IoReader<R>>
3015where
3016    R: BufRead,
3017{
3018    /// Create new deserializer that will copy data from the specified reader
3019    /// into internal buffer.
3020    ///
3021    /// If you already have a string use [`Self::from_str`] instead, because it
3022    /// will borrow instead of copy. If you have `&[u8]` which is known to represent
3023    /// UTF-8, you can decode it first before using [`from_str`].
3024    ///
3025    /// Deserializer created with this method will not resolve custom entities.
3026    pub fn from_reader(reader: R) -> Self {
3027        Self::with_resolver(reader, PredefinedEntityResolver)
3028    }
3029}
3030
3031impl<'de, R, E> Deserializer<'de, IoReader<R>, E>
3032where
3033    R: BufRead,
3034    E: EntityResolver,
3035{
3036    /// Create new deserializer that will copy data from the specified reader
3037    /// into internal buffer and use specified entity resolver.
3038    ///
3039    /// If you already have a string use [`Self::from_str`] instead, because it
3040    /// will borrow instead of copy. If you have `&[u8]` which is known to represent
3041    /// UTF-8, you can decode it first before using [`from_str`].
3042    pub fn with_resolver(reader: R, entity_resolver: E) -> Self {
3043        let mut reader = NsReader::from_reader(reader);
3044        let config = reader.config_mut();
3045        config.expand_empty_elements = true;
3046
3047        Self::new(
3048            IoReader {
3049                reader,
3050                buf: Vec::new(),
3051            },
3052            entity_resolver,
3053        )
3054    }
3055}
3056
3057impl<'de, 'a, R, E> de::Deserializer<'de> for &'a mut Deserializer<'de, R, E>
3058where
3059    R: XmlRead<'de>,
3060    E: EntityResolver,
3061{
3062    type Error = DeError;
3063
3064    deserialize_primitives!();
3065
3066    fn deserialize_struct<V>(
3067        self,
3068        _name: &'static str,
3069        fields: &'static [&'static str],
3070        visitor: V,
3071    ) -> Result<V::Value, DeError>
3072    where
3073        V: Visitor<'de>,
3074    {
3075        // When document is pretty-printed there could be whitespaces before the root element
3076        self.skip_whitespaces()?;
3077        match self.next()? {
3078            DeEvent::Start(e) => visitor.visit_map(ElementMapAccess::new(self, e, fields)?),
3079            // SAFETY: The reader is guaranteed that we don't have unmatched tags
3080            // If we here, then our deserializer has a bug
3081            DeEvent::End(e) => unreachable!("{:?}", e),
3082            // Deserializer methods are only hints, if deserializer could not satisfy
3083            // request, it should return the data that it has. It is responsibility
3084            // of a Visitor to return an error if it does not understand the data
3085            DeEvent::Text(e) => match e.text {
3086                Cow::Borrowed(s) => visitor.visit_borrowed_str(s),
3087                Cow::Owned(s) => visitor.visit_string(s),
3088            },
3089            DeEvent::Eof => Err(DeError::UnexpectedEof),
3090        }
3091    }
3092
3093    /// Unit represented in XML as a `xs:element` or text/CDATA content.
3094    /// Any content inside `xs:element` is ignored and skipped.
3095    ///
3096    /// Produces unit struct from any of following inputs:
3097    /// - any `<tag ...>...</tag>`
3098    /// - any `<tag .../>`
3099    /// - any consequent text / CDATA content (can consist of several parts
3100    ///   delimited by comments and processing instructions)
3101    ///
3102    /// # Events handling
3103    ///
3104    /// |Event             |XML                        |Handling
3105    /// |------------------|---------------------------|-------------------------------------------
3106    /// |[`DeEvent::Start`]|`<tag>...</tag>`           |Calls `visitor.visit_unit()`, consumes all events up to and including corresponding `End` event
3107    /// |[`DeEvent::End`]  |`</tag>`                   |This is impossible situation, the method will panic if it happens
3108    /// |[`DeEvent::Text`] |`text content` or `<![CDATA[cdata content]]>` (probably mixed)|Calls `visitor.visit_unit()`. The content is ignored
3109    /// |[`DeEvent::Eof`]  |                           |Emits [`UnexpectedEof`](DeError::UnexpectedEof)
3110    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, DeError>
3111    where
3112        V: Visitor<'de>,
3113    {
3114        match self.next()? {
3115            DeEvent::Start(s) => {
3116                self.read_to_end(s.name())?;
3117                visitor.visit_unit()
3118            }
3119            DeEvent::Text(_) => visitor.visit_unit(),
3120            // SAFETY: The reader is guaranteed that we don't have unmatched tags
3121            // If we here, then our deserializer has a bug
3122            DeEvent::End(e) => unreachable!("{:?}", e),
3123            DeEvent::Eof => Err(DeError::UnexpectedEof),
3124        }
3125    }
3126
3127    /// Forwards deserialization of the inner type. Always calls [`Visitor::visit_newtype_struct`]
3128    /// with the same deserializer.
3129    fn deserialize_newtype_struct<V>(
3130        self,
3131        _name: &'static str,
3132        visitor: V,
3133    ) -> Result<V::Value, DeError>
3134    where
3135        V: Visitor<'de>,
3136    {
3137        visitor.visit_newtype_struct(self)
3138    }
3139
3140    fn deserialize_enum<V>(
3141        self,
3142        _name: &'static str,
3143        _variants: &'static [&'static str],
3144        visitor: V,
3145    ) -> Result<V::Value, DeError>
3146    where
3147        V: Visitor<'de>,
3148    {
3149        // When document is pretty-printed there could be whitespaces before the root element
3150        // which represents the enum variant
3151        // Checked by `top_level::list_of_enum` test in serde-de-seq
3152        self.skip_whitespaces()?;
3153        visitor.visit_enum(var::EnumAccess::new(self))
3154    }
3155
3156    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, DeError>
3157    where
3158        V: Visitor<'de>,
3159    {
3160        visitor.visit_seq(self)
3161    }
3162
3163    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, DeError>
3164    where
3165        V: Visitor<'de>,
3166    {
3167        // We cannot use result of `peek()` directly because of borrow checker
3168        let _ = self.peek()?;
3169        match self.last_peeked() {
3170            DeEvent::Text(t) if t.is_empty() => visitor.visit_none(),
3171            DeEvent::Eof => visitor.visit_none(),
3172            // if the `xsi:nil` attribute is set to true we got a none value
3173            DeEvent::Start(start) if self.reader.reader.has_nil_attr(&start) => {
3174                self.skip_next_tree()?;
3175                visitor.visit_none()
3176            }
3177            _ => visitor.visit_some(self),
3178        }
3179    }
3180
3181    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, DeError>
3182    where
3183        V: Visitor<'de>,
3184    {
3185        match self.peek()? {
3186            DeEvent::Text(_) => self.deserialize_str(visitor),
3187            _ => self.deserialize_map(visitor),
3188        }
3189    }
3190}
3191
3192/// An accessor to sequence elements forming a value for top-level sequence of XML
3193/// elements.
3194///
3195/// Technically, multiple top-level elements violates XML rule of only one top-level
3196/// element, but we consider this as several concatenated XML documents.
3197impl<'de, 'a, R, E> SeqAccess<'de> for &'a mut Deserializer<'de, R, E>
3198where
3199    R: XmlRead<'de>,
3200    E: EntityResolver,
3201{
3202    type Error = DeError;
3203
3204    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
3205    where
3206        T: DeserializeSeed<'de>,
3207    {
3208        // When document is pretty-printed there could be whitespaces before, between
3209        // and after root elements. We cannot defer decision if we need to skip spaces
3210        // or not: if we have a sequence of type that does not accept blank text, it
3211        // will need to return something and it can return only error. For example,
3212        // it can be enum without `$text` variant
3213        // Checked by `top_level::list_of_enum` test in serde-de-seq
3214        self.skip_whitespaces()?;
3215        match self.peek()? {
3216            DeEvent::Eof => Ok(None),
3217
3218            // Start(tag), End(tag), Text
3219            _ => seed.deserialize(&mut **self).map(Some),
3220        }
3221    }
3222}
3223
3224impl<'de, 'a, R, E> IntoDeserializer<'de, DeError> for &'a mut Deserializer<'de, R, E>
3225where
3226    R: XmlRead<'de>,
3227    E: EntityResolver,
3228{
3229    type Deserializer = Self;
3230
3231    #[inline]
3232    fn into_deserializer(self) -> Self {
3233        self
3234    }
3235}
3236
3237////////////////////////////////////////////////////////////////////////////////////////////////////
3238
3239/// Converts raw reader's event into a payload event.
3240/// Returns `None`, if event should be skipped.
3241#[inline(always)]
3242fn skip_uninterested<'a>(event: Event<'a>) -> Option<PayloadEvent<'a>> {
3243    let event = match event {
3244        Event::DocType(e) => PayloadEvent::DocType(e),
3245        Event::Start(e) => PayloadEvent::Start(e),
3246        Event::End(e) => PayloadEvent::End(e),
3247        Event::Eof => PayloadEvent::Eof,
3248
3249        // Do not trim next text event after Text, CDATA or reference event
3250        Event::CData(e) => PayloadEvent::CData(e),
3251        Event::Text(e) => PayloadEvent::Text(e),
3252        Event::GeneralRef(e) => PayloadEvent::GeneralRef(e),
3253
3254        _ => return None,
3255    };
3256    Some(event)
3257}
3258
3259////////////////////////////////////////////////////////////////////////////////////////////////////
3260
3261/// Trait used by the deserializer for iterating over input. This is manually
3262/// "specialized" for iterating over `&[u8]`.
3263///
3264/// You do not need to implement this trait, it is needed to abstract from
3265/// [borrowing](SliceReader) and [copying](IoReader) data sources and reuse code in
3266/// deserializer
3267pub trait XmlRead<'i> {
3268    /// Return an input-borrowing event.
3269    fn next(&mut self) -> Result<PayloadEvent<'i>, DeError>;
3270
3271    /// Skips until end element is found. Unlike `next()` it will not allocate
3272    /// when it cannot satisfy the lifetime.
3273    fn read_to_end(&mut self, name: QName) -> Result<(), DeError>;
3274
3275    /// A copy of the reader's decoder used to decode strings.
3276    fn decoder(&self) -> Decoder;
3277
3278    /// Checks if the `start` tag has a [`xsi:nil`] attribute. This method ignores
3279    /// any errors in attributes.
3280    ///
3281    /// [`xsi:nil`]: https://www.w3.org/TR/xmlschema-1/#xsi_nil
3282    fn has_nil_attr(&self, start: &BytesStart) -> bool;
3283}
3284
3285/// XML input source that reads from a std::io input stream.
3286///
3287/// You cannot create it, it is created automatically when you call
3288/// [`Deserializer::from_reader`]
3289pub struct IoReader<R: BufRead> {
3290    reader: NsReader<R>,
3291    buf: Vec<u8>,
3292}
3293
3294impl<R: BufRead> IoReader<R> {
3295    /// Returns the underlying XML reader.
3296    ///
3297    /// ```
3298    /// # use pretty_assertions::assert_eq;
3299    /// use serde::Deserialize;
3300    /// use std::io::Cursor;
3301    /// use quick_xml::de::Deserializer;
3302    /// use quick_xml::NsReader;
3303    ///
3304    /// #[derive(Deserialize)]
3305    /// struct SomeStruct {
3306    ///     field1: String,
3307    ///     field2: String,
3308    /// }
3309    ///
3310    /// // Try to deserialize from broken XML
3311    /// let mut de = Deserializer::from_reader(Cursor::new(
3312    ///     "<SomeStruct><field1><field2></SomeStruct>"
3313    /// //   0                           ^= 28        ^= 41
3314    /// ));
3315    ///
3316    /// let err = SomeStruct::deserialize(&mut de);
3317    /// assert!(err.is_err());
3318    ///
3319    /// let reader: &NsReader<Cursor<&str>> = de.get_ref().get_ref();
3320    ///
3321    /// assert_eq!(reader.error_position(), 28);
3322    /// assert_eq!(reader.buffer_position(), 41);
3323    /// ```
3324    pub const fn get_ref(&self) -> &NsReader<R> {
3325        &self.reader
3326    }
3327}
3328
3329impl<'i, R: BufRead> XmlRead<'i> for IoReader<R> {
3330    fn next(&mut self) -> Result<PayloadEvent<'static>, DeError> {
3331        loop {
3332            self.buf.clear();
3333
3334            let event = self.reader.read_event_into(&mut self.buf)?;
3335            if let Some(event) = skip_uninterested(event) {
3336                return Ok(event.into_owned());
3337            }
3338        }
3339    }
3340
3341    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
3342        match self.reader.read_to_end_into(name, &mut self.buf) {
3343            Err(e) => Err(e.into()),
3344            Ok(_) => Ok(()),
3345        }
3346    }
3347
3348    fn decoder(&self) -> Decoder {
3349        self.reader.decoder()
3350    }
3351
3352    fn has_nil_attr(&self, start: &BytesStart) -> bool {
3353        start.attributes().has_nil(&self.reader)
3354    }
3355}
3356
3357/// XML input source that reads from a slice of bytes and can borrow from it.
3358///
3359/// You cannot create it, it is created automatically when you call
3360/// [`Deserializer::from_str`].
3361pub struct SliceReader<'de> {
3362    reader: NsReader<&'de [u8]>,
3363}
3364
3365impl<'de> SliceReader<'de> {
3366    /// Returns the underlying XML reader.
3367    ///
3368    /// ```
3369    /// # use pretty_assertions::assert_eq;
3370    /// use serde::Deserialize;
3371    /// use quick_xml::de::Deserializer;
3372    /// use quick_xml::NsReader;
3373    ///
3374    /// #[derive(Deserialize)]
3375    /// struct SomeStruct {
3376    ///     field1: String,
3377    ///     field2: String,
3378    /// }
3379    ///
3380    /// // Try to deserialize from broken XML
3381    /// let mut de = Deserializer::from_str(
3382    ///     "<SomeStruct><field1><field2></SomeStruct>"
3383    /// //   0                           ^= 28        ^= 41
3384    /// );
3385    ///
3386    /// let err = SomeStruct::deserialize(&mut de);
3387    /// assert!(err.is_err());
3388    ///
3389    /// let reader: &NsReader<&[u8]> = de.get_ref().get_ref();
3390    ///
3391    /// assert_eq!(reader.error_position(), 28);
3392    /// assert_eq!(reader.buffer_position(), 41);
3393    /// ```
3394    pub const fn get_ref(&self) -> &NsReader<&'de [u8]> {
3395        &self.reader
3396    }
3397}
3398
3399impl<'de> XmlRead<'de> for SliceReader<'de> {
3400    fn next(&mut self) -> Result<PayloadEvent<'de>, DeError> {
3401        loop {
3402            let event = self.reader.read_event()?;
3403            if let Some(event) = skip_uninterested(event) {
3404                return Ok(event);
3405            }
3406        }
3407    }
3408
3409    fn read_to_end(&mut self, name: QName) -> Result<(), DeError> {
3410        match self.reader.read_to_end(name) {
3411            Err(e) => Err(e.into()),
3412            Ok(_) => Ok(()),
3413        }
3414    }
3415
3416    fn decoder(&self) -> Decoder {
3417        self.reader.decoder()
3418    }
3419
3420    fn has_nil_attr(&self, start: &BytesStart) -> bool {
3421        start.attributes().has_nil(&self.reader)
3422    }
3423}
3424
3425#[cfg(test)]
3426mod tests {
3427    use super::*;
3428    use crate::errors::IllFormedError;
3429    use pretty_assertions::assert_eq;
3430
3431    fn make_de<'de>(source: &'de str) -> Deserializer<'de, SliceReader<'de>> {
3432        dbg!(source);
3433        Deserializer::from_str(source)
3434    }
3435
3436    #[cfg(feature = "overlapped-lists")]
3437    mod skip {
3438        use super::*;
3439        use crate::de::DeEvent::*;
3440        use crate::events::BytesEnd;
3441        use pretty_assertions::assert_eq;
3442
3443        /// Checks that `peek()` and `read()` behaves correctly after `skip()`
3444        #[test]
3445        fn read_and_peek() {
3446            let mut de = make_de(
3447                "\
3448                <root>\
3449                    <inner>\
3450                        text\
3451                        <inner/>\
3452                    </inner>\
3453                    <next/>\
3454                    <target/>\
3455                </root>\
3456                ",
3457            );
3458
3459            // Initial conditions - both are empty
3460            assert_eq!(de.read, vec![]);
3461            assert_eq!(de.write, vec![]);
3462
3463            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
3464            assert_eq!(de.peek().unwrap(), &Start(BytesStart::new("inner")));
3465
3466            // Mark that start_replay() should begin replay from this point
3467            let checkpoint = de.skip_checkpoint();
3468            assert_eq!(checkpoint, 0);
3469
3470            // Should skip first <inner> tree
3471            de.skip().unwrap();
3472            assert_eq!(de.read, vec![]);
3473            assert_eq!(
3474                de.write,
3475                vec![
3476                    Start(BytesStart::new("inner")),
3477                    Text("text".into()),
3478                    Start(BytesStart::new("inner")),
3479                    End(BytesEnd::new("inner")),
3480                    End(BytesEnd::new("inner")),
3481                ]
3482            );
3483
3484            // Consume <next/>. Now unconsumed XML looks like:
3485            //
3486            //   <inner>
3487            //     text
3488            //     <inner/>
3489            //   </inner>
3490            //   <target/>
3491            // </root>
3492            assert_eq!(de.next().unwrap(), Start(BytesStart::new("next")));
3493            assert_eq!(de.next().unwrap(), End(BytesEnd::new("next")));
3494
3495            // We finish writing. Next call to `next()` should start replay that messages:
3496            //
3497            //   <inner>
3498            //     text
3499            //     <inner/>
3500            //   </inner>
3501            //
3502            // and after that stream that messages:
3503            //
3504            //   <target/>
3505            // </root>
3506            de.start_replay(checkpoint);
3507            assert_eq!(
3508                de.read,
3509                vec![
3510                    Start(BytesStart::new("inner")),
3511                    Text("text".into()),
3512                    Start(BytesStart::new("inner")),
3513                    End(BytesEnd::new("inner")),
3514                    End(BytesEnd::new("inner")),
3515                ]
3516            );
3517            assert_eq!(de.write, vec![]);
3518            assert_eq!(de.next().unwrap(), Start(BytesStart::new("inner")));
3519
3520            // Mark that start_replay() should begin replay from this point
3521            let checkpoint = de.skip_checkpoint();
3522            assert_eq!(checkpoint, 0);
3523
3524            // Skip `$text` node and consume <inner/> after it
3525            de.skip().unwrap();
3526            assert_eq!(
3527                de.read,
3528                vec![
3529                    Start(BytesStart::new("inner")),
3530                    End(BytesEnd::new("inner")),
3531                    End(BytesEnd::new("inner")),
3532                ]
3533            );
3534            assert_eq!(
3535                de.write,
3536                vec![
3537                    // This comment here to keep the same formatting of both arrays
3538                    // otherwise rustfmt suggest one-line it
3539                    Text("text".into()),
3540                ]
3541            );
3542
3543            assert_eq!(de.next().unwrap(), Start(BytesStart::new("inner")));
3544            assert_eq!(de.next().unwrap(), End(BytesEnd::new("inner")));
3545
3546            // We finish writing. Next call to `next()` should start replay messages:
3547            //
3548            //     text
3549            //   </inner>
3550            //
3551            // and after that stream that messages:
3552            //
3553            //   <target/>
3554            // </root>
3555            de.start_replay(checkpoint);
3556            assert_eq!(
3557                de.read,
3558                vec![
3559                    // This comment here to keep the same formatting as others
3560                    // otherwise rustfmt suggest one-line it
3561                    Text("text".into()),
3562                    End(BytesEnd::new("inner")),
3563                ]
3564            );
3565            assert_eq!(de.write, vec![]);
3566            assert_eq!(de.next().unwrap(), Text("text".into()));
3567            assert_eq!(de.next().unwrap(), End(BytesEnd::new("inner")));
3568            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target")));
3569            assert_eq!(de.next().unwrap(), End(BytesEnd::new("target")));
3570            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
3571            assert_eq!(de.next().unwrap(), Eof);
3572        }
3573
3574        /// Checks that `read_to_end()` behaves correctly after `skip()`
3575        #[test]
3576        fn read_to_end() {
3577            let mut de = make_de(
3578                "\
3579                <root>\
3580                    <skip>\
3581                        text\
3582                        <skip/>\
3583                    </skip>\
3584                    <target>\
3585                        <target/>\
3586                    </target>\
3587                </root>\
3588                ",
3589            );
3590
3591            // Initial conditions - both are empty
3592            assert_eq!(de.read, vec![]);
3593            assert_eq!(de.write, vec![]);
3594
3595            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
3596
3597            // Mark that start_replay() should begin replay from this point
3598            let checkpoint = de.skip_checkpoint();
3599            assert_eq!(checkpoint, 0);
3600
3601            // Skip the <skip> tree
3602            de.skip().unwrap();
3603            assert_eq!(de.read, vec![]);
3604            assert_eq!(
3605                de.write,
3606                vec![
3607                    Start(BytesStart::new("skip")),
3608                    Text("text".into()),
3609                    Start(BytesStart::new("skip")),
3610                    End(BytesEnd::new("skip")),
3611                    End(BytesEnd::new("skip")),
3612                ]
3613            );
3614
3615            // Drop all events that represents <target> tree. Now unconsumed XML looks like:
3616            //
3617            //   <skip>
3618            //     text
3619            //     <skip/>
3620            //   </skip>
3621            // </root>
3622            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target")));
3623            de.read_to_end(QName(b"target")).unwrap();
3624            assert_eq!(de.read, vec![]);
3625            assert_eq!(
3626                de.write,
3627                vec![
3628                    Start(BytesStart::new("skip")),
3629                    Text("text".into()),
3630                    Start(BytesStart::new("skip")),
3631                    End(BytesEnd::new("skip")),
3632                    End(BytesEnd::new("skip")),
3633                ]
3634            );
3635
3636            // We finish writing. Next call to `next()` should start replay that messages:
3637            //
3638            //   <skip>
3639            //     text
3640            //     <skip/>
3641            //   </skip>
3642            //
3643            // and after that stream that messages:
3644            //
3645            // </root>
3646            de.start_replay(checkpoint);
3647            assert_eq!(
3648                de.read,
3649                vec![
3650                    Start(BytesStart::new("skip")),
3651                    Text("text".into()),
3652                    Start(BytesStart::new("skip")),
3653                    End(BytesEnd::new("skip")),
3654                    End(BytesEnd::new("skip")),
3655                ]
3656            );
3657            assert_eq!(de.write, vec![]);
3658
3659            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skip")));
3660            de.read_to_end(QName(b"skip")).unwrap();
3661
3662            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
3663            assert_eq!(de.next().unwrap(), Eof);
3664        }
3665
3666        /// Checks that replay replayes only part of events
3667        /// Test for https://github.com/tafia/quick-xml/issues/435
3668        #[test]
3669        fn partial_replay() {
3670            let mut de = make_de(
3671                "\
3672                <root>\
3673                    <skipped-1/>\
3674                    <skipped-2/>\
3675                    <inner>\
3676                        <skipped-3/>\
3677                        <skipped-4/>\
3678                        <target-2/>\
3679                    </inner>\
3680                    <target-1/>\
3681                </root>\
3682                ",
3683            );
3684
3685            // Initial conditions - both are empty
3686            assert_eq!(de.read, vec![]);
3687            assert_eq!(de.write, vec![]);
3688
3689            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
3690
3691            // start_replay() should start replay from this point
3692            let checkpoint1 = de.skip_checkpoint();
3693            assert_eq!(checkpoint1, 0);
3694
3695            // Should skip first and second <skipped-N/> elements
3696            de.skip().unwrap(); // skipped-1
3697            de.skip().unwrap(); // skipped-2
3698            assert_eq!(de.read, vec![]);
3699            assert_eq!(
3700                de.write,
3701                vec![
3702                    Start(BytesStart::new("skipped-1")),
3703                    End(BytesEnd::new("skipped-1")),
3704                    Start(BytesStart::new("skipped-2")),
3705                    End(BytesEnd::new("skipped-2")),
3706                ]
3707            );
3708
3709            ////////////////////////////////////////////////////////////////////////////////////////
3710
3711            assert_eq!(de.next().unwrap(), Start(BytesStart::new("inner")));
3712            assert_eq!(de.peek().unwrap(), &Start(BytesStart::new("skipped-3")));
3713            assert_eq!(
3714                de.read,
3715                vec![
3716                    // This comment here to keep the same formatting of both arrays
3717                    // otherwise rustfmt suggest one-line it
3718                    Start(BytesStart::new("skipped-3")),
3719                ]
3720            );
3721            assert_eq!(
3722                de.write,
3723                vec![
3724                    Start(BytesStart::new("skipped-1")),
3725                    End(BytesEnd::new("skipped-1")),
3726                    Start(BytesStart::new("skipped-2")),
3727                    End(BytesEnd::new("skipped-2")),
3728                ]
3729            );
3730
3731            // start_replay() should start replay from this point
3732            let checkpoint2 = de.skip_checkpoint();
3733            assert_eq!(checkpoint2, 4);
3734
3735            // Should skip third and forth <skipped-N/> elements
3736            de.skip().unwrap(); // skipped-3
3737            de.skip().unwrap(); // skipped-4
3738            assert_eq!(de.read, vec![]);
3739            assert_eq!(
3740                de.write,
3741                vec![
3742                    // checkpoint 1
3743                    Start(BytesStart::new("skipped-1")),
3744                    End(BytesEnd::new("skipped-1")),
3745                    Start(BytesStart::new("skipped-2")),
3746                    End(BytesEnd::new("skipped-2")),
3747                    // checkpoint 2
3748                    Start(BytesStart::new("skipped-3")),
3749                    End(BytesEnd::new("skipped-3")),
3750                    Start(BytesStart::new("skipped-4")),
3751                    End(BytesEnd::new("skipped-4")),
3752                ]
3753            );
3754            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target-2")));
3755            assert_eq!(de.next().unwrap(), End(BytesEnd::new("target-2")));
3756            assert_eq!(de.peek().unwrap(), &End(BytesEnd::new("inner")));
3757            assert_eq!(
3758                de.read,
3759                vec![
3760                    // This comment here to keep the same formatting of both arrays
3761                    // otherwise rustfmt suggest one-line it
3762                    End(BytesEnd::new("inner")),
3763                ]
3764            );
3765            assert_eq!(
3766                de.write,
3767                vec![
3768                    // checkpoint 1
3769                    Start(BytesStart::new("skipped-1")),
3770                    End(BytesEnd::new("skipped-1")),
3771                    Start(BytesStart::new("skipped-2")),
3772                    End(BytesEnd::new("skipped-2")),
3773                    // checkpoint 2
3774                    Start(BytesStart::new("skipped-3")),
3775                    End(BytesEnd::new("skipped-3")),
3776                    Start(BytesStart::new("skipped-4")),
3777                    End(BytesEnd::new("skipped-4")),
3778                ]
3779            );
3780
3781            // Start replay events from checkpoint 2
3782            de.start_replay(checkpoint2);
3783            assert_eq!(
3784                de.read,
3785                vec![
3786                    Start(BytesStart::new("skipped-3")),
3787                    End(BytesEnd::new("skipped-3")),
3788                    Start(BytesStart::new("skipped-4")),
3789                    End(BytesEnd::new("skipped-4")),
3790                    End(BytesEnd::new("inner")),
3791                ]
3792            );
3793            assert_eq!(
3794                de.write,
3795                vec![
3796                    Start(BytesStart::new("skipped-1")),
3797                    End(BytesEnd::new("skipped-1")),
3798                    Start(BytesStart::new("skipped-2")),
3799                    End(BytesEnd::new("skipped-2")),
3800                ]
3801            );
3802
3803            // Replayed events
3804            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-3")));
3805            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-3")));
3806            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-4")));
3807            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-4")));
3808
3809            assert_eq!(de.next().unwrap(), End(BytesEnd::new("inner")));
3810            assert_eq!(de.read, vec![]);
3811            assert_eq!(
3812                de.write,
3813                vec![
3814                    Start(BytesStart::new("skipped-1")),
3815                    End(BytesEnd::new("skipped-1")),
3816                    Start(BytesStart::new("skipped-2")),
3817                    End(BytesEnd::new("skipped-2")),
3818                ]
3819            );
3820
3821            ////////////////////////////////////////////////////////////////////////////////////////
3822
3823            // New events
3824            assert_eq!(de.next().unwrap(), Start(BytesStart::new("target-1")));
3825            assert_eq!(de.next().unwrap(), End(BytesEnd::new("target-1")));
3826
3827            assert_eq!(de.read, vec![]);
3828            assert_eq!(
3829                de.write,
3830                vec![
3831                    Start(BytesStart::new("skipped-1")),
3832                    End(BytesEnd::new("skipped-1")),
3833                    Start(BytesStart::new("skipped-2")),
3834                    End(BytesEnd::new("skipped-2")),
3835                ]
3836            );
3837
3838            // Start replay events from checkpoint 1
3839            de.start_replay(checkpoint1);
3840            assert_eq!(
3841                de.read,
3842                vec![
3843                    Start(BytesStart::new("skipped-1")),
3844                    End(BytesEnd::new("skipped-1")),
3845                    Start(BytesStart::new("skipped-2")),
3846                    End(BytesEnd::new("skipped-2")),
3847                ]
3848            );
3849            assert_eq!(de.write, vec![]);
3850
3851            // Replayed events
3852            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-1")));
3853            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-1")));
3854            assert_eq!(de.next().unwrap(), Start(BytesStart::new("skipped-2")));
3855            assert_eq!(de.next().unwrap(), End(BytesEnd::new("skipped-2")));
3856
3857            assert_eq!(de.read, vec![]);
3858            assert_eq!(de.write, vec![]);
3859
3860            // New events
3861            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
3862            assert_eq!(de.next().unwrap(), Eof);
3863        }
3864
3865        /// Checks that limiting buffer size works correctly
3866        #[test]
3867        fn limit() {
3868            use serde::Deserialize;
3869
3870            #[derive(Debug, Deserialize)]
3871            #[allow(unused)]
3872            struct List {
3873                item: Vec<()>,
3874            }
3875
3876            let mut de = make_de(
3877                "\
3878                <any-name>\
3879                    <item/>\
3880                    <another-item>\
3881                        <some-element>with text</some-element>\
3882                        <yet-another-element/>\
3883                    </another-item>\
3884                    <item/>\
3885                    <item/>\
3886                </any-name>\
3887                ",
3888            );
3889            de.event_buffer_size(NonZeroUsize::new(3));
3890
3891            match List::deserialize(&mut de) {
3892                Err(DeError::TooManyEvents(count)) => assert_eq!(count.get(), 3),
3893                e => panic!("Expected `Err(TooManyEvents(3))`, but got `{:?}`", e),
3894            }
3895        }
3896
3897        /// Without handling Eof in `skip` this test failed with memory allocation
3898        #[test]
3899        fn invalid_xml() {
3900            use crate::de::DeEvent::*;
3901
3902            let mut de = make_de("<root>");
3903
3904            // Cache all events
3905            let checkpoint = de.skip_checkpoint();
3906            de.skip().unwrap();
3907            de.start_replay(checkpoint);
3908            assert_eq!(de.read, vec![Start(BytesStart::new("root")), Eof]);
3909        }
3910    }
3911
3912    mod read_to_end {
3913        use super::*;
3914        use crate::de::DeEvent::*;
3915        use pretty_assertions::assert_eq;
3916
3917        #[test]
3918        fn complex() {
3919            let mut de = make_de(
3920                r#"
3921                <root>
3922                    <tag a="1"><tag>text</tag>content</tag>
3923                    <tag a="2"><![CDATA[cdata content]]></tag>
3924                    <self-closed/>
3925                </root>
3926                "#,
3927            );
3928
3929            assert_eq!(de.next().unwrap(), Text("\n                ".into()));
3930            assert_eq!(de.next().unwrap(), Start(BytesStart::new("root")));
3931
3932            assert_eq!(de.next().unwrap(), Text("\n                    ".into()));
3933            assert_eq!(
3934                de.next().unwrap(),
3935                Start(BytesStart::from_content(r#"tag a="1""#, 3))
3936            );
3937            assert_eq!(de.read_to_end(QName(b"tag")).unwrap(), ());
3938
3939            assert_eq!(de.next().unwrap(), Text("\n                    ".into()));
3940            assert_eq!(
3941                de.next().unwrap(),
3942                Start(BytesStart::from_content(r#"tag a="2""#, 3))
3943            );
3944            assert_eq!(de.next().unwrap(), Text("cdata content".into()));
3945            assert_eq!(de.next().unwrap(), End(BytesEnd::new("tag")));
3946
3947            assert_eq!(de.next().unwrap(), Text("\n                    ".into()));
3948            assert_eq!(de.next().unwrap(), Start(BytesStart::new("self-closed")));
3949            assert_eq!(de.read_to_end(QName(b"self-closed")).unwrap(), ());
3950
3951            assert_eq!(de.next().unwrap(), Text("\n                ".into()));
3952            assert_eq!(de.next().unwrap(), End(BytesEnd::new("root")));
3953            assert_eq!(de.next().unwrap(), Text("\n                ".into()));
3954            assert_eq!(de.next().unwrap(), Eof);
3955        }
3956
3957        #[test]
3958        fn invalid_xml1() {
3959            let mut de = make_de("<tag><tag></tag>");
3960
3961            assert_eq!(de.next().unwrap(), Start(BytesStart::new("tag")));
3962            assert_eq!(de.peek().unwrap(), &Start(BytesStart::new("tag")));
3963
3964            match de.read_to_end(QName(b"tag")) {
3965                Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
3966                    assert_eq!(cause, IllFormedError::MissingEndTag("tag".into()))
3967                }
3968                x => panic!(
3969                    "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
3970                    x
3971                ),
3972            }
3973            assert_eq!(de.next().unwrap(), Eof);
3974        }
3975
3976        #[test]
3977        fn invalid_xml2() {
3978            let mut de = make_de("<tag><![CDATA[]]><tag></tag>");
3979
3980            assert_eq!(de.next().unwrap(), Start(BytesStart::new("tag")));
3981            assert_eq!(de.peek().unwrap(), &Text("".into()));
3982
3983            match de.read_to_end(QName(b"tag")) {
3984                Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
3985                    assert_eq!(cause, IllFormedError::MissingEndTag("tag".into()))
3986                }
3987                x => panic!(
3988                    "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
3989                    x
3990                ),
3991            }
3992            assert_eq!(de.next().unwrap(), Eof);
3993        }
3994    }
3995
3996    #[test]
3997    fn borrowing_reader_parity() {
3998        let s = r#"
3999            <item name="hello" source="world.rs">Some text</item>
4000            <item2/>
4001            <item3 value="world" />
4002        "#;
4003
4004        let mut reader1 = IoReader {
4005            reader: NsReader::from_reader(s.as_bytes()),
4006            buf: Vec::new(),
4007        };
4008        let mut reader2 = SliceReader {
4009            reader: NsReader::from_str(s),
4010        };
4011
4012        loop {
4013            let event1 = reader1.next().unwrap();
4014            let event2 = reader2.next().unwrap();
4015
4016            if let (PayloadEvent::Eof, PayloadEvent::Eof) = (&event1, &event2) {
4017                break;
4018            }
4019
4020            assert_eq!(event1, event2);
4021        }
4022    }
4023
4024    #[test]
4025    fn borrowing_reader_events() {
4026        let s = r#"
4027            <item name="hello" source="world.rs">Some text</item>
4028            <item2></item2>
4029            <item3/>
4030            <item4 value="world" />
4031        "#;
4032
4033        let mut reader = SliceReader {
4034            reader: NsReader::from_str(s),
4035        };
4036
4037        let config = reader.reader.config_mut();
4038        config.expand_empty_elements = true;
4039
4040        let mut events = Vec::new();
4041
4042        loop {
4043            let event = reader.next().unwrap();
4044            if let PayloadEvent::Eof = event {
4045                break;
4046            }
4047            events.push(event);
4048        }
4049
4050        use crate::de::PayloadEvent::*;
4051
4052        assert_eq!(
4053            events,
4054            vec![
4055                Text(BytesText::from_escaped("\n            ")),
4056                Start(BytesStart::from_content(
4057                    r#"item name="hello" source="world.rs""#,
4058                    4
4059                )),
4060                Text(BytesText::from_escaped("Some text")),
4061                End(BytesEnd::new("item")),
4062                Text(BytesText::from_escaped("\n            ")),
4063                Start(BytesStart::from_content("item2", 5)),
4064                End(BytesEnd::new("item2")),
4065                Text(BytesText::from_escaped("\n            ")),
4066                Start(BytesStart::from_content("item3", 5)),
4067                End(BytesEnd::new("item3")),
4068                Text(BytesText::from_escaped("\n            ")),
4069                Start(BytesStart::from_content(r#"item4 value="world" "#, 5)),
4070                End(BytesEnd::new("item4")),
4071                Text(BytesText::from_escaped("\n        ")),
4072            ]
4073        )
4074    }
4075
4076    /// Ensures, that [`Deserializer::read_string()`] never can get an `End` event,
4077    /// because parser reports error early
4078    #[test]
4079    fn read_string() {
4080        match from_str::<String>(r#"</root>"#) {
4081            Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4082                assert_eq!(cause, IllFormedError::UnmatchedEndTag("root".into()));
4083            }
4084            x => panic!(
4085                "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4086                x
4087            ),
4088        }
4089
4090        let s: String = from_str(r#"<root></root>"#).unwrap();
4091        assert_eq!(s, "");
4092
4093        match from_str::<String>(r#"<root></other>"#) {
4094            Err(DeError::InvalidXml(Error::IllFormed(cause))) => assert_eq!(
4095                cause,
4096                IllFormedError::MismatchedEndTag {
4097                    expected: "root".into(),
4098                    found: "other".into(),
4099                }
4100            ),
4101            x => panic!("Expected `Err(InvalidXml(IllFormed(_))`, but got `{:?}`", x),
4102        }
4103    }
4104
4105    /// Tests for https://github.com/tafia/quick-xml/issues/474.
4106    ///
4107    /// That tests ensures that comments and processed instructions is ignored
4108    /// and can split one logical string in pieces.
4109    mod merge_text {
4110        use super::*;
4111        use pretty_assertions::assert_eq;
4112
4113        #[test]
4114        fn text() {
4115            let mut de = make_de("text");
4116            assert_eq!(de.next().unwrap(), DeEvent::Text("text".into()));
4117        }
4118
4119        #[test]
4120        fn cdata() {
4121            let mut de = make_de("<![CDATA[cdata]]>");
4122            assert_eq!(de.next().unwrap(), DeEvent::Text("cdata".into()));
4123        }
4124
4125        #[test]
4126        fn text_and_cdata() {
4127            let mut de = make_de("text and <![CDATA[cdata]]>");
4128            assert_eq!(de.next().unwrap(), DeEvent::Text("text and cdata".into()));
4129        }
4130
4131        #[test]
4132        fn text_and_empty_cdata() {
4133            let mut de = make_de("text and <![CDATA[]]>");
4134            assert_eq!(de.next().unwrap(), DeEvent::Text("text and ".into()));
4135        }
4136
4137        #[test]
4138        fn cdata_and_text() {
4139            let mut de = make_de("<![CDATA[cdata]]> and text");
4140            assert_eq!(de.next().unwrap(), DeEvent::Text("cdata and text".into()));
4141        }
4142
4143        #[test]
4144        fn empty_cdata_and_text() {
4145            let mut de = make_de("<![CDATA[]]> and text");
4146            assert_eq!(de.next().unwrap(), DeEvent::Text(" and text".into()));
4147        }
4148
4149        #[test]
4150        fn cdata_and_cdata() {
4151            let mut de = make_de(
4152                "\
4153                    <![CDATA[cdata]]]]>\
4154                    <![CDATA[>cdata]]>\
4155                ",
4156            );
4157            assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4158        }
4159
4160        mod comment_between {
4161            use super::*;
4162            use pretty_assertions::assert_eq;
4163
4164            #[test]
4165            fn text() {
4166                let mut de = make_de(
4167                    "\
4168                        text \
4169                        <!--comment 1--><!--comment 2--> \
4170                        text\
4171                    ",
4172                );
4173                assert_eq!(de.next().unwrap(), DeEvent::Text("text  text".into()));
4174            }
4175
4176            #[test]
4177            fn cdata() {
4178                let mut de = make_de(
4179                    "\
4180                        <![CDATA[cdata]]]]>\
4181                        <!--comment 1--><!--comment 2-->\
4182                        <![CDATA[>cdata]]>\
4183                    ",
4184                );
4185                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4186            }
4187
4188            #[test]
4189            fn text_and_cdata() {
4190                let mut de = make_de(
4191                    "\
4192                        text \
4193                        <!--comment 1--><!--comment 2-->\
4194                        <![CDATA[ cdata]]>\
4195                    ",
4196                );
4197                assert_eq!(de.next().unwrap(), DeEvent::Text("text  cdata".into()));
4198            }
4199
4200            #[test]
4201            fn text_and_empty_cdata() {
4202                let mut de = make_de(
4203                    "\
4204                        text \
4205                        <!--comment 1--><!--comment 2-->\
4206                        <![CDATA[]]>\
4207                    ",
4208                );
4209                assert_eq!(de.next().unwrap(), DeEvent::Text("text ".into()));
4210            }
4211
4212            #[test]
4213            fn cdata_and_text() {
4214                let mut de = make_de(
4215                    "\
4216                        <![CDATA[cdata ]]>\
4217                        <!--comment 1--><!--comment 2--> \
4218                        text \
4219                    ",
4220                );
4221                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata  text ".into()));
4222            }
4223
4224            #[test]
4225            fn empty_cdata_and_text() {
4226                let mut de = make_de(
4227                    "\
4228                        <![CDATA[]]>\
4229                        <!--comment 1--><!--comment 2--> \
4230                        text \
4231                    ",
4232                );
4233                assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4234            }
4235
4236            #[test]
4237            fn cdata_and_cdata() {
4238                let mut de = make_de(
4239                    "\
4240                        <![CDATA[cdata]]]>\
4241                        <!--comment 1--><!--comment 2-->\
4242                        <![CDATA[]>cdata]]>\
4243                    ",
4244                );
4245                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4246            }
4247        }
4248
4249        mod pi_between {
4250            use super::*;
4251            use pretty_assertions::assert_eq;
4252
4253            #[test]
4254            fn text() {
4255                let mut de = make_de(
4256                    "\
4257                        text \
4258                        <?pi 1?><?pi 2?> \
4259                        text\
4260                    ",
4261                );
4262                assert_eq!(de.next().unwrap(), DeEvent::Text("text  text".into()));
4263            }
4264
4265            #[test]
4266            fn cdata() {
4267                let mut de = make_de(
4268                    "\
4269                        <![CDATA[cdata]]]]>\
4270                        <?pi 1?><?pi 2?>\
4271                        <![CDATA[>cdata]]>\
4272                    ",
4273                );
4274                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4275            }
4276
4277            #[test]
4278            fn text_and_cdata() {
4279                let mut de = make_de(
4280                    "\
4281                        text \
4282                        <?pi 1?><?pi 2?>\
4283                        <![CDATA[ cdata]]>\
4284                    ",
4285                );
4286                assert_eq!(de.next().unwrap(), DeEvent::Text("text  cdata".into()));
4287            }
4288
4289            #[test]
4290            fn text_and_empty_cdata() {
4291                let mut de = make_de(
4292                    "\
4293                        text \
4294                        <?pi 1?><?pi 2?>\
4295                        <![CDATA[]]>\
4296                    ",
4297                );
4298                assert_eq!(de.next().unwrap(), DeEvent::Text("text ".into()));
4299            }
4300
4301            #[test]
4302            fn cdata_and_text() {
4303                let mut de = make_de(
4304                    "\
4305                        <![CDATA[cdata ]]>\
4306                        <?pi 1?><?pi 2?> \
4307                        text \
4308                    ",
4309                );
4310                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata  text ".into()));
4311            }
4312
4313            #[test]
4314            fn empty_cdata_and_text() {
4315                let mut de = make_de(
4316                    "\
4317                        <![CDATA[]]>\
4318                        <?pi 1?><?pi 2?> \
4319                        text \
4320                    ",
4321                );
4322                assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4323            }
4324
4325            #[test]
4326            fn cdata_and_cdata() {
4327                let mut de = make_de(
4328                    "\
4329                        <![CDATA[cdata]]]>\
4330                        <?pi 1?><?pi 2?>\
4331                        <![CDATA[]>cdata]]>\
4332                    ",
4333                );
4334                assert_eq!(de.next().unwrap(), DeEvent::Text("cdata]]>cdata".into()));
4335            }
4336        }
4337    }
4338
4339    /// Tests for https://github.com/tafia/quick-xml/issues/474.
4340    ///
4341    /// This tests ensures that any combination of payload data is processed
4342    /// as expected.
4343    mod triples {
4344        use super::*;
4345        use pretty_assertions::assert_eq;
4346
4347        mod start {
4348            use super::*;
4349
4350            /// <tag1><tag2>...
4351            mod start {
4352                use super::*;
4353                use pretty_assertions::assert_eq;
4354
4355                #[test]
4356                fn start() {
4357                    let mut de = make_de("<tag1><tag2><tag3>");
4358                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4359                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4360                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag3")));
4361                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4362                }
4363
4364                /// Not matching end tag will result to error
4365                #[test]
4366                fn end() {
4367                    let mut de = make_de("<tag1><tag2></tag2>");
4368                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4369                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4370                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag2")));
4371                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4372                }
4373
4374                #[test]
4375                fn text() {
4376                    let mut de = make_de("<tag1><tag2> text ");
4377                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4378                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4379                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4380                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4381                }
4382
4383                #[test]
4384                fn cdata() {
4385                    let mut de = make_de("<tag1><tag2><![CDATA[ cdata ]]>");
4386                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4387                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4388                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4389                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4390                }
4391
4392                #[test]
4393                fn eof() {
4394                    let mut de = make_de("<tag1><tag2>");
4395                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4396                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4397                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4398                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4399                }
4400            }
4401
4402            /// <tag></tag>...
4403            mod end {
4404                use super::*;
4405                use pretty_assertions::assert_eq;
4406
4407                #[test]
4408                fn start() {
4409                    let mut de = make_de("<tag></tag><tag2>");
4410                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4411                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4412                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4413                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4414                }
4415
4416                #[test]
4417                fn end() {
4418                    let mut de = make_de("<tag></tag></tag2>");
4419                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4420                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4421                    match de.next() {
4422                        Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4423                            assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag2".into()));
4424                        }
4425                        x => panic!(
4426                            "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4427                            x
4428                        ),
4429                    }
4430                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4431                }
4432
4433                #[test]
4434                fn text() {
4435                    let mut de = make_de("<tag></tag> text ");
4436                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4437                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4438                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4439                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4440                }
4441
4442                #[test]
4443                fn cdata() {
4444                    let mut de = make_de("<tag></tag><![CDATA[ cdata ]]>");
4445                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4446                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4447                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4448                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4449                }
4450
4451                #[test]
4452                fn eof() {
4453                    let mut de = make_de("<tag></tag>");
4454                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4455                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4456                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4457                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4458                }
4459            }
4460
4461            /// <tag> text ...
4462            mod text {
4463                use super::*;
4464                use pretty_assertions::assert_eq;
4465
4466                #[test]
4467                fn start() {
4468                    let mut de = make_de("<tag> text <tag2>");
4469                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4470                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4471                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4472                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4473                }
4474
4475                #[test]
4476                fn end() {
4477                    let mut de = make_de("<tag> text </tag>");
4478                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4479                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4480                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4481                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4482                }
4483
4484                // start::text::text has no difference from start::text
4485
4486                #[test]
4487                fn cdata() {
4488                    let mut de = make_de("<tag> text <![CDATA[ cdata ]]>");
4489                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4490                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4491                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4492                }
4493
4494                #[test]
4495                fn eof() {
4496                    let mut de = make_de("<tag> text ");
4497                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4498                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4499                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4500                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4501                }
4502            }
4503
4504            /// <tag><![CDATA[ cdata ]]>...
4505            mod cdata {
4506                use super::*;
4507                use pretty_assertions::assert_eq;
4508
4509                #[test]
4510                fn start() {
4511                    let mut de = make_de("<tag><![CDATA[ cdata ]]><tag2>");
4512                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4513                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4514                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4515                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4516                }
4517
4518                #[test]
4519                fn end() {
4520                    let mut de = make_de("<tag><![CDATA[ cdata ]]></tag>");
4521                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4522                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4523                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4524                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4525                }
4526
4527                #[test]
4528                fn text() {
4529                    let mut de = make_de("<tag><![CDATA[ cdata ]]> text ");
4530                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4531                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  text ".into()));
4532                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4533                }
4534
4535                #[test]
4536                fn cdata() {
4537                    let mut de = make_de("<tag><![CDATA[ cdata ]]><![CDATA[ cdata2 ]]>");
4538                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4539                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
4540                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4541                }
4542
4543                #[test]
4544                fn eof() {
4545                    let mut de = make_de("<tag><![CDATA[ cdata ]]>");
4546                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4547                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4548                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4549                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4550                }
4551            }
4552        }
4553
4554        /// Start from End event will always generate an error
4555        #[test]
4556        fn end() {
4557            let mut de = make_de("</tag>");
4558            match de.next() {
4559                Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4560                    assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4561                }
4562                x => panic!(
4563                    "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4564                    x
4565                ),
4566            }
4567            assert_eq!(de.next().unwrap(), DeEvent::Eof);
4568        }
4569
4570        mod text {
4571            use super::*;
4572            use pretty_assertions::assert_eq;
4573
4574            mod start {
4575                use super::*;
4576                use pretty_assertions::assert_eq;
4577
4578                #[test]
4579                fn start() {
4580                    let mut de = make_de(" text <tag1><tag2>");
4581                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4582                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4583                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4584                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4585                }
4586
4587                /// Not matching end tag will result in error
4588                #[test]
4589                fn end() {
4590                    let mut de = make_de(" text <tag></tag>");
4591                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4592                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4593                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4594                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4595                }
4596
4597                #[test]
4598                fn text() {
4599                    let mut de = make_de(" text <tag> text2 ");
4600                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4601                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4602                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text2 ".into()));
4603                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4604                }
4605
4606                #[test]
4607                fn cdata() {
4608                    let mut de = make_de(" text <tag><![CDATA[ cdata ]]>");
4609                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4610                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4611                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4612                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4613                }
4614
4615                #[test]
4616                fn eof() {
4617                    let mut de = make_de(" text <tag>");
4618                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4619                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4620                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4621                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4622                }
4623            }
4624
4625            /// End event without corresponding start event will always generate an error
4626            #[test]
4627            fn end() {
4628                let mut de = make_de(" text </tag>");
4629                assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4630                match de.next() {
4631                    Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4632                        assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4633                    }
4634                    x => panic!(
4635                        "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4636                        x
4637                    ),
4638                }
4639                assert_eq!(de.next().unwrap(), DeEvent::Eof);
4640            }
4641
4642            // text::text::something is equivalent to text::something
4643
4644            mod cdata {
4645                use super::*;
4646                use pretty_assertions::assert_eq;
4647
4648                #[test]
4649                fn start() {
4650                    let mut de = make_de(" text <![CDATA[ cdata ]]><tag>");
4651                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4652                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4653                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4654                }
4655
4656                #[test]
4657                fn end() {
4658                    let mut de = make_de(" text <![CDATA[ cdata ]]></tag>");
4659                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4660                    match de.next() {
4661                        Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4662                            assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4663                        }
4664                        x => panic!(
4665                            "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4666                            x
4667                        ),
4668                    }
4669                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4670                }
4671
4672                #[test]
4673                fn text() {
4674                    let mut de = make_de(" text <![CDATA[ cdata ]]> text2 ");
4675                    assert_eq!(
4676                        de.next().unwrap(),
4677                        DeEvent::Text(" text  cdata  text2 ".into())
4678                    );
4679                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4680                }
4681
4682                #[test]
4683                fn cdata() {
4684                    let mut de = make_de(" text <![CDATA[ cdata ]]><![CDATA[ cdata2 ]]>");
4685                    assert_eq!(
4686                        de.next().unwrap(),
4687                        DeEvent::Text(" text  cdata  cdata2 ".into())
4688                    );
4689                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4690                }
4691
4692                #[test]
4693                fn eof() {
4694                    let mut de = make_de(" text <![CDATA[ cdata ]]>");
4695                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text  cdata ".into()));
4696                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4697                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4698                }
4699            }
4700        }
4701
4702        mod cdata {
4703            use super::*;
4704            use pretty_assertions::assert_eq;
4705
4706            mod start {
4707                use super::*;
4708                use pretty_assertions::assert_eq;
4709
4710                #[test]
4711                fn start() {
4712                    let mut de = make_de("<![CDATA[ cdata ]]><tag1><tag2>");
4713                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4714                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag1")));
4715                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag2")));
4716                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4717                }
4718
4719                /// Not matching end tag will result in error
4720                #[test]
4721                fn end() {
4722                    let mut de = make_de("<![CDATA[ cdata ]]><tag></tag>");
4723                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4724                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4725                    assert_eq!(de.next().unwrap(), DeEvent::End(BytesEnd::new("tag")));
4726                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4727                }
4728
4729                #[test]
4730                fn text() {
4731                    let mut de = make_de("<![CDATA[ cdata ]]><tag> text ");
4732                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4733                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4734                    assert_eq!(de.next().unwrap(), DeEvent::Text(" text ".into()));
4735                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4736                }
4737
4738                #[test]
4739                fn cdata() {
4740                    let mut de = make_de("<![CDATA[ cdata ]]><tag><![CDATA[ cdata2 ]]>");
4741                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4742                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4743                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata2 ".into()));
4744                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4745                }
4746
4747                #[test]
4748                fn eof() {
4749                    let mut de = make_de("<![CDATA[ cdata ]]><tag>");
4750                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4751                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4752                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4753                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4754                }
4755            }
4756
4757            /// End event without corresponding start event will always generate an error
4758            #[test]
4759            fn end() {
4760                let mut de = make_de("<![CDATA[ cdata ]]></tag>");
4761                assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata ".into()));
4762                match de.next() {
4763                    Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4764                        assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4765                    }
4766                    x => panic!(
4767                        "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4768                        x
4769                    ),
4770                }
4771                assert_eq!(de.next().unwrap(), DeEvent::Eof);
4772            }
4773
4774            mod text {
4775                use super::*;
4776                use pretty_assertions::assert_eq;
4777
4778                #[test]
4779                fn start() {
4780                    let mut de = make_de("<![CDATA[ cdata ]]> text <tag>");
4781                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  text ".into()));
4782                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4783                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4784                }
4785
4786                #[test]
4787                fn end() {
4788                    let mut de = make_de("<![CDATA[ cdata ]]> text </tag>");
4789                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  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                // cdata::text::text is equivalent to cdata::text
4803
4804                #[test]
4805                fn cdata() {
4806                    let mut de = make_de("<![CDATA[ cdata ]]> text <![CDATA[ cdata2 ]]>");
4807                    assert_eq!(
4808                        de.next().unwrap(),
4809                        DeEvent::Text(" cdata  text  cdata2 ".into())
4810                    );
4811                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4812                }
4813
4814                #[test]
4815                fn eof() {
4816                    let mut de = make_de("<![CDATA[ cdata ]]> text ");
4817                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  text ".into()));
4818                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4819                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4820                }
4821            }
4822
4823            mod cdata {
4824                use super::*;
4825                use pretty_assertions::assert_eq;
4826
4827                #[test]
4828                fn start() {
4829                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]><tag>");
4830                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
4831                    assert_eq!(de.next().unwrap(), DeEvent::Start(BytesStart::new("tag")));
4832                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4833                }
4834
4835                #[test]
4836                fn end() {
4837                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]></tag>");
4838                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
4839                    match de.next() {
4840                        Err(DeError::InvalidXml(Error::IllFormed(cause))) => {
4841                            assert_eq!(cause, IllFormedError::UnmatchedEndTag("tag".into()));
4842                        }
4843                        x => panic!(
4844                            "Expected `Err(InvalidXml(IllFormed(_)))`, but got `{:?}`",
4845                            x
4846                        ),
4847                    }
4848                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4849                }
4850
4851                #[test]
4852                fn text() {
4853                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]> text ");
4854                    assert_eq!(
4855                        de.next().unwrap(),
4856                        DeEvent::Text(" cdata  cdata2  text ".into())
4857                    );
4858                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4859                }
4860
4861                #[test]
4862                fn cdata() {
4863                    let mut de =
4864                        make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]><![CDATA[ cdata3 ]]>");
4865                    assert_eq!(
4866                        de.next().unwrap(),
4867                        DeEvent::Text(" cdata  cdata2  cdata3 ".into())
4868                    );
4869                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4870                }
4871
4872                #[test]
4873                fn eof() {
4874                    let mut de = make_de("<![CDATA[ cdata ]]><![CDATA[ cdata2 ]]>");
4875                    assert_eq!(de.next().unwrap(), DeEvent::Text(" cdata  cdata2 ".into()));
4876                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4877                    assert_eq!(de.next().unwrap(), DeEvent::Eof);
4878                }
4879            }
4880        }
4881    }
4882}