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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use crate::errors::{ValidationError, ValidationResult};
use core::str::FromStr;
use regex::Regex;

lazy_static! {
    static ref TYPE_VALIDATOR: Regex = Regex::new("^[a-zA-Z0-9-_]+$").unwrap();
}

/// An edge or vertex type.
///
/// Types must be less than 256 characters long, and can only contain letters,
/// numbers, dashes and underscores.
#[derive(Eq, PartialEq, Clone, Debug, Hash, Ord, PartialOrd)]
pub struct Type(pub String);

impl Type {
    /// Constructs a new type.
    ///
    /// # Arguments
    ///
    /// * `t` - The type, which must be less than 256 characters long.
    ///
    /// # Errors
    /// Returns a `ValidationError` if the type is longer than 255 characters,
    /// or has invalid characters.
    pub fn new<S: Into<String>>(s: S) -> ValidationResult<Self> {
        let s = s.into();

        if s.len() > 255 {
            Err(ValidationError::ValueTooLong)
        } else if !TYPE_VALIDATOR.is_match(&s[..]) {
            Err(ValidationError::InvalidValue)
        } else {
            Ok(Type(s))
        }
    }

    pub unsafe fn new_unchecked<S: Into<String>>(s: S) -> Self {
        Type(s.into())
    }
}

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 crate::util::generate_random_secret;
    use std::str::FromStr;

    #[test]
    fn should_fail_for_invalid_types() {
        assert!(Type::new(generate_random_secret(256)).is_err());
        assert!(Type::new("$").is_err());
    }

    #[test]
    fn should_convert_str_to_type() {
        assert_eq!(Type::from_str("foo").unwrap(), Type::new("foo").unwrap());
    }
}