2021-08-21 17:17:54 +08:00
|
|
|
use crate::errors::UserErrCode;
|
2021-06-29 23:21:25 +08:00
|
|
|
use validator::validate_email;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
2021-07-05 16:54:41 +08:00
|
|
|
pub struct UserEmail(pub String);
|
2021-06-29 23:21:25 +08:00
|
|
|
|
|
|
|
impl UserEmail {
|
2021-08-21 17:17:54 +08:00
|
|
|
pub fn parse(s: String) -> Result<UserEmail, UserErrCode> {
|
2021-07-06 14:14:47 +08:00
|
|
|
if s.trim().is_empty() {
|
2021-08-21 17:17:54 +08:00
|
|
|
return Err(UserErrCode::EmailIsEmpty);
|
2021-07-06 14:14:47 +08:00
|
|
|
}
|
|
|
|
|
2021-06-29 23:21:25 +08:00
|
|
|
if validate_email(&s) {
|
|
|
|
Ok(Self(s))
|
|
|
|
} else {
|
2021-08-21 17:17:54 +08:00
|
|
|
Err(UserErrCode::EmailFormatInvalid)
|
2021-06-29 23:21:25 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsRef<str> for UserEmail {
|
|
|
|
fn as_ref(&self) -> &str { &self.0 }
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use claim::assert_err;
|
|
|
|
use fake::{faker::internet::en::SafeEmail, Fake};
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn empty_string_is_rejected() {
|
|
|
|
let email = "".to_string();
|
|
|
|
assert_err!(UserEmail::parse(email));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn email_missing_at_symbol_is_rejected() {
|
|
|
|
let email = "helloworld.com".to_string();
|
|
|
|
assert_err!(UserEmail::parse(email));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn email_missing_subject_is_rejected() {
|
|
|
|
let email = "@domain.com".to_string();
|
|
|
|
assert_err!(UserEmail::parse(email));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
struct ValidEmailFixture(pub String);
|
|
|
|
|
|
|
|
impl quickcheck::Arbitrary for ValidEmailFixture {
|
|
|
|
fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self {
|
|
|
|
let email = SafeEmail().fake_with_rng(g);
|
|
|
|
Self(email)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[quickcheck_macros::quickcheck]
|
|
|
|
fn valid_emails_are_parsed_successfully(valid_email: ValidEmailFixture) -> bool {
|
|
|
|
UserEmail::parse(valid_email.0).is_ok()
|
|
|
|
}
|
|
|
|
}
|