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