use core::str::FromStr;
use errors::{ValidationError, ValidationResult};
use regex::Regex;
lazy_static! {
static ref TYPE_VALIDATOR: Regex = Regex::new("^[a-zA-Z0-9-_]+$").unwrap();
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash, Ord, PartialOrd)]
pub struct Type(pub String);
impl Type {
pub fn new(t: String) -> ValidationResult<Self> {
if t.len() > 255 {
Err("Type is too long".into())
} else if !TYPE_VALIDATOR.is_match(&t[..]) {
Err("Invalid type".into())
} else {
Ok(Type(t))
}
}
}
impl Default for Type {
fn default() -> Self {
Self { 0: "".to_string() }
}
}
impl FromStr for Type {
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::new(s.to_string())?)
}
}
#[cfg(test)]
mod tests {
use super::Type;
use std::str::FromStr;
use util::generate_random_secret;
#[test]
fn should_fail_for_invalid_types() {
assert!(Type::new(generate_random_secret(256)).is_err());
assert!(Type::new("$".to_string()).is_err());
}
#[test]
fn should_convert_str_to_type() {
assert_eq!(Type::from_str("foo").unwrap(), Type::new("foo".to_string()).unwrap());
}
}