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 #[must_use]
56 pub const fn from_static(src: &'static str) -> Self {
57 Self(HeaderValueString::from_static(src))
58 }
59
60 /// Create the default rama 'UserAgent'.
61 #[must_use]
62 pub const fn rama() -> Self {
63 Self(HeaderValueString::from_static(const_format::formatcp!(
64 "{}/{}",
65 rama_utils::info::NAME,
66 rama_utils::info::VERSION,
67 )))
68 }
69
70 /// View this `UserAgent` as a `&str`.
71 pub fn as_str(&self) -> &str {
72 self.0.as_str()
73 }
74}
75
76rama_utils::macros::error::static_str_error! {
77 #[doc = "ua is not valid"]
78 pub struct InvalidUserAgent;
79}
80
81impl FromStr for UserAgent {
82 type Err = InvalidUserAgent;
83 fn from_str(src: &str) -> Result<Self, Self::Err> {
84 HeaderValueString::from_str(src)
85 .map(UserAgent)
86 .map_err(|_e| InvalidUserAgent)
87 }
88}
89
90impl fmt::Display for UserAgent {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 fmt::Display::fmt(&self.0, f)
93 }
94}