hyper_sync/header/common/
host.rs1use std::borrow::Cow;
2use std::fmt;
3use std::str::FromStr;
4
5use header::{Header, Raw};
6use header::parsing::from_one_raw_str;
7
8#[derive(Clone, PartialEq, Debug)]
31pub struct Host {
32 hostname: Cow<'static, str>,
33 port: Option<u16>
34}
35
36impl Host {
37 pub fn new<H, P>(hostname: H, port: P) -> Host
39 where H: Into<Cow<'static, str>>,
40 P: Into<Option<u16>>
41 {
42 Host {
43 hostname: hostname.into(),
44 port: port.into(),
45 }
46 }
47
48 pub fn hostname(&self) -> &str {
50 self.hostname.as_ref()
51 }
52
53 pub fn port(&self) -> Option<u16> {
55 self.port
56 }
57}
58
59impl Header for Host {
60 fn header_name() -> &'static str {
61 static NAME: &'static str = "Host";
62 NAME
63 }
64
65 fn parse_header(raw: &Raw) -> ::Result<Host> {
66 from_one_raw_str(raw)
67 }
68
69 fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
70 f.fmt_line(self)
71 }
72}
73
74impl fmt::Display for Host {
75 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76 match self.port {
77 None | Some(80) | Some(443) => f.write_str(&self.hostname[..]),
78 Some(port) => write!(f, "{}:{}", self.hostname, port)
79 }
80 }
81}
82
83impl FromStr for Host {
84 type Err = ::Error;
85
86 fn from_str(s: &str) -> ::Result<Host> {
87 let idx = s.rfind(':');
88 let port = idx.and_then(
89 |idx| s[idx + 1..].parse().ok()
90 );
91 let hostname = match port {
92 None => s,
93 Some(_) => &s[..idx.unwrap()]
94 };
95
96 Ok(Host {
97 hostname: hostname.to_owned().into(),
98 port: port,
99 })
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use super::Host;
106 use header::Header;
107
108
109 #[test]
110 fn test_host() {
111 let host = Header::parse_header(&vec![b"foo.com".to_vec()].into());
112 assert_eq!(host.ok(), Some(Host::new("foo.com", None)));
113
114 let host = Header::parse_header(&vec![b"foo.com:8080".to_vec()].into());
115 assert_eq!(host.ok(), Some(Host::new("foo.com", Some(8080))));
116
117 let host = Header::parse_header(&vec![b"foo.com".to_vec()].into());
118 assert_eq!(host.ok(), Some(Host::new("foo.com", None)));
119
120 let host = Header::parse_header(&vec![b"[::1]:8080".to_vec()].into());
121 assert_eq!(host.ok(), Some(Host::new("[::1]", Some(8080))));
122
123 let host = Header::parse_header(&vec![b"[::1]".to_vec()].into());
124 assert_eq!(host.ok(), Some(Host::new("[::1]", None)));
125 }
126}
127
128bench_header!(bench, Host, { vec![b"foo.com:3000".to_vec()] });