1use crate::macros::string_newtype;
2
3string_newtype! {
4 pub struct EmailAddress;
6 error = EmailAddressError;
7 expecting = "an ASCII email address (local-part@domain.tld)";
8}
9
10impl EmailAddress {
11 pub const MAX_LEN: usize = 254;
13 pub const LOCAL_PART_MAX_LEN: usize = 64;
15 pub const DOMAIN_MAX_LEN: usize = 253;
17 pub const DOMAIN_LABEL_MAX_LEN: usize = 63;
19 pub const TLD_MIN_LEN: usize = 2;
21
22 fn normalize(s: &mut str) {
23 s.make_ascii_lowercase();
24 }
25
26 fn validate(s: &str) -> Result<(), EmailAddressError> {
27 if !s.is_ascii() || s.contains(char::is_whitespace) {
28 return Err(EmailAddressError::Format);
29 }
30 if s.len() > Self::MAX_LEN {
31 return Err(EmailAddressError::Length);
32 }
33 let Some((local, domain)) = s.split_once('@') else {
34 return Err(EmailAddressError::Format);
35 };
36 if domain.contains('@') {
37 return Err(EmailAddressError::Format);
38 }
39 Self::validate_local_part(local)?;
40 Self::validate_domain(domain)
41 }
42
43 const fn is_allowed_local_byte(b: u8) -> bool {
44 b.is_ascii_alphanumeric()
45 || matches!(
46 b,
47 b'.' | b'!'
48 | b'#'
49 | b'$'
50 | b'%'
51 | b'&'
52 | b'\''
53 | b'*'
54 | b'+'
55 | b'-'
56 | b'/'
57 | b'='
58 | b'?'
59 | b'^'
60 | b'_'
61 | b'`'
62 | b'{'
63 | b'|'
64 | b'}'
65 | b'~'
66 )
67 }
68
69 fn validate_local_part(local: &str) -> Result<(), EmailAddressError> {
70 if local.is_empty()
71 || local.len() > Self::LOCAL_PART_MAX_LEN
72 || local.starts_with('.')
73 || local.ends_with('.')
74 || local.contains("..")
75 || !local.bytes().all(Self::is_allowed_local_byte)
76 {
77 return Err(EmailAddressError::Format);
78 }
79 Ok(())
80 }
81
82 fn validate_domain(domain: &str) -> Result<(), EmailAddressError> {
83 if domain.is_empty() || domain.len() > Self::DOMAIN_MAX_LEN {
84 return Err(EmailAddressError::Format);
85 }
86 let mut labels = 0usize;
87 let mut tld = "";
88 for label in domain.split('.') {
89 if label.is_empty()
90 || label.len() > Self::DOMAIN_LABEL_MAX_LEN
91 || label.starts_with('-')
92 || label.ends_with('-')
93 || !label
94 .bytes()
95 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
96 {
97 return Err(EmailAddressError::Format);
98 }
99 labels += 1;
100 tld = label;
101 }
102 if labels < 2
103 || tld.len() < Self::TLD_MIN_LEN
104 || !tld.bytes().all(|b| b.is_ascii_alphabetic())
105 {
106 return Err(EmailAddressError::Format);
107 }
108 Ok(())
109 }
110
111 #[inline]
113 #[must_use]
114 pub fn local_part(&self) -> &str {
115 self.0.split_once('@').map_or(self.0.as_str(), |(l, _)| l)
116 }
117
118 #[inline]
120 #[must_use]
121 pub fn domain(&self) -> &str {
122 self.0.split_once('@').map_or("", |(_, d)| d)
123 }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
128#[non_exhaustive]
129pub enum EmailAddressError {
130 #[error("email is too long, maximum is {} bytes", EmailAddress::MAX_LEN)]
132 Length,
133 #[error("email format is invalid, expected valid local-part and domain")]
135 Format,
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 #[test]
143 fn parse_and_accessors() {
144 let e = EmailAddress::parse(" User.Name@Example.COM ").unwrap();
145 assert_eq!(e.as_str(), "user.name@example.com");
146 assert_eq!(e.local_part(), "user.name");
147 assert_eq!(e.domain(), "example.com");
148 assert!(EmailAddress::parse("a@b.co").is_ok());
149 assert_eq!(EmailAddress::parse("a@b.c"), Err(EmailAddressError::Format));
150 assert_eq!(EmailAddress::parse("a@b"), Err(EmailAddressError::Format));
151 }
152
153 #[test]
154 fn accepts_ascii_email_at_max_length() {
155 let input = format!(
156 "{}@{}.{}.{}",
157 "a".repeat(64),
158 "b".repeat(63),
159 "c".repeat(63),
160 "d".repeat(61)
161 );
162 assert_eq!(input.len(), 254);
163 let parsed = EmailAddress::parse(&input).unwrap();
164 assert_eq!(parsed.as_str(), input);
165 assert_eq!(EmailAddress::try_from(input), Ok(parsed));
166 }
167
168 #[test]
169 fn errors_are_precise_above_max_length() {
170 let ascii = format!(
171 "{}@{}.{}.{}",
172 "a".repeat(64),
173 "b".repeat(63),
174 "c".repeat(63),
175 "d".repeat(62)
176 );
177 let whitespace = format!("{} {}", "a".repeat(127), "b".repeat(127));
178 assert_eq!(ascii.len(), 255);
179 assert_eq!(whitespace.len(), 255);
180
181 for (input, expected) in [
182 (ascii, EmailAddressError::Length),
183 ("é".repeat(128), EmailAddressError::Format),
184 (whitespace, EmailAddressError::Format),
185 ] {
186 assert!(input.len() > EmailAddress::MAX_LEN);
187 assert_eq!(EmailAddress::parse(&input), Err(expected));
188 assert_eq!(EmailAddress::try_from(input), Err(expected));
189 }
190 }
191}