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    #[cfg(feature = "parse")]
86    pub(crate) fn parse(buf: &[u8]) -> crate::Result<Self> {
87        str::from_utf8(buf)
88            .map_err(|_| Error::InvalidVersion)?
89            .parse()
90    }
91}
92
93impl FromStr for Version {
94    type Err = Error;
95
96    fn from_str(s: &str) -> Result<Self, Self::Err> {
97        match s {
98            "HTTP/0.9" | "http/0.9" | "0.9" => Ok(Self::Http0_9),
99            "HTTP/1.0" | "http/1.0" | "1.0" => Ok(Self::Http1_0),
100            "HTTP/1.1" | "http/1.1" | "1.1" => Ok(Self::Http1_1),
101            "HTTP/2" | "http/2" | "2" => Ok(Self::Http2),
102            "HTTP/3" | "http/3" | "3" => Ok(Self::Http3),
103            _ => Err(Error::InvalidVersion),
104        }
105    }
106}
107
108impl AsRef<str> for Version {
109    fn as_ref(&self) -> &str {
110        self.as_str()
111    }
112}
113
114impl AsRef<[u8]> for Version {
115    fn as_ref(&self) -> &[u8] {
116        self.as_str().as_bytes()
117    }
118}
119
120impl Display for Version {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        f.write_str(self.as_ref())
123    }
124}
125
126#[cfg(test)]
127mod test {
128    use super::*;
129    #[test]
130    fn from_str() {
131        let versions = [
132            Version::Http0_9,
133            Version::Http1_0,
134            Version::Http1_1,
135            Version::Http2,
136            Version::Http3,
137        ];
138
139        for version in versions {
140            assert_eq!(version.as_str().parse::<Version>().unwrap(), version);
141            assert_eq!(version.to_string().parse::<Version>().unwrap(), version);
142        }
143
144        assert_eq!(
145            "not a version".parse::<Version>().unwrap_err().to_string(),
146            "Invalid or missing version"
147        );
148    }
149
150    #[test]
151    fn eq() {
152        assert_eq!(Version::Http1_1, Version::Http1_1);
153        assert_eq!(Version::Http1_1, &Version::Http1_1);
154        assert_eq!(&Version::Http1_1, Version::Http1_1);
155    }
156
157    #[test]
158    fn to_string() {
159        let output = format!(
160            "{} {} {} {} {}",
161            Version::Http0_9,
162            Version::Http1_0,
163            Version::Http1_1,
164            Version::Http2,
165            Version::Http3
166        );
167        assert_eq!("HTTP/0.9 HTTP/1.0 HTTP/1.1 HTTP/2 HTTP/3", output);
168    }
169
170    #[test]
171    fn ord() {
172        use Version::{Http0_9, Http1_0, Http1_1, Http2, Http3};
173        assert!(Http3 > Http2);
174        assert!(Http2 > Http1_1);
175        assert!(Http1_1 > Http1_0);
176        assert!(Http1_0 > Http0_9);
177    }
178}