http_protocol/http_version/
mod.rs

1use bytes::Bytes;
2use std::error::Error;
3use std::fmt;
4
5#[derive(Debug, Clone)]
6pub enum HttpVersionError {
7    InvalidHttpVersion,
8}
9
10impl fmt::Display for HttpVersionError {
11    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12        match self {
13            HttpVersionError::InvalidHttpVersion => write!(f, "Invalid HTTP version."),
14        }
15    }
16}
17
18impl Error for HttpVersionError {}
19
20#[derive(Debug, Clone, Eq, PartialEq)]
21pub enum HttpVersion {
22    Http10,
23    Http11,
24}
25
26impl HttpVersion {
27    #[inline]
28    pub fn major(&self) -> u8 {
29        match self {
30            HttpVersion::Http10 => 1,
31            HttpVersion::Http11 => 1,
32        }
33    }
34
35    #[inline]
36    pub fn minor(&self) -> u8 {
37        match self {
38            HttpVersion::Http10 => 0,
39            HttpVersion::Http11 => 1,
40        }
41    }
42}
43
44impl From<HttpVersion> for Bytes {
45    #[inline]
46    fn from(v: HttpVersion) -> Self {
47        match v {
48            HttpVersion::Http10 => Bytes::from_static(b"HTTP/1.0"),
49            HttpVersion::Http11 => Bytes::from_static(b"HTTP/1.1"),
50        }
51    }
52}
53
54#[inline]
55pub fn get_http_version(v: &[u8]) -> Result<HttpVersion, HttpVersionError> {
56    if v.len() != 8 {
57        return Err(HttpVersionError::InvalidHttpVersion);
58    }
59
60    let mut buf = [0u8; 8];
61    buf.copy_from_slice(v);
62
63    let val = u64::from_be_bytes(buf);
64
65    match val {
66        0x485454502f312e30 => Ok(HttpVersion::Http10),
67        0x485454502f312e31 => Ok(HttpVersion::Http11),
68        _ => Err(HttpVersionError::InvalidHttpVersion),
69    }
70}