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
extern crate regex;

use self::regex::Regex;
use super::{Validated, ValidatedWrapper};

use std::fmt::{self, Display, Debug, Formatter};
use std::str::Utf8Error;

use super::domain::{Domain, DomainUnlocalhostableWithoutPort, DomainError};

#[derive(Debug, PartialEq, Clone)]
pub enum EmailError {
    IncorrectLocalPart,
    IncorrectDomainPart(DomainError),
    UTF8Error(Utf8Error),
}

pub type EmailResult = Result<Email, EmailError>;

pub struct EmailValidator {}

#[derive(Clone)]
pub struct Email {
    domain: Domain,
    domain_index: usize,
    full_email: String,
}

impl Email {
    pub fn get_local(&self) -> &str {
        &self.full_email[..(self.domain_index - 1)]
    }
    pub fn get_domain(&self) -> &Domain {
        &self.domain
    }
    pub fn get_full_email(&self) -> &str {
        &self.full_email
    }
}

impl Validated for Email {}

impl Debug for Email {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_fmt(format_args!("Email({})", self.full_email))?;
        Ok(())
    }
}

impl Display for Email {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(&self.full_email)?;
        Ok(())
    }
}

impl PartialEq for Email {
    fn eq(&self, other: &Self) -> bool {
        if self.get_local().ne(other.get_local()) {
            return false;
        }

        self.get_domain().eq(other.get_domain())
    }

    fn ne(&self, other: &Self) -> bool {
        if self.get_local().ne(other.get_local()) {
            return true;
        }

        self.get_domain().ne(other.get_domain())
    }
}

impl EmailValidator {
    pub fn is_email(&self, full_email: &str) -> bool {
        self.parse_inner(full_email).is_ok()
    }

    pub fn parse_string(&self, full_email: String) -> EmailResult {
        let mut email_inner = self.parse_inner(&full_email)?;

        email_inner.full_email = full_email;

        Ok(email_inner)
    }

    pub fn parse_str(&self, full_email: &str) -> EmailResult {
        let mut email_inner = self.parse_inner(full_email)?;

        email_inner.full_email = full_email.to_string();

        Ok(email_inner)
    }

    fn parse_inner(&self, full_email: &str) -> EmailResult {
        let re = Regex::new("^(([0-9A-Za-z!#$%&'*+-/=?^_`{|}~&&[^@]]+)|(\"([0-9A-Za-z!#$%&'*+-/=?^_`{|}~ \"(),:;<>@\\[\\\\\\]]+)\"))@").unwrap();

        let c = match re.captures(&full_email) {
            Some(c) => c,
            None => return Err(EmailError::IncorrectLocalPart)
        };

        let domain_index;

        match c.get(1) {
            Some(m) => {
                domain_index = m.end() + 1;

                m.start()
            }
            None => {
                panic!("impossible");
            }
        };

        let duwnp = match DomainUnlocalhostableWithoutPort::from_str(&full_email[domain_index..]) {
            Ok(d) => d,
            Err(err) => return Err(EmailError::IncorrectDomainPart(err))
        };

        let domain = duwnp.into_domain();

        Ok(Email {
            domain,
            domain_index,
            full_email: String::new(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_email_methods() {
        let email = "len@magiclen.org".to_string();

        let ev = EmailValidator {};

        let email = ev.parse_string(email).unwrap();

        assert_eq!("len@magiclen.org", email.get_full_email());
        assert_eq!("len", email.get_local());
        assert_eq!("magiclen.org", email.get_domain().get_full_domain());
    }

    #[test]
    fn test_email_lv1() {
        let email = "len@magiclen.org".to_string();

        let ev = EmailValidator {};

        ev.parse_string(email).unwrap();
    }
}

// Email's wrapper struct is itself
impl ValidatedWrapper for Email {
    type Error = EmailError;

    fn from_string(email: String) -> Result<Self, Self::Error> {
        Email::from_string(email)
    }

    fn from_str(email: &str) -> Result<Self, Self::Error> {
        Email::from_str(email)
    }
}

impl Email {
    pub fn from_string(full_email: String) -> Result<Self, EmailError> {
        let ev = EmailValidator {};

        ev.parse_string(full_email)
    }

    pub fn from_str(full_email: &str) -> Result<Self, EmailError> {
        let ev = EmailValidator {};

        ev.parse_str(full_email)
    }
}


#[cfg(feature = "rocketly")]
impl<'a> ::rocket::request::FromFormValue<'a> for Email {
    type Error = EmailError;

    fn from_form_value(form_value: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error> {
        Email::from_string(form_value.url_decode().map_err(|err| EmailError::UTF8Error(err))?)
    }
}