http1/
version.rs

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
use std::{fmt::Display, str::FromStr};

/// Represents the http protocol version.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Version {
    // HTTP/1.0 version.
    Http1_0,

    // HTTP/1.1 version.
    #[default]
    Http1_1,
}

impl Version {
    /// Gets the version as `str`.
    pub fn as_str(&self) -> &str {
        match self {
            Version::Http1_0 => "HTTP/1.0",
            Version::Http1_1 => "HTTP/1.1",
        }
    }
}

impl Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

///  An error when fails to parse the version.
#[derive(Debug)]
pub struct InvalidVersion(String);

impl std::error::Error for InvalidVersion {}

impl Display for InvalidVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid http version: {}", self.0)
    }
}

impl FromStr for Version {
    type Err = InvalidVersion;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            s if s.eq_ignore_ascii_case("HTTP/1.0") => Ok(Version::Http1_0),
            s if s.eq_ignore_ascii_case("HTTP/1.1") => Ok(Version::Http1_1),
            _ => Err(InvalidVersion(s.to_owned())),
        }
    }
}