rapid_xml/
de.rs

1//! Contains serde Deserializer build on top of `Parser` from `parse`.
2
3use std::fmt::Display;
4use std::io::Read;
5
6use inlinable_string::InlinableString;
7use serde::{Deserializer as _, forward_to_deserialize_any};
8use serde::de::{DeserializeSeed, IntoDeserializer, Visitor};
9
10use crate::parser::{Event, EventCode, ParseError, Parser, DecodeError};
11
12/// Error while parsing or deserializing
13#[derive(Debug)]
14pub enum DeserializeError {
15    /// Error from underlying parser
16    Parsing(ParseError),
17
18    /// Error decoding string
19    Decoding(DecodeError),
20
21    /// Error parsing integer
22    ParseInt(btoi::ParseIntegerError),
23
24    /// Error parsing floating point number
25    ParseFloat(std::num::ParseFloatError),
26
27    /// Error parsing bool
28    ParseBool(std::str::ParseBoolError),
29
30    /// Error deserializing character - there was none or too many characters
31    NotOneCharacter,
32
33    /// EOF came too early.
34    UnexpectedEof,
35
36    /// Deserializer was expecting an element, but found something else
37    ExpectedElement,
38
39    /// Deserializer was expecting text, but found none
40    ExpectedText,
41
42    /// Deserializer was not expecting end tag, but it came
43    UnexpectedEndTag,
44
45    /// Custom error from Serde
46    Custom(String),
47}
48
49impl Display for DeserializeError {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
51        match self {
52            DeserializeError::Parsing(err) => Display::fmt(err, f),
53            DeserializeError::Decoding(err) => Display::fmt(err, f),
54            DeserializeError::ParseInt(err) => Display::fmt(err, f),
55            DeserializeError::ParseFloat(err) => Display::fmt(err, f),
56            DeserializeError::ParseBool(err) => Display::fmt(err, f),
57            DeserializeError::NotOneCharacter => write!(f, "Expected character, but found string with more or less than 1 character."),
58            DeserializeError::UnexpectedEof => write!(f, "Unexpected EOF."),
59            DeserializeError::ExpectedElement => write!(f, "Expected element, but found something else."),
60            DeserializeError::ExpectedText => write!(f, "Expected text, but found none."),
61            DeserializeError::UnexpectedEndTag => write!(f, "Unexpected end tag."),
62            DeserializeError::Custom(string) => write!(f, "{}", string),
63        }
64    }
65}
66
67impl std::error::Error for DeserializeError {}
68
69impl From<ParseError> for DeserializeError {
70    fn from(err: ParseError) -> Self {
71        DeserializeError::Parsing(err)
72    }
73}
74
75impl From<DecodeError> for DeserializeError {
76    fn from(err: DecodeError) -> Self {
77        DeserializeError::Decoding(err)
78    }
79}
80
81impl From<btoi::ParseIntegerError> for DeserializeError {
82    fn from(err: btoi::ParseIntegerError) -> Self {
83        DeserializeError::ParseInt(err)
84    }
85}
86
87impl From<std::num::ParseFloatError> for DeserializeError {
88    fn from(err: std::num::ParseFloatError) -> Self {
89        DeserializeError::ParseFloat(err)
90    }
91}
92
93impl From<std::str::ParseBoolError> for DeserializeError {
94    fn from(err: std::str::ParseBoolError) -> Self {
95        DeserializeError::ParseBool(err)
96    }
97}
98
99impl serde::de::Error for DeserializeError {
100    fn custom<T: std::fmt::Display>(msg: T) -> Self {
101        DeserializeError::Custom(msg.to_string())
102    }
103}
104
105/// Serde `Deserializer` that builds types from XML [`Event`]s produced by [`Parser`]
106pub struct Deserializer<'a, R: Read> {
107    parser: &'a mut Parser<R>,
108    opening_tag: InlinableString,
109    only_attributes: bool,
110}
111
112impl<'a, R: Read> Deserializer<'a, R> {
113    /// Create new `TreeDeserializer` from given `Parser`.
114    pub fn new(parser: &'a mut Parser<R>) -> Result<Self, DeserializeError> {
115        // Enter the root element
116        loop {
117            let mut event = parser.next()?;
118            match event.code() {
119                EventCode::StartTag => {
120                    let opening_tag = event.get_str()?.into();
121                    return Ok(Self::new_inside_tag(parser, opening_tag, false));
122                }
123
124                EventCode::Text => {
125                    /* Text before the first tag, we ignore it... */
126                }
127
128                _ => {
129                    return Err(DeserializeError::ExpectedElement);
130                }
131            }
132        }
133    }
134
135    // TODO: Should we expose something like this to public?
136    pub(crate) fn new_inside_tag(parser: &'a mut Parser<R>, opening_tag: InlinableString, only_attributes: bool) -> Self {
137        Self {
138            parser,
139            opening_tag,
140            only_attributes,
141        }
142    }
143
144    /// Call given callback on the next `Text` event
145    fn with_next_text<'x: 'a, F: FnOnce(Event) -> Result<O, DeserializeError>, O>(&'x mut self, f: F) -> Result<O, DeserializeError> {
146        let mut depth = 1;
147        while depth > 0 {
148            let event = self.parser.next()?;
149            match event.code() {
150                EventCode::StartTag => depth += 1,
151                EventCode::EndTag | EventCode::EndTagImmediate => depth -= 1,
152                EventCode::AttributeName | EventCode::AttributeValue => { /*NOOP*/ },
153                EventCode::Text => {
154                    let out = f(event);
155                    self.parser.finish_tag(depth)?;
156                    return out;
157                }
158                EventCode::Eof => break,
159            }
160        }
161
162        Err(DeserializeError::ExpectedText)
163    }
164}
165
166impl<'de: 'a, 'a, R: Read> serde::Deserializer<'de> for &'a mut Deserializer<'a, R> {
167    type Error = DeserializeError;
168
169    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
170        self.deserialize_str(visitor)
171    }
172
173    fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
174        // TODO: Do we want to accept other strings in addition to "true" and "false"?
175        self.with_next_text(|mut e| visitor.visit_bool(e.get_str()?.parse()?))
176    }
177
178    fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
179        self.with_next_text(|mut e| visitor.visit_i8(btoi::btoi(e.get_bytes()?)?))
180    }
181
182    fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
183        self.with_next_text(|mut e| visitor.visit_i16(btoi::btoi(e.get_bytes()?)?))
184    }
185
186    fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
187        self.with_next_text(|mut e| visitor.visit_i32(btoi::btoi(e.get_bytes()?)?))
188    }
189
190    fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
191        self.with_next_text(|mut e| visitor.visit_i64(btoi::btoi(e.get_bytes()?)?))
192    }
193
194    fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
195        self.with_next_text(|mut e| visitor.visit_u8(btoi::btou(e.get_bytes()?)?))
196    }
197
198    fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
199        self.with_next_text(|mut e| visitor.visit_u16(btoi::btou(e.get_bytes()?)?))
200    }
201
202    fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
203        self.with_next_text(|mut e| visitor.visit_u32(btoi::btou(e.get_bytes()?)?))
204    }
205
206    fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
207        self.with_next_text(|mut e| visitor.visit_u64(btoi::btou(e.get_bytes()?)?))
208    }
209
210    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
211        self.with_next_text(|mut e| visitor.visit_f32(e.get_str()?.parse()?))
212    }
213
214    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
215        self.with_next_text(|mut e| visitor.visit_f64(e.get_str()?.parse()?))
216    }
217
218    fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
219        self.with_next_text(|mut e| {
220            let string = e.get_str()?;
221            if string.len() == 1 {
222                visitor.visit_char(string.chars().next().unwrap()) // NOTE(unwrap): We know there is exactly one character.
223            } else {
224                Err(DeserializeError::NotOneCharacter)
225            }
226        })
227    }
228
229    fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
230        self.deserialize_string(visitor)
231    }
232
233    fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
234        self.with_next_text(|mut e| {
235            visitor.visit_str(e.get_str()?)
236        })
237    }
238
239    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
240        self.with_next_text(|mut event| {
241            visitor.visit_bytes(event.get_bytes()?)
242        })
243    }
244
245    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
246        self.deserialize_bytes(visitor)
247    }
248
249    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
250        // We don't really have a "null" value. The only `Option`s that will work are for map keys that are
251        // not present. If someone is trying to deserialize `Option` in other place, then we will always give
252        // `Some` and try to deserialize the content.
253        visitor.visit_some(self)
254    }
255
256    fn deserialize_unit<V: Visitor<'de>>(self, _visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
257        unimplemented!()
258    }
259
260    fn deserialize_unit_struct<V: Visitor<'de>>(self, _name: &'static str, _visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
261        unimplemented!()
262    }
263
264    fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, _visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
265        unimplemented!()
266    }
267
268    fn deserialize_seq<V: Visitor<'de>>(self, _visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
269        unimplemented!()
270    }
271
272    fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, _visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
273        unimplemented!()
274    }
275
276    fn deserialize_tuple_struct<V: Visitor<'de>>(self, _name: &'static str, _len: usize, _visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
277        unimplemented!()
278    }
279
280    fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
281        struct MapAccess<'a, R: Read> {
282            parser: &'a mut Parser<R>,
283            in_tag: Option<InlinableString>,
284            only_attributes: bool,
285        }
286
287        impl<'a, 'de: 'a, R: Read> serde::de::MapAccess<'de> for MapAccess<'a, R> {
288            type Error = DeserializeError;
289
290            fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<<K as DeserializeSeed<'de>>::Value>, Self::Error> {
291                loop {
292                    let mut event = self.parser.peek()?;
293                    return match event.code() {
294                        EventCode::AttributeName => {
295                            let out = seed.deserialize(event.get_str()?.into_deserializer()).map(Some);
296                            let _ = self.parser.next(); // Consume the event (we know there is no error, if there was, we would get it in peek)
297                            out
298                        }
299                        EventCode::StartTag => {
300                            if self.only_attributes {
301                                return Ok(None);
302                            }
303
304                            let tag_name: InlinableString = event.get_str()?.into();
305                            let out = seed.deserialize(tag_name.into_deserializer()).map(Some);
306                            self.in_tag = Some(tag_name);
307                            let _ = self.parser.next(); // Consume the event (we know there is no error, if there was, we would get it in peek)
308                            out
309                        }
310                        EventCode::EndTag | EventCode::EndTagImmediate => {
311                            if !self.only_attributes {
312                                let _ = self.parser.next(); // Consume the event (we know there is no error, if there was, we would get it in peek)
313                            }
314                            Ok(None)
315                        },
316                        _ => {
317                            if self.only_attributes {
318                                Ok(None)
319                            } else {
320                                let _ = self.parser.next(); // Consume the event (we know there is no error, if there was, we would get it in peek)
321                                continue;
322                            }
323                        },
324                    };
325                }
326            }
327
328            fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<<V as DeserializeSeed<'de>>::Value, Self::Error> {
329                if let Some(tag_name) = self.in_tag.take() {
330                    return seed.deserialize(&mut Deserializer {
331                        parser: self.parser,
332                        opening_tag: tag_name,
333                        only_attributes: self.only_attributes, // Should be true at this point.
334                    });
335                }
336
337                let event = self.parser.next()?;
338                match event.code() {
339                    EventCode::AttributeValue =>
340                        seed.deserialize(ParseDeserializer {
341                            value_event: event,
342                        }),
343                    e => unreachable!("Parser should have never given us {:?} event in this place.", e),
344                }
345            }
346        }
347
348        visitor.visit_map(MapAccess {
349            parser: &mut *self.parser,
350            in_tag: None,
351            only_attributes: self.only_attributes,
352        })
353    }
354
355    fn deserialize_struct<V: Visitor<'de>>(self, _name: &'static str, _fields: &'static [&'static str], visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
356        self.deserialize_map(visitor)
357    }
358
359    fn deserialize_enum<V: Visitor<'de>>(self, _name: &'static str, _variants: &'static [&'static str], visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
360        struct EnumAccess<'a, R: Read> {
361            parser: &'a mut Parser<R>,
362            opening_tag: InlinableString,
363        }
364
365        impl<'a, 'de: 'a, R: Read> serde::de::EnumAccess<'de> for EnumAccess<'a, R> {
366            type Error = DeserializeError;
367            type Variant = Self;
368
369            fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(<V as DeserializeSeed<'de>>::Value, Self::Variant), Self::Error> {
370                seed.deserialize(&mut Deserializer {
371                    parser: self.parser,
372                    opening_tag: self.opening_tag.clone(),
373                    only_attributes: false,
374                }).map(|value| (value, self))
375            }
376        }
377
378        impl<'a, 'de: 'a, R: Read> serde::de::VariantAccess<'de> for EnumAccess<'a, R> {
379            type Error = DeserializeError;
380
381            fn unit_variant(self) -> Result<(), Self::Error> {
382                self.parser.finish_tag(1)?; // ?
383
384                Ok(())
385            }
386
387            fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<<T as DeserializeSeed<'de>>::Value, Self::Error> {
388                let deserializer = &mut Deserializer {
389                    parser: self.parser,
390                    opening_tag: self.opening_tag,
391                    only_attributes: false,
392                };
393                seed.deserialize(deserializer)
394            }
395
396            fn tuple_variant<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
397                let deserializer = &mut Deserializer {
398                    parser: self.parser,
399                    opening_tag: self.opening_tag,
400                    only_attributes: false,
401                };
402                deserializer.deserialize_seq(visitor)
403            }
404
405            fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
406                let deserializer = &mut Deserializer {
407                    parser: self.parser,
408                    opening_tag: self.opening_tag,
409                    only_attributes: false,
410                };
411                deserializer.deserialize_struct("", fields, visitor)
412            }
413        }
414
415        visitor.visit_enum(EnumAccess {
416            parser: self.parser,
417            opening_tag: self.opening_tag.clone(),
418        })
419    }
420
421    fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
422        visitor.visit_str(&self.opening_tag)
423    }
424
425    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
426        self.parser.finish_tag(1)?;
427
428        visitor.visit_unit()
429    }
430}
431
432struct ParseDeserializer<'a> {
433    value_event: Event<'a>,
434}
435
436impl<'de: 'a, 'a> serde::Deserializer<'de> for ParseDeserializer<'a> {
437    type Error = DeserializeError;
438
439    fn deserialize_any<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
440        visitor.visit_str(self.value_event.get_str()?)
441    }
442
443    fn deserialize_bool<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
444        // TODO: Do we want to accept other strings in addition to "true" and "false"?
445        visitor.visit_bool(self.value_event.get_str()?.parse()?)
446    }
447
448    fn deserialize_i8<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
449        visitor.visit_i8(btoi::btoi(self.value_event.get_bytes()?)?)
450    }
451
452    fn deserialize_i16<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
453        visitor.visit_i16(btoi::btoi(self.value_event.get_bytes()?)?)
454    }
455
456    fn deserialize_i32<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
457        visitor.visit_i32(btoi::btoi(self.value_event.get_bytes()?)?)
458    }
459
460    fn deserialize_i64<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
461        visitor.visit_i64(btoi::btoi(self.value_event.get_bytes()?)?)
462    }
463
464    fn deserialize_u8<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
465        visitor.visit_u8(btoi::btou(self.value_event.get_bytes()?)?)
466    }
467
468    fn deserialize_u16<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
469        visitor.visit_u16(btoi::btou(self.value_event.get_bytes()?)?)
470    }
471
472    fn deserialize_u32<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
473        visitor.visit_u32(btoi::btou(self.value_event.get_bytes()?)?)
474    }
475
476    fn deserialize_u64<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
477        visitor.visit_u64(btoi::btou(self.value_event.get_bytes()?)?)
478    }
479
480    fn deserialize_f32<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
481        visitor.visit_f32(self.value_event.get_str()?.parse()?)
482    }
483
484    fn deserialize_f64<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
485        visitor.visit_f64(self.value_event.get_str()?.parse()?)
486    }
487
488    fn deserialize_char<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
489        let s = self.value_event.get_str()?;
490        if s.len() == 1 {
491            visitor.visit_char(s.chars().next().unwrap()) // NOTE(unwrap): We know there is exactly one character.
492        } else {
493            Err(DeserializeError::NotOneCharacter)
494        }
495    }
496
497    fn deserialize_str<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
498        visitor.visit_str(self.value_event.get_str()?)
499    }
500
501    fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
502        self.deserialize_str(visitor)
503    }
504
505    fn deserialize_bytes<V: Visitor<'de>>(mut self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
506        visitor.visit_bytes(self.value_event.get_bytes()?)
507    }
508
509    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
510        self.deserialize_bytes(visitor)
511    }
512
513    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
514        // We don't really have a "null" value. The only `Option`s that will work are for map keys that are
515        // not present. If someone is trying to deserialize `Option` in other place, then we will always give
516        // `Some` and try to deserialize the content.
517        visitor.visit_some(self)
518    }
519
520    forward_to_deserialize_any! { unit unit_struct newtype_struct seq tuple tuple_struct map struct enum }
521
522    fn deserialize_identifier<V: Visitor<'de>>(self, _visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
523        unimplemented!()
524    }
525
526    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<<V as Visitor<'de>>::Value, Self::Error> {
527        visitor.visit_unit()
528    }
529}
530
531#[cfg(test)]
532mod tests {
533    use std::io::Cursor;
534
535    use serde::Deserialize as _;
536    use serde_derive::Deserialize;
537
538    use super::*;
539
540    #[test]
541    fn test_deserializer() {
542        #[derive(Clone, Debug, Deserialize, PartialEq)]
543        struct MyStruct {
544            a_string: String,
545            a_opt_string_none: Option<String>,
546            a_opt_string_some: Option<String>,
547
548            t_string: String,
549            t_opt_string_none: Option<String>,
550            t_opt_string_some: Option<String>,
551
552            a_u32: u32,
553            a_opt_u32_none: Option<u32>,
554            a_opt_u32_some: Option<u32>,
555
556            t_u32: u32,
557            t_opt_u32_none: Option<u32>,
558            t_opt_u32_some: Option<u32>,
559
560            a_i8: i8,
561            a_opt_i8_none: Option<i8>,
562            a_opt_i8_some: Option<i8>,
563
564            t_i8: i8,
565            t_opt_i8_none: Option<i8>,
566            t_opt_i8_some: Option<i8>,
567
568            a_bool: bool,
569            a_opt_bool_none: Option<bool>,
570            a_opt_bool_some: Option<bool>,
571
572            t_bool: bool,
573            t_opt_bool_none: Option<bool>,
574            t_opt_bool_some: Option<bool>,
575
576            a_f32: f32,
577            a_opt_f32_none: Option<f32>,
578            a_opt_f32_some: Option<f32>,
579
580            t_f32: f32,
581            t_opt_f32_none: Option<f32>,
582            t_opt_f32_some: Option<f32>,
583        }
584
585        let xml = br#"
586            <my-struct a_string='bla' a_opt_string_some='ble' a_u32="1" a_opt_u32_some="2" a_i8='-1' a_opt_i8_some='-2' a_bool="true" a_opt_bool_some="false" a_f32="1.1" a_opt_f32_some="2.2">
587                <t_string>bli</t_string>
588                <t_opt_string_some>blo</t_string_opt_some>
589                <t_u32>3</t_u32>
590                <t_opt_u32_some>4</t_u32_opt_some>
591                <t_i8>-3</t_i8>
592                <t_opt_i8_some>-4</t_i8_opt_some>
593                <t_bool>false</t_bool>
594                <t_opt_bool_some>true</t_bool_opt_some>
595                <t_f32>3.3</t_f32>
596                <t_opt_f32_some>4.4</t_f32_opt_some>
597            </my-struct>"#;
598        let mut parser = Parser::new(Cursor::new(&xml[..]));
599        let mut deserializer = Deserializer::new(&mut parser).unwrap();
600
601        let my_struct = MyStruct::deserialize(&mut deserializer).unwrap();
602        assert_eq!(my_struct, MyStruct {
603            a_string: "bla".to_string(),
604            a_opt_string_none: None,
605            a_opt_string_some: Some("ble".to_string()),
606            t_string: "bli".to_string(),
607            t_opt_string_none: None,
608            t_opt_string_some: Some("blo".to_string()),
609            a_u32: 1,
610            a_opt_u32_none: None,
611            a_opt_u32_some: Some(2),
612            t_u32: 3,
613            t_opt_u32_none: None,
614            t_opt_u32_some: Some(4),
615            a_i8: -1,
616            a_opt_i8_none: None,
617            a_opt_i8_some: Some(-2),
618            t_i8: -3,
619            t_opt_i8_none: None,
620            t_opt_i8_some: Some(-4),
621            a_bool: true,
622            a_opt_bool_none: None,
623            a_opt_bool_some: Some(false),
624            t_bool: false,
625            t_opt_bool_none: None,
626            t_opt_bool_some: Some(true),
627            a_f32: 1.1,
628            a_opt_f32_none: None,
629            a_opt_f32_some: Some(2.2),
630            t_f32: 3.3,
631            t_opt_f32_none: None,
632            t_opt_f32_some: Some(4.4),
633        });
634    }
635
636    #[test]
637    fn test_deserializer_enum() {
638        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
639        enum MyEnum {
640            #[serde(rename = "variant-a")]
641            VariantA {
642                t_string: String,
643            },
644            #[serde(rename = "variant-b")]
645            VariantB {
646                t_u32: u32,
647            },
648        }
649
650        let xml_a = br#"
651                <variant-a>
652                    <t_string>ble</t_string>
653                </variant-a>"#;
654
655        let mut parser = Parser::new(Cursor::new(&xml_a[..]));
656        let mut deserializer = Deserializer::new(&mut parser).unwrap();
657        let my_enum = MyEnum::deserialize(&mut deserializer).unwrap();
658        assert_eq!(my_enum, MyEnum::VariantA {
659            t_string: "ble".to_string(),
660        });
661
662        let xml_b = br#"
663                <variant-b>
664                    <t_u32>456</t_u32>
665                </variant-b>"#;
666
667        let mut parser = Parser::new(Cursor::new(&xml_b[..]));
668        let mut deserializer = Deserializer::new(&mut parser).unwrap();
669        let my_enum = MyEnum::deserialize(&mut deserializer).unwrap();
670        assert_eq!(my_enum, MyEnum::VariantB {
671            t_u32: 456,
672        });
673    }
674
675    #[test]
676    fn test_proper() {
677        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
678        #[serde(untagged)]
679        enum MyEnum {
680            VariantA {
681                bla: String,
682            },
683            VariantB {
684                ble: String,
685            },
686        }
687
688        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
689        struct MyStruct {
690            attr: String,
691
692            #[serde(flatten)]
693            kind: MyEnum,
694        }
695
696        let xml = br#"<variant-a attr='aaa'><bla>bbb</bla></variant-a>"#;
697        let mut parser = Parser::new(Cursor::new(&xml[..]));
698        let mut deserializer = Deserializer::new(&mut parser).unwrap();
699        let my_struct = MyStruct::deserialize(&mut deserializer).unwrap();
700        assert_eq!(my_struct, MyStruct {
701            attr: "aaa".to_string(),
702            kind: MyEnum::VariantA {
703                bla: "bbb".to_string(),
704            }
705        });
706
707        let xml = br#"<variant-b attr='aaa'><ble>bbb</ble></variant-b>"#;
708        let mut parser = Parser::new(Cursor::new(&xml[..]));
709        let mut deserializer = Deserializer::new(&mut parser).unwrap();
710        let my_struct = MyStruct::deserialize(&mut deserializer).unwrap();
711        assert_eq!(my_struct, MyStruct {
712            attr: "aaa".to_string(),
713            kind: MyEnum::VariantB {
714                ble: "bbb".to_string(),
715            }
716        });
717    }
718}