headers/common/
user_agent.rs

1use std::fmt;
2use std::str::FromStr;
3
4use util::HeaderValueString;
5
6/// `User-Agent` header, defined in
7/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.5.3)
8///
9/// The `User-Agent` header field contains information about the user
10/// agent originating the request, which is often used by servers to help
11/// identify the scope of reported interoperability problems, to work
12/// around or tailor responses to avoid particular user agent
13/// limitations, and for analytics regarding browser or operating system
14/// use.  A user agent SHOULD send a User-Agent field in each request
15/// unless specifically configured not to do so.
16///
17/// # ABNF
18///
19/// ```text
20/// User-Agent = product *( RWS ( product / comment ) )
21/// product         = token ["/" product-version]
22/// product-version = token
23/// ```
24///
25/// # Example values
26///
27/// * `CERN-LineMode/2.15 libwww/2.17b3`
28/// * `Bunnies`
29///
30/// # Notes
31///
32/// * The parser does not split the value
33///
34/// # Example
35///
36/// ```
37/// # extern crate headers;
38/// use headers::UserAgent;
39///
40/// let ua = UserAgent::from_static("hyper/0.12.2");
41/// ```
42#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
43pub struct UserAgent(HeaderValueString);
44
45derive_header! {
46    UserAgent(_),
47    name: USER_AGENT
48}
49
50impl UserAgent {
51    /// Create a `UserAgent` from a static string.
52    ///
53    /// # Panic
54    ///
55    /// Panics if the static string is not a legal header value.
56    pub fn from_static(src: &'static str) -> UserAgent {
57        UserAgent(HeaderValueString::from_static(src))
58    }
59
60    /// View this `UserAgent` as a `&str`.
61    pub fn as_str(&self) -> &str {
62        self.0.as_str()
63    }
64}
65
66error_type!(InvalidUserAgent);
67
68impl FromStr for UserAgent {
69    type Err = InvalidUserAgent;
70    fn from_str(src: &str) -> Result<Self, Self::Err> {
71        HeaderValueString::from_str(src)
72            .map(UserAgent)
73            .map_err(|_| InvalidUserAgent { _inner: () })
74    }
75}
76
77impl fmt::Display for UserAgent {
78    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79        fmt::Display::fmt(&self.0, f)
80    }
81}