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