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
use header::{Header, HeaderFormat};
use Port;
use std::fmt;
use header::shared::util::from_one_raw_str;
#[derive(Clone, PartialEq, Show)]
pub struct Host {
pub hostname: String,
pub port: Option<Port>
}
impl Header for Host {
fn header_name(_: Option<Host>) -> &'static str {
"Host"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Host> {
from_one_raw_str(raw).and_then(|mut s: String| {
let idx = {
let slice = &s[];
if slice.char_at(1) == '[' {
match slice.rfind(']') {
Some(idx) => {
if slice.len() > idx + 2 {
Some(idx + 1)
} else {
None
}
}
None => return None
}
} else {
slice.rfind(':')
}
};
let port = match idx {
Some(idx) => s[].slice_from(idx + 1).parse(),
None => None
};
match idx {
Some(idx) => s.truncate(idx),
None => ()
}
Some(Host {
hostname: s,
port: port
})
})
}
}
impl HeaderFormat for Host {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.port {
None | Some(80) | Some(443) => write!(fmt, "{}", self.hostname),
Some(port) => write!(fmt, "{}:{}", self.hostname, port)
}
}
}
#[cfg(test)]
mod tests {
use super::Host;
use header::Header;
#[test]
fn test_host() {
let host = Header::parse_header([b"foo.com".to_vec()].as_slice());
assert_eq!(host, Some(Host {
hostname: "foo.com".to_string(),
port: None
}));
let host = Header::parse_header([b"foo.com:8080".to_vec()].as_slice());
assert_eq!(host, Some(Host {
hostname: "foo.com".to_string(),
port: Some(8080)
}));
}
}
bench_header!(bench, Host, { vec![b"foo.com:3000".to_vec()] });