safe_http 0.1.0-beta.4

Simple and safe HTTP types.
Documentation
mod constants;
mod invalid;
mod kind;

use self::kind::MethodKind;
use shared_bytes::SharedStr;
use std::{fmt, sync::Arc};

pub use self::invalid::InvalidMethod;

#[derive(Debug, Clone, PartialEq, Hash)]
pub struct Method(MethodKind);

impl Method {
    fn internal_try_from(string: SharedStr) -> Result<Self, InvalidMethod> {
        match MethodKind::standard(string.as_str()) {
            Some(kind) => Ok(Self(kind)),
            None => Self::internal_try_from_extension(string),
        }
    }

    fn internal_try_from_extension(string: SharedStr) -> Result<Self, InvalidMethod> {
        match validate(string.as_bytes()) {
            Ok(()) => Ok(Self(MethodKind::Extension(string))),
            Err(e) => Err(e),
        }
    }

    fn try_from_string(value: String) -> Result<Self, InvalidMethod> {
        match MethodKind::standard(&value) {
            Some(kind) => Ok(Self(kind)),
            None => Self::internal_try_from_extension(value.into()),
        }
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for Method {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Eq for Method {}

impl PartialEq<str> for Method {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<String> for Method {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other
    }
}

impl<T> PartialEq<&'_ T> for Method
where
    Self: PartialEq<T>,
    T: ?Sized,
{
    fn eq(&self, other: &&T) -> bool {
        self.eq(*other)
    }
}

impl TryFrom<&'static str> for Method {
    type Error = InvalidMethod;

    fn try_from(x: &'static str) -> Result<Self, Self::Error> {
        Self::internal_try_from(SharedStr::from_static(x))
    }
}

impl TryFrom<String> for Method {
    type Error = InvalidMethod;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from_string(value)
    }
}

impl TryFrom<Arc<String>> for Method {
    type Error = InvalidMethod;

    fn try_from(value: Arc<String>) -> Result<Self, Self::Error> {
        Self::internal_try_from(value.into())
    }
}

impl TryFrom<SharedStr> for Method {
    type Error = InvalidMethod;

    fn try_from(value: SharedStr) -> Result<Self, Self::Error> {
        Self::internal_try_from(value)
    }
}

impl Default for Method {
    fn default() -> Self {
        Method::GET
    }
}

impl fmt::Display for Method {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

fn validate(bytes: &[u8]) -> Result<(), InvalidMethod> {
    match crate::rfc::token::validate(bytes) {
        Ok(()) => Ok(()),
        Err(e) => Err(InvalidMethod { byte: e.byte }),
    }
}