ping: Port to TryFrom/Into.

This commit is contained in:
Emmanuel Gil Peyrot 2017-05-04 01:31:13 +01:00
commit 033cbe777b
2 changed files with 26 additions and 19 deletions

View file

@ -5,6 +5,8 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::convert::TryFrom;
use minidom::Element;
use error::Error;
@ -14,37 +16,42 @@ use ns;
#[derive(Debug, Clone)]
pub struct Ping;
pub fn parse_ping(root: &Element) -> Result<Ping, Error> {
if !root.is("ping", ns::PING) {
return Err(Error::ParseError("This is not a ping element."));
}
impl<'a> TryFrom<&'a Element> for Ping {
type Error = Error;
for _ in root.children() {
return Err(Error::ParseError("Unknown child in ping element."));
fn try_from(elem: &'a Element) -> Result<Ping, Error> {
if !elem.is("ping", ns::PING) {
return Err(Error::ParseError("This is not a ping element."));
}
for _ in elem.children() {
return Err(Error::ParseError("Unknown child in ping element."));
}
Ok(Ping)
}
Ok(Ping { })
}
pub fn serialise_ping() -> Element {
Element::builder("ping").ns(ns::PING).build()
impl<'a> Into<Element> for &'a Ping {
fn into(self) -> Element {
Element::builder("ping")
.ns(ns::PING)
.build()
}
}
#[cfg(test)]
mod tests {
use minidom::Element;
use error::Error;
use ping;
use super::*;
#[test]
fn test_simple() {
let elem: Element = "<ping xmlns='urn:xmpp:ping'/>".parse().unwrap();
ping::parse_ping(&elem).unwrap();
Ping::try_from(&elem).unwrap();
}
#[test]
fn test_invalid() {
let elem: Element = "<ping xmlns='urn:xmpp:ping'><coucou/></ping>".parse().unwrap();
let error = ping::parse_ping(&elem).unwrap_err();
let error = Ping::try_from(&elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
@ -56,7 +63,7 @@ mod tests {
#[ignore]
fn test_invalid_attribute() {
let elem: Element = "<ping xmlns='urn:xmpp:ping' coucou=''/>".parse().unwrap();
let error = ping::parse_ping(&elem).unwrap_err();
let error = Ping::try_from(&elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),