http_type/status_code/
impl.rs

1use crate::*;
2
3/// The `StatusCode` enum represents the HTTP status codes.
4///
5/// It maps common HTTP status codes to their respective meanings. It provides methods to retrieve
6/// the corresponding numeric code as well as the associated status text. Additionally, it implements
7/// conversion from a string representation of the status code.
8///
9/// # Variants
10/// - `Ok`: HTTP status 200, indicating a successful request.
11/// - `Created`: HTTP status 201, indicating that the request was successful and resulted in a resource creation.
12/// - `NoContent`: HTTP status 204, indicating that the request was successful, but there is no content to return.
13/// - `BadRequest`: HTTP status 400, indicating a bad request, often due to incorrect syntax or invalid data.
14/// - `Unauthorized`: HTTP status 401, indicating that authentication is required and has failed or not been provided.
15/// - `Forbidden`: HTTP status 403, indicating that the server understands the request but refuses to authorize it.
16/// - `NotFound`: HTTP status 404, indicating that the requested resource could not be found.
17/// - `InternalServerError`: HTTP status 500, indicating that the server encountered an internal error.
18/// - `NotImplemented`: HTTP status 501, indicating that the server does not support the functionality required to fulfill the request.
19/// - `BadGateway`: HTTP status 502, indicating that the server, while acting as a gateway or proxy, received an invalid response from an upstream server.
20/// - `Unknown`: A default variant for unrecognized or undefined status codes.
21impl StatusCode {
22    /// Returns the numeric HTTP status code associated with this status code variant.
23    ///
24    /// This method returns the corresponding HTTP numeric status code based on the `StatusCode` variant.
25    /// For example:
26    /// - `Self::Ok` returns 200.
27    /// - `Self::BadRequest` returns 400.
28    /// - `Self::Unknown` returns 0 (the default for unrecognized status codes).
29    ///
30    /// # Parameters
31    /// - `&self`: A reference to the `StatusCode` enum instance. This represents the specific variant of the `StatusCode` enum that the method is called on.
32    ///
33    /// # Return Value
34    /// - `u16`: The numeric HTTP status code associated with the `StatusCode` variant. For example:
35    ///   - `Self::Ok` returns `200`.
36    ///   - `Self::BadRequest` returns `400`.
37    ///   - `Self::Unknown` returns `0`.
38    #[inline]
39    pub fn code(&self) -> StatusCodeUsize {
40        match self {
41            Self::Ok => 200,
42            Self::Created => 201,
43            Self::NoContent => 204,
44            Self::BadRequest => 400,
45            Self::Unauthorized => 401,
46            Self::Forbidden => 403,
47            Self::NotFound => 404,
48            Self::InternalServerError => 500,
49            Self::NotImplemented => 501,
50            Self::BadGateway => 502,
51            Self::Unknown => 0,
52        }
53    }
54
55    /// Converts an HTTP status code to its corresponding textual description.
56    ///
57    /// This method matches a given numeric HTTP status code and returns the corresponding
58    /// textual representation defined in the `StatusCode` enum.
59    ///
60    /// # Parameters
61    /// - `code`: A `usize` representing the HTTP status code to convert.
62    ///
63    /// # Return Value
64    /// - `String`: A string representing the textual description of the HTTP status code.
65    ///   For example:
66    ///   - `200` returns `"OK"`.
67    ///   - `404` returns `"Not Found"`.
68    ///   - Unrecognized codes return `"Unknown"`.
69    #[inline]
70    pub fn phrase(code: usize) -> String {
71        match code {
72            200 => Self::Ok.to_string(),
73            201 => Self::Created.to_string(),
74            204 => Self::NoContent.to_string(),
75            400 => Self::BadRequest.to_string(),
76            401 => Self::Unauthorized.to_string(),
77            403 => Self::Forbidden.to_string(),
78            404 => Self::NotFound.to_string(),
79            500 => Self::InternalServerError.to_string(),
80            501 => Self::NotImplemented.to_string(),
81            502 => Self::BadGateway.to_string(),
82            _ => Self::Unknown.to_string(),
83        }
84    }
85
86    #[inline]
87    pub fn same(&self, code_str: &str) -> bool {
88        self.code().to_string() == code_str || self.to_string() == code_str
89    }
90}
91
92impl Display for StatusCode {
93    #[inline]
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        let res: &str = match self {
96            Self::Ok => "OK",
97            Self::Created => "Created",
98            Self::NoContent => "No Content",
99            Self::BadRequest => "Bad Request",
100            Self::Unauthorized => "Unauthorized",
101            Self::Forbidden => "Forbidden",
102            Self::NotFound => "Not Found",
103            Self::InternalServerError => "Internal Server Error",
104            Self::NotImplemented => "Not Implemented",
105            Self::BadGateway => "Bad Gateway",
106            Self::Unknown => "Unknown",
107        };
108        write!(f, "{}", res)
109    }
110}
111
112impl FromStr for StatusCode {
113    type Err = ();
114
115    #[inline]
116    fn from_str(code_str: &str) -> Result<Self, Self::Err> {
117        match code_str {
118            _code_str if Self::Ok.same(_code_str) => Ok(Self::Ok),
119            _code_str if Self::Created.same(_code_str) => Ok(Self::Created),
120            _code_str if Self::NoContent.same(_code_str) => Ok(Self::NoContent),
121            _code_str if Self::BadRequest.same(_code_str) => Ok(Self::BadRequest),
122            _code_str if Self::Unauthorized.same(_code_str) => Ok(Self::Unauthorized),
123            _code_str if Self::Forbidden.same(_code_str) => Ok(Self::Forbidden),
124            _code_str if Self::NotFound.same(_code_str) => Ok(Self::NotFound),
125            _code_str if Self::InternalServerError.same(_code_str) => Ok(Self::InternalServerError),
126            _code_str if Self::NotImplemented.same(_code_str) => Ok(Self::NotImplemented),
127            _code_str if Self::BadGateway.same(_code_str) => Ok(Self::BadGateway),
128            _ => Ok(Self::Unknown),
129        }
130    }
131}
132
133impl Default for StatusCode {
134    #[inline]
135    fn default() -> Self {
136        Self::Ok
137    }
138}