quick_xml/de/
text.rs

1use crate::{
2    de::simple_type::SimpleTypeDeserializer,
3    de::{str2bool, Text, TEXT_KEY},
4    errors::serialize::DeError,
5};
6use serde::de::value::BorrowedStrDeserializer;
7use serde::de::{DeserializeSeed, Deserializer, EnumAccess, VariantAccess, Visitor};
8use serde::serde_if_integer128;
9use std::borrow::Cow;
10
11/// A deserializer for a single text node of a mixed sequence of tags and text.
12///
13/// This deserializer are very similar to a [`MapValueDeserializer`] (when it
14/// processes the [`DeEvent::Text`] event). The only difference in the
15/// `deserialize_seq` method. This deserializer will perform deserialization
16/// from a textual content, whereas the [`MapValueDeserializer`] will iterate
17/// over tags / text within it's parent tag.
18///
19/// This deserializer processes items as following:
20/// - numbers are parsed from a text content using [`FromStr`];
21/// - booleans converted from the text according to the XML [specification]:
22///   - `"true"` and `"1"` converted to `true`;
23///   - `"false"` and `"0"` converted to `false`;
24/// - strings returned as is;
25/// - characters also returned as strings. If string contain more than one character
26///   or empty, it is responsibility of a type to return an error;
27/// - `Option`:
28///   - empty text is deserialized as `None`;
29///   - everything else is deserialized as `Some` using the same deserializer;
30/// - units (`()`) and unit structs always deserialized successfully;
31/// - newtype structs forwards deserialization to the inner type using the same
32///   deserializer;
33/// - sequences, tuples and tuple structs are deserialized using [`SimpleTypeDeserializer`]
34///   (this is the difference): text content passed to the deserializer directly;
35/// - structs and maps calls [`Visitor::visit_borrowed_str`] or [`Visitor::visit_string`],
36///   it is responsibility of the type to return an error if it do not able to process
37///   this data;
38/// - enums:
39///   - the variant name is deserialized as `$text`;
40///   - the content is deserialized using the same deserializer:
41///     - unit variants: just return `()`;
42///     - newtype variants forwards deserialization to the inner type using the
43///       same deserializer;
44///     - tuple and struct variants are deserialized using [`SimpleTypeDeserializer`].
45///
46/// [`MapValueDeserializer`]: ../map/struct.MapValueDeserializer.html
47/// [`DeEvent::Text`]: crate::de::DeEvent::Text
48/// [`FromStr`]: std::str::FromStr
49/// [specification]: https://www.w3.org/TR/xmlschema11-2/#boolean
50pub struct TextDeserializer<'de>(pub Text<'de>);
51
52impl<'de> TextDeserializer<'de> {
53    /// Returns a next string as concatenated content of consequent [`Text`] and
54    /// [`CData`] events, used inside [`deserialize_primitives!()`].
55    ///
56    /// [`Text`]: crate::events::Event::Text
57    /// [`CData`]: crate::events::Event::CData
58    #[inline]
59    fn read_string(self) -> Result<Cow<'de, str>, DeError> {
60        Ok(self.0.text)
61    }
62}
63
64impl<'de> Deserializer<'de> for TextDeserializer<'de> {
65    type Error = DeError;
66
67    deserialize_primitives!();
68
69    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
70    where
71        V: Visitor<'de>,
72    {
73        visitor.visit_unit()
74    }
75
76    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
77    where
78        V: Visitor<'de>,
79    {
80        if self.0.is_empty() {
81            visitor.visit_none()
82        } else {
83            visitor.visit_some(self)
84        }
85    }
86
87    /// Forwards deserialization of the inner type. Always calls [`Visitor::visit_newtype_struct`]
88    /// with this deserializer.
89    fn deserialize_newtype_struct<V>(
90        self,
91        _name: &'static str,
92        visitor: V,
93    ) -> Result<V::Value, Self::Error>
94    where
95        V: Visitor<'de>,
96    {
97        visitor.visit_newtype_struct(self)
98    }
99
100    /// This method deserializes a sequence inside of element that itself is a
101    /// sequence element:
102    ///
103    /// ```xml
104    /// <>
105    ///   ...
106    ///   inner sequence as xs:list
107    ///   ...
108    /// </>
109    /// ```
110    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
111    where
112        V: Visitor<'de>,
113    {
114        SimpleTypeDeserializer::from_text_content(self.0).deserialize_seq(visitor)
115    }
116
117    #[inline]
118    fn deserialize_struct<V>(
119        self,
120        _name: &'static str,
121        _fields: &'static [&'static str],
122        visitor: V,
123    ) -> Result<V::Value, Self::Error>
124    where
125        V: Visitor<'de>,
126    {
127        // Deserializer methods are only hints, if deserializer could not satisfy
128        // request, it should return the data that it has. It is responsibility
129        // of a Visitor to return an error if it does not understand the data
130        self.deserialize_str(visitor)
131    }
132
133    fn deserialize_enum<V>(
134        self,
135        _name: &'static str,
136        _variants: &'static [&'static str],
137        visitor: V,
138    ) -> Result<V::Value, Self::Error>
139    where
140        V: Visitor<'de>,
141    {
142        visitor.visit_enum(self)
143    }
144
145    #[inline]
146    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
147    where
148        V: Visitor<'de>,
149    {
150        self.deserialize_str(visitor)
151    }
152}
153
154impl<'de> EnumAccess<'de> for TextDeserializer<'de> {
155    type Error = DeError;
156    type Variant = Self;
157
158    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
159    where
160        V: DeserializeSeed<'de>,
161    {
162        let name = seed.deserialize(BorrowedStrDeserializer::<DeError>::new(TEXT_KEY))?;
163        Ok((name, self))
164    }
165}
166
167impl<'de> VariantAccess<'de> for TextDeserializer<'de> {
168    type Error = DeError;
169
170    #[inline]
171    fn unit_variant(self) -> Result<(), Self::Error> {
172        Ok(())
173    }
174
175    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
176    where
177        T: DeserializeSeed<'de>,
178    {
179        seed.deserialize(self)
180    }
181
182    #[inline]
183    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
184    where
185        V: Visitor<'de>,
186    {
187        self.deserialize_tuple(len, visitor)
188    }
189
190    #[inline]
191    fn struct_variant<V>(
192        self,
193        fields: &'static [&'static str],
194        visitor: V,
195    ) -> Result<V::Value, Self::Error>
196    where
197        V: Visitor<'de>,
198    {
199        self.deserialize_struct("", fields, visitor)
200    }
201}