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