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