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