quick_xml/de/
mod.rs

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