use std::fmt;
use serde::{Deserialize, Serialize};
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Method {
Get,
Put,
Post,
Delete,
Options,
Head,
Patch,
Trace,
#[cfg(feature = "openapi32")]
Query,
}
impl Method {
#[must_use]
pub fn all() -> &'static [Self] {
&[
Self::Get,
Self::Put,
Self::Post,
Self::Delete,
Self::Options,
Self::Head,
Self::Patch,
Self::Trace,
#[cfg(feature = "openapi32")]
Self::Query,
]
}
#[must_use]
pub fn as_wire_str(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Put => "PUT",
Self::Post => "POST",
Self::Delete => "DELETE",
Self::Options => "OPTIONS",
Self::Head => "HEAD",
Self::Patch => "PATCH",
Self::Trace => "TRACE",
#[cfg(feature = "openapi32")]
Self::Query => "QUERY",
}
}
#[must_use]
pub fn from_wire_str(name: &str) -> Option<Self> {
Some(match name {
"GET" => Self::Get,
"PUT" => Self::Put,
"POST" => Self::Post,
"DELETE" => Self::Delete,
"OPTIONS" => Self::Options,
"HEAD" => Self::Head,
"PATCH" => Self::Patch,
"TRACE" => Self::Trace,
#[cfg(feature = "openapi32")]
"QUERY" => Self::Query,
_ => return None,
})
}
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_wire_str())
}
}
#[cfg(feature = "http")]
impl From<Method> for http::Method {
fn from(method: Method) -> Self {
Self::from_bytes(method.as_wire_str().as_bytes())
.expect("every described method is a valid HTTP method token")
}
}
#[cfg(feature = "http")]
impl TryFrom<&http::Method> for Method {
type Error = UnnamedMethod;
fn try_from(method: &http::Method) -> Result<Self, Self::Error> {
Method::from_wire_str(method.as_str()).ok_or_else(|| UnnamedMethod {
method: method.as_str().to_owned(),
})
}
}
#[cfg(feature = "http")]
impl TryFrom<http::Method> for Method {
type Error = UnnamedMethod;
fn try_from(method: http::Method) -> Result<Self, Self::Error> {
Self::try_from(&method)
}
}
#[cfg(feature = "http")]
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error(
"`{method}` is not a method a Path Item has a field for; 3.2 describes one through \
`additionalOperations`"
)]
pub struct UnnamedMethod {
pub method: String,
}