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