use serde::{
Deserialize, Deserializer, Serialize, Serializer,
de::{self, Visitor},
};
use crate::prelude::UserId;
use super::{IdentityError as Err, canonical_identity_string, is_valid_identity_string};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InboxId(String);
impl TryFrom<UserId> for InboxId {
type Error = Err;
fn try_from(user: UserId) -> Result<Self, Err> {
match user.inbox() {
Some(inbox) => Ok(inbox.clone()),
None => Err(Err::InvalidInbox),
}
}
}
impl TryFrom<&str> for InboxId {
type Error = Err;
fn try_from(value: &str) -> Result<Self, Err> {
InboxId::parse(value)
}
}
impl TryFrom<String> for InboxId {
type Error = Err;
fn try_from(value: String) -> Result<Self, Err> {
InboxId::parse(value)
}
}
impl InboxId {
pub fn parse(input: impl AsRef<str>) -> Result<Self, Err> {
let input = input.as_ref();
if input.is_empty() {
return Err(Err::InvalidInbox);
}
if !is_valid_identity_string(input) {
return Err(Err::InvalidIdentityString);
}
let canonical = canonical_identity_string(input);
Ok(Self(canonical))
}
pub fn replace(&mut self, new_value: impl AsRef<str>) -> Result<(), Err> {
*self = Self::parse(new_value)?;
Ok(())
}
pub fn canonical(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for InboxId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.canonical())
}
}
impl Serialize for InboxId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.canonical())
}
}
impl<'de> Deserialize<'de> for InboxId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct InboxIdVisitor;
impl<'de> Visitor<'de> for InboxIdVisitor {
type Value = InboxId;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a canonical Relay Mail address string")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
InboxId::parse(value)
.map_err(|e| de::Error::custom(format!("invalid address `{}`: {}", value, e)))
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: de::Error,
{
self.visit_str(&value)
}
}
deserializer.deserialize_str(InboxIdVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_and_canonicalizes() {
assert_eq!(InboxId::parse("Work").unwrap().canonical(), "work");
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidInbox")]
fn rejects_empty() {
let _ = InboxId::parse("").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
fn rejects_invalid_chars() {
let _ = InboxId::parse("Invalid Inbox!").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
fn reject_untrimmed() {
let _ = InboxId::parse(" trim_me ").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
fn rejects_non_ascii() {
let _ = InboxId::parse("调试输出").unwrap();
}
#[test]
#[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
fn rejects_homoglyphs() {
let _ = InboxId::parse("wоrk").unwrap(); }
}