Skip to content

Commit

Permalink
Improve bool parsing as XML can support also 0/1 value as bool (#88)
Browse files Browse the repository at this point in the history
Improve bool parsing as XML can support also 0/1 value as bool
  • Loading branch information
punkstarman authored Mar 11, 2019
1 parent b854e1a commit e6bf15a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::io::Read;

use serde::de;
use serde::de::{self, Unexpected};
use xml::reader::{EventReader, ParserConfig, XmlEvent};
use xml::name::OwnedName;

Expand Down Expand Up @@ -227,7 +227,25 @@ impl<'de, 'a, R: Read> de::Deserializer<'de> for &'a mut Deserializer<R> {
deserialize_type!(deserialize_u64 => visit_u64);
deserialize_type!(deserialize_f32 => visit_f32);
deserialize_type!(deserialize_f64 => visit_f64);
deserialize_type!(deserialize_bool => visit_bool);

fn deserialize_bool<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
if let XmlEvent::StartElement { .. } = *self.peek()? {
self.set_map_value()
}
self.read_inner_value::<V, V::Value, _>(|this| {
if let XmlEvent::EndElement { .. } = *this.peek()? {
return visitor.visit_bool(false);
}
expect!(this.next()?, XmlEvent::Characters(s) => {
match s.as_str() {
"true" | "1" => visitor.visit_bool(true),
"false" | "0" => visitor.visit_bool(false),
_ => Err(de::Error::invalid_value(Unexpected::Str(&s), &"a boolean")),
}

})
})
}

fn deserialize_char<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
self.deserialize_string(visitor)
Expand Down
17 changes: 17 additions & 0 deletions tests/migrated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,18 @@ where
}
}

fn test_parse_invalid<'de, 'a, T>(errors: &[&'a str])
where
T: PartialEq + Debug + ser::Serialize + de::Deserialize<'de>,
{
for &s in errors {
assert!(match from_str::<T>(s) {
Err(Error(_, _)) => true,
_ => false,
});
}
}

#[test]
fn test_namespaces() {
let _ = simple_logger::init();
Expand Down Expand Up @@ -318,12 +330,17 @@ fn test_parse_u64() {

#[test]
fn test_parse_bool() {
let _ = simple_logger::init();
test_parse_ok(&[
("<bla>true</bla>", true),
("<bla>false</bla>", false),
("<bla> true </bla>", true),
("<bla> false </bla>", false),
("<bla>1</bla>", true),
("<bla>0</bla>", false),
]);

test_parse_invalid::<bool>(&["<bla>verum</bla>"]);
}

#[test]
Expand Down

0 comments on commit e6bf15a

Please sign in to comment.