use serde::{Deserialize, Serialize};
use super::{AgentId, IdentityError as Err, InboxId, UserId};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Address {
pub inbox: Option<InboxId>,
pub user: UserId,
pub agent: AgentId,
}
impl TryFrom<&str> for Address {
type Error = Err;
fn try_from(value: &str) -> Result<Self, Err> {
Address::parse(value)
}
}
impl TryFrom<String> for Address {
type Error = Err;
fn try_from(value: String) -> Result<Self, Err> {
Address::parse(value)
}
}
impl Address {
pub fn new(inbox: Option<InboxId>, user: UserId, agent: AgentId) -> Self {
Address { inbox, user, agent }
}
pub fn parse(input: impl AsRef<str>) -> Result<Self, Err> {
let input = input.as_ref();
if input.trim() != input {
return Err(Err::InvalidAddress);
}
let (left, agent_str) = input.rsplit_once('@').ok_or(Err::InvalidAddress)?;
let agent = AgentId::parse(agent_str)?;
let (inbox, user_str) = if let Some((inbox_str, user_str)) = left.rsplit_once('#') {
let inbox = if inbox_str.is_empty() {
None
} else {
Some(InboxId::parse(inbox_str)?)
};
(inbox, user_str)
} else {
(None, left)
};
let user = UserId::parse(user_str)?;
Ok(Address { inbox, user, agent })
}
pub fn canonical(&self) -> String {
match &self.inbox {
Some(inbox) => format!(
"{}#{}@{}",
inbox.canonical(),
self.user.canonical(),
self.agent.canonical()
),
None => format!("#{}@{}", self.user.canonical(), self.agent.canonical()),
}
}
pub fn inbox(&self) -> Option<&InboxId> {
self.inbox.as_ref()
}
pub fn user(&self) -> &UserId {
&self.user
}
pub fn agent(&self) -> &AgentId {
&self.agent
}
}
impl std::fmt::Display for Address {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.canonical())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_and_canonicalizes() {
assert_eq!(
Address::parse("#Bob@example.org").unwrap().canonical(),
"#bob@example.org"
);
assert_eq!(
Address::parse("Bob@example.org").unwrap().canonical(),
"#bob@example.org"
);
assert_eq!(
Address::parse("wORk#Bob@example.ORG").unwrap().canonical(),
"work#bob@example.org"
);
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
fn rejects_empty() {
let _ = Address::parse("").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
fn rejects_invalid_chars() {
let _ = Address::parse("Invalid Address!").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
fn reject_untrimmed() {
let _ = Address::parse(" trim_me ").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
fn rejects_non_ascii() {
let _ = Address::parse("调试输出").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
fn rejects_homoglyphs() {
let _ = Address::parse("wоrk#аlice@us.exaмple.org").unwrap(); }
}