Skip None attributes

This commit is contained in:
Dirkjan Ochtman 2022-12-02 14:41:07 +01:00
parent 958790be0b
commit e186684824
4 changed files with 32 additions and 1 deletions

View File

@ -298,7 +298,9 @@ fn named_field(
attributes.extend(quote!(
#error
serializer.write_attr(#tag, #ns, &self.#field_name)?;
if self.#field_name.present() {
serializer.write_attr(#tag, #ns, &self.#field_name)?;
}
));
return Ok(());
}

View File

@ -453,6 +453,10 @@ impl<T: ToXml> ToXml for Option<T> {
None => Ok(()),
}
}
fn present(&self) -> bool {
self.is_some()
}
}
fn encode(input: &str) -> Result<Cow<'_, str>, Error> {

View File

@ -20,6 +20,10 @@ pub trait ToXml {
field: Option<Id<'_>>,
serializer: &mut Serializer<W>,
) -> Result<(), Error>;
fn present(&self) -> bool {
true
}
}
impl<'a, T: ToXml + ?Sized> ToXml for &'a T {

View File

@ -17,3 +17,24 @@ fn option_vec() {
assert_eq!(xml, to_string(&v).unwrap());
assert_eq!(v, from_str(xml).unwrap());
}
#[derive(Debug, Eq, FromXml, PartialEq, ToXml)]
struct Bar<'a> {
#[xml(attribute, borrow)]
maybe: Option<&'a str>,
}
#[test]
fn option_borrow() {
let v = Bar { maybe: Some("a") };
let xml = r#"<Bar maybe="a"></Bar>"#;
assert_eq!(xml, to_string(&v).unwrap());
assert_eq!(v, from_str(xml).unwrap());
let v = Bar { maybe: None };
let xml = r#"<Bar></Bar>"#;
assert_eq!(xml, to_string(&v).unwrap());
assert_eq!(v, from_str(xml).unwrap());
}