Skip to main content

systemprompt_identifiers/
email.rs

1//! Email identifier type with validation.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use crate::error::IdValidationError;
7use crate::{DbValue, ToDbValue};
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use std::fmt;
11
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, JsonSchema)]
13#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
14#[cfg_attr(feature = "sqlx", sqlx(transparent))]
15#[serde(transparent)]
16pub struct Email(String);
17
18impl Email {
19    pub fn try_new(value: impl Into<String>) -> Result<Self, IdValidationError> {
20        let value = value.into();
21        if value.is_empty() {
22            return Err(IdValidationError::empty("Email"));
23        }
24        let parts: Vec<&str> = value.split('@').collect();
25        if parts.len() != 2 {
26            return Err(IdValidationError::invalid(
27                "Email",
28                "must contain exactly one '@' symbol",
29            ));
30        }
31        let local = parts[0];
32        let domain = parts[1];
33        if local.is_empty() {
34            return Err(IdValidationError::invalid(
35                "Email",
36                "local part (before @) cannot be empty",
37            ));
38        }
39        if local.starts_with('.') || local.ends_with('.') {
40            return Err(IdValidationError::invalid(
41                "Email",
42                "local part cannot start or end with '.'",
43            ));
44        }
45        if local.contains("..") {
46            return Err(IdValidationError::invalid(
47                "Email",
48                "local part cannot contain consecutive dots",
49            ));
50        }
51        if local.contains('\n') || local.contains('\r') {
52            return Err(IdValidationError::invalid(
53                "Email",
54                "email cannot contain newline characters",
55            ));
56        }
57        if domain.is_empty() {
58            return Err(IdValidationError::invalid(
59                "Email",
60                "domain part (after @) cannot be empty",
61            ));
62        }
63        if !domain.contains('.') {
64            return Err(IdValidationError::invalid(
65                "Email",
66                "domain must contain at least one '.'",
67            ));
68        }
69        if domain.starts_with('.') || domain.ends_with('.') {
70            return Err(IdValidationError::invalid(
71                "Email",
72                "domain cannot start or end with '.'",
73            ));
74        }
75        if domain.contains("..") {
76            return Err(IdValidationError::invalid(
77                "Email",
78                "domain cannot contain consecutive dots",
79            ));
80        }
81        if let Some(tld) = domain.rsplit('.').next()
82            && tld.len() < 2
83        {
84            return Err(IdValidationError::invalid(
85                "Email",
86                "TLD must be at least 2 characters",
87            ));
88        }
89        Ok(Self(value))
90    }
91
92    #[must_use]
93    pub fn as_str(&self) -> &str {
94        &self.0
95    }
96
97    #[must_use]
98    pub fn local_part(&self) -> &str {
99        self.0.split('@').next().unwrap_or("")
100    }
101
102    #[must_use]
103    pub fn domain(&self) -> &str {
104        self.0.split('@').nth(1).unwrap_or("")
105    }
106
107    // Why: the placeholder mailbox generated profiles carry until an operator
108    // sets a real one; `localhost.localdomain` is RFC 6761-reserved so it can
109    // never receive mail.
110    #[must_use]
111    pub fn local_admin() -> Self {
112        Self("admin@localhost.localdomain".to_owned())
113    }
114}
115
116impl fmt::Display for Email {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        write!(f, "{}", self.0)
119    }
120}
121
122impl TryFrom<String> for Email {
123    type Error = IdValidationError;
124
125    fn try_from(s: String) -> Result<Self, Self::Error> {
126        Self::try_new(s)
127    }
128}
129
130impl TryFrom<&str> for Email {
131    type Error = IdValidationError;
132
133    fn try_from(s: &str) -> Result<Self, Self::Error> {
134        Self::try_new(s)
135    }
136}
137
138impl std::str::FromStr for Email {
139    type Err = IdValidationError;
140
141    fn from_str(s: &str) -> Result<Self, Self::Err> {
142        Self::try_new(s)
143    }
144}
145
146impl AsRef<str> for Email {
147    fn as_ref(&self) -> &str {
148        &self.0
149    }
150}
151
152impl<'de> Deserialize<'de> for Email {
153    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
154    where
155        D: serde::Deserializer<'de>,
156    {
157        let s = String::deserialize(deserializer)?;
158        Self::try_new(s).map_err(serde::de::Error::custom)
159    }
160}
161
162impl ToDbValue for Email {
163    fn to_db_value(&self) -> DbValue {
164        DbValue::String(self.0.clone())
165    }
166}
167
168impl ToDbValue for &Email {
169    fn to_db_value(&self) -> DbValue {
170        DbValue::String(self.0.clone())
171    }
172}