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());
}
}