http_type/protocol/
impl.rs

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