hashes.rs

 1use minidom::Element;
 2
 3use error::Error;
 4
 5use ns;
 6
 7#[derive(Debug, Clone, PartialEq)]
 8pub struct Hash {
 9    pub algo: String,
10    pub hash: String,
11}
12
13pub fn parse_hash(root: &Element) -> Result<Hash, Error> {
14    if !root.is("hash", ns::HASHES) {
15        return Err(Error::ParseError("This is not a hash element."));
16    }
17    for _ in root.children() {
18        return Err(Error::ParseError("Unknown child in hash element."));
19    }
20    let algo = root.attr("algo").ok_or(Error::ParseError("Mandatory argument 'algo' not present in hash element."))?.to_owned();
21    let hash = match root.text().as_ref() {
22        "" => return Err(Error::ParseError("Hash element shouldn’t be empty.")),
23        text => text.to_owned(),
24    };
25    Ok(Hash {
26        algo: algo,
27        hash: hash,
28    })
29}
30
31pub fn serialise(hash: &Hash) -> Element {
32    Element::builder("hash")
33            .ns(ns::HASHES)
34            .attr("algo", hash.algo.clone())
35            .append(hash.hash.clone())
36            .build()
37}
38
39#[cfg(test)]
40mod tests {
41    use minidom::Element;
42    use error::Error;
43    use hashes;
44
45    #[test]
46    fn test_simple() {
47        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
48        let hash = hashes::parse_hash(&elem).unwrap();
49        assert_eq!(hash.algo, "sha-256");
50        assert_eq!(hash.hash, "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=");
51    }
52
53    #[test]
54    fn test_unknown() {
55        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
56        let error = hashes::parse_hash(&elem).unwrap_err();
57        let message = match error {
58            Error::ParseError(string) => string,
59            _ => panic!(),
60        };
61        assert_eq!(message, "This is not a hash element.");
62    }
63
64    #[test]
65    fn test_invalid_child() {
66        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>".parse().unwrap();
67        let error = hashes::parse_hash(&elem).unwrap_err();
68        let message = match error {
69            Error::ParseError(string) => string,
70            _ => panic!(),
71        };
72        assert_eq!(message, "Unknown child in hash element.");
73    }
74}