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
use std::fmt::{Formatter, Result};
use hyper::error::{self, Error};
use hyper::header::{HeaderFormat, Header};
const BOOTID_HEADER_NAME: &'static str = "BOOTID.UPNP.ORG";
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct BootID(pub u32);
impl Header for BootID {
fn header_name() -> &'static str {
BOOTID_HEADER_NAME
}
fn parse_header(raw: &[Vec<u8>]) -> error::Result<Self> {
if raw.len() != 1 {
return Err(Error::Header);
}
let cow_str = String::from_utf8_lossy(&raw[0][..]);
let value = match i32::from_str_radix(&*cow_str, 10) {
Ok(n) => n,
Err(_) => return Err(Error::Header),
};
if value.is_negative() {
Err(Error::Header)
} else {
Ok(BootID(value as u32))
}
}
}
impl HeaderFormat for BootID {
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::BootID;
#[test]
fn positive_bootid() {
let bootid_header_value = &[b"1216907400"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
#[test]
fn positive_leading_zeros() {
let bootid_header_value = &[b"0000001216907400"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
#[test]
fn positive_lower_bound() {
let bootid_header_value = &[b"0"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
#[test]
fn positive_upper_bound() {
let bootid_header_value = &[b"2147483647"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
#[test]
fn positive_negative_zero() {
let bootid_header_value = &[b"-0"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
#[test]
#[should_panic]
fn negative_overflow() {
let bootid_header_value = &[b"2290649224"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
#[test]
#[should_panic]
fn negative_negative_overflow() {
let bootid_header_value = &[b"-2290649224"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
#[test]
#[should_panic]
fn negative_nan() {
let bootid_header_value = &[b"2290wow649224"[..].to_vec()];
BootID::parse_header(bootid_header_value).unwrap();
}
}