Skip to content

Commit

Permalink
feat(version): impl FromStr for HttpVersion
Browse files Browse the repository at this point in the history
  • Loading branch information
liamchristopher authored and seanmonstar committed Mar 30, 2017
1 parent 8dc06f2 commit 47f3aa6
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
//! Instead of relying on typo-prone Strings, use expected HTTP versions as
//! the `HttpVersion` enum.
use std::fmt;
use std::str::FromStr;

use error::Error;
use self::HttpVersion::{Http09, Http10, Http11, H2, H2c};

/// Represents a version of the HTTP spec.
Expand Down Expand Up @@ -36,8 +38,54 @@ impl fmt::Display for HttpVersion {
}
}

impl FromStr for HttpVersion {
type Err = Error;
fn from_str(s: &str) -> Result<HttpVersion, Error> {
Ok(match s {
"HTTP/0.9" => Http09,
"HTTP/1.0" => Http10,
"HTTP/1.1" => Http11,
"h2" => H2,
"h2c" => H2c,
_ => return Err(Error::Version),
})
}
}

impl Default for HttpVersion {
fn default() -> HttpVersion {
Http11
}
}

#[cfg(test)]
mod tests {
use std::str::FromStr;
use error::Error;
use super::HttpVersion;
use super::HttpVersion::{Http09,Http10,Http11,H2,H2c};

#[test]
fn test_default() {
assert_eq!(Http11, HttpVersion::default());
}

#[test]
fn test_from_str() {
assert_eq!(Http09, HttpVersion::from_str("HTTP/0.9").unwrap());
assert_eq!(Http10, HttpVersion::from_str("HTTP/1.0").unwrap());
assert_eq!(Http11, HttpVersion::from_str("HTTP/1.1").unwrap());
assert_eq!(H2, HttpVersion::from_str("h2").unwrap());
assert_eq!(H2c, HttpVersion::from_str("h2c").unwrap());
}

#[test]
fn test_from_str_panic() {
match HttpVersion::from_str("foo") {
Err(Error::Version) => assert!(true),
Err(_) => assert!(false),
Ok(_) => assert!(false),
}
}

}

0 comments on commit 47f3aa6

Please sign in to comment.