Support FromParam on Uuid

This commit is contained in:
Lori Holden 2017-01-10 13:23:10 -05:00
parent b109bb41ff
commit df04aa21c6
3 changed files with 39 additions and 0 deletions

View File

@ -19,6 +19,7 @@ log = "^0.3"
url = "^1"
toml = "^0.2"
# cookie = "^0.3"
uuid = { version="^0.3", optional=true }
[dependencies.hyper]
version = "^0.9"
@ -27,6 +28,7 @@ default-features = false
[dev-dependencies]
lazy_static = "0.2"
rocket_codegen = { version = "0.1.4", path = "../codegen" }
uuid = { version="^0.3" }
[features]
testing = []

View File

@ -96,6 +96,9 @@ extern crate hyper;
extern crate url;
extern crate toml;
#[cfg(any(test, feature = "uuid"))]
extern crate uuid;
#[cfg(test)] #[macro_use] extern crate lazy_static;
#[doc(hidden)] #[macro_use] pub mod logger;

View File

@ -5,6 +5,9 @@ use std::fmt::Debug;
use http::uri::{URI, Segments};
#[cfg(any(test, feature = "uuid"))]
use uuid::{self, Uuid};
/// Trait to convert a dynamic path segment string to a concrete value.
///
/// This trait is used by Rocket's code generation facilities to parse dynamic
@ -210,6 +213,14 @@ impl<'a> FromParam<'a> for String {
}
}
#[cfg(any(test, feature = "uuid"))]
impl<'a> FromParam<'a> for Uuid {
type Error = uuid::ParseError;
fn from_param(p: &'a str) -> Result<Uuid, Self::Error> {
p.parse()
}
}
macro_rules! impl_with_fromstr {
($($T:ident),+) => ($(
impl<'a> FromParam<'a> for $T {
@ -321,3 +332,26 @@ impl<'a, T: FromSegments<'a>> FromSegments<'a> for Option<T> {
})
}
}
#[cfg(test)]
mod test {
use uuid::{self, Uuid};
use super::FromParam;
#[test]
fn test_from_param_uuid() {
let uuid_str = "c1aa1e3b-9614-4895-9ebd-705255fa5bc2";
let uuid_result = Uuid::from_param(uuid_str);
assert!(uuid_result.is_ok());
let uuid = uuid_result.unwrap();
assert!(uuid_str.to_string() == uuid.to_string())
}
#[test]
fn test_from_param_invalid_uuid() {
let uuid_str = "c1aa1e3b-9614-4895-9ebd-705255fa5bc2p";
let uuid_result = Uuid::from_param(uuid_str);
assert!(!uuid_result.is_ok());
assert!(uuid_result == Err(uuid::ParseError::InvalidLength(37)));
}
}