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