use crate::*;
use std::{
fmt::{self, Display},
str::FromStr,
};
impl StatusCode {
#[inline]
pub fn code(&self) -> StatusCodeUsize {
match self {
Self::Ok => 200,
Self::Created => 201,
Self::NoContent => 204,
Self::BadRequest => 400,
Self::Unauthorized => 401,
Self::Forbidden => 403,
Self::NotFound => 404,
Self::InternalServerError => 500,
Self::NotImplemented => 501,
Self::BadGateway => 502,
Self::Unknown => 0,
}
}
#[inline]
pub fn phrase(code: usize) -> String {
match code {
200 => Self::Ok.to_string(),
201 => Self::Created.to_string(),
204 => Self::NoContent.to_string(),
400 => Self::BadRequest.to_string(),
401 => Self::Unauthorized.to_string(),
403 => Self::Forbidden.to_string(),
404 => Self::NotFound.to_string(),
500 => Self::InternalServerError.to_string(),
501 => Self::NotImplemented.to_string(),
502 => Self::BadGateway.to_string(),
_ => Self::Unknown.to_string(),
}
}
#[inline]
pub fn same(&self, code_str: &str) -> bool {
self.code().to_string() == code_str || self.to_string() == code_str
}
}
impl Display for StatusCode {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res: &str = match self {
Self::Ok => "OK",
Self::Created => "Created",
Self::NoContent => "No Content",
Self::BadRequest => "Bad Request",
Self::Unauthorized => "Unauthorized",
Self::Forbidden => "Forbidden",
Self::NotFound => "Not Found",
Self::InternalServerError => "Internal Server Error",
Self::NotImplemented => "Not Implemented",
Self::BadGateway => "Bad Gateway",
Self::Unknown => "Unknown",
};
write!(f, "{}", res)
}
}
impl FromStr for StatusCode {
type Err = ();
#[inline]
fn from_str(code_str: &str) -> Result<Self, Self::Err> {
match code_str {
_code_str if Self::Ok.same(_code_str) => Ok(Self::Ok),
_code_str if Self::Created.same(_code_str) => Ok(Self::Created),
_code_str if Self::NoContent.same(_code_str) => Ok(Self::NoContent),
_code_str if Self::BadRequest.same(_code_str) => Ok(Self::BadRequest),
_code_str if Self::Unauthorized.same(_code_str) => Ok(Self::Unauthorized),
_code_str if Self::Forbidden.same(_code_str) => Ok(Self::Forbidden),
_code_str if Self::NotFound.same(_code_str) => Ok(Self::NotFound),
_code_str if Self::InternalServerError.same(_code_str) => Ok(Self::InternalServerError),
_code_str if Self::NotImplemented.same(_code_str) => Ok(Self::NotImplemented),
_code_str if Self::BadGateway.same(_code_str) => Ok(Self::BadGateway),
_ => Ok(Self::Unknown),
}
}
}
impl Default for StatusCode {
#[inline]
fn default() -> Self {
Self::Ok
}
}