Skip to main content

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    /// Gets the numeric HTTP status code.
10    ///
11    /// Returns the corresponding HTTP status code number for the enum variant.
12    ///
13    /// # Returns
14    ///
15    /// - `u16` - The numeric status code.
16    pub fn code(&self) -> ResponseStatusCode {
17        match self {
18            Self::Continue => 100,
19            Self::SwitchingProtocols => 101,
20            Self::Processing => 102,
21            Self::EarlyHints => 103,
22            Self::Ok => 200,
23            Self::Created => 201,
24            Self::Accepted => 202,
25            Self::NonAuthoritativeInformation => 203,
26            Self::NoContent => 204,
27            Self::ResetContent => 205,
28            Self::PartialContent => 206,
29            Self::MultiStatus => 207,
30            Self::AlreadyReported => 208,
31            Self::IMUsed => 226,
32            Self::MultipleChoices => 300,
33            Self::MovedPermanently => 301,
34            Self::Found => 302,
35            Self::SeeOther => 303,
36            Self::NotModified => 304,
37            Self::UseProxy => 305,
38            Self::TemporaryRedirect => 307,
39            Self::PermanentRedirect => 308,
40            Self::BadRequest => 400,
41            Self::Unauthorized => 401,
42            Self::PaymentRequired => 402,
43            Self::Forbidden => 403,
44            Self::NotFound => 404,
45            Self::MethodNotAllowed => 405,
46            Self::NotAcceptable => 406,
47            Self::ProxyAuthenticationRequired => 407,
48            Self::RequestTimeout => 408,
49            Self::Conflict => 409,
50            Self::Gone => 410,
51            Self::LengthRequired => 411,
52            Self::PreconditionFailed => 412,
53            Self::PayloadTooLarge => 413,
54            Self::URITooLong => 414,
55            Self::UnsupportedMediaType => 415,
56            Self::RangeNotSatisfiable => 416,
57            Self::ExpectationFailed => 417,
58            Self::ImATeapot => 418,
59            Self::MisdirectedRequest => 421,
60            Self::UnprocessableEntity => 422,
61            Self::Locked => 423,
62            Self::FailedDependency => 424,
63            Self::TooEarly => 425,
64            Self::UpgradeRequired => 426,
65            Self::PreconditionRequired => 428,
66            Self::TooManyRequests => 429,
67            Self::RequestHeaderFieldsTooLarge => 431,
68            Self::UnavailableForLegalReasons => 451,
69            Self::InternalServerError => 500,
70            Self::NotImplemented => 501,
71            Self::BadGateway => 502,
72            Self::ServiceUnavailable => 503,
73            Self::GatewayTimeout => 504,
74            Self::HTTPVersionNotSupported => 505,
75            Self::VariantAlsoNegotiates => 506,
76            Self::InsufficientStorage => 507,
77            Self::LoopDetected => 508,
78            Self::NotExtended => 510,
79            Self::NetworkAuthenticationRequired => 511,
80            Self::Unknown => 0,
81        }
82    }
83
84    /// Gets the textual description for a status code.
85    ///
86    /// Returns the standard HTTP status text for the given numeric code.
87    ///
88    /// # Arguments
89    ///
90    /// - `u16` - The numeric HTTP status code.
91    ///
92    /// # Returns
93    ///
94    /// - `String` - The standard status text description.
95    pub fn phrase(code: ResponseStatusCode) -> String {
96        match code {
97            100 => Self::Continue.to_string(),
98            101 => Self::SwitchingProtocols.to_string(),
99            102 => Self::Processing.to_string(),
100            103 => Self::EarlyHints.to_string(),
101            200 => Self::Ok.to_string(),
102            201 => Self::Created.to_string(),
103            202 => Self::Accepted.to_string(),
104            203 => Self::NonAuthoritativeInformation.to_string(),
105            204 => Self::NoContent.to_string(),
106            205 => Self::ResetContent.to_string(),
107            206 => Self::PartialContent.to_string(),
108            207 => Self::MultiStatus.to_string(),
109            208 => Self::AlreadyReported.to_string(),
110            226 => Self::IMUsed.to_string(),
111            300 => Self::MultipleChoices.to_string(),
112            301 => Self::MovedPermanently.to_string(),
113            302 => Self::Found.to_string(),
114            303 => Self::SeeOther.to_string(),
115            304 => Self::NotModified.to_string(),
116            305 => Self::UseProxy.to_string(),
117            307 => Self::TemporaryRedirect.to_string(),
118            308 => Self::PermanentRedirect.to_string(),
119            400 => Self::BadRequest.to_string(),
120            401 => Self::Unauthorized.to_string(),
121            402 => Self::PaymentRequired.to_string(),
122            403 => Self::Forbidden.to_string(),
123            404 => Self::NotFound.to_string(),
124            405 => Self::MethodNotAllowed.to_string(),
125            406 => Self::NotAcceptable.to_string(),
126            407 => Self::ProxyAuthenticationRequired.to_string(),
127            408 => Self::RequestTimeout.to_string(),
128            409 => Self::Conflict.to_string(),
129            410 => Self::Gone.to_string(),
130            411 => Self::LengthRequired.to_string(),
131            412 => Self::PreconditionFailed.to_string(),
132            413 => Self::PayloadTooLarge.to_string(),
133            414 => Self::URITooLong.to_string(),
134            415 => Self::UnsupportedMediaType.to_string(),
135            416 => Self::RangeNotSatisfiable.to_string(),
136            417 => Self::ExpectationFailed.to_string(),
137            418 => Self::ImATeapot.to_string(),
138            421 => Self::MisdirectedRequest.to_string(),
139            422 => Self::UnprocessableEntity.to_string(),
140            423 => Self::Locked.to_string(),
141            424 => Self::FailedDependency.to_string(),
142            425 => Self::TooEarly.to_string(),
143            426 => Self::UpgradeRequired.to_string(),
144            428 => Self::PreconditionRequired.to_string(),
145            429 => Self::TooManyRequests.to_string(),
146            431 => Self::RequestHeaderFieldsTooLarge.to_string(),
147            451 => Self::UnavailableForLegalReasons.to_string(),
148            500 => Self::InternalServerError.to_string(),
149            501 => Self::NotImplemented.to_string(),
150            502 => Self::BadGateway.to_string(),
151            503 => Self::ServiceUnavailable.to_string(),
152            504 => Self::GatewayTimeout.to_string(),
153            505 => Self::HTTPVersionNotSupported.to_string(),
154            506 => Self::VariantAlsoNegotiates.to_string(),
155            507 => Self::InsufficientStorage.to_string(),
156            508 => Self::LoopDetected.to_string(),
157            510 => Self::NotExtended.to_string(),
158            511 => Self::NetworkAuthenticationRequired.to_string(),
159            _ => Self::Unknown.to_string(),
160        }
161    }
162
163    /// Checks if status matches a string representation.
164    ///
165    /// Compares case-insensitively against both numeric code and text description.
166    ///
167    /// # Arguments
168    ///
169    /// - `AsRef<str>` - The string to compare against.
170    ///
171    /// # Returns
172    ///
173    /// - `bool` - True if the string matches either code or description.
174    pub fn same<C>(&self, code_str: C) -> bool
175    where
176        C: AsRef<str>,
177    {
178        self.to_string().eq_ignore_ascii_case(code_str.as_ref())
179    }
180}
181
182/// Implements the `Display` trait for `HttpStatus`, allowing it to be formatted as a string.
183impl Display for HttpStatus {
184    /// Formats the status code as text.
185    ///
186    /// # Arguments
187    ///
188    /// - `&mut fmt::Formatter` - The formatter to write to.
189    ///
190    /// # Returns
191    ///
192    /// - `fmt::Result` - The formatting result.
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        let res: &str = match self {
195            Self::Continue => CONTINUE,
196            Self::SwitchingProtocols => SWITCHING_PROTOCOLS,
197            Self::Processing => PROCESSING,
198            Self::EarlyHints => EARLY_HINTS,
199            Self::Ok => OK,
200            Self::Created => CREATED,
201            Self::Accepted => ACCEPTED,
202            Self::NonAuthoritativeInformation => NON_AUTHORITATIVE_INFORMATION,
203            Self::NoContent => NO_CONTENT,
204            Self::ResetContent => RESET_CONTENT,
205            Self::PartialContent => PARTIAL_CONTENT,
206            Self::MultiStatus => MULTI_STATUS,
207            Self::AlreadyReported => ALREADY_REPORTED,
208            Self::IMUsed => IM_USED,
209            Self::MultipleChoices => MULTIPLE_CHOICES,
210            Self::MovedPermanently => MOVED_PERMANENTLY,
211            Self::Found => FOUND,
212            Self::SeeOther => SEE_OTHER,
213            Self::NotModified => NOT_MODIFIED,
214            Self::UseProxy => USE_PROXY,
215            Self::TemporaryRedirect => TEMPORARY_REDIRECT,
216            Self::PermanentRedirect => PERMANENT_REDIRECT,
217            Self::BadRequest => BAD_REQUEST,
218            Self::Unauthorized => UNAUTHORIZED,
219            Self::PaymentRequired => PAYMENT_REQUIRED,
220            Self::Forbidden => FORBIDDEN,
221            Self::NotFound => NOT_FOUND,
222            Self::MethodNotAllowed => METHOD_NOT_ALLOWED,
223            Self::NotAcceptable => NOT_ACCEPTABLE,
224            Self::ProxyAuthenticationRequired => PROXY_AUTHENTICATION_REQUIRED,
225            Self::RequestTimeout => REQUEST_TIMEOUT,
226            Self::Conflict => CONFLICT,
227            Self::Gone => GONE,
228            Self::LengthRequired => LENGTH_REQUIRED,
229            Self::PreconditionFailed => PRECONDITION_FAILED,
230            Self::PayloadTooLarge => PAYLOAD_TOO_LARGE,
231            Self::URITooLong => URI_TOO_LONG,
232            Self::UnsupportedMediaType => UNSUPPORTED_MEDIA_TYPE,
233            Self::RangeNotSatisfiable => RANGE_NOT_SATISFIABLE,
234            Self::ExpectationFailed => EXPECTATION_FAILED,
235            Self::ImATeapot => IM_A_TEAPOT,
236            Self::MisdirectedRequest => MISDIRECTED_REQUEST,
237            Self::UnprocessableEntity => UNPROCESSABLE_ENTITY,
238            Self::Locked => LOCKED,
239            Self::FailedDependency => FAILED_DEPENDENCY,
240            Self::TooEarly => TOO_EARLY,
241            Self::UpgradeRequired => UPGRADE_REQUIRED,
242            Self::PreconditionRequired => PRECONDITION_REQUIRED,
243            Self::TooManyRequests => TOO_MANY_REQUESTS,
244            Self::RequestHeaderFieldsTooLarge => REQUEST_HEADER_FIELDS_TOO_LARGE,
245            Self::UnavailableForLegalReasons => UNAVAILABLE_FOR_LEGAL_REASONS,
246            Self::InternalServerError => INTERNAL_SERVER_ERROR,
247            Self::NotImplemented => NOT_IMPLEMENTED,
248            Self::BadGateway => BAD_GATEWAY,
249            Self::ServiceUnavailable => SERVICE_UNAVAILABLE,
250            Self::GatewayTimeout => GATEWAY_TIMEOUT,
251            Self::HTTPVersionNotSupported => HTTP_VERSION_NOT_SUPPORTED,
252            Self::VariantAlsoNegotiates => VARIANT_ALSO_NEGOTIATES,
253            Self::InsufficientStorage => INSUFFICIENT_STORAGE,
254            Self::LoopDetected => LOOP_DETECTED,
255            Self::NotExtended => NOT_EXTENDED,
256            Self::NetworkAuthenticationRequired => NETWORK_AUTHENTICATION_REQUIRED,
257            Self::Unknown => UNKNOWN,
258        };
259        write!(f, "{res}")
260    }
261}
262
263/// Implements the `FromStr` trait for `HttpStatus`, allowing conversion from a string slice.
264impl FromStr for HttpStatus {
265    /// The error type returned when conversion fails.
266    type Err = ();
267
268    /// Parses a string into an HttpStatus.
269    ///
270    /// Attempts to convert the string to a numeric code and match known status codes.
271    ///
272    /// # Arguments
273    ///
274    /// - `&str` - The string to parse.
275    ///
276    /// # Returns
277    ///
278    /// - `Result<HttpStatus, ()>` - The parsed status or error.
279    fn from_str(code_str: &str) -> Result<Self, Self::Err> {
280        if let Ok(code) = code_str.parse::<ResponseStatusCode>() {
281            match code {
282                100 => Ok(Self::Continue),
283                101 => Ok(Self::SwitchingProtocols),
284                102 => Ok(Self::Processing),
285                103 => Ok(Self::EarlyHints),
286                200 => Ok(Self::Ok),
287                201 => Ok(Self::Created),
288                202 => Ok(Self::Accepted),
289                203 => Ok(Self::NonAuthoritativeInformation),
290                204 => Ok(Self::NoContent),
291                205 => Ok(Self::ResetContent),
292                206 => Ok(Self::PartialContent),
293                207 => Ok(Self::MultiStatus),
294                208 => Ok(Self::AlreadyReported),
295                226 => Ok(Self::IMUsed),
296                300 => Ok(Self::MultipleChoices),
297                301 => Ok(Self::MovedPermanently),
298                302 => Ok(Self::Found),
299                303 => Ok(Self::SeeOther),
300                304 => Ok(Self::NotModified),
301                305 => Ok(Self::UseProxy),
302                307 => Ok(Self::TemporaryRedirect),
303                308 => Ok(Self::PermanentRedirect),
304                400 => Ok(Self::BadRequest),
305                401 => Ok(Self::Unauthorized),
306                402 => Ok(Self::PaymentRequired),
307                403 => Ok(Self::Forbidden),
308                404 => Ok(Self::NotFound),
309                405 => Ok(Self::MethodNotAllowed),
310                406 => Ok(Self::NotAcceptable),
311                407 => Ok(Self::ProxyAuthenticationRequired),
312                408 => Ok(Self::RequestTimeout),
313                409 => Ok(Self::Conflict),
314                410 => Ok(Self::Gone),
315                411 => Ok(Self::LengthRequired),
316                412 => Ok(Self::PreconditionFailed),
317                413 => Ok(Self::PayloadTooLarge),
318                414 => Ok(Self::URITooLong),
319                415 => Ok(Self::UnsupportedMediaType),
320                416 => Ok(Self::RangeNotSatisfiable),
321                417 => Ok(Self::ExpectationFailed),
322                418 => Ok(Self::ImATeapot),
323                421 => Ok(Self::MisdirectedRequest),
324                422 => Ok(Self::UnprocessableEntity),
325                423 => Ok(Self::Locked),
326                424 => Ok(Self::FailedDependency),
327                425 => Ok(Self::TooEarly),
328                426 => Ok(Self::UpgradeRequired),
329                428 => Ok(Self::PreconditionRequired),
330                429 => Ok(Self::TooManyRequests),
331                431 => Ok(Self::RequestHeaderFieldsTooLarge),
332                451 => Ok(Self::UnavailableForLegalReasons),
333                500 => Ok(Self::InternalServerError),
334                501 => Ok(Self::NotImplemented),
335                502 => Ok(Self::BadGateway),
336                503 => Ok(Self::ServiceUnavailable),
337                504 => Ok(Self::GatewayTimeout),
338                505 => Ok(Self::HTTPVersionNotSupported),
339                506 => Ok(Self::VariantAlsoNegotiates),
340                507 => Ok(Self::InsufficientStorage),
341                508 => Ok(Self::LoopDetected),
342                510 => Ok(Self::NotExtended),
343                511 => Ok(Self::NetworkAuthenticationRequired),
344                _ => Ok(Self::Unknown),
345            }
346        } else {
347            Ok(Self::Unknown)
348        }
349    }
350}