rama_http_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 rama_http_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 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
65rama_utils::macros::error::static_str_error! {
66 #[doc = "ua is not valid"]
67 pub struct InvalidUserAgent;
68}
69
70impl FromStr for UserAgent {
71 type Err = InvalidUserAgent;
72 fn from_str(src: &str) -> Result<Self, Self::Err> {
73 HeaderValueString::from_str(src)
74 .map(UserAgent)
75 .map_err(|_| InvalidUserAgent)
76 }
77}
78
79impl fmt::Display for UserAgent {
80 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81 fmt::Display::fmt(&self.0, f)
82 }
83}