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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use std::convert::TryFrom;
use std::str::FromStr;
use crate::errors::{ValidationError, ValidationResult};
use serde::{Deserialize, Serialize};
#[derive(Eq, PartialEq, Clone, Debug, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Identifier(pub(crate) String);
impl Identifier {
pub fn new<S: Into<String>>(s: S) -> ValidationResult<Self> {
let s = s.into();
if s.len() > 255 {
Err(ValidationError::ValueTooLong)
} else if !s.chars().all(|c| c == '-' || c == '_' || c.is_alphanumeric()) {
Err(ValidationError::InvalidValue)
} else {
Ok(Identifier(s))
}
}
pub unsafe fn new_unchecked<S: Into<String>>(s: S) -> Self {
Identifier(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl Default for Identifier {
fn default() -> Self {
Self("".to_string())
}
}
impl FromStr for Identifier {
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s.to_string())
}
}
impl TryFrom<String> for Identifier {
type Error = ValidationError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
impl ToString for Identifier {
fn to_string(&self) -> String {
self.0.clone()
}
}
#[cfg(test)]
mod tests {
use super::Identifier;
use std::str::FromStr;
#[test]
fn should_fail_for_invalid_identifiers() {
let long_t = (0..256).map(|_| "X").collect::<String>();
assert!(Identifier::new(long_t).is_err());
assert!(Identifier::new("$").is_err());
}
#[test]
fn should_convert_str_to_identifier() {
assert_eq!(Identifier::from_str("foo").unwrap(), Identifier::new("foo").unwrap());
}
}