use {
alloc::string::String,
core::{
convert::TryFrom,
fmt::{self, Display, Formatter},
str::FromStr,
},
};
use crate::Error;
const S_HTTP_0_9: &str = "HTTP/0.9";
const S_HTTP_1_0: &str = "HTTP/1.0";
const S_HTTP_1_1: &str = "HTTP/1.1";
const S_HTTP_2_0: &str = "HTTP/2.0";
const S_HTTP_3_0: &str = "HTTP/3.0";
#[derive(Debug, Eq, PartialEq, Hash, Clone, Ord, PartialOrd)]
pub enum Version {
V0_9,
V1_0,
V1_1,
V2_0,
V3_0,
}
impl Default for Version {
fn default() -> Self {
Version::V1_1
}
}
impl Display for Version {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
f.write_str(match self {
Version::V0_9 => S_HTTP_0_9,
Version::V1_0 => S_HTTP_1_0,
Version::V1_1 => S_HTTP_1_1,
Version::V2_0 => S_HTTP_2_0,
Version::V3_0 => S_HTTP_3_0,
})
}
}
impl FromStr for Version {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
S_HTTP_0_9 => Ok(Version::V0_9),
S_HTTP_1_0 => Ok(Version::V1_0),
S_HTTP_1_1 => Ok(Version::V1_1),
S_HTTP_2_0 => Ok(Version::V2_0),
S_HTTP_3_0 => Ok(Version::V3_0),
_ => Err(e!("Unknown version: {}", s)),
}
}
}
impl TryFrom<&[u8]> for Version {
type Error = Error;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
if S_HTTP_0_9.as_bytes() == bytes {
return Ok(Version::V0_9);
}
if S_HTTP_1_0.as_bytes() == bytes {
return Ok(Version::V1_0);
}
if S_HTTP_1_1.as_bytes() == bytes {
return Ok(Version::V1_1);
}
if S_HTTP_2_0.as_bytes() == bytes {
return Ok(Version::V2_0);
}
if S_HTTP_3_0.as_bytes() == bytes {
return Ok(Version::V3_0);
}
Err(e!("Unknown version: {:?}...", String::from_utf8_lossy(&bytes[..bytes.len().min(20)])))
}
}