roster: Parse query using the new helpers.

This commit is contained in:
Emmanuel Gil Peyrot 2017-11-23 16:45:05 +00:00
parent e4cfc1b867
commit cec581baa0

View file

@ -82,57 +82,22 @@ impl From<Item> for Element {
} }
} }
/// The contact list of the user. generate_element_with_children!(
#[derive(Debug, Clone)] /// The contact list of the user.
pub struct Roster { Roster, "query", ns::ROSTER,
/// Version of the contact list. attributes: [
/// /// Version of the contact list.
/// This is an opaque string that should only be sent back to the server on ///
/// a new connection, if this client is storing the contact list between /// This is an opaque string that should only be sent back to the server on
/// connections. /// a new connection, if this client is storing the contact list between
pub ver: Option<String>, /// connections.
ver: Option<String> = "ver" => optional
/// List of the contacts of the user. ],
pub items: Vec<Item>, children: [
} /// List of the contacts of the user.
items: Vec<Item> = ("item", ns::ROSTER) => Item
impl TryFrom<Element> for Roster { ]
type Err = Error; );
fn try_from(elem: Element) -> Result<Roster, Error> {
if !elem.is("query", ns::ROSTER) {
return Err(Error::ParseError("This is not a roster element."));
}
for (attr, _) in elem.attrs() {
if attr != "ver" {
return Err(Error::ParseError("Unknown attribute in roster element."));
}
}
let mut roster = Roster {
ver: get_attr!(elem, "ver", optional),
items: vec!(),
};
for child in elem.children() {
if !child.is("item", ns::ROSTER) {
return Err(Error::ParseError("Unknown element in roster element."));
}
let item = Item::try_from(child.clone())?;
roster.items.push(item);
}
Ok(roster)
}
}
impl From<Roster> for Element {
fn from(roster: Roster) -> Element {
Element::builder("query")
.ns(ns::ROSTER)
.attr("ver", roster.ver)
.append(roster.items)
.build()
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@ -256,7 +221,7 @@ mod tests {
Error::ParseError(string) => string, Error::ParseError(string) => string,
_ => panic!(), _ => panic!(),
}; };
assert_eq!(message, "Unknown element in roster element."); assert_eq!(message, "Unknown child in query element.");
let elem: Element = "<query xmlns='jabber:iq:roster' coucou=''/>".parse().unwrap(); let elem: Element = "<query xmlns='jabber:iq:roster' coucou=''/>".parse().unwrap();
let error = Roster::try_from(elem).unwrap_err(); let error = Roster::try_from(elem).unwrap_err();
@ -264,7 +229,7 @@ mod tests {
Error::ParseError(string) => string, Error::ParseError(string) => string,
_ => panic!(), _ => panic!(),
}; };
assert_eq!(message, "Unknown attribute in roster element."); assert_eq!(message, "Unknown attribute in query element.");
} }
#[test] #[test]