Skip to main content

trillium_http/
version.rs

1// originally from https://github.com/http-rs/http-types/blob/main/src/version.rs
2
3use crate::Error;
4use std::{
5    fmt::Display,
6    str::{self, FromStr},
7};
8
9/// The version of the HTTP protocol in use.
10#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
11#[non_exhaustive]
12pub enum Version {
13    /// HTTP/0.9
14    Http0_9,
15
16    /// HTTP/1.0
17    Http1_0,
18
19    /// HTTP/1.1
20    Http1_1,
21
22    /// HTTP/2
23    Http2,
24
25    /// HTTP/3
26    Http3,
27}
28
29#[cfg(feature = "serde")]
30impl serde::Serialize for Version {
31    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
32    where
33        S: serde::Serializer,
34    {
35        serializer.collect_str(self)
36    }
37}
38
39#[cfg(feature = "serde")]
40impl<'de> serde::Deserialize<'de> for Version {
41    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
42    where
43        D: serde::Deserializer<'de>,
44    {
45        String::deserialize(deserializer)?
46            .parse()
47            .map_err(serde::de::Error::custom)
48    }
49}
50
51impl PartialEq<&Version> for Version {
52    #[allow(
53        clippy::unconditional_recursion,
54        reason = "*other deref'd to &Version dispatches to the derived PartialEq, not back to \
55                  this impl"
56    )]
57    fn eq(&self, other: &&Version) -> bool {
58        self == *other
59    }
60}
61
62impl PartialEq<Version> for &Version {
63    #[allow(
64        clippy::unconditional_recursion,
65        reason = "*self deref'd to Version dispatches to the derived PartialEq, not back to this \
66                  impl"
67    )]
68    fn eq(&self, other: &Version) -> bool {
69        *self == other
70    }
71}
72
73impl Version {
74    /// returns the http version as a static str, such as "HTTP/1.1"
75    pub const fn as_str(&self) -> &'static str {
76        match self {
77            Version::Http0_9 => "HTTP/0.9",
78            Version::Http1_0 => "HTTP/1.0",
79            Version::Http1_1 => "HTTP/1.1",
80            Version::Http2 => "HTTP/2",
81            Version::Http3 => "HTTP/3",
82        }
83    }
84
85    pub(crate) fn parse(buf: &[u8]) -> crate::Result<Self> {
86        // The request-line HTTP-version is case-sensitive (`HTTP-name` is the literal uppercase
87        // bytes), unlike the lenient `FromStr` used elsewhere. A higher minor of our major is
88        // processed as 1.1. A well-formed version with any other major (`HTTP/2.0`, `HTTP/0.9`) is
89        // one we don't speak; anything else (lowercase, garbage) is a malformed request-line.
90        match *buf {
91            [b'H', b'T', b'T', b'P', b'/', b'1', b'.', b'0'] => Ok(Self::Http1_0),
92            [b'H', b'T', b'T', b'P', b'/', b'1', b'.', b'1'..=b'9'] => Ok(Self::Http1_1),
93            [
94                b'H',
95                b'T',
96                b'T',
97                b'P',
98                b'/',
99                major @ b'0'..=b'9',
100                b'.',
101                minor @ b'0'..=b'9',
102            ] => Err(Error::UnsupportedVersionNumber {
103                major: major - b'0',
104                minor: minor - b'0',
105            }),
106            _ => Err(Error::InvalidVersion),
107        }
108    }
109}
110
111impl FromStr for Version {
112    type Err = Error;
113
114    fn from_str(s: &str) -> Result<Self, Self::Err> {
115        match s {
116            "HTTP/0.9" | "http/0.9" | "0.9" => Ok(Self::Http0_9),
117            "HTTP/1.0" | "http/1.0" | "1.0" => Ok(Self::Http1_0),
118            "HTTP/1.1" | "http/1.1" | "1.1" => Ok(Self::Http1_1),
119            "HTTP/2" | "http/2" | "2" => Ok(Self::Http2),
120            "HTTP/3" | "http/3" | "3" => Ok(Self::Http3),
121            _ => Err(Error::InvalidVersion),
122        }
123    }
124}
125
126impl AsRef<str> for Version {
127    fn as_ref(&self) -> &str {
128        self.as_str()
129    }
130}
131
132impl AsRef<[u8]> for Version {
133    fn as_ref(&self) -> &[u8] {
134        self.as_str().as_bytes()
135    }
136}
137
138impl Display for Version {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        f.write_str(self.as_ref())
141    }
142}
143
144#[cfg(test)]
145mod test {
146    use super::*;
147    #[test]
148    fn from_str() {
149        let versions = [
150            Version::Http0_9,
151            Version::Http1_0,
152            Version::Http1_1,
153            Version::Http2,
154            Version::Http3,
155        ];
156
157        for version in versions {
158            assert_eq!(version.as_str().parse::<Version>().unwrap(), version);
159            assert_eq!(version.to_string().parse::<Version>().unwrap(), version);
160        }
161
162        assert_eq!(
163            "not a version".parse::<Version>().unwrap_err().to_string(),
164            "Invalid or missing version"
165        );
166    }
167
168    #[test]
169    fn eq() {
170        assert_eq!(Version::Http1_1, Version::Http1_1);
171        assert_eq!(Version::Http1_1, &Version::Http1_1);
172        assert_eq!(&Version::Http1_1, Version::Http1_1);
173    }
174
175    #[test]
176    fn to_string() {
177        let output = format!(
178            "{} {} {} {} {}",
179            Version::Http0_9,
180            Version::Http1_0,
181            Version::Http1_1,
182            Version::Http2,
183            Version::Http3
184        );
185        assert_eq!("HTTP/0.9 HTTP/1.0 HTTP/1.1 HTTP/2 HTTP/3", output);
186    }
187
188    #[test]
189    fn ord() {
190        use Version::{Http0_9, Http1_0, Http1_1, Http2, Http3};
191        assert!(Http3 > Http2);
192        assert!(Http2 > Http1_1);
193        assert!(Http1_1 > Http1_0);
194        assert!(Http1_0 > Http0_9);
195    }
196}