use std::{
fmt::{self, Display, Formatter},
str::FromStr,
};
use crate::{domain::Domain, error::EmailAddressError};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Message {
pub from: String,
pub subject: String,
pub body: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EmailAddress {
pub name: String,
pub domain: Domain,
}
impl EmailAddress {
pub fn new(name: impl Into<String>, domain: Domain) -> Self {
Self {
name: name.into(),
domain,
}
}
}
impl Display for EmailAddress {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}@{}", self.name, self.domain)
}
}
impl FromStr for EmailAddress {
type Err = EmailAddressError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (name, domain) = s
.split_once('@')
.ok_or(EmailAddressError::InvalidEmailAddress(s.into()))?;
Ok(Self {
name: name.into(),
domain: domain.into(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_email_address_display() {
assert_eq!(
EmailAddress::new("test", Domain::TerribleCoffeeOrg).to_string(),
"test@terriblecoffee.org"
);
assert_eq!(
EmailAddress::new("test", Domain::Custom("custom.com".into())).to_string(),
"test@custom.com"
);
}
#[test]
fn test_email_address_from_str() {
let email: EmailAddress = "test@terriblecoffee.org".parse().unwrap();
assert_eq!(email.name, "test");
assert_eq!(email.domain, Domain::TerribleCoffeeOrg);
let email: EmailAddress = "test@custom.com".parse().unwrap();
assert_eq!(email.name, "test");
assert_eq!(email.domain, Domain::Custom("custom.com".into()));
}
#[test]
fn test_email_address_from_str_invalid() {
let email: Result<EmailAddress, _> = "invalid-email".parse();
assert!(email.is_err());
}
}