headers/common/
user_agent.rs

1use std::fmt;
2use std::str::FromStr;
3
4use crate::util::HeaderValueString;
5
6/// `User-Agent` header, defined in
7/// [RFC7231](https://datatracker.ietf.org/doc/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/// use headers::UserAgent;
38///
39/// let ua = UserAgent::from_static("hyper/0.12.2");
40/// ```
41#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct UserAgent(HeaderValueString);
43
44derive_header! {
45    UserAgent(_),
46    name: USER_AGENT
47}
48
49impl UserAgent {
50    /// Create a `UserAgent` from a static string.
51    ///
52    /// # Panic
53    ///
54    /// Panics if the static string is not a legal header value.
55    pub const fn from_static(src: &'static str) -> UserAgent {
56        UserAgent(HeaderValueString::from_static(src))
57    }
58
59    /// View this `UserAgent` as a `&str`.
60    pub fn as_str(&self) -> &str {
61        self.0.as_str()
62    }
63}
64
65error_type!(InvalidUserAgent);
66
67impl FromStr for UserAgent {
68    type Err = InvalidUserAgent;
69    fn from_str(src: &str) -> Result<Self, Self::Err> {
70        HeaderValueString::from_str(src)
71            .map(UserAgent)
72            .map_err(|_| InvalidUserAgent { _inner: () })
73    }
74}
75
76impl fmt::Display for UserAgent {
77    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78        fmt::Display::fmt(&self.0, f)
79    }
80}