http_type/protocol/impl.rs
1use crate::*;
2
3/// Provides a default value for `Protocol`.
4///
5/// The default `Protocol` is `Protocol::Unknown` with an empty string.
6impl Default for Protocol {
7 #[inline(always)]
8 fn default() -> Self {
9 Self::Unknown(String::new())
10 }
11}
12
13/// Provides utility methods for the `Protocol` type.
14impl Protocol {
15 /// Checks if the current protocol is `HTTP`.
16 ///
17 /// # Arguments
18 ///
19 /// - `self` - A reference to the `Protocol` instance.
20 ///
21 /// # Returns
22 ///
23 /// `true` if the protocol is `HTTP`, otherwise returns `false`.
24 #[inline(always)]
25 pub fn is_http(&self) -> bool {
26 *self == Self::Http
27 }
28
29 /// Checks if the current protocol is `HTTPS`.
30 ///
31 /// # Arguments
32 ///
33 /// - `self` - A reference to the `Protocol` instance.
34 ///
35 /// # Returns
36 ///
37 /// `true` if the protocol is `HTTPS`, otherwise returns `false`.
38 #[inline(always)]
39 pub fn is_https(&self) -> bool {
40 *self == Self::Https
41 }
42
43 /// Returns the default port associated with the protocol.
44 ///
45 /// # Arguments
46 ///
47 /// - `self` - A reference to the `Protocol` instance.
48 ///
49 /// # Returns
50 ///
51 /// The default port number for the protocol. Returns `80` for `HTTP` and unknown protocols,
52 /// and `443` for `HTTPS`.
53 #[inline(always)]
54 pub fn get_port(&self) -> u16 {
55 match self {
56 Self::Http => 80,
57 Self::Https => 443,
58 Self::Unknown(_) => 80,
59 }
60 }
61}
62
63impl Display for Protocol {
64 #[inline(always)]
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 let res: &str = match self {
67 Self::Http => HTTP_LOWERCASE,
68 Self::Https => HTTPS_LOWERCASE,
69 Self::Unknown(protocol) => protocol,
70 };
71 write!(f, "{res}")
72 }
73}
74
75impl FromStr for Protocol {
76 type Err = &'static str;
77
78 #[inline(always)]
79 fn from_str(data: &str) -> Result<Self, Self::Err> {
80 match data.to_ascii_lowercase().as_str() {
81 HTTP_LOWERCASE => Ok(Self::Http),
82 HTTPS_LOWERCASE => Ok(Self::Https),
83 _ => Ok(Self::Unknown(data.to_string())),
84 }
85 }
86}