use std::fmt;
use std::str::FromStr;
use self::Method::*;
use crate::hyper;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Method {
Get,
Put,
Post,
Delete,
Options,
Head,
Trace,
Connect,
Patch
}
impl Method {
#[doc(hidden)]
pub fn from_hyp(method: &hyper::Method) -> Option<Method> {
match *method {
hyper::Method::GET => Some(Get),
hyper::Method::PUT => Some(Put),
hyper::Method::POST => Some(Post),
hyper::Method::DELETE => Some(Delete),
hyper::Method::OPTIONS => Some(Options),
hyper::Method::HEAD => Some(Head),
hyper::Method::TRACE => Some(Trace),
hyper::Method::CONNECT => Some(Connect),
hyper::Method::PATCH => Some(Patch),
_ => None,
}
}
#[inline]
pub fn supports_payload(self) -> bool {
match self {
Put | Post | Delete | Patch => true,
Get | Head | Connect | Trace | Options => false,
}
}
#[inline]
pub fn as_str(self) -> &'static str {
match self {
Get => "GET",
Put => "PUT",
Post => "POST",
Delete => "DELETE",
Options => "OPTIONS",
Head => "HEAD",
Trace => "TRACE",
Connect => "CONNECT",
Patch => "PATCH",
}
}
}
impl FromStr for Method {
type Err = ();
fn from_str(s: &str) -> Result<Method, ()> {
match s {
x if uncased::eq(x, Get.as_str()) => Ok(Get),
x if uncased::eq(x, Put.as_str()) => Ok(Put),
x if uncased::eq(x, Post.as_str()) => Ok(Post),
x if uncased::eq(x, Delete.as_str()) => Ok(Delete),
x if uncased::eq(x, Options.as_str()) => Ok(Options),
x if uncased::eq(x, Head.as_str()) => Ok(Head),
x if uncased::eq(x, Trace.as_str()) => Ok(Trace),
x if uncased::eq(x, Connect.as_str()) => Ok(Connect),
x if uncased::eq(x, Patch.as_str()) => Ok(Patch),
_ => Err(()),
}
}
}
impl fmt::Display for Method {
#[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_str().fmt(f)
}
}
#[cfg(feature = "serde")]
mod serde {
use std::fmt;
use super::*;
use serde_::ser::{Serialize, Serializer};
use serde_::de::{Deserialize, Deserializer, Error, Visitor, Unexpected};
impl<'a> Serialize for Method {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
struct DeVisitor;
impl<'de> Visitor<'de> for DeVisitor {
type Value = Method;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "valid HTTP method string")
}
fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
Method::from_str(v).map_err(|_| E::invalid_value(Unexpected::Str(v), &self))
}
}
impl<'de> Deserialize<'de> for Method {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_str(DeVisitor)
}
}
}