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
pub fn is_label(input: &str) -> bool {
let mut chars = input.chars();
let first = match chars.next() {
None => {
return false;
}
Some(c) => c,
};
if !first.is_ascii_alphanumeric() {
return false;
}
let last_index = input.len() - 2.min(input.len());
for (index, c) in chars.enumerate() {
if !c.is_ascii_alphanumeric() && (index == last_index || c != '-') {
return false;
}
}
true
}
pub fn is_email_local(input: &str) -> bool {
let mut chars = input.chars();
let first = match chars.next() {
None => {
return false;
}
Some(c) => c,
};
let last_index = input.len() - 2.min(input.len());
if first == ' ' {
return false;
} else if first == '"' {
if input.len() == 1 {
return false;
}
for (index, c) in chars.enumerate() {
if index == last_index {
if c != '"' {
return false;
}
} else if !is_combined(c) && !is_quoted(c) {
return false;
}
}
} else {
if first == '.' {
return false;
}
for (index, c) in chars.enumerate() {
if !is_combined(c) && (index == last_index || c != '.') {
return false;
}
}
}
true
}
fn is_global(c: char) -> bool {
c.is_ascii_alphanumeric()
|| c == '-'
|| c == '!'
|| c == '#'
|| c == '$'
|| c == '%'
|| c == '&'
|| c == '\''
|| c == '*'
|| c == '+'
|| c == '/'
|| c == '='
|| c == '?'
|| c == '^'
|| c == '_'
|| c == '`'
|| c == '{'
|| c == '|'
|| c == '}'
|| c == '~'
}
fn is_non_ascii(c: char) -> bool {
c as u32 > 0x7f
}
fn is_quoted(c: char) -> bool {
c == '"'
|| c == '.'
|| c == ' '
|| c == '('
|| c == ')'
|| c == ','
|| c == '\\'
|| c == ':'
|| c == ';'
|| c == '<'
|| c == '>'
|| c == '@'
|| c == '['
|| c == ']'
}
fn is_combined(c: char) -> bool {
is_global(c) || is_non_ascii(c)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn is_label_correct() {
for l in &["a", "ab", "a-b", "a--b", "0Z"] {
assert!(is_label(l));
}
}
#[test]
fn is_label_incorrect() {
for l in &["", "-", "a-", "-b", "$"] {
assert!(!is_label(l));
}
}
#[test]
fn is_email_local_correct() {
for l in &[
"a",
"ab",
"a.b",
"a\u{0080}",
"$",
"\"\"\"",
"\"a b\"",
"\" \"",
"\"a<>@\"",
] {
assert!(is_email_local(l));
}
}
#[test]
fn is_email_local_incorrect() {
for l in &["", " a", "a ", "a.", ".b", "a\x7f", "\"", "\"a", "a\""] {
assert!(!is_email_local(l));
}
}
}