diff --git a/src/hashes.rs b/src/hashes.rs new file mode 100644 index 00000000..21301633 --- /dev/null +++ b/src/hashes.rs @@ -0,0 +1,66 @@ +use minidom::Element; + +use error::Error; + +use ns; + +#[derive(Debug, Clone)] +pub struct Hash { + pub algo: String, + pub hash: String, +} + +pub fn parse_hash(root: &Element) -> Result { + if !root.is("hash", ns::HASHES) { + return Err(Error::ParseError("This is not a hash element.")); + } + for _ in root.children() { + return Err(Error::ParseError("Unknown child in hash element.")); + } + let algo = root.attr("algo").ok_or(Error::ParseError("Mandatory argument 'algo' not present in hash element."))?.to_owned(); + let hash = match root.text().as_ref() { + "" => return Err(Error::ParseError("Hash element shouldn’t be empty.")), + text => text.to_owned(), + }; + Ok(Hash { + algo: algo, + hash: hash, + }) +} + +#[cfg(test)] +mod tests { + use minidom::Element; + use error::Error; + use hashes; + + #[test] + fn test_simple() { + let elem: Element = "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=".parse().unwrap(); + let hash = hashes::parse_hash(&elem).unwrap(); + assert_eq!(hash.algo, "sha-256"); + assert_eq!(hash.hash, "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU="); + } + + #[test] + fn test_unknown() { + let elem: Element = "".parse().unwrap(); + let error = hashes::parse_hash(&elem).unwrap_err(); + let message = match error { + Error::ParseError(string) => string, + _ => panic!(), + }; + assert_eq!(message, "This is not a hash element."); + } + + #[test] + fn test_invalid_child() { + let elem: Element = "".parse().unwrap(); + let error = hashes::parse_hash(&elem).unwrap_err(); + let message = match error { + Error::ParseError(string) => string, + _ => panic!(), + }; + assert_eq!(message, "Unknown child in hash element."); + } +} diff --git a/src/lib.rs b/src/lib.rs index e00ccb52..d26a5c9a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,6 +49,9 @@ pub mod media_element; /// XEP-0224: Attention pub mod attention; +/// XEP-0300: Use of Cryptographic Hash Functions in XMPP +pub mod hashes; + /// XEP-0308: Last Message Correction pub mod message_correct; diff --git a/src/ns.rs b/src/ns.rs index 8aefa2ee..d3d21068 100644 --- a/src/ns.rs +++ b/src/ns.rs @@ -31,6 +31,9 @@ pub const MEDIA_ELEMENT: &'static str = "urn:xmpp:media-element"; /// XEP-0224: Attention pub const ATTENTION: &'static str = "urn:xmpp:attention:0"; +/// XEP-0300: Use of Cryptographic Hash Functions in XMPP +pub const HASHES: &'static str = "urn:xmpp:hashes:2"; + /// XEP-0308: Last Message Correction pub const MESSAGE_CORRECT: &'static str = "urn:xmpp:message-correct:0";