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