http_protocol/method/
mod.rs1use bytes::Bytes;
2use std::error::Error;
3use std::fmt;
4
5#[derive(Debug, Clone)]
6pub enum MethodError {
7 InvalidMethod,
8}
9
10impl fmt::Display for MethodError {
11 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12 match self {
13 MethodError::InvalidMethod => write!(f, "Invalid method."),
14 }
15 }
16}
17
18impl Error for MethodError {}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum Method {
22 Get,
23 Head,
24 Post,
25 Put,
26 Delete,
27 Connect,
28 Options,
29 Trace,
30 Patch,
31}
32
33impl From<Method> for Bytes {
34 fn from(x: Method) -> Self {
35 match x {
36 Method::Get => Bytes::from_static(b"GET"),
37 Method::Head => Bytes::from_static(b"HEAD"),
38 Method::Post => Bytes::from_static(b"POST"),
39 Method::Put => Bytes::from_static(b"PUT"),
40 Method::Delete => Bytes::from_static(b"DELETE"),
41 Method::Connect => Bytes::from_static(b"CONNECT"),
42 Method::Options => Bytes::from_static(b"OPTIONS"),
43 Method::Trace => Bytes::from_static(b"TRACE"),
44 Method::Patch => Bytes::from_static(b"PATCH"),
45 }
46 }
47}
48
49#[inline]
50pub fn parse_method(v: &[u8]) -> Result<Method, MethodError> {
51 if v.len() < 3 || v.len() > 7 {
52 return Err(MethodError::InvalidMethod);
53 }
54
55 let mut buf = [0u8; 8];
56 &buf[0..v.len()].copy_from_slice(v);
57
58 let val = u64::from_be_bytes(buf);
59
60 match val {
61 0x4745540000000000 => Ok(Method::Get),
62 0x4845414400000000 => Ok(Method::Head),
63 0x504f535400000000 => Ok(Method::Post),
64 0x5055540000000000 => Ok(Method::Put),
65 0x44454c4554450000 => Ok(Method::Delete),
66 0x434f4e4e45435400 => Ok(Method::Connect),
67 0x4f5054494f4e5300 => Ok(Method::Options),
68 0x5452414345000000 => Ok(Method::Trace),
69 0x5041544348000000 => Ok(Method::Patch),
70 _ => Err(MethodError::InvalidMethod),
71 }
72}