use crate::errors::ValidationError;
use crate::traits::{PrimitiveValue, ValueObject};
use regex::Regex;
use std::sync::LazyLock;
pub type EmailAddressInput = String;
static EMAIL_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^[^\s@]+@[^\s@]+\.[^\s@]{2,}$").unwrap());
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct EmailAddress(String);
impl ValueObject for EmailAddress {
type Input = EmailAddressInput;
type Error = ValidationError;
fn new(value: Self::Input) -> Result<Self, Self::Error> {
let normalised = value.trim().to_lowercase();
if normalised.is_empty() {
return Err(ValidationError::empty("EmailAddress"));
}
if !EMAIL_REGEX.is_match(&normalised) {
return Err(ValidationError::invalid("EmailAddress", &normalised));
}
Ok(Self(normalised))
}
fn into_inner(self) -> Self::Input {
self.0
}
}
impl PrimitiveValue for EmailAddress {
type Primitive = String;
fn value(&self) -> &String {
&self.0
}
}
impl EmailAddress {
pub fn local_part(&self) -> &str {
self.0.split('@').next().unwrap_or("")
}
pub fn domain(&self) -> &str {
self.0.split('@').nth(1).unwrap_or("")
}
}
impl TryFrom<String> for EmailAddress {
type Error = ValidationError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
#[cfg(feature = "serde")]
impl From<EmailAddress> for String {
fn from(v: EmailAddress) -> String {
v.0
}
}
impl TryFrom<&str> for EmailAddress {
type Error = ValidationError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value.to_owned())
}
}
impl std::fmt::Display for EmailAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalises_to_lowercase() {
let e = EmailAddress::new("User@Example.COM".into()).unwrap();
assert_eq!(e.value(), "user@example.com");
}
#[test]
fn trims_surrounding_whitespace() {
let e = EmailAddress::new(" hello@example.com ".into()).unwrap();
assert_eq!(e.value(), "hello@example.com");
}
#[test]
fn rejects_missing_at_sign() {
assert!(EmailAddress::new("notanemail".into()).is_err());
}
#[test]
fn rejects_empty_string() {
assert!(EmailAddress::new(String::new()).is_err());
}
#[test]
fn equal_after_normalisation() {
let a = EmailAddress::new("User@Example.COM".into()).unwrap();
let b = EmailAddress::new("user@example.com".into()).unwrap();
assert_eq!(a, b);
}
#[test]
fn local_part_returns_part_before_at() {
let e = EmailAddress::new("user@example.com".into()).unwrap();
assert_eq!(e.local_part(), "user");
}
#[test]
fn domain_returns_part_after_at() {
let e = EmailAddress::new("user@example.com".into()).unwrap();
assert_eq!(e.domain(), "example.com");
}
#[test]
fn try_from_str() {
let e: EmailAddress = "hello@example.com".try_into().unwrap();
assert_eq!(e.value(), "hello@example.com");
}
#[cfg(feature = "serde")]
#[test]
fn serde_roundtrip() {
let v = EmailAddress::try_from("user@example.com").unwrap();
let json = serde_json::to_string(&v).unwrap();
let back: EmailAddress = serde_json::from_str(&json).unwrap();
assert_eq!(v, back);
}
#[cfg(feature = "serde")]
#[test]
fn serde_deserialize_validates() {
let result: Result<EmailAddress, _> = serde_json::from_str("\"__invalid__\"");
assert!(result.is_err());
}
}