headers_ext/common/
host.rs

1use std::fmt;
2
3use bytes::Bytes;
4use http::uri::Authority;
5
6/// The `Host` header.
7#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
8pub struct Host(Authority);
9
10impl Host {
11    /// Get the hostname, such as example.domain.
12    pub fn hostname(&self) -> &str {
13        self.0.host()
14    }
15
16    /// Get the optional port number.
17    pub fn port(&self) -> Option<u16> {
18        self.0.port_part().map(|p| p.as_u16())
19    }
20}
21
22impl ::Header for Host {
23    const NAME: &'static ::HeaderName = &::http::header::HOST;
24
25    fn decode<'i, I: Iterator<Item = &'i ::HeaderValue>>(values: &mut I) -> Result<Self, ::Error> {
26        values
27            .next()
28            .cloned()
29            .map(Bytes::from)
30            .and_then(|bytes| Authority::from_shared(bytes).ok())
31            .map(Host)
32            .ok_or_else(::Error::invalid)
33    }
34
35    fn encode<E: Extend<::HeaderValue>>(&self, values: &mut E) {
36        let bytes = Bytes::from(self.0.clone());
37
38        let val = ::HeaderValue::from_shared(bytes)
39            .expect("Authority is a valid HeaderValue");
40
41        values.extend(::std::iter::once(val));
42    }
43}
44
45impl From<Authority> for Host {
46    fn from(auth: Authority) -> Host {
47        Host(auth)
48    }
49}
50
51impl fmt::Display for Host {
52    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53        fmt::Display::fmt(&self.0, f)
54    }
55}
56