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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use header::{Header, HeaderFormat};
use std::fmt;
use std::str::FromStr;
use header::parsing::from_one_raw_str;
use url::idna::domain_to_unicode;
#[derive(Clone, PartialEq, Debug)]
pub struct Host {
pub hostname: String,
pub port: Option<u16>
}
impl Header for Host {
fn header_name() -> &'static str {
"Host"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<Host> {
from_one_raw_str(raw)
}
}
impl HeaderFormat for Host {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.port {
None | Some(80) | Some(443) => f.write_str(&self.hostname[..]),
Some(port) => write!(f, "{}:{}", self.hostname, port)
}
}
}
impl fmt::Display for Host {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.fmt_header(f)
}
}
impl FromStr for Host {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Host> {
let idx = s.rfind(':');
let port = idx.and_then(
|idx| s[idx + 1..].parse().ok()
);
let hostname_encoded = match port {
None => s,
Some(_) => &s[..idx.unwrap()]
};
let hostname = if hostname_encoded.starts_with("[") {
if !hostname_encoded.ends_with("]") {
return Err(::Error::Header)
}
hostname_encoded.to_owned()
} else {
let (hostname, res) = domain_to_unicode(hostname_encoded);
if res.is_err() {
return Err(::Error::Header)
}
hostname
};
Ok(Host {
hostname: hostname,
port: 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_ref());
assert_eq!(host.ok(), Some(Host {
hostname: "foo.com".to_owned(),
port: None
}));
let host = Header::parse_header([b"foo.com:8080".to_vec()].as_ref());
assert_eq!(host.ok(), Some(Host {
hostname: "foo.com".to_owned(),
port: Some(8080)
}));
let host = Header::parse_header([b"foo.com".to_vec()].as_ref());
assert_eq!(host.ok(), Some(Host {
hostname: "foo.com".to_owned(),
port: None
}));
let host = Header::parse_header([b"[::1]:8080".to_vec()].as_ref());
assert_eq!(host.ok(), Some(Host {
hostname: "[::1]".to_owned(),
port: Some(8080)
}));
let host = Header::parse_header([b"[::1]".to_vec()].as_ref());
assert_eq!(host.ok(), Some(Host {
hostname: "[::1]".to_owned(),
port: None
}));
}
}
bench_header!(bench, Host, { vec![b"foo.com:3000".to_vec()] });