Skip to main content

quick_xml/de/
simple_type.rs

1//! Contains Serde `Deserializer` for XML [simple types] [as defined] in the XML Schema.
2//!
3//! [simple types]: https://www.w3schools.com/xml/el_simpletype.asp
4//! [as defined]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition
5
6use crate::de::Text;
7use crate::encoding::Decoder;
8use crate::errors::serialize::DeError;
9use crate::escape::resolve_predefined_entity;
10use crate::utils::{trim_xml_spaces, CowRef};
11use crate::XmlVersion;
12use memchr::memchr;
13use serde::de::value::UnitDeserializer;
14use serde::de::{
15    DeserializeSeed, Deserializer, EnumAccess, IntoDeserializer, SeqAccess, VariantAccess, Visitor,
16};
17use std::borrow::Cow;
18use std::ops::Range;
19
20macro_rules! deserialize_num {
21    ($method:ident => $visit:ident) => {
22        #[inline]
23        fn $method<V>(self, visitor: V) -> Result<V::Value, Self::Error>
24        where
25            V: Visitor<'de>,
26        {
27            let text: &str = self.content.as_ref();
28            match trim_xml_spaces(text).parse() {
29                Ok(number) => visitor.$visit(number),
30                Err(_) => self.deserialize_str(visitor),
31            }
32        }
33    };
34}
35
36macro_rules! deserialize_primitive {
37    ($method:ident) => {
38        fn $method<V>(self, visitor: V) -> Result<V::Value, Self::Error>
39        where
40            V: Visitor<'de>,
41        {
42            let de = AtomicDeserializer {
43                content: self.content()?,
44            };
45            de.$method(visitor)
46        }
47    };
48}
49
50macro_rules! unsupported {
51    (
52        $deserialize:ident
53        $(
54            ($($type:ty),*)
55        )?
56    ) => {
57        #[inline]
58        fn $deserialize<V: Visitor<'de>>(
59            self,
60            $($(_: $type,)*)?
61            visitor: V
62        ) -> Result<V::Value, Self::Error> {
63            // Deserializer methods are only hints, if deserializer could not satisfy
64            // request, it should return the data that it has. It is responsibility
65            // of a Visitor to return an error if it does not understand the data
66            self.deserialize_str(visitor)
67        }
68    };
69}
70
71////////////////////////////////////////////////////////////////////////////////////////////////////
72
73/// A version of [`Cow`] that can borrow from two different buffers, one of them
74/// is a deserializer input, and conceptually contains only part of owned data.
75///
76/// # Lifetimes
77/// - `'de` -- lifetime of the data that deserializer borrow from the parsed input
78/// - `'a` -- lifetime of the data that owned by a deserializer
79enum Content<'de, 'a> {
80    /// An input borrowed from the parsed data
81    Input(&'de str),
82    /// An input borrowed from the buffer owned by another deserializer
83    Slice(&'a str),
84    /// An input taken from an external deserializer, owned by that deserializer.
85    /// Only part of this data, located after offset represented by `usize`, used
86    /// to deserialize data, the other is a garbage that can't be dropped because
87    /// we do not want to make reallocations if they will not required.
88    Owned(String, usize),
89}
90impl<'de, 'a> Content<'de, 'a> {
91    /// Returns string representation of the content
92    fn as_str(&self) -> &str {
93        match self {
94            Content::Input(s) => s,
95            Content::Slice(s) => s,
96            Content::Owned(s, offset) => s.split_at(*offset).1,
97        }
98    }
99}
100
101/// A deserializer that handles ordinary [simple type definition][item] with
102/// `{variety} = atomic`, or an ordinary [simple type] definition with
103/// `{variety} = union` whose basic members are all atomic.
104///
105/// This deserializer can deserialize only primitive types:
106/// - numbers
107/// - booleans
108/// - strings
109/// - units
110/// - options
111/// - unit variants of enums
112///
113/// Identifiers represented as strings and deserialized accordingly.
114///
115/// Deserialization of all other types will provide a string and in most cases
116/// the deserialization will fail because visitor does not expect that.
117///
118/// The `Owned` variant of the content acts as a storage for data, allocated by
119/// an external deserializer that pass it via [`ListIter`].
120///
121/// [item]: https://www.w3.org/TR/xmlschema11-1/#std-item_type_definition
122/// [simple type]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition
123struct AtomicDeserializer<'de, 'a> {
124    /// Content of the attribute value, text content or CDATA content
125    content: CowRef<'de, 'a, str>,
126}
127
128impl<'de, 'a> Deserializer<'de> for AtomicDeserializer<'de, 'a> {
129    type Error = DeError;
130
131    /// Forwards deserialization to the [`Self::deserialize_str`]
132    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
133    where
134        V: Visitor<'de>,
135    {
136        self.deserialize_str(visitor)
137    }
138
139    /// According to the <https://www.w3.org/TR/xmlschema11-2/#boolean>,
140    /// valid boolean representations are only `"true"`, `"false"`, `"1"`,
141    /// and `"0"`.
142    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
143    where
144        V: Visitor<'de>,
145    {
146        let text: &str = self.content.as_ref();
147        match trim_xml_spaces(text) {
148            "1" | "true" => visitor.visit_bool(true),
149            "0" | "false" => visitor.visit_bool(false),
150            _ => self.content.deserialize_str(visitor),
151        }
152    }
153
154    deserialize_num!(deserialize_i8  => visit_i8);
155    deserialize_num!(deserialize_i16 => visit_i16);
156    deserialize_num!(deserialize_i32 => visit_i32);
157    deserialize_num!(deserialize_i64 => visit_i64);
158
159    deserialize_num!(deserialize_u8  => visit_u8);
160    deserialize_num!(deserialize_u16 => visit_u16);
161    deserialize_num!(deserialize_u32 => visit_u32);
162    deserialize_num!(deserialize_u64 => visit_u64);
163
164    deserialize_num!(deserialize_i128 => visit_i128);
165    deserialize_num!(deserialize_u128 => visit_u128);
166
167    deserialize_num!(deserialize_f32 => visit_f32);
168    deserialize_num!(deserialize_f64 => visit_f64);
169
170    /// Forwards deserialization to the [`Self::deserialize_str`]
171    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
172    where
173        V: Visitor<'de>,
174    {
175        let text: &str = self.content.as_ref();
176        let trimmed = trim_xml_spaces(text);
177        // If string is empty or contains only XML space characters (probably only one),
178        // deserialize as usual string and allow visitor to accept or reject it.
179        // Otherwise trim spaces and allow visitor to accept or reject the rest.
180        if trimmed.is_empty() {
181            self.content.deserialize_str(visitor)
182        } else {
183            visitor.visit_str(trimmed)
184        }
185    }
186
187    /// Supply to the visitor borrowed string, string slice, or owned string
188    /// depending on the kind of input and presence of the escaped data.
189    ///
190    /// If string requires unescaping, then calls [`Visitor::visit_string`] with
191    /// new allocated buffer with unescaped data.
192    ///
193    /// Otherwise calls
194    /// - [`Visitor::visit_borrowed_str`] if data borrowed from the input
195    /// - [`Visitor::visit_str`] if data borrowed from other deserializer
196    /// - [`Visitor::visit_string`] if data owned by this deserializer
197    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
198    where
199        V: Visitor<'de>,
200    {
201        self.content.deserialize_str(visitor)
202    }
203
204    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
205    where
206        V: Visitor<'de>,
207    {
208        self.deserialize_str(visitor)
209    }
210
211    /// If `content` is an empty string then calls [`Visitor::visit_none`],
212    /// otherwise calls [`Visitor::visit_some`] with itself
213    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
214    where
215        V: Visitor<'de>,
216    {
217        let text: &str = self.content.as_ref();
218        if text.is_empty() {
219            visitor.visit_none()
220        } else {
221            visitor.visit_some(self)
222        }
223    }
224
225    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
226    where
227        V: Visitor<'de>,
228    {
229        visitor.visit_unit()
230    }
231
232    /// Forwards deserialization to the [`Self::deserialize_unit`]
233    fn deserialize_unit_struct<V>(
234        self,
235        _name: &'static str,
236        visitor: V,
237    ) -> Result<V::Value, Self::Error>
238    where
239        V: Visitor<'de>,
240    {
241        self.deserialize_unit(visitor)
242    }
243
244    fn deserialize_newtype_struct<V>(
245        self,
246        _name: &'static str,
247        visitor: V,
248    ) -> Result<V::Value, Self::Error>
249    where
250        V: Visitor<'de>,
251    {
252        visitor.visit_newtype_struct(self)
253    }
254
255    fn deserialize_enum<V>(
256        self,
257        _name: &'static str,
258        _variants: &'static [&'static str],
259        visitor: V,
260    ) -> Result<V::Value, Self::Error>
261    where
262        V: Visitor<'de>,
263    {
264        visitor.visit_enum(self)
265    }
266
267    /// Forwards deserialization to the [`Self::deserialize_str`]
268    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
269    where
270        V: Visitor<'de>,
271    {
272        self.deserialize_str(visitor)
273    }
274
275    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
276    where
277        V: Visitor<'de>,
278    {
279        visitor.visit_unit()
280    }
281
282    unsupported!(deserialize_bytes);
283    unsupported!(deserialize_byte_buf);
284    unsupported!(deserialize_seq);
285    unsupported!(deserialize_tuple(usize));
286    unsupported!(deserialize_tuple_struct(&'static str, usize));
287    unsupported!(deserialize_map);
288    unsupported!(deserialize_struct(&'static str, &'static [&'static str]));
289}
290
291impl<'de, 'a> EnumAccess<'de> for AtomicDeserializer<'de, 'a> {
292    type Error = DeError;
293    type Variant = UnitOnly;
294
295    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), DeError>
296    where
297        V: DeserializeSeed<'de>,
298    {
299        let name = seed.deserialize(self)?;
300        Ok((name, UnitOnly))
301    }
302}
303
304////////////////////////////////////////////////////////////////////////////////////////////////////
305
306/// Deserializer of variant data, that supports only unit variants.
307/// Attempt to deserialize newtype will provide [`UnitDeserializer`].
308/// Attempt to deserialize tuple or struct variant will result to call of
309/// [`Visitor::visit_unit`].
310pub struct UnitOnly;
311impl<'de> VariantAccess<'de> for UnitOnly {
312    type Error = DeError;
313
314    #[inline]
315    fn unit_variant(self) -> Result<(), Self::Error> {
316        Ok(())
317    }
318
319    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
320    where
321        T: DeserializeSeed<'de>,
322    {
323        seed.deserialize(UnitDeserializer::<Self::Error>::new())
324    }
325
326    #[inline]
327    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
328    where
329        V: Visitor<'de>,
330    {
331        visitor.visit_unit()
332    }
333
334    #[inline]
335    fn struct_variant<V>(
336        self,
337        _fields: &'static [&'static str],
338        visitor: V,
339    ) -> Result<V::Value, Self::Error>
340    where
341        V: Visitor<'de>,
342    {
343        visitor.visit_unit()
344    }
345}
346
347////////////////////////////////////////////////////////////////////////////////////////////////////
348
349/// Iterator over string sub-slices delimited by one or several spaces.
350/// Contains decoded value of the `simpleType`.
351/// Iteration ends when list contains `None`.
352struct ListIter<'de, 'a> {
353    /// If `Some`, contains unconsumed data of the list
354    content: Option<Content<'de, 'a>>,
355}
356impl<'de, 'a> SeqAccess<'de> for ListIter<'de, 'a> {
357    type Error = DeError;
358
359    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, DeError>
360    where
361        T: DeserializeSeed<'de>,
362    {
363        if let Some(mut content) = self.content.take() {
364            const DELIMITER: u8 = b' ';
365
366            loop {
367                let string = content.as_str();
368                if string.is_empty() {
369                    return Ok(None);
370                }
371                return match memchr(DELIMITER, string.as_bytes()) {
372                    // No delimiters in the `content`, deserialize it as a whole atomic
373                    None => match content {
374                        Content::Input(s) => seed.deserialize(AtomicDeserializer {
375                            content: CowRef::Input(s),
376                        }),
377                        Content::Slice(s) => seed.deserialize(AtomicDeserializer {
378                            content: CowRef::Slice(s),
379                        }),
380                        Content::Owned(s, 0) => seed.deserialize(AtomicDeserializer {
381                            content: CowRef::Owned(s),
382                        }),
383                        Content::Owned(s, offset) => seed.deserialize(AtomicDeserializer {
384                            content: CowRef::Slice(s.split_at(offset).1),
385                        }),
386                    },
387                    // `content` started with a space, skip them all
388                    Some(0) => {
389                        // Skip all spaces
390                        let start = string.as_bytes().iter().position(|ch| *ch != DELIMITER);
391                        content = match (start, content) {
392                            // We cannot find any non-space character, so string contains only spaces
393                            (None, _) => return Ok(None),
394                            // Borrow result from input or deserializer depending on the initial borrowing
395                            (Some(start), Content::Input(s)) => Content::Input(s.split_at(start).1),
396                            (Some(start), Content::Slice(s)) => Content::Slice(s.split_at(start).1),
397                            // Skip additional bytes if we own data
398                            (Some(start), Content::Owned(s, skip)) => {
399                                Content::Owned(s, skip + start)
400                            }
401                        };
402                        continue;
403                    }
404                    // `content` started from an atomic
405                    Some(end) => match content {
406                        // Borrow for the next iteration from input or deserializer depending on
407                        // the initial borrowing
408                        Content::Input(s) => {
409                            let (item, rest) = s.split_at(end);
410                            self.content = Some(Content::Input(rest));
411
412                            seed.deserialize(AtomicDeserializer {
413                                content: CowRef::Input(item),
414                            })
415                        }
416                        Content::Slice(s) => {
417                            let (item, rest) = s.split_at(end);
418                            self.content = Some(Content::Slice(rest));
419
420                            seed.deserialize(AtomicDeserializer {
421                                content: CowRef::Slice(item),
422                            })
423                        }
424                        // Skip additional bytes if we own data for next iteration, but deserialize from
425                        // the borrowed data from our buffer
426                        Content::Owned(s, skip) => {
427                            let rest = s.split_at(skip).1;
428                            let item = rest.split_at(end).0;
429                            let result = seed.deserialize(AtomicDeserializer {
430                                content: CowRef::Slice(item),
431                            });
432
433                            self.content = Some(Content::Owned(s, skip + end));
434
435                            result
436                        }
437                    },
438                }
439                .map(Some);
440            }
441        }
442        Ok(None)
443    }
444}
445
446////////////////////////////////////////////////////////////////////////////////////////////////////
447
448/// A deserializer for an xml probably escaped and encoded value of XSD [simple types].
449/// This deserializer will borrow from the input as much as possible.
450///
451/// `deserialize_any()` returns the whole string that deserializer contains.
452///
453/// Escaping the value is actually not always necessary, for instance when
454/// converting to a float, we don't expect any escapable character anyway.
455/// In that cases deserializer skips unescaping step.
456///
457/// Used for deserialize values from:
458/// - attribute values (`<... ...="value" ...>`)
459/// - mixed text / CDATA content (`<...>text<![CDATA[cdata]]></...>`)
460///
461/// This deserializer processes items as following:
462/// - numbers are parsed from a text content using [`FromStr`]; in case of error
463///   [`Visitor::visit_borrowed_str`], [`Visitor::visit_str`], or [`Visitor::visit_string`]
464///   is called; it is responsibility of the type to return an error if it does
465///   not able to process passed data;
466/// - booleans converted from the text according to the XML [specification]:
467///   - `"true"` and `"1"` converted to `true`;
468///   - `"false"` and `"0"` converted to `false`;
469///   - everything else calls [`Visitor::visit_borrowed_str`], [`Visitor::visit_str`],
470///     or [`Visitor::visit_string`]; it is responsibility of the type to return
471///     an error if it does not able to process passed data;
472/// - strings returned as is;
473/// - characters also returned as strings. If string contain more than one character
474///   or empty, it is responsibility of a type to return an error;
475/// - `Option` always deserialized as `Some` using the same deserializer.
476///   If attribute or text content is missed, then the deserializer even wouldn't
477///   be used, so if it is used, then the value should be;
478/// - units (`()`) and unit structs always deserialized successfully, the content is ignored;
479/// - newtype structs forwards deserialization to the inner type using the same
480///   deserializer;
481/// - sequences, tuples and tuple structs are deserialized as `xs:list`s. Only
482///   sequences of primitive types is possible to deserialize this way and they
483///   should be delimited by a space (` `, `\t`, `\r`, or `\n`);
484/// - structs and maps delegates to [`Self::deserialize_str`] which calls
485///   [`Visitor::visit_borrowed_str`] or [`Visitor::visit_string`]; it is responsibility
486///   of the type to return an error if it does not able to process passed data;
487/// - enums:
488///   - the variant name is deserialized using the same deserializer;
489///   - the content is deserialized using the deserializer that always returns unit (`()`):
490///     - unit variants: just return `()`;
491///     - newtype variants: deserialize from [`UnitDeserializer`];
492///     - tuple and struct variants: call [`Visitor::visit_unit`];
493/// - identifiers are deserialized as strings.
494///
495/// [simple types]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition
496/// [`FromStr`]: std::str::FromStr
497/// [specification]: https://www.w3.org/TR/xmlschema11-2/#boolean
498pub struct SimpleTypeDeserializer<'de, 'a> {
499    /// - In case of attribute contains escaped attribute value
500    /// - In case of text contains unescaped text value
501    content: CowRef<'de, 'a, [u8]>,
502    /// If `true`, `content` in escaped form and should be unescaped before use
503    is_attr: bool,
504    /// Decoder used to deserialize string data, numeric and boolean data.
505    /// Not used for deserializing raw byte buffers
506    decoder: Decoder,
507    version: XmlVersion,
508}
509
510impl<'de, 'a> SimpleTypeDeserializer<'de, 'a> {
511    /// Creates a deserializer from a value, that possible borrowed from input.
512    ///
513    /// It is assumed that `text` does not have entities.
514    pub fn from_text(text: Cow<'de, str>) -> Self {
515        let content = match text {
516            Cow::Borrowed(slice) => CowRef::Input(slice.as_bytes()),
517            Cow::Owned(content) => CowRef::Owned(content.into_bytes()),
518        };
519        Self::new(content, false, XmlVersion::Implicit1_0, Decoder::utf8())
520    }
521    /// Creates a deserializer from an XML text node, that possible borrowed from input.
522    ///
523    /// It is assumed that `text` does not have entities.
524    ///
525    /// This constructor used internally to deserialize from text nodes.
526    pub fn from_text_content(value: Text<'de>) -> Self {
527        Self::from_text(value.text)
528    }
529
530    /// Creates a deserializer from a part of value at specified range.
531    ///
532    /// This constructor used internally to deserialize from attribute values.
533    #[allow(clippy::ptr_arg)]
534    pub(crate) fn from_attr(
535        value: &'a Cow<'de, [u8]>,
536        range: Range<usize>,
537        version: XmlVersion,
538        decoder: Decoder,
539    ) -> Self {
540        let content = match value {
541            Cow::Borrowed(slice) => CowRef::Input(&slice[range]),
542            Cow::Owned(slice) => CowRef::Slice(&slice[range]),
543        };
544        Self::new(content, true, version, decoder)
545    }
546
547    /// Constructor for tests
548    #[inline]
549    const fn new(
550        content: CowRef<'de, 'a, [u8]>,
551        is_attr: bool,
552        version: XmlVersion,
553        decoder: Decoder,
554    ) -> Self {
555        Self {
556            content,
557            is_attr,
558            decoder,
559            version,
560        }
561    }
562
563    /// Decodes raw bytes using the encoding specified.
564    /// The method will borrow if has the UTF-8 compatible representation.
565    #[inline]
566    fn decode<'b>(&'b self) -> Result<CowRef<'de, 'b, str>, DeError> {
567        Ok(match self.content {
568            CowRef::Input(content) => match self.decoder.decode(content)? {
569                Cow::Borrowed(content) => CowRef::Input(content),
570                Cow::Owned(content) => CowRef::Owned(content),
571            },
572            CowRef::Slice(content) => match self.decoder.decode(content)? {
573                Cow::Borrowed(content) => CowRef::Slice(content),
574                Cow::Owned(content) => CowRef::Owned(content),
575            },
576            CowRef::Owned(ref content) => match self.decoder.decode(content)? {
577                Cow::Borrowed(content) => CowRef::Slice(content),
578                Cow::Owned(content) => CowRef::Owned(content),
579            },
580        })
581    }
582
583    fn content<'b>(&'b self) -> Result<CowRef<'de, 'b, str>, DeError> {
584        let content = self.decode()?;
585        if self.is_attr {
586            let value =
587                self.version
588                    .normalize_attribute_value(&content, 128, resolve_predefined_entity)?;
589            return Ok(match value {
590                Cow::Borrowed(_) => content,
591                Cow::Owned(value) => CowRef::Owned(value),
592            });
593        }
594        Ok(content)
595    }
596}
597
598impl<'de, 'a> Deserializer<'de> for SimpleTypeDeserializer<'de, 'a> {
599    type Error = DeError;
600
601    /// Forwards deserialization to the [`Self::deserialize_str`]
602    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
603    where
604        V: Visitor<'de>,
605    {
606        self.deserialize_str(visitor)
607    }
608
609    deserialize_primitive!(deserialize_bool);
610
611    deserialize_primitive!(deserialize_i8);
612    deserialize_primitive!(deserialize_i16);
613    deserialize_primitive!(deserialize_i32);
614    deserialize_primitive!(deserialize_i64);
615
616    deserialize_primitive!(deserialize_u8);
617    deserialize_primitive!(deserialize_u16);
618    deserialize_primitive!(deserialize_u32);
619    deserialize_primitive!(deserialize_u64);
620
621    deserialize_primitive!(deserialize_i128);
622    deserialize_primitive!(deserialize_u128);
623
624    deserialize_primitive!(deserialize_f32);
625    deserialize_primitive!(deserialize_f64);
626
627    deserialize_primitive!(deserialize_char);
628    deserialize_primitive!(deserialize_str);
629    deserialize_primitive!(deserialize_string);
630    deserialize_primitive!(deserialize_bytes);
631    deserialize_primitive!(deserialize_byte_buf);
632
633    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
634    where
635        V: Visitor<'de>,
636    {
637        visitor.visit_some(self)
638    }
639
640    #[inline]
641    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
642    where
643        V: Visitor<'de>,
644    {
645        visitor.visit_unit()
646    }
647
648    /// Forwards deserialization to the [`Self::deserialize_unit`]
649    #[inline]
650    fn deserialize_unit_struct<V>(
651        self,
652        _name: &'static str,
653        visitor: V,
654    ) -> Result<V::Value, Self::Error>
655    where
656        V: Visitor<'de>,
657    {
658        self.deserialize_unit(visitor)
659    }
660
661    fn deserialize_newtype_struct<V>(
662        self,
663        _name: &'static str,
664        visitor: V,
665    ) -> Result<V::Value, Self::Error>
666    where
667        V: Visitor<'de>,
668    {
669        visitor.visit_newtype_struct(self)
670    }
671
672    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
673    where
674        V: Visitor<'de>,
675    {
676        let content = match self.content()? {
677            CowRef::Input(s) => Content::Input(s),
678            CowRef::Slice(s) => Content::Slice(s),
679            CowRef::Owned(s) => Content::Owned(s, 0),
680        };
681        visitor.visit_seq(ListIter {
682            content: Some(content),
683        })
684    }
685
686    /// Representation of tuples the same as [sequences][Self::deserialize_seq].
687    #[inline]
688    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
689    where
690        V: Visitor<'de>,
691    {
692        self.deserialize_seq(visitor)
693    }
694
695    /// Representation of named tuples the same as [unnamed tuples][Self::deserialize_tuple].
696    #[inline]
697    fn deserialize_tuple_struct<V>(
698        self,
699        _name: &'static str,
700        len: usize,
701        visitor: V,
702    ) -> Result<V::Value, DeError>
703    where
704        V: Visitor<'de>,
705    {
706        self.deserialize_tuple(len, visitor)
707    }
708
709    unsupported!(deserialize_map);
710    unsupported!(deserialize_struct(&'static str, &'static [&'static str]));
711
712    fn deserialize_enum<V>(
713        self,
714        _name: &'static str,
715        _variants: &'static [&'static str],
716        visitor: V,
717    ) -> Result<V::Value, Self::Error>
718    where
719        V: Visitor<'de>,
720    {
721        visitor.visit_enum(self)
722    }
723
724    /// Forwards deserialization to the [`Self::deserialize_str`]
725    #[inline]
726    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
727    where
728        V: Visitor<'de>,
729    {
730        self.deserialize_str(visitor)
731    }
732
733    #[inline]
734    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
735    where
736        V: Visitor<'de>,
737    {
738        visitor.visit_unit()
739    }
740}
741
742impl<'de, 'a> EnumAccess<'de> for SimpleTypeDeserializer<'de, 'a> {
743    type Error = DeError;
744    type Variant = UnitOnly;
745
746    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), DeError>
747    where
748        V: DeserializeSeed<'de>,
749    {
750        let name = seed.deserialize(self)?;
751        Ok((name, UnitOnly))
752    }
753}
754
755impl<'de, 'a> IntoDeserializer<'de, DeError> for SimpleTypeDeserializer<'de, 'a> {
756    type Deserializer = Self;
757
758    #[inline]
759    fn into_deserializer(self) -> Self {
760        self
761    }
762}
763
764////////////////////////////////////////////////////////////////////////////////////////////////////
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769    use crate::se::simple_type::{QuoteTarget, SimpleTypeSerializer};
770    use crate::se::QuoteLevel;
771    use crate::utils::{ByteBuf, Bytes};
772    use serde::de::IgnoredAny;
773    use serde::{Deserialize, Serialize};
774    use std::collections::HashMap;
775
776    macro_rules! simple_only {
777        ($encoding:ident, $name:ident: $type:ty = $xml:expr => $result:expr) => {
778            #[test]
779            fn $name() {
780                let decoder = Decoder::$encoding();
781                let xml = $xml;
782                let de = SimpleTypeDeserializer::new(
783                    CowRef::Input(xml.as_ref()),
784                    true,
785                    XmlVersion::Implicit1_0,
786                    decoder,
787                );
788                let data: $type = Deserialize::deserialize(de).unwrap();
789
790                assert_eq!(data, $result);
791            }
792        };
793    }
794
795    macro_rules! simple {
796        ($encoding:ident, $name:ident: $type:ty = $xml:expr => $result:expr) => {
797            #[test]
798            fn $name() {
799                let decoder = Decoder::$encoding();
800                let xml = $xml;
801                let de = SimpleTypeDeserializer::new(
802                    CowRef::Input(xml.as_ref()),
803                    true,
804                    XmlVersion::Implicit1_0,
805                    decoder,
806                );
807                let data: $type = Deserialize::deserialize(de).unwrap();
808
809                assert_eq!(data, $result);
810
811                // Roundtrip to ensure that serializer corresponds to deserializer
812                assert_eq!(
813                    data.serialize(SimpleTypeSerializer {
814                        writer: String::new(),
815                        target: QuoteTarget::Text,
816                        level: QuoteLevel::Full,
817                    })
818                    .unwrap(),
819                    xml
820                );
821            }
822        };
823    }
824
825    macro_rules! err {
826        ($encoding:ident, $name:ident: $type:ty = $xml:expr => $kind:ident($reason:literal)) => {
827            #[test]
828            fn $name() {
829                let decoder = Decoder::$encoding();
830                let xml = $xml;
831                let de = SimpleTypeDeserializer::new(
832                    CowRef::Input(xml.as_ref()),
833                    true,
834                    XmlVersion::Implicit1_0,
835                    decoder,
836                );
837                let err = <$type as Deserialize>::deserialize(de).unwrap_err();
838
839                match err {
840                    DeError::$kind(e) => assert_eq!(e, $reason),
841                    _ => panic!(
842                        "Expected `Err({}({}))`, but got `{:?}`",
843                        stringify!($kind),
844                        $reason,
845                        err
846                    ),
847                }
848            }
849        };
850    }
851
852    #[derive(Debug, Deserialize, Serialize, PartialEq)]
853    struct Unit;
854
855    #[derive(Debug, Deserialize, Serialize, PartialEq)]
856    struct Newtype(String);
857
858    #[derive(Debug, Deserialize, Serialize, PartialEq)]
859    struct Tuple((), ());
860
861    #[derive(Debug, Deserialize, Serialize, PartialEq)]
862    struct BorrowedNewtype<'a>(&'a str);
863
864    #[derive(Debug, Deserialize, Serialize, PartialEq)]
865    struct Struct {
866        key: String,
867        val: usize,
868    }
869
870    #[derive(Debug, Deserialize, Serialize, PartialEq)]
871    enum Enum {
872        Unit,
873        Newtype(String),
874        Tuple(String, usize),
875        Struct { key: String, val: usize },
876    }
877
878    #[derive(Debug, Deserialize, PartialEq)]
879    #[serde(field_identifier)]
880    enum Id {
881        Field,
882    }
883
884    #[derive(Debug, Deserialize)]
885    #[serde(transparent)]
886    struct Any(IgnoredAny);
887    impl PartialEq for Any {
888        fn eq(&self, _other: &Any) -> bool {
889            true
890        }
891    }
892
893    /// Tests for deserialize atomic and union values, as defined in XSD specification
894    mod atomic {
895        use super::*;
896        use crate::se::simple_type::AtomicSerializer;
897        use pretty_assertions::assert_eq;
898        use std::ops::Deref;
899
900        /// Checks that given `$input` successfully deserializing into given `$result`
901        macro_rules! deserialized_to_only {
902            ($name:ident: $type:ty = $input:literal => $result:expr) => {
903                #[test]
904                fn $name() {
905                    let de = AtomicDeserializer {
906                        content: CowRef::Input($input),
907                    };
908                    let data: $type = Deserialize::deserialize(de).unwrap();
909
910                    assert_eq!(data, $result);
911                }
912            };
913        }
914
915        /// Checks that given `$input` successfully deserializing into given `$result`
916        /// and the result is serialized back to the `$input`
917        macro_rules! deserialized_to {
918            ($name:ident: $type:ty = $input:literal => $result:expr) => {
919                #[test]
920                fn $name() {
921                    let de = AtomicDeserializer {
922                        content: CowRef::Input($input),
923                    };
924                    let data: $type = Deserialize::deserialize(de).unwrap();
925
926                    assert_eq!(data, $result, "deserialization failed");
927
928                    // Roundtrip to ensure that serializer corresponds to deserializer
929                    let mut buffer = String::new();
930                    let has_written = data
931                        .serialize(AtomicSerializer {
932                            writer: &mut buffer,
933                            target: QuoteTarget::Text,
934                            level: QuoteLevel::Full,
935                            write_delimiter: false,
936                        })
937                        .unwrap();
938                    assert_eq!(buffer, $input, "serialization failed");
939                    assert_eq!(has_written, !buffer.is_empty());
940                }
941            };
942        }
943
944        /// Checks that attempt to deserialize given `$input` as a `$type` results to a
945        /// deserialization error `$kind` with `$reason`
946        macro_rules! err {
947            ($name:ident: $type:ty = $input:literal => $kind:ident($reason:literal)) => {
948                #[test]
949                fn $name() {
950                    let de = AtomicDeserializer {
951                        content: CowRef::Input($input),
952                    };
953                    let err = <$type as Deserialize>::deserialize(de).unwrap_err();
954
955                    match err {
956                        DeError::$kind(e) => assert_eq!(e, $reason),
957                        _ => panic!(
958                            "Expected `Err({}({}))`, but got `{:?}`",
959                            stringify!($kind),
960                            $reason,
961                            err
962                        ),
963                    }
964                }
965            };
966        }
967
968        deserialized_to!(false_: bool = "false" => false);
969        deserialized_to!(true_: bool  = "true" => true);
970
971        deserialized_to!(i8_:  i8  = "-2" => -2);
972        deserialized_to!(i16_: i16 = "-2" => -2);
973        deserialized_to!(i32_: i32 = "-2" => -2);
974        deserialized_to!(i64_: i64 = "-2" => -2);
975
976        deserialized_to!(u8_:  u8  = "3" => 3);
977        deserialized_to!(u16_: u16 = "3" => 3);
978        deserialized_to!(u32_: u32 = "3" => 3);
979        deserialized_to!(u64_: u64 = "3" => 3);
980
981        deserialized_to!(i128_: i128 = "-2" => -2);
982        deserialized_to!(u128_: u128 = "2" => 2);
983
984        deserialized_to!(f32_: f32 = "1.23" => 1.23);
985        deserialized_to!(f64_: f64 = "1.23" => 1.23);
986
987        deserialized_to!(char_unescaped: char = "h" => 'h');
988        err!(char_escaped: char = "&lt;"
989                => Custom("invalid value: string \"&lt;\", expected a character"));
990
991        // AtomicDeserializer and AtomicSerializer are asymmetric:
992        // - AtomicDeserializer operates by already normalized (including unescaped) values
993        // - AtomicSerializer escapes values
994        deserialized_to_only!(string: String = "&lt;escaped&#32;string" => "&lt;escaped&#32;string");
995        // Serializer will escape space. Because borrowing has meaning only for deserializer,
996        // no need to test roundtrip here, it is already tested with non-borrowing version
997        deserialized_to_only!(borrowed_str: &str = "non-escaped string" => "non-escaped string");
998        deserialized_to_only!(escaped_str: &str = "escaped&#32;string" => "escaped&#32;string");
999
1000        err!(byte_buf: ByteBuf = "&lt;escaped&#32;string"
1001                => Custom("invalid type: string \"&lt;escaped&#32;string\", expected byte data"));
1002        err!(borrowed_bytes: Bytes = "non-escaped string"
1003                => Custom("invalid type: string \"non-escaped string\", expected borrowed bytes"));
1004
1005        deserialized_to!(option_none: Option<&str> = "" => None);
1006        deserialized_to!(option_some: Option<&str> = "non-escaped-string" => Some("non-escaped-string"));
1007
1008        deserialized_to_only!(unit: () = "<root>anything</root>" => ());
1009        deserialized_to_only!(unit_struct: Unit = "<root>anything</root>" => Unit);
1010
1011        deserialized_to_only!(newtype_owned: Newtype = "&lt;escaped&#32;string" => Newtype("&lt;escaped&#32;string".into()));
1012        // Serializer will escape space. Because borrowing has meaning only for deserializer,
1013        // no need to test roundtrip here, it is already tested with non-borrowing version
1014        deserialized_to_only!(newtype_borrowed: BorrowedNewtype = "non-escaped string"
1015                => BorrowedNewtype("non-escaped string"));
1016
1017        err!(seq: Vec<()> = "non-escaped string"
1018                => Custom("invalid type: string \"non-escaped string\", expected a sequence"));
1019        err!(tuple: ((), ()) = "non-escaped string"
1020                => Custom("invalid type: string \"non-escaped string\", expected a tuple of size 2"));
1021        err!(tuple_struct: Tuple = "non-escaped string"
1022                => Custom("invalid type: string \"non-escaped string\", expected tuple struct Tuple"));
1023
1024        err!(map: HashMap<(), ()> = "non-escaped string"
1025                => Custom("invalid type: string \"non-escaped string\", expected a map"));
1026        err!(struct_: Struct = "non-escaped string"
1027                => Custom("invalid type: string \"non-escaped string\", expected struct Struct"));
1028
1029        deserialized_to!(enum_unit: Enum = "Unit" => Enum::Unit);
1030        err!(enum_newtype: Enum = "Newtype"
1031                => Custom("invalid type: unit value, expected a string"));
1032        err!(enum_tuple: Enum = "Tuple"
1033                => Custom("invalid type: unit value, expected tuple variant Enum::Tuple"));
1034        err!(enum_struct: Enum = "Struct"
1035                => Custom("invalid type: unit value, expected struct variant Enum::Struct"));
1036        err!(enum_other: Enum = "any data"
1037                => Custom("unknown variant `any data`, expected one of `Unit`, `Newtype`, `Tuple`, `Struct`"));
1038
1039        deserialized_to_only!(identifier: Id = "Field" => Id::Field);
1040        deserialized_to_only!(ignored_any: Any = "any data" => Any(IgnoredAny));
1041
1042        /// Checks that deserialization from an owned content is working
1043        #[test]
1044        #[cfg(feature = "encoding")]
1045        fn owned_data() {
1046            let de = AtomicDeserializer {
1047                content: CowRef::Owned("string slice".into()),
1048            };
1049            assert_eq!(de.content.deref(), "string slice");
1050
1051            let data: String = Deserialize::deserialize(de).unwrap();
1052            assert_eq!(data, "string slice");
1053        }
1054
1055        /// Checks that deserialization from a content borrowed from some
1056        /// buffer other that input is working
1057        #[test]
1058        fn borrowed_from_deserializer() {
1059            let de = AtomicDeserializer {
1060                content: CowRef::Slice("string slice"),
1061            };
1062            assert_eq!(de.content.deref(), "string slice");
1063
1064            let data: String = Deserialize::deserialize(de).unwrap();
1065            assert_eq!(data, "string slice");
1066        }
1067    }
1068
1069    /// Module for testing list accessor
1070    mod list {
1071        use super::*;
1072        use pretty_assertions::assert_eq;
1073
1074        #[test]
1075        fn empty() {
1076            let mut seq = ListIter {
1077                content: Some(Content::Input("")),
1078            };
1079
1080            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1081            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1082        }
1083
1084        #[test]
1085        fn only_spaces() {
1086            let mut seq = ListIter {
1087                content: Some(Content::Input("  ")),
1088            };
1089
1090            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1091            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1092        }
1093
1094        #[test]
1095        fn one_item() {
1096            let mut seq = ListIter {
1097                content: Some(Content::Input("abc")),
1098            };
1099
1100            assert_eq!(seq.next_element::<&str>().unwrap(), Some("abc"));
1101            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1102            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1103        }
1104
1105        #[test]
1106        fn two_items() {
1107            let mut seq = ListIter {
1108                content: Some(Content::Input("abc def")),
1109            };
1110
1111            assert_eq!(seq.next_element::<&str>().unwrap(), Some("abc"));
1112            assert_eq!(seq.next_element::<&str>().unwrap(), Some("def"));
1113            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1114            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1115        }
1116
1117        #[test]
1118        fn leading_spaces() {
1119            let mut seq = ListIter {
1120                content: Some(Content::Input("  def")),
1121            };
1122
1123            assert_eq!(seq.next_element::<&str>().unwrap(), Some("def"));
1124            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1125            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1126        }
1127
1128        #[test]
1129        fn trailing_spaces() {
1130            let mut seq = ListIter {
1131                content: Some(Content::Input("abc  ")),
1132            };
1133
1134            assert_eq!(seq.next_element::<&str>().unwrap(), Some("abc"));
1135            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1136            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1137        }
1138
1139        #[test]
1140        fn mixed_types() {
1141            let mut seq = ListIter {
1142                content: Some(Content::Input("string 1.23 42 true false h Unit")),
1143            };
1144
1145            assert_eq!(seq.next_element::<&str>().unwrap(), Some("string"));
1146            assert_eq!(seq.next_element::<f32>().unwrap(), Some(1.23));
1147            assert_eq!(seq.next_element::<u32>().unwrap(), Some(42));
1148            assert_eq!(seq.next_element::<bool>().unwrap(), Some(true));
1149            assert_eq!(seq.next_element::<bool>().unwrap(), Some(false));
1150            assert_eq!(seq.next_element::<char>().unwrap(), Some('h'));
1151            assert_eq!(seq.next_element::<Enum>().unwrap(), Some(Enum::Unit));
1152            assert_eq!(seq.next_element::<()>().unwrap(), None);
1153            assert_eq!(seq.next_element::<()>().unwrap(), None);
1154        }
1155    }
1156
1157    mod utf8 {
1158        use super::*;
1159        use pretty_assertions::assert_eq;
1160
1161        simple!(utf8, i8_:  i8  = "-2" => -2);
1162        simple!(utf8, i16_: i16 = "-2" => -2);
1163        simple!(utf8, i32_: i32 = "-2" => -2);
1164        simple!(utf8, i64_: i64 = "-2" => -2);
1165
1166        simple!(utf8, u8_:  u8  = "3" => 3);
1167        simple!(utf8, u16_: u16 = "3" => 3);
1168        simple!(utf8, u32_: u32 = "3" => 3);
1169        simple!(utf8, u64_: u64 = "3" => 3);
1170
1171        simple!(utf8, i128_: i128 = "-2" => -2);
1172        simple!(utf8, u128_: u128 = "2" => 2);
1173
1174        simple!(utf8, f32_: f32 = "1.23" => 1.23);
1175        simple!(utf8, f64_: f64 = "1.23" => 1.23);
1176
1177        simple!(utf8, false_: bool = "false" => false);
1178        simple!(utf8, true_: bool  = "true" => true);
1179        simple!(utf8, char_unescaped: char = "h" => 'h');
1180        simple!(utf8, char_escaped: char = "&lt;" => '<');
1181
1182        simple!(utf8, string: String = "&lt;escaped string" => "<escaped string");
1183        err!(utf8, byte_buf: ByteBuf = "&lt;escaped&#32;string"
1184             => Custom("invalid type: string \"<escaped string\", expected byte data"));
1185
1186        simple!(utf8, borrowed_str: &str = "non-escaped string" => "non-escaped string");
1187        err!(utf8, borrowed_bytes: Bytes = "&lt;escaped&#32;string"
1188             => Custom("invalid type: string \"<escaped string\", expected borrowed bytes"));
1189
1190        simple!(utf8, option_none: Option<&str> = "" => Some(""));
1191        simple!(utf8, option_some: Option<&str> = "non-escaped string" => Some("non-escaped string"));
1192
1193        simple_only!(utf8, unit: () = "any data" => ());
1194        simple_only!(utf8, unit_struct: Unit = "any data" => Unit);
1195
1196        // Serializer will not escape space because this is unnecessary.
1197        // Because borrowing has meaning only for deserializer, no need to test
1198        // roundtrip here, it is already tested for strings where compatible list
1199        // of escaped characters is used
1200        simple_only!(utf8, newtype_owned: Newtype = "&lt;escaped&#32;string"
1201            => Newtype("<escaped string".into()));
1202        simple_only!(utf8, newtype_borrowed: BorrowedNewtype = "non-escaped string"
1203            => BorrowedNewtype("non-escaped string"));
1204
1205        err!(utf8, map: HashMap<(), ()> = "any data"
1206             => Custom("invalid type: string \"any data\", expected a map"));
1207        err!(utf8, struct_: Struct = "any data"
1208             => Custom("invalid type: string \"any data\", expected struct Struct"));
1209
1210        simple!(utf8, enum_unit: Enum = "Unit" => Enum::Unit);
1211        err!(utf8, enum_newtype: Enum = "Newtype"
1212             => Custom("invalid type: unit value, expected a string"));
1213        err!(utf8, enum_tuple: Enum = "Tuple"
1214             => Custom("invalid type: unit value, expected tuple variant Enum::Tuple"));
1215        err!(utf8, enum_struct: Enum = "Struct"
1216             => Custom("invalid type: unit value, expected struct variant Enum::Struct"));
1217        err!(utf8, enum_other: Enum = "any data"
1218             => Custom("unknown variant `any data`, expected one of `Unit`, `Newtype`, `Tuple`, `Struct`"));
1219
1220        simple_only!(utf8, identifier: Id = "Field" => Id::Field);
1221        simple_only!(utf8, ignored_any: Any = "any data" => Any(IgnoredAny));
1222    }
1223
1224    #[cfg(feature = "encoding")]
1225    mod utf16 {
1226        use super::*;
1227        use pretty_assertions::assert_eq;
1228
1229        fn to_utf16(string: &str) -> Vec<u8> {
1230            let mut bytes = Vec::new();
1231            for ch in string.encode_utf16() {
1232                bytes.extend_from_slice(&ch.to_le_bytes());
1233            }
1234            bytes
1235        }
1236
1237        macro_rules! utf16 {
1238            ($name:ident: $type:ty = $xml:literal => $result:expr) => {
1239                simple_only!(utf16, $name: $type = to_utf16($xml) => $result);
1240            };
1241        }
1242
1243        macro_rules! unsupported {
1244            ($name:ident: $type:ty = $xml:literal => $err:literal) => {
1245                err!(utf16, $name: $type = to_utf16($xml) => Custom($err));
1246            };
1247        }
1248
1249        utf16!(i8_:  i8  = "-2" => -2);
1250        utf16!(i16_: i16 = "-2" => -2);
1251        utf16!(i32_: i32 = "-2" => -2);
1252        utf16!(i64_: i64 = "-2" => -2);
1253
1254        utf16!(u8_:  u8  = "3" => 3);
1255        utf16!(u16_: u16 = "3" => 3);
1256        utf16!(u32_: u32 = "3" => 3);
1257        utf16!(u64_: u64 = "3" => 3);
1258
1259        utf16!(i128_: i128 = "-2" => -2);
1260        utf16!(u128_: u128 = "2" => 2);
1261
1262        utf16!(f32_: f32 = "1.23" => 1.23);
1263        utf16!(f64_: f64 = "1.23" => 1.23);
1264
1265        utf16!(false_: bool = "false" => false);
1266        utf16!(true_: bool  = "true" => true);
1267        utf16!(char_unescaped: char = "h" => 'h');
1268        utf16!(char_escaped: char = "&lt;" => '<');
1269
1270        utf16!(string: String = "&lt;escaped&#32;string" => "<escaped string");
1271        unsupported!(borrowed_bytes: Bytes = "&lt;escaped&#32;string"
1272                    => "invalid type: string \"<escaped string\", expected borrowed bytes");
1273
1274        utf16!(option_none: Option<()> = "" => Some(()));
1275        utf16!(option_some: Option<()> = "any data" => Some(()));
1276
1277        utf16!(unit: () = "any data" => ());
1278        utf16!(unit_struct: Unit = "any data" => Unit);
1279
1280        utf16!(newtype_owned: Newtype = "&lt;escaped&#32;string" => Newtype("<escaped string".into()));
1281
1282        // UTF-16 data never borrow because data was decoded not in-place
1283        unsupported!(newtype_borrowed: BorrowedNewtype = "non-escaped string"
1284                    => "invalid type: string \"non-escaped string\", expected a borrowed string");
1285
1286        unsupported!(map: HashMap<(), ()> = "any data"
1287                    => "invalid type: string \"any data\", expected a map");
1288        unsupported!(struct_: Struct = "any data"
1289                    => "invalid type: string \"any data\", expected struct Struct");
1290
1291        utf16!(enum_unit: Enum = "Unit" => Enum::Unit);
1292        unsupported!(enum_newtype: Enum = "Newtype"
1293                    => "invalid type: unit value, expected a string");
1294        unsupported!(enum_tuple: Enum = "Tuple"
1295                    => "invalid type: unit value, expected tuple variant Enum::Tuple");
1296        unsupported!(enum_struct: Enum = "Struct"
1297                    => "invalid type: unit value, expected struct variant Enum::Struct");
1298        unsupported!(enum_other: Enum = "any data"
1299                    => "unknown variant `any data`, expected one of `Unit`, `Newtype`, `Tuple`, `Struct`");
1300
1301        utf16!(identifier: Id = "Field" => Id::Field);
1302        utf16!(ignored_any: Any = "any data" => Any(IgnoredAny));
1303    }
1304}