Skip to main content

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