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 /// Creates a new instance of `Protocol` with the default value of `Self::HTTP`.
16 ///
17 /// # Returns
18 ///
19 /// A new `Protocol` instance, defaulting to `Protocol::HTTP`.
20 #[inline(always)]
21 pub fn new() -> Self {
22 Self::default()
23 }
24
25 /// Checks if the current protocol is `HTTP`.
26 ///
27 /// # Arguments
28 ///
29 /// - `self` - A reference to the `Protocol` instance.
30 ///
31 /// # Returns
32 ///
33 /// `true` if the protocol is `HTTP`, otherwise returns `false`.
34 #[inline(always)]
35 pub fn is_http(&self) -> bool {
36 *self == Self::HTTP
37 }
38
39 /// Checks if the current protocol is `HTTPS`.
40 ///
41 /// # Arguments
42 ///
43 /// - `self` - A reference to the `Protocol` instance.
44 ///
45 /// # Returns
46 ///
47 /// `true` if the protocol is `HTTPS`, otherwise returns `false`.
48 #[inline(always)]
49 pub fn is_https(&self) -> bool {
50 *self == Self::HTTPS
51 }
52
53 /// Returns the default port associated with the protocol.
54 ///
55 /// # Arguments
56 ///
57 /// - `self` - A reference to the `Protocol` instance.
58 ///
59 /// # Returns
60 ///
61 /// The default port number for the protocol. Returns `80` for `HTTP` and unknown protocols,
62 /// and `443` for `HTTPS`.
63 #[inline(always)]
64 pub fn get_port(&self) -> u16 {
65 match self {
66 Self::HTTP => 80,
67 Self::HTTPS => 443,
68 Self::Unknown(_) => 80,
69 }
70 }
71}
72
73impl Display for Protocol {
74 #[inline(always)]
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 let res: &str = match self {
77 Self::HTTP => HTTP_LOWERCASE,
78 Self::HTTPS => HTTPS_LOWERCASE,
79 Self::Unknown(protocol) => protocol,
80 };
81 write!(f, "{res}")
82 }
83}
84
85impl FromStr for Protocol {
86 type Err = &'static str;
87
88 #[inline(always)]
89 fn from_str(data: &str) -> Result<Self, Self::Err> {
90 match data.to_ascii_lowercase().as_str() {
91 HTTP_LOWERCASE => Ok(Self::HTTP),
92 HTTPS_LOWERCASE => Ok(Self::HTTPS),
93 _ => Ok(Self::Unknown(data.to_string())),
94 }
95 }
96}