receipts: Parse 'id' using get_attr!(), and make it optional.

This commit is contained in:
Emmanuel Gil Peyrot 2017-05-24 22:43:21 +01:00
parent 47fc116906
commit 947c49330f

View file

@ -15,7 +15,7 @@ use ns;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Receipt { pub enum Receipt {
Request, Request,
Received(String), Received(Option<String>),
} }
impl TryFrom<Element> for Receipt { impl TryFrom<Element> for Receipt {
@ -26,9 +26,17 @@ impl TryFrom<Element> for Receipt {
return Err(Error::ParseError("Unknown child in receipt element.")); return Err(Error::ParseError("Unknown child in receipt element."));
} }
if elem.is("request", ns::RECEIPTS) { if elem.is("request", ns::RECEIPTS) {
for _ in elem.attrs() {
return Err(Error::ParseError("Unknown attribute in request element."));
}
Ok(Receipt::Request) Ok(Receipt::Request)
} else if elem.is("received", ns::RECEIPTS) { } else if elem.is("received", ns::RECEIPTS) {
let id = elem.attr("id").unwrap_or("").to_owned(); for (attr, _) in elem.attrs() {
if attr != "id" {
return Err(Error::ParseError("Unknown attribute in received element."));
}
}
let id = get_attr!(elem, "id", optional);
Ok(Receipt::Received(id)) Ok(Receipt::Received(id))
} else { } else {
Err(Error::ParseError("This is not a receipt element.")) Err(Error::ParseError("This is not a receipt element."))
@ -40,13 +48,11 @@ impl Into<Element> for Receipt {
fn into(self) -> Element { fn into(self) -> Element {
match self { match self {
Receipt::Request => Element::builder("request") Receipt::Request => Element::builder("request")
.ns(ns::RECEIPTS) .ns(ns::RECEIPTS),
.build(),
Receipt::Received(id) => Element::builder("received") Receipt::Received(id) => Element::builder("received")
.ns(ns::RECEIPTS) .ns(ns::RECEIPTS)
.attr("id", id) .attr("id", id),
.build(), }.build()
}
} }
} }
@ -72,7 +78,7 @@ mod tests {
let elem: Element = receipt.into(); let elem: Element = receipt.into();
assert!(elem.is("request", ns::RECEIPTS)); assert!(elem.is("request", ns::RECEIPTS));
let receipt = Receipt::Received("coucou".to_owned()); let receipt = Receipt::Received(Some(String::from("coucou")));
let elem: Element = receipt.into(); let elem: Element = receipt.into();
assert!(elem.is("received", ns::RECEIPTS)); assert!(elem.is("received", ns::RECEIPTS));
assert_eq!(elem.attr("id"), Some("coucou")); assert_eq!(elem.attr("id"), Some("coucou"));