http_type/http_status/
impl.rs

1use crate::*;
2
3/// The `HttpStatus` 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.
8impl HttpStatus {
9    /// Returns the numeric HTTP status code associated with this status code variant.
10    ///
11    /// This method returns the corresponding HTTP numeric status code based on the `HttpStatus` variant.
12    /// For example:
13    /// - `Self::Ok` returns 200.
14    /// - `Self::BadRequest` returns 400.
15    /// - `Self::Unknown` returns 0 (the default for unrecognized status codes).
16    ///
17    /// # Parameters
18    /// - `&self`: A reference to the `HttpStatus` enum instance. This represents the specific variant of the `HttpStatus` enum that the method is called on.
19    ///
20    /// # Return Value
21    /// - `ResponseStatusCode`: The numeric HTTP status code associated with the `HttpStatus` variant. For example:
22    pub fn code(&self) -> ResponseStatusCode {
23        match self {
24            Self::Continue => 100,
25            Self::SwitchingProtocols => 101,
26            Self::Processing => 102,
27            Self::EarlyHints => 103,
28            Self::Ok => 200,
29            Self::Created => 201,
30            Self::Accepted => 202,
31            Self::NonAuthoritativeInformation => 203,
32            Self::NoContent => 204,
33            Self::ResetContent => 205,
34            Self::PartialContent => 206,
35            Self::MultiStatus => 207,
36            Self::AlreadyReported => 208,
37            Self::IMUsed => 226,
38            Self::MultipleChoices => 300,
39            Self::MovedPermanently => 301,
40            Self::Found => 302,
41            Self::SeeOther => 303,
42            Self::NotModified => 304,
43            Self::UseProxy => 305,
44            Self::TemporaryRedirect => 307,
45            Self::PermanentRedirect => 308,
46            Self::BadRequest => 400,
47            Self::Unauthorized => 401,
48            Self::PaymentRequired => 402,
49            Self::Forbidden => 403,
50            Self::NotFound => 404,
51            Self::MethodNotAllowed => 405,
52            Self::NotAcceptable => 406,
53            Self::ProxyAuthenticationRequired => 407,
54            Self::RequestTimeout => 408,
55            Self::Conflict => 409,
56            Self::Gone => 410,
57            Self::LengthRequired => 411,
58            Self::PreconditionFailed => 412,
59            Self::PayloadTooLarge => 413,
60            Self::URITooLong => 414,
61            Self::UnsupportedMediaType => 415,
62            Self::RangeNotSatisfiable => 416,
63            Self::ExpectationFailed => 417,
64            Self::ImATeapot => 418,
65            Self::MisdirectedRequest => 421,
66            Self::UnprocessableEntity => 422,
67            Self::Locked => 423,
68            Self::FailedDependency => 424,
69            Self::TooEarly => 425,
70            Self::UpgradeRequired => 426,
71            Self::PreconditionRequired => 428,
72            Self::TooManyRequests => 429,
73            Self::RequestHeaderFieldsTooLarge => 431,
74            Self::UnavailableForLegalReasons => 451,
75            Self::InternalServerError => 500,
76            Self::NotImplemented => 501,
77            Self::BadGateway => 502,
78            Self::ServiceUnavailable => 503,
79            Self::GatewayTimeout => 504,
80            Self::HTTPVersionNotSupported => 505,
81            Self::VariantAlsoNegotiates => 506,
82            Self::InsufficientStorage => 507,
83            Self::LoopDetected => 508,
84            Self::NotExtended => 510,
85            Self::NetworkAuthenticationRequired => 511,
86            Self::Unknown => 0,
87        }
88    }
89
90    /// Converts an HTTP status code to its corresponding textual description.
91    ///
92    /// This method matches a given numeric HTTP status code and returns the corresponding
93    /// textual representation defined in the `HttpStatus` enum.
94    ///
95    /// # Parameters
96    /// - `code`: A `ResponseStatusCode` representing the HTTP status code to convert.
97    ///
98    /// # Return Value
99    /// - `String`: A string representing the textual description of the HTTP status code.
100    pub fn phrase(code: ResponseStatusCode) -> String {
101        match code {
102            100 => Self::Continue.to_string(),
103            101 => Self::SwitchingProtocols.to_string(),
104            102 => Self::Processing.to_string(),
105            103 => Self::EarlyHints.to_string(),
106            200 => Self::Ok.to_string(),
107            201 => Self::Created.to_string(),
108            202 => Self::Accepted.to_string(),
109            203 => Self::NonAuthoritativeInformation.to_string(),
110            204 => Self::NoContent.to_string(),
111            205 => Self::ResetContent.to_string(),
112            206 => Self::PartialContent.to_string(),
113            207 => Self::MultiStatus.to_string(),
114            208 => Self::AlreadyReported.to_string(),
115            226 => Self::IMUsed.to_string(),
116            300 => Self::MultipleChoices.to_string(),
117            301 => Self::MovedPermanently.to_string(),
118            302 => Self::Found.to_string(),
119            303 => Self::SeeOther.to_string(),
120            304 => Self::NotModified.to_string(),
121            305 => Self::UseProxy.to_string(),
122            307 => Self::TemporaryRedirect.to_string(),
123            308 => Self::PermanentRedirect.to_string(),
124            400 => Self::BadRequest.to_string(),
125            401 => Self::Unauthorized.to_string(),
126            402 => Self::PaymentRequired.to_string(),
127            403 => Self::Forbidden.to_string(),
128            404 => Self::NotFound.to_string(),
129            405 => Self::MethodNotAllowed.to_string(),
130            406 => Self::NotAcceptable.to_string(),
131            407 => Self::ProxyAuthenticationRequired.to_string(),
132            408 => Self::RequestTimeout.to_string(),
133            409 => Self::Conflict.to_string(),
134            410 => Self::Gone.to_string(),
135            411 => Self::LengthRequired.to_string(),
136            412 => Self::PreconditionFailed.to_string(),
137            413 => Self::PayloadTooLarge.to_string(),
138            414 => Self::URITooLong.to_string(),
139            415 => Self::UnsupportedMediaType.to_string(),
140            416 => Self::RangeNotSatisfiable.to_string(),
141            417 => Self::ExpectationFailed.to_string(),
142            418 => Self::ImATeapot.to_string(),
143            421 => Self::MisdirectedRequest.to_string(),
144            422 => Self::UnprocessableEntity.to_string(),
145            423 => Self::Locked.to_string(),
146            424 => Self::FailedDependency.to_string(),
147            425 => Self::TooEarly.to_string(),
148            426 => Self::UpgradeRequired.to_string(),
149            428 => Self::PreconditionRequired.to_string(),
150            429 => Self::TooManyRequests.to_string(),
151            431 => Self::RequestHeaderFieldsTooLarge.to_string(),
152            451 => Self::UnavailableForLegalReasons.to_string(),
153            500 => Self::InternalServerError.to_string(),
154            501 => Self::NotImplemented.to_string(),
155            502 => Self::BadGateway.to_string(),
156            503 => Self::ServiceUnavailable.to_string(),
157            504 => Self::GatewayTimeout.to_string(),
158            505 => Self::HTTPVersionNotSupported.to_string(),
159            506 => Self::VariantAlsoNegotiates.to_string(),
160            507 => Self::InsufficientStorage.to_string(),
161            508 => Self::LoopDetected.to_string(),
162            510 => Self::NotExtended.to_string(),
163            511 => Self::NetworkAuthenticationRequired.to_string(),
164            _ => Self::Unknown.to_string(),
165        }
166    }
167
168    /// Compares the current status code with a given string representation.
169    ///
170    /// This method checks if the given `code_str` matches either the numeric HTTP status code
171    /// returned by `code()` or the string representation of the status code variant.
172    /// The comparison is case-insensitive.
173    ///
174    /// # Parameters
175    /// - `&self`: A reference to the `HttpStatus` enum instance.
176    /// - `code_str`: A string slice containing the status code to compare against.
177    ///
178    /// # Return Value
179    /// - `bool`: Returns `true` if `code_str` matches the numeric code or the string representation of `self`, otherwise `false`.
180    pub fn same(&self, code_str: &str) -> bool {
181        self.to_string().eq_ignore_ascii_case(code_str)
182    }
183}
184
185impl Display for HttpStatus {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        let res: &str = match self {
188            Self::Continue => "Continue",
189            Self::SwitchingProtocols => "Switching Protocols",
190            Self::Processing => "Processing",
191            Self::EarlyHints => "Early Hints",
192            Self::Ok => "OK",
193            Self::Created => "Created",
194            Self::Accepted => "Accepted",
195            Self::NonAuthoritativeInformation => "Non-Authoritative Information",
196            Self::NoContent => "No Content",
197            Self::ResetContent => "Reset Content",
198            Self::PartialContent => "Partial Content",
199            Self::MultiStatus => "Multi-Status",
200            Self::AlreadyReported => "Already Reported",
201            Self::IMUsed => "IM Used",
202            Self::MultipleChoices => "Multiple Choices",
203            Self::MovedPermanently => "Moved Permanently",
204            Self::Found => "Found",
205            Self::SeeOther => "See Other",
206            Self::NotModified => "Not Modified",
207            Self::UseProxy => "Use Proxy",
208            Self::TemporaryRedirect => "Temporary Redirect",
209            Self::PermanentRedirect => "Permanent Redirect",
210            Self::BadRequest => "Bad Request",
211            Self::Unauthorized => "Unauthorized",
212            Self::PaymentRequired => "Payment Required",
213            Self::Forbidden => "Forbidden",
214            Self::NotFound => "Not Found",
215            Self::MethodNotAllowed => "Method Not Allowed",
216            Self::NotAcceptable => "Not Acceptable",
217            Self::ProxyAuthenticationRequired => "Proxy Authentication Required",
218            Self::RequestTimeout => "Request Timeout",
219            Self::Conflict => "Conflict",
220            Self::Gone => "Gone",
221            Self::LengthRequired => "Length Required",
222            Self::PreconditionFailed => "Precondition Failed",
223            Self::PayloadTooLarge => "Payload Too Large",
224            Self::URITooLong => "URI Too Long",
225            Self::UnsupportedMediaType => "Unsupported Media Type",
226            Self::RangeNotSatisfiable => "Range Not Satisfiable",
227            Self::ExpectationFailed => "Expectation Failed",
228            Self::ImATeapot => "I'm a teapot",
229            Self::MisdirectedRequest => "Misdirected Request",
230            Self::UnprocessableEntity => "Unprocessable Entity",
231            Self::Locked => "Locked",
232            Self::FailedDependency => "Failed Dependency",
233            Self::TooEarly => "Too Early",
234            Self::UpgradeRequired => "Upgrade Required",
235            Self::PreconditionRequired => "Precondition Required",
236            Self::TooManyRequests => "Too Many Requests",
237            Self::RequestHeaderFieldsTooLarge => "Request Header Fields Too Large",
238            Self::UnavailableForLegalReasons => "Unavailable For Legal Reasons",
239            Self::InternalServerError => "Internal Server Error",
240            Self::NotImplemented => "Not Implemented",
241            Self::BadGateway => "Bad Gateway",
242            Self::ServiceUnavailable => "Service Unavailable",
243            Self::GatewayTimeout => "Gateway Timeout",
244            Self::HTTPVersionNotSupported => "HTTP Version Not Supported",
245            Self::VariantAlsoNegotiates => "Variant Also Negotiates",
246            Self::InsufficientStorage => "Insufficient Storage",
247            Self::LoopDetected => "Loop Detected",
248            Self::NotExtended => "Not Extended",
249            Self::NetworkAuthenticationRequired => "Network Authentication Required",
250            Self::Unknown => "Unknown",
251        };
252        write!(f, "{}", res)
253    }
254}
255
256impl FromStr for HttpStatus {
257    type Err = ();
258
259    fn from_str(code_str: &str) -> Result<Self, Self::Err> {
260        match code_str {
261            _code_str if Self::Continue.same(_code_str) => Ok(Self::Continue),
262            _code_str if Self::SwitchingProtocols.same(_code_str) => Ok(Self::SwitchingProtocols),
263            _code_str if Self::Processing.same(_code_str) => Ok(Self::Processing),
264            _code_str if Self::EarlyHints.same(_code_str) => Ok(Self::EarlyHints),
265            _code_str if Self::Ok.same(_code_str) => Ok(Self::Ok),
266            _code_str if Self::Created.same(_code_str) => Ok(Self::Created),
267            _code_str if Self::Accepted.same(_code_str) => Ok(Self::Accepted),
268            _code_str if Self::NonAuthoritativeInformation.same(_code_str) => {
269                Ok(Self::NonAuthoritativeInformation)
270            }
271            _code_str if Self::NoContent.same(_code_str) => Ok(Self::NoContent),
272            _code_str if Self::ResetContent.same(_code_str) => Ok(Self::ResetContent),
273            _code_str if Self::PartialContent.same(_code_str) => Ok(Self::PartialContent),
274            _code_str if Self::MultiStatus.same(_code_str) => Ok(Self::MultiStatus),
275            _code_str if Self::AlreadyReported.same(_code_str) => Ok(Self::AlreadyReported),
276            _code_str if Self::IMUsed.same(_code_str) => Ok(Self::IMUsed),
277            _code_str if Self::MultipleChoices.same(_code_str) => Ok(Self::MultipleChoices),
278            _code_str if Self::MovedPermanently.same(_code_str) => Ok(Self::MovedPermanently),
279            _code_str if Self::Found.same(_code_str) => Ok(Self::Found),
280            _code_str if Self::SeeOther.same(_code_str) => Ok(Self::SeeOther),
281            _code_str if Self::NotModified.same(_code_str) => Ok(Self::NotModified),
282            _code_str if Self::UseProxy.same(_code_str) => Ok(Self::UseProxy),
283            _code_str if Self::TemporaryRedirect.same(_code_str) => Ok(Self::TemporaryRedirect),
284            _code_str if Self::PermanentRedirect.same(_code_str) => Ok(Self::PermanentRedirect),
285            _code_str if Self::BadRequest.same(_code_str) => Ok(Self::BadRequest),
286            _code_str if Self::Unauthorized.same(_code_str) => Ok(Self::Unauthorized),
287            _code_str if Self::PaymentRequired.same(_code_str) => Ok(Self::PaymentRequired),
288            _code_str if Self::Forbidden.same(_code_str) => Ok(Self::Forbidden),
289            _code_str if Self::NotFound.same(_code_str) => Ok(Self::NotFound),
290            _code_str if Self::MethodNotAllowed.same(_code_str) => Ok(Self::MethodNotAllowed),
291            _code_str if Self::NotAcceptable.same(_code_str) => Ok(Self::NotAcceptable),
292            _code_str if Self::ProxyAuthenticationRequired.same(_code_str) => {
293                Ok(Self::ProxyAuthenticationRequired)
294            }
295            _code_str if Self::RequestTimeout.same(_code_str) => Ok(Self::RequestTimeout),
296            _code_str if Self::Conflict.same(_code_str) => Ok(Self::Conflict),
297            _code_str if Self::Gone.same(_code_str) => Ok(Self::Gone),
298            _code_str if Self::LengthRequired.same(_code_str) => Ok(Self::LengthRequired),
299            _code_str if Self::PreconditionFailed.same(_code_str) => Ok(Self::PreconditionFailed),
300            _code_str if Self::PayloadTooLarge.same(_code_str) => Ok(Self::PayloadTooLarge),
301            _code_str if Self::URITooLong.same(_code_str) => Ok(Self::URITooLong),
302            _code_str if Self::UnsupportedMediaType.same(_code_str) => {
303                Ok(Self::UnsupportedMediaType)
304            }
305            _code_str if Self::RangeNotSatisfiable.same(_code_str) => Ok(Self::RangeNotSatisfiable),
306            _code_str if Self::ExpectationFailed.same(_code_str) => Ok(Self::ExpectationFailed),
307            _code_str if Self::ImATeapot.same(_code_str) => Ok(Self::ImATeapot),
308            _code_str if Self::MisdirectedRequest.same(_code_str) => Ok(Self::MisdirectedRequest),
309            _code_str if Self::UnprocessableEntity.same(_code_str) => Ok(Self::UnprocessableEntity),
310            _code_str if Self::Locked.same(_code_str) => Ok(Self::Locked),
311            _code_str if Self::FailedDependency.same(_code_str) => Ok(Self::FailedDependency),
312            _code_str if Self::TooEarly.same(_code_str) => Ok(Self::TooEarly),
313            _code_str if Self::UpgradeRequired.same(_code_str) => Ok(Self::UpgradeRequired),
314            _code_str if Self::PreconditionRequired.same(_code_str) => {
315                Ok(Self::PreconditionRequired)
316            }
317            _code_str if Self::TooManyRequests.same(_code_str) => Ok(Self::TooManyRequests),
318            _code_str if Self::RequestHeaderFieldsTooLarge.same(_code_str) => {
319                Ok(Self::RequestHeaderFieldsTooLarge)
320            }
321            _code_str if Self::UnavailableForLegalReasons.same(_code_str) => {
322                Ok(Self::UnavailableForLegalReasons)
323            }
324            _code_str if Self::InternalServerError.same(_code_str) => Ok(Self::InternalServerError),
325            _code_str if Self::NotImplemented.same(_code_str) => Ok(Self::NotImplemented),
326            _code_str if Self::BadGateway.same(_code_str) => Ok(Self::BadGateway),
327            _code_str if Self::ServiceUnavailable.same(_code_str) => Ok(Self::ServiceUnavailable),
328            _code_str if Self::GatewayTimeout.same(_code_str) => Ok(Self::GatewayTimeout),
329            _code_str if Self::HTTPVersionNotSupported.same(_code_str) => {
330                Ok(Self::HTTPVersionNotSupported)
331            }
332            _code_str if Self::VariantAlsoNegotiates.same(_code_str) => {
333                Ok(Self::VariantAlsoNegotiates)
334            }
335            _code_str if Self::InsufficientStorage.same(_code_str) => Ok(Self::InsufficientStorage),
336            _code_str if Self::LoopDetected.same(_code_str) => Ok(Self::LoopDetected),
337            _code_str if Self::NotExtended.same(_code_str) => Ok(Self::NotExtended),
338            _code_str if Self::NetworkAuthenticationRequired.same(_code_str) => {
339                Ok(Self::NetworkAuthenticationRequired)
340            }
341            _ => Ok(Self::Unknown),
342        }
343    }
344}
345
346impl Default for HttpStatus {
347    fn default() -> Self {
348        Self::Ok
349    }
350}