use std::fmt::{Display, Formatter};
use std::str::FromStr;
use crate::HttpError;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum Method {
Get,
Head,
Post,
Put,
Patch,
Delete,
Options,
}
impl Method {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Head => "HEAD",
Self::Post => "POST",
Self::Put => "PUT",
Self::Patch => "PATCH",
Self::Delete => "DELETE",
Self::Options => "OPTIONS",
}
}
}
impl Display for Method {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Method {
type Err = HttpError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.to_ascii_uppercase().as_str() {
"GET" => Ok(Self::Get),
"HEAD" => Ok(Self::Head),
"POST" => Ok(Self::Post),
"PUT" => Ok(Self::Put),
"PATCH" => Ok(Self::Patch),
"DELETE" => Ok(Self::Delete),
"OPTIONS" => Ok(Self::Options),
_ => Err(HttpError::status(
405,
format!("unsupported method `{value}`"),
)),
}
}
}