1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::fmt::{Formatter, Result};
use hyper::error::{self, Error};
use hyper::header::{HeaderFormat, Header};
use {SSDPResult, SSDPErrorKind};
const MX_HEADER_NAME: &'static str = "MX";
pub const MX_HEADER_MIN: u8 = 1;
pub const MX_HEADER_MAX: u8 = 120;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct MX(pub u8);
impl MX {
pub fn new(wait_bound: u8) -> SSDPResult<MX> {
if wait_bound < MX_HEADER_MIN || wait_bound > MX_HEADER_MAX {
Err(SSDPErrorKind::InvalidHeader(MX_HEADER_NAME, "Supplied Wait Bound Is Out Of Bounds").into())
} else {
Ok(MX(wait_bound))
}
}
}
impl Header for MX {
fn header_name() -> &'static str {
MX_HEADER_NAME
}
fn parse_header(raw: &[Vec<u8>]) -> error::Result<Self> {
if raw.len() != 1 {
return Err(Error::Header);
}
let cow_string = String::from_utf8_lossy(&raw[0][..]);
match u8::from_str_radix(&cow_string, 10) {
Ok(n) if n >= MX_HEADER_MIN && n <= MX_HEADER_MAX => Ok(MX(n)),
_ => Err(Error::Header),
}
}
}
impl HeaderFormat for MX {
fn fmt_header(&self, fmt: &mut Formatter) -> Result {
try!(fmt.write_fmt(format_args!("{}", self.0)));
Ok(())
}
}
#[cfg(test)]
mod tests {
use hyper::header::Header;
use super::MX;
#[test]
fn positive_lower_bound() {
let mx_lower_header = &[b"1"[..].to_vec()];
match MX::parse_header(mx_lower_header) {
Ok(n) if n == MX(1) => (),
_ => panic!("Failed To Accept 1 As MX Value"),
};
}
#[test]
fn positive_inner_bound() {
let mx_inner_header = &[b"5"[..].to_vec()];
match MX::parse_header(mx_inner_header) {
Ok(n) if n == MX(5) => (),
_ => panic!("Failed To Accept 5 As MX Value"),
};
}
#[test]
fn positive_upper_bound() {
let mx_upper_header = &[b"120"[..].to_vec()];
match MX::parse_header(mx_upper_header) {
Ok(n) if n == MX(120) => (),
_ => panic!("Failed To Accept 120 As MX Value"),
};
}
#[test]
#[should_panic]
fn negative_decimal_bound() {
let mx_decimal_header = &[b"0.5"[..].to_vec()];
MX::parse_header(mx_decimal_header).unwrap();
}
#[test]
#[should_panic]
fn negative_negative_bound() {
let mx_negative_header = &[b"-5"[..].to_vec()];
MX::parse_header(mx_negative_header).unwrap();
}
#[test]
#[should_panic]
fn negative_too_high_bound() {
let mx_too_high_header = &[b"121"[..].to_vec()];
MX::parse_header(mx_too_high_header).unwrap();
}
#[test]
#[should_panic]
fn negative_zero_bound() {
let mx_zero_header = &[b"0"[..].to_vec()];
MX::parse_header(mx_zero_header).unwrap();
}
}