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        escaped: bool,
543        decoder: Decoder,
544    ) -> Self {
545        let content = match value {
546            Cow::Borrowed(slice) => CowRef::Input(&slice[range]),
547            Cow::Owned(slice) => CowRef::Slice(&slice[range]),
548        };
549        Self::new(content, escaped, decoder)
550    }
551
552    /// Constructor for tests
553    #[inline]
554    const fn new(content: CowRef<'de, 'a, [u8]>, escaped: bool, decoder: Decoder) -> Self {
555        Self {
556            content,
557            escaped,
558            decoder,
559        }
560    }
561
562    /// Decodes raw bytes using the encoding specified.
563    /// The method will borrow if has the UTF-8 compatible representation.
564    #[inline]
565    fn decode<'b>(&'b self) -> Result<CowRef<'de, 'b, str>, DeError> {
566        Ok(match self.content {
567            CowRef::Input(content) => match self.decoder.decode(content)? {
568                Cow::Borrowed(content) => CowRef::Input(content),
569                Cow::Owned(content) => CowRef::Owned(content),
570            },
571            CowRef::Slice(content) => match self.decoder.decode(content)? {
572                Cow::Borrowed(content) => CowRef::Slice(content),
573                Cow::Owned(content) => CowRef::Owned(content),
574            },
575            CowRef::Owned(ref content) => match self.decoder.decode(content)? {
576                Cow::Borrowed(content) => CowRef::Slice(content),
577                Cow::Owned(content) => CowRef::Owned(content),
578            },
579        })
580    }
581}
582
583impl<'de, 'a> Deserializer<'de> for SimpleTypeDeserializer<'de, 'a> {
584    type Error = DeError;
585
586    /// Forwards deserialization to the [`Self::deserialize_str`]
587    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
588    where
589        V: Visitor<'de>,
590    {
591        self.deserialize_str(visitor)
592    }
593
594    deserialize_primitive!(deserialize_bool);
595
596    deserialize_primitive!(deserialize_i8);
597    deserialize_primitive!(deserialize_i16);
598    deserialize_primitive!(deserialize_i32);
599    deserialize_primitive!(deserialize_i64);
600
601    deserialize_primitive!(deserialize_u8);
602    deserialize_primitive!(deserialize_u16);
603    deserialize_primitive!(deserialize_u32);
604    deserialize_primitive!(deserialize_u64);
605
606    serde_if_integer128! {
607        deserialize_primitive!(deserialize_i128);
608        deserialize_primitive!(deserialize_u128);
609    }
610
611    deserialize_primitive!(deserialize_f32);
612    deserialize_primitive!(deserialize_f64);
613
614    deserialize_primitive!(deserialize_str);
615
616    /// Forwards deserialization to the [`Self::deserialize_str`]
617    #[inline]
618    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
619    where
620        V: Visitor<'de>,
621    {
622        self.deserialize_str(visitor)
623    }
624
625    /// Forwards deserialization to the [`Self::deserialize_str`]
626    #[inline]
627    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
628    where
629        V: Visitor<'de>,
630    {
631        self.deserialize_str(visitor)
632    }
633
634    /// Forwards deserialization to the [`Self::deserialize_str`]
635    #[inline]
636    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
637    where
638        V: Visitor<'de>,
639    {
640        self.deserialize_str(visitor)
641    }
642
643    /// Forwards deserialization to the [`Self::deserialize_str`]
644    #[inline]
645    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
646    where
647        V: Visitor<'de>,
648    {
649        self.deserialize_bytes(visitor)
650    }
651
652    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
653    where
654        V: Visitor<'de>,
655    {
656        visitor.visit_some(self)
657    }
658
659    #[inline]
660    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
661    where
662        V: Visitor<'de>,
663    {
664        visitor.visit_unit()
665    }
666
667    /// Forwards deserialization to the [`Self::deserialize_unit`]
668    #[inline]
669    fn deserialize_unit_struct<V>(
670        self,
671        _name: &'static str,
672        visitor: V,
673    ) -> Result<V::Value, Self::Error>
674    where
675        V: Visitor<'de>,
676    {
677        self.deserialize_unit(visitor)
678    }
679
680    fn deserialize_newtype_struct<V>(
681        self,
682        _name: &'static str,
683        visitor: V,
684    ) -> Result<V::Value, Self::Error>
685    where
686        V: Visitor<'de>,
687    {
688        visitor.visit_newtype_struct(self)
689    }
690
691    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
692    where
693        V: Visitor<'de>,
694    {
695        let content = match self.decode()? {
696            CowRef::Input(s) => Content::Input(s),
697            CowRef::Slice(s) => Content::Slice(s),
698            CowRef::Owned(s) => Content::Owned(s, 0),
699        };
700        visitor.visit_seq(ListIter {
701            content: Some(content),
702            escaped: self.escaped,
703        })
704    }
705
706    /// Representation of tuples the same as [sequences][Self::deserialize_seq].
707    #[inline]
708    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
709    where
710        V: Visitor<'de>,
711    {
712        self.deserialize_seq(visitor)
713    }
714
715    /// Representation of named tuples the same as [unnamed tuples][Self::deserialize_tuple].
716    #[inline]
717    fn deserialize_tuple_struct<V>(
718        self,
719        _name: &'static str,
720        len: usize,
721        visitor: V,
722    ) -> Result<V::Value, DeError>
723    where
724        V: Visitor<'de>,
725    {
726        self.deserialize_tuple(len, visitor)
727    }
728
729    unsupported!(deserialize_map);
730    unsupported!(deserialize_struct(&'static str, &'static [&'static str]));
731
732    fn deserialize_enum<V>(
733        self,
734        _name: &'static str,
735        _variants: &'static [&'static str],
736        visitor: V,
737    ) -> Result<V::Value, Self::Error>
738    where
739        V: Visitor<'de>,
740    {
741        visitor.visit_enum(self)
742    }
743
744    /// Forwards deserialization to the [`Self::deserialize_str`]
745    #[inline]
746    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
747    where
748        V: Visitor<'de>,
749    {
750        self.deserialize_str(visitor)
751    }
752
753    #[inline]
754    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
755    where
756        V: Visitor<'de>,
757    {
758        visitor.visit_unit()
759    }
760}
761
762impl<'de, 'a> EnumAccess<'de> for SimpleTypeDeserializer<'de, 'a> {
763    type Error = DeError;
764    type Variant = UnitOnly;
765
766    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), DeError>
767    where
768        V: DeserializeSeed<'de>,
769    {
770        let name = seed.deserialize(self)?;
771        Ok((name, UnitOnly))
772    }
773}
774
775impl<'de, 'a> IntoDeserializer<'de, DeError> for SimpleTypeDeserializer<'de, 'a> {
776    type Deserializer = Self;
777
778    #[inline]
779    fn into_deserializer(self) -> Self {
780        self
781    }
782}
783
784////////////////////////////////////////////////////////////////////////////////////////////////////
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789    use crate::se::simple_type::{QuoteTarget, SimpleTypeSerializer};
790    use crate::se::QuoteLevel;
791    use crate::utils::{ByteBuf, Bytes};
792    use serde::de::IgnoredAny;
793    use serde::{Deserialize, Serialize};
794    use std::collections::HashMap;
795
796    macro_rules! simple_only {
797        ($encoding:ident, $name:ident: $type:ty = $xml:expr => $result:expr) => {
798            #[test]
799            fn $name() {
800                let decoder = Decoder::$encoding();
801                let xml = $xml;
802                let de = SimpleTypeDeserializer::new(CowRef::Input(xml.as_ref()), true, decoder);
803                let data: $type = Deserialize::deserialize(de).unwrap();
804
805                assert_eq!(data, $result);
806            }
807        };
808    }
809
810    macro_rules! simple {
811        ($encoding:ident, $name:ident: $type:ty = $xml:expr => $result:expr) => {
812            #[test]
813            fn $name() {
814                let decoder = Decoder::$encoding();
815                let xml = $xml;
816                let de = SimpleTypeDeserializer::new(CowRef::Input(xml.as_ref()), true, decoder);
817                let data: $type = Deserialize::deserialize(de).unwrap();
818
819                assert_eq!(data, $result);
820
821                // Roundtrip to ensure that serializer corresponds to deserializer
822                assert_eq!(
823                    data.serialize(SimpleTypeSerializer {
824                        writer: String::new(),
825                        target: QuoteTarget::Text,
826                        level: QuoteLevel::Full,
827                    })
828                    .unwrap(),
829                    xml
830                );
831            }
832        };
833    }
834
835    macro_rules! err {
836        ($encoding:ident, $name:ident: $type:ty = $xml:expr => $kind:ident($reason:literal)) => {
837            #[test]
838            fn $name() {
839                let decoder = Decoder::$encoding();
840                let xml = $xml;
841                let de = SimpleTypeDeserializer::new(CowRef::Input(xml.as_ref()), true, decoder);
842                let err = <$type as Deserialize>::deserialize(de).unwrap_err();
843
844                match err {
845                    DeError::$kind(e) => assert_eq!(e, $reason),
846                    _ => panic!(
847                        "Expected `Err({}({}))`, but got `{:?}`",
848                        stringify!($kind),
849                        $reason,
850                        err
851                    ),
852                }
853            }
854        };
855    }
856
857    #[derive(Debug, Deserialize, Serialize, PartialEq)]
858    struct Unit;
859
860    #[derive(Debug, Deserialize, Serialize, PartialEq)]
861    struct Newtype(String);
862
863    #[derive(Debug, Deserialize, Serialize, PartialEq)]
864    struct Tuple((), ());
865
866    #[derive(Debug, Deserialize, Serialize, PartialEq)]
867    struct BorrowedNewtype<'a>(&'a str);
868
869    #[derive(Debug, Deserialize, Serialize, PartialEq)]
870    struct Struct {
871        key: String,
872        val: usize,
873    }
874
875    #[derive(Debug, Deserialize, Serialize, PartialEq)]
876    enum Enum {
877        Unit,
878        Newtype(String),
879        Tuple(String, usize),
880        Struct { key: String, val: usize },
881    }
882
883    #[derive(Debug, Deserialize, PartialEq)]
884    #[serde(field_identifier)]
885    enum Id {
886        Field,
887    }
888
889    #[derive(Debug, Deserialize)]
890    #[serde(transparent)]
891    struct Any(IgnoredAny);
892    impl PartialEq for Any {
893        fn eq(&self, _other: &Any) -> bool {
894            true
895        }
896    }
897
898    /// Tests for deserialize atomic and union values, as defined in XSD specification
899    mod atomic {
900        use super::*;
901        use crate::se::simple_type::AtomicSerializer;
902        use pretty_assertions::assert_eq;
903        use std::ops::Deref;
904
905        /// Checks that given `$input` successfully deserializing into given `$result`
906        macro_rules! deserialized_to_only {
907            ($name:ident: $type:ty = $input:literal => $result:expr) => {
908                #[test]
909                fn $name() {
910                    let de = AtomicDeserializer {
911                        content: CowRef::Input($input),
912                        escaped: true,
913                    };
914                    let data: $type = Deserialize::deserialize(de).unwrap();
915
916                    assert_eq!(data, $result);
917                }
918            };
919        }
920
921        /// Checks that given `$input` successfully deserializing into given `$result`
922        /// and the result is serialized back to the `$input`
923        macro_rules! deserialized_to {
924            ($name:ident: $type:ty = $input:literal => $result:expr) => {
925                #[test]
926                fn $name() {
927                    let de = AtomicDeserializer {
928                        content: CowRef::Input($input),
929                        escaped: true,
930                    };
931                    let data: $type = Deserialize::deserialize(de).unwrap();
932
933                    assert_eq!(data, $result);
934
935                    // Roundtrip to ensure that serializer corresponds to deserializer
936                    let mut buffer = String::new();
937                    let has_written = data
938                        .serialize(AtomicSerializer {
939                            writer: &mut buffer,
940                            target: QuoteTarget::Text,
941                            level: QuoteLevel::Full,
942                            write_delimiter: false,
943                        })
944                        .unwrap();
945                    assert_eq!(buffer, $input);
946                    assert_eq!(has_written, !buffer.is_empty());
947                }
948            };
949        }
950
951        /// Checks that attempt to deserialize given `$input` as a `$type` results to a
952        /// deserialization error `$kind` with `$reason`
953        macro_rules! err {
954            ($name:ident: $type:ty = $input:literal => $kind:ident($reason:literal)) => {
955                #[test]
956                fn $name() {
957                    let de = AtomicDeserializer {
958                        content: CowRef::Input($input),
959                        escaped: true,
960                    };
961                    let err = <$type as Deserialize>::deserialize(de).unwrap_err();
962
963                    match err {
964                        DeError::$kind(e) => assert_eq!(e, $reason),
965                        _ => panic!(
966                            "Expected `Err({}({}))`, but got `{:?}`",
967                            stringify!($kind),
968                            $reason,
969                            err
970                        ),
971                    }
972                }
973            };
974        }
975
976        deserialized_to!(false_: bool = "false" => false);
977        deserialized_to!(true_: bool  = "true" => true);
978
979        deserialized_to!(i8_:  i8  = "-2" => -2);
980        deserialized_to!(i16_: i16 = "-2" => -2);
981        deserialized_to!(i32_: i32 = "-2" => -2);
982        deserialized_to!(i64_: i64 = "-2" => -2);
983
984        deserialized_to!(u8_:  u8  = "3" => 3);
985        deserialized_to!(u16_: u16 = "3" => 3);
986        deserialized_to!(u32_: u32 = "3" => 3);
987        deserialized_to!(u64_: u64 = "3" => 3);
988
989        serde_if_integer128! {
990            deserialized_to!(i128_: i128 = "-2" => -2);
991            deserialized_to!(u128_: u128 = "2" => 2);
992        }
993
994        deserialized_to!(f32_: f32 = "1.23" => 1.23);
995        deserialized_to!(f64_: f64 = "1.23" => 1.23);
996
997        deserialized_to!(char_unescaped: char = "h" => 'h');
998        deserialized_to!(char_escaped: char = "&lt;" => '<');
999
1000        deserialized_to!(string: String = "&lt;escaped&#32;string" => "<escaped string");
1001        // Serializer will escape space. Because borrowing has meaning only for deserializer,
1002        // no need to test roundtrip here, it is already tested with non-borrowing version
1003        deserialized_to_only!(borrowed_str: &str = "non-escaped string" => "non-escaped string");
1004        err!(escaped_str: &str = "escaped&#32;string"
1005                => Custom("invalid type: string \"escaped string\", expected a borrowed string"));
1006
1007        err!(byte_buf: ByteBuf = "&lt;escaped&#32;string"
1008                => Custom("invalid type: string \"<escaped string\", expected byte data"));
1009        err!(borrowed_bytes: Bytes = "non-escaped string"
1010                => Custom("invalid type: string \"non-escaped string\", expected borrowed bytes"));
1011
1012        deserialized_to!(option_none: Option<&str> = "" => None);
1013        deserialized_to!(option_some: Option<&str> = "non-escaped-string" => Some("non-escaped-string"));
1014
1015        deserialized_to_only!(unit: () = "<root>anything</root>" => ());
1016        deserialized_to_only!(unit_struct: Unit = "<root>anything</root>" => Unit);
1017
1018        deserialized_to!(newtype_owned: Newtype = "&lt;escaped&#32;string" => Newtype("<escaped string".into()));
1019        // Serializer will escape space. Because borrowing has meaning only for deserializer,
1020        // no need to test roundtrip here, it is already tested with non-borrowing version
1021        deserialized_to_only!(newtype_borrowed: BorrowedNewtype = "non-escaped string"
1022                => BorrowedNewtype("non-escaped string"));
1023
1024        err!(seq: Vec<()> = "non-escaped string"
1025                => Custom("invalid type: string \"non-escaped string\", expected a sequence"));
1026        err!(tuple: ((), ()) = "non-escaped string"
1027                => Custom("invalid type: string \"non-escaped string\", expected a tuple of size 2"));
1028        err!(tuple_struct: Tuple = "non-escaped string"
1029                => Custom("invalid type: string \"non-escaped string\", expected tuple struct Tuple"));
1030
1031        err!(map: HashMap<(), ()> = "non-escaped string"
1032                => Custom("invalid type: string \"non-escaped string\", expected a map"));
1033        err!(struct_: Struct = "non-escaped string"
1034                => Custom("invalid type: string \"non-escaped string\", expected struct Struct"));
1035
1036        deserialized_to!(enum_unit: Enum = "Unit" => Enum::Unit);
1037        err!(enum_newtype: Enum = "Newtype"
1038                => Custom("invalid type: unit value, expected a string"));
1039        err!(enum_tuple: Enum = "Tuple"
1040                => Custom("invalid type: unit value, expected tuple variant Enum::Tuple"));
1041        err!(enum_struct: Enum = "Struct"
1042                => Custom("invalid type: unit value, expected struct variant Enum::Struct"));
1043        err!(enum_other: Enum = "any data"
1044                => Custom("unknown variant `any data`, expected one of `Unit`, `Newtype`, `Tuple`, `Struct`"));
1045
1046        deserialized_to_only!(identifier: Id = "Field" => Id::Field);
1047        deserialized_to_only!(ignored_any: Any = "any data" => Any(IgnoredAny));
1048
1049        /// Checks that deserialization from an owned content is working
1050        #[test]
1051        #[cfg(feature = "encoding")]
1052        fn owned_data() {
1053            let de = AtomicDeserializer {
1054                content: CowRef::Owned("string slice".into()),
1055                escaped: true,
1056            };
1057            assert_eq!(de.content.deref(), "string slice");
1058
1059            let data: String = Deserialize::deserialize(de).unwrap();
1060            assert_eq!(data, "string slice");
1061        }
1062
1063        /// Checks that deserialization from a content borrowed from some
1064        /// buffer other that input is working
1065        #[test]
1066        fn borrowed_from_deserializer() {
1067            let de = AtomicDeserializer {
1068                content: CowRef::Slice("string slice"),
1069                escaped: true,
1070            };
1071            assert_eq!(de.content.deref(), "string slice");
1072
1073            let data: String = Deserialize::deserialize(de).unwrap();
1074            assert_eq!(data, "string slice");
1075        }
1076    }
1077
1078    /// Module for testing list accessor
1079    mod list {
1080        use super::*;
1081        use pretty_assertions::assert_eq;
1082
1083        #[test]
1084        fn empty() {
1085            let mut seq = ListIter {
1086                content: Some(Content::Input("")),
1087                escaped: true,
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 only_spaces() {
1096            let mut seq = ListIter {
1097                content: Some(Content::Input("  ")),
1098                escaped: true,
1099            };
1100
1101            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1102            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1103        }
1104
1105        #[test]
1106        fn one_item() {
1107            let mut seq = ListIter {
1108                content: Some(Content::Input("abc")),
1109                escaped: true,
1110            };
1111
1112            assert_eq!(seq.next_element::<&str>().unwrap(), Some("abc"));
1113            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1114            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1115        }
1116
1117        #[test]
1118        fn two_items() {
1119            let mut seq = ListIter {
1120                content: Some(Content::Input("abc def")),
1121                escaped: true,
1122            };
1123
1124            assert_eq!(seq.next_element::<&str>().unwrap(), Some("abc"));
1125            assert_eq!(seq.next_element::<&str>().unwrap(), Some("def"));
1126            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1127            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1128        }
1129
1130        #[test]
1131        fn leading_spaces() {
1132            let mut seq = ListIter {
1133                content: Some(Content::Input("  def")),
1134                escaped: true,
1135            };
1136
1137            assert_eq!(seq.next_element::<&str>().unwrap(), Some("def"));
1138            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1139            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1140        }
1141
1142        #[test]
1143        fn trailing_spaces() {
1144            let mut seq = ListIter {
1145                content: Some(Content::Input("abc  ")),
1146                escaped: true,
1147            };
1148
1149            assert_eq!(seq.next_element::<&str>().unwrap(), Some("abc"));
1150            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1151            assert_eq!(seq.next_element::<&str>().unwrap(), None);
1152        }
1153
1154        #[test]
1155        fn mixed_types() {
1156            let mut seq = ListIter {
1157                content: Some(Content::Input("string 1.23 42 true false h Unit")),
1158                escaped: true,
1159            };
1160
1161            assert_eq!(seq.next_element::<&str>().unwrap(), Some("string"));
1162            assert_eq!(seq.next_element::<f32>().unwrap(), Some(1.23));
1163            assert_eq!(seq.next_element::<u32>().unwrap(), Some(42));
1164            assert_eq!(seq.next_element::<bool>().unwrap(), Some(true));
1165            assert_eq!(seq.next_element::<bool>().unwrap(), Some(false));
1166            assert_eq!(seq.next_element::<char>().unwrap(), Some('h'));
1167            assert_eq!(seq.next_element::<Enum>().unwrap(), Some(Enum::Unit));
1168            assert_eq!(seq.next_element::<()>().unwrap(), None);
1169            assert_eq!(seq.next_element::<()>().unwrap(), None);
1170        }
1171    }
1172
1173    mod utf8 {
1174        use super::*;
1175        use pretty_assertions::assert_eq;
1176
1177        simple!(utf8, i8_:  i8  = "-2" => -2);
1178        simple!(utf8, i16_: i16 = "-2" => -2);
1179        simple!(utf8, i32_: i32 = "-2" => -2);
1180        simple!(utf8, i64_: i64 = "-2" => -2);
1181
1182        simple!(utf8, u8_:  u8  = "3" => 3);
1183        simple!(utf8, u16_: u16 = "3" => 3);
1184        simple!(utf8, u32_: u32 = "3" => 3);
1185        simple!(utf8, u64_: u64 = "3" => 3);
1186
1187        serde_if_integer128! {
1188            simple!(utf8, i128_: i128 = "-2" => -2);
1189            simple!(utf8, u128_: u128 = "2" => 2);
1190        }
1191
1192        simple!(utf8, f32_: f32 = "1.23" => 1.23);
1193        simple!(utf8, f64_: f64 = "1.23" => 1.23);
1194
1195        simple!(utf8, false_: bool = "false" => false);
1196        simple!(utf8, true_: bool  = "true" => true);
1197        simple!(utf8, char_unescaped: char = "h" => 'h');
1198        simple!(utf8, char_escaped: char = "&lt;" => '<');
1199
1200        simple!(utf8, string: String = "&lt;escaped string" => "<escaped string");
1201        err!(utf8, byte_buf: ByteBuf = "&lt;escaped&#32;string"
1202             => Custom("invalid type: string \"<escaped string\", expected byte data"));
1203
1204        simple!(utf8, borrowed_str: &str = "non-escaped string" => "non-escaped string");
1205        err!(utf8, borrowed_bytes: Bytes = "&lt;escaped&#32;string"
1206             => Custom("invalid type: string \"<escaped string\", expected borrowed bytes"));
1207
1208        simple!(utf8, option_none: Option<&str> = "" => Some(""));
1209        simple!(utf8, option_some: Option<&str> = "non-escaped string" => Some("non-escaped string"));
1210
1211        simple_only!(utf8, unit: () = "any data" => ());
1212        simple_only!(utf8, unit_struct: Unit = "any data" => Unit);
1213
1214        // Serializer will not escape space because this is unnecessary.
1215        // Because borrowing has meaning only for deserializer, no need to test
1216        // roundtrip here, it is already tested for strings where compatible list
1217        // of escaped characters is used
1218        simple_only!(utf8, newtype_owned: Newtype = "&lt;escaped&#32;string"
1219            => Newtype("<escaped string".into()));
1220        simple_only!(utf8, newtype_borrowed: BorrowedNewtype = "non-escaped string"
1221            => BorrowedNewtype("non-escaped string"));
1222
1223        err!(utf8, map: HashMap<(), ()> = "any data"
1224             => Custom("invalid type: string \"any data\", expected a map"));
1225        err!(utf8, struct_: Struct = "any data"
1226             => Custom("invalid type: string \"any data\", expected struct Struct"));
1227
1228        simple!(utf8, enum_unit: Enum = "Unit" => Enum::Unit);
1229        err!(utf8, enum_newtype: Enum = "Newtype"
1230             => Custom("invalid type: unit value, expected a string"));
1231        err!(utf8, enum_tuple: Enum = "Tuple"
1232             => Custom("invalid type: unit value, expected tuple variant Enum::Tuple"));
1233        err!(utf8, enum_struct: Enum = "Struct"
1234             => Custom("invalid type: unit value, expected struct variant Enum::Struct"));
1235        err!(utf8, enum_other: Enum = "any data"
1236             => Custom("unknown variant `any data`, expected one of `Unit`, `Newtype`, `Tuple`, `Struct`"));
1237
1238        simple_only!(utf8, identifier: Id = "Field" => Id::Field);
1239        simple_only!(utf8, ignored_any: Any = "any data" => Any(IgnoredAny));
1240    }
1241
1242    #[cfg(feature = "encoding")]
1243    mod utf16 {
1244        use super::*;
1245        use pretty_assertions::assert_eq;
1246
1247        fn to_utf16(string: &str) -> Vec<u8> {
1248            let mut bytes = Vec::new();
1249            for ch in string.encode_utf16() {
1250                bytes.extend_from_slice(&ch.to_le_bytes());
1251            }
1252            bytes
1253        }
1254
1255        macro_rules! utf16 {
1256            ($name:ident: $type:ty = $xml:literal => $result:expr) => {
1257                simple_only!(utf16, $name: $type = to_utf16($xml) => $result);
1258            };
1259        }
1260
1261        macro_rules! unsupported {
1262            ($name:ident: $type:ty = $xml:literal => $err:literal) => {
1263                err!(utf16, $name: $type = to_utf16($xml) => Custom($err));
1264            };
1265        }
1266
1267        utf16!(i8_:  i8  = "-2" => -2);
1268        utf16!(i16_: i16 = "-2" => -2);
1269        utf16!(i32_: i32 = "-2" => -2);
1270        utf16!(i64_: i64 = "-2" => -2);
1271
1272        utf16!(u8_:  u8  = "3" => 3);
1273        utf16!(u16_: u16 = "3" => 3);
1274        utf16!(u32_: u32 = "3" => 3);
1275        utf16!(u64_: u64 = "3" => 3);
1276
1277        serde_if_integer128! {
1278            utf16!(i128_: i128 = "-2" => -2);
1279            utf16!(u128_: u128 = "2" => 2);
1280        }
1281
1282        utf16!(f32_: f32 = "1.23" => 1.23);
1283        utf16!(f64_: f64 = "1.23" => 1.23);
1284
1285        utf16!(false_: bool = "false" => false);
1286        utf16!(true_: bool  = "true" => true);
1287        utf16!(char_unescaped: char = "h" => 'h');
1288        utf16!(char_escaped: char = "&lt;" => '<');
1289
1290        utf16!(string: String = "&lt;escaped&#32;string" => "<escaped string");
1291        unsupported!(borrowed_bytes: Bytes = "&lt;escaped&#32;string"
1292                    => "invalid type: string \"<escaped string\", expected borrowed bytes");
1293
1294        utf16!(option_none: Option<()> = "" => Some(()));
1295        utf16!(option_some: Option<()> = "any data" => Some(()));
1296
1297        utf16!(unit: () = "any data" => ());
1298        utf16!(unit_struct: Unit = "any data" => Unit);
1299
1300        utf16!(newtype_owned: Newtype = "&lt;escaped&#32;string" => Newtype("<escaped string".into()));
1301
1302        // UTF-16 data never borrow because data was decoded not in-place
1303        unsupported!(newtype_borrowed: BorrowedNewtype = "non-escaped string"
1304                    => "invalid type: string \"non-escaped string\", expected a borrowed string");
1305
1306        unsupported!(map: HashMap<(), ()> = "any data"
1307                    => "invalid type: string \"any data\", expected a map");
1308        unsupported!(struct_: Struct = "any data"
1309                    => "invalid type: string \"any data\", expected struct Struct");
1310
1311        utf16!(enum_unit: Enum = "Unit" => Enum::Unit);
1312        unsupported!(enum_newtype: Enum = "Newtype"
1313                    => "invalid type: unit value, expected a string");
1314        unsupported!(enum_tuple: Enum = "Tuple"
1315                    => "invalid type: unit value, expected tuple variant Enum::Tuple");
1316        unsupported!(enum_struct: Enum = "Struct"
1317                    => "invalid type: unit value, expected struct variant Enum::Struct");
1318        unsupported!(enum_other: Enum = "any data"
1319                    => "unknown variant `any data`, expected one of `Unit`, `Newtype`, `Tuple`, `Struct`");
1320
1321        utf16!(identifier: Id = "Field" => Id::Field);
1322        utf16!(ignored_any: Any = "any data" => Any(IgnoredAny));
1323    }
1324}