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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use std::borrow::{Borrow, Cow};
use std::str::FromStr;
use super::{Value, BaseValue, InvalidValue};
#[derive(Debug, PartialEq, Clone)]
pub struct EmailValue {
val: Cow<'static, str>,
}
impl EmailValue {
pub fn try_new<STR>(val: STR) -> Result<Self, InvalidValue>
where STR: Into<Cow<'static, str>>
{
let val = val.into();
Self::validate(&val)?;
Ok(Self { val })
}
pub fn validate(val: &Cow<'static, str>) -> Result<(), InvalidValue> {
if val.is_empty() {
return Err(InvalidValue::Empty);
}
if extract_login(val).is_none() {
return Err(InvalidValue::BadFormat)
}
Ok(())
}
pub fn val(&self) -> &str {
self.val.borrow()
}
pub fn boxed(self) -> Box<dyn Value> {
Box::new(self)
}
}
fn is_valid_email_local_part_char(c: char) -> bool {
if c.is_alphanumeric() {
return true;
}
match c {
'!' | '#' | '$' | '%' | '&' | '*' | '+' | '-' | '/' | '=' | '?' | '^' | '_' | '`' | '{' | '|' | '}' | '~' => true,
_ => false
}
}
fn extract_login(input: &str) -> Option<&str> {
#[derive(PartialEq, Debug)]
enum ExtractState {
LoginAnyLocalPartChar,
LoginAnyLocalPartCharAndDot,
Domain
}
let mut end_range = 0;
let mut state = ExtractState::LoginAnyLocalPartChar;
let mut login: &str = "";
for c in input.chars() {
if c.is_whitespace() {
return None;
}
end_range += 1;
state = match state {
ExtractState::LoginAnyLocalPartChar |
ExtractState::LoginAnyLocalPartCharAndDot => {
if is_valid_email_local_part_char(c) {
ExtractState::LoginAnyLocalPartCharAndDot
} else if state == ExtractState::LoginAnyLocalPartCharAndDot && c == '.' {
ExtractState::LoginAnyLocalPartChar
} else if c == '@' {
login = input.get(0..end_range-1)?;
if login.chars().last()? == '.' {
return None;
}
ExtractState::Domain
} else {
return None;
}
}
ExtractState::Domain => {
match c {
'@' => return None,
_ => ExtractState::Domain,
}
}
}
}
if login.is_empty() {
None
} else {
Some(login)
}
}
define_value_impl!(EmailValue);
impl FromStr for EmailValue {
type Err = InvalidValue;
fn from_str(s: &str) -> Result<Self, Self::Err> {
EmailValue::try_new(s.to_owned())
}
}
#[cfg(test)]
mod tests {
use super::super::InvalidValue;
use super::{ extract_login, EmailValue };
#[test]
fn test_extract_valid_email() {
let emails = vec![
("email@example.com", "email"),
("firstname.lastname@example.com", "firstname.lastname"),
("email@subdomain.example.com", "email"),
("firstname+lastname@example.com", "firstname+lastname"),
("email@123.123.123.123", "email"),
("email@[123.123.123.123]", "email"),
("1234567890@example.com", "1234567890"),
("email@example-one.com", "email"),
("_______@example.com", "_______"),
("email@example.name", "email"),
("email@example.museum", "email"),
("email@example.co.jp", "email"),
("firstname-lastname@example.com", "firstname-lastname"),
];
for (email, login) in emails {
println!("Checking GOOD {}", email);
let extracted_login = extract_login(email).unwrap();
assert_eq!(extracted_login, login);
}
}
#[test]
fn test_extract_invalid_email() {
let bad_emails = vec![
"plainaddress",
"#@%^%#$@#$@#.com",
"@example.com",
"Joe Smith <email@example.com>",
"email.example.com",
"email@example@example.com",
".email@example.com",
"email.@example.com",
"email..email@example.com",
"あいうえお@example.com",
"email@example.com (Joe Smith)",
"Abc..123@example.com",
"”(),:;<>[\\]@example.com",
"just”not”right@example.com",
"this\\ is\"really\"not\\allowed@example.com",
];
for bad_email in bad_emails {
println!("Checking BAD {}", bad_email);
assert_eq!(extract_login(bad_email), None);
}
}
#[test]
fn test_good_email() {
let email = EmailValue::try_new("a@b.com").unwrap();
assert_eq!(email.val(), "a@b.com");
}
#[test]
fn test_bad_email() {
let email_result = EmailValue::try_new("");
assert_eq!(email_result, Err(InvalidValue::Empty));
let email_result = EmailValue::try_new("ab.com");
assert_eq!(email_result, Err(InvalidValue::BadFormat));
}
#[test]
fn test_fromstr() {
assert!(matches!("".parse::<EmailValue>(), Err(_)));
assert!(matches!("notemail".parse::<EmailValue>(), Err(_)));
assert_eq!("valid@email.com".parse::<EmailValue>().unwrap(), EmailValue::try_new("valid@email.com").unwrap());
}
}