1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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)])))
}
}