Skip to main content

klick_domain/authentication/
email.rs

1use std::{fmt, str::FromStr};
2
3use mailparse::addrparse;
4use thiserror::Error;
5
6#[derive(Debug, Clone, Eq, PartialEq, Hash)]
7pub struct EmailAddress(String);
8
9#[derive(Debug, Error)]
10#[error("The given email address is invalid")]
11pub struct ParseError;
12
13impl FromStr for EmailAddress {
14    type Err = ParseError;
15    fn from_str(s: &str) -> Result<Self, Self::Err> {
16        addrparse(s)
17            .ok()
18            .and_then(mailparse::MailAddrList::extract_single_info)
19            .map(|single_info| Self(single_info.addr))
20            .ok_or(ParseError)
21    }
22}
23
24impl EmailAddress {
25    #[must_use]
26    pub const fn new_unchecked(address: String) -> Self {
27        Self(address)
28    }
29
30    #[must_use]
31    pub fn as_str(&self) -> &str {
32        &self.0
33    }
34
35    #[must_use]
36    pub fn into_string(self) -> String {
37        self.0
38    }
39}
40
41impl fmt::Display for EmailAddress {
42    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43        write!(f, "{}", self.0)
44    }
45}