use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Method {
Get,
Head,
Post,
Put,
Patch,
Delete,
Options,
Trace,
Connect,
}
impl Method {
pub fn parse(token: &str) -> Option<Method> {
Some(match token {
"GET" => Method::Get,
"HEAD" => Method::Head,
"POST" => Method::Post,
"PUT" => Method::Put,
"PATCH" => Method::Patch,
"DELETE" => Method::Delete,
"OPTIONS" => Method::Options,
"TRACE" => Method::Trace,
"CONNECT" => Method::Connect,
_ => return None,
})
}
pub fn as_str(self) -> &'static str {
match self {
Method::Get => "GET",
Method::Head => "HEAD",
Method::Post => "POST",
Method::Put => "PUT",
Method::Patch => "PATCH",
Method::Delete => "DELETE",
Method::Options => "OPTIONS",
Method::Trace => "TRACE",
Method::Connect => "CONNECT",
}
}
pub fn expects_body(self) -> bool {
matches!(self, Method::Post | Method::Put | Method::Patch)
}
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_known_methods() {
assert_eq!(Method::parse("GET"), Some(Method::Get));
assert_eq!(Method::parse("DELETE"), Some(Method::Delete));
}
#[test]
fn rejects_unknown_and_lowercase() {
assert_eq!(Method::parse("get"), None);
assert_eq!(Method::parse("BREW"), None);
}
#[test]
fn round_trips() {
let all = [
Method::Get,
Method::Head,
Method::Post,
Method::Put,
Method::Patch,
Method::Delete,
Method::Options,
Method::Trace,
Method::Connect,
];
for m in all {
assert_eq!(Method::parse(m.as_str()), Some(m));
}
}
}