Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

serde #12

Open
beckend opened this issue Oct 7, 2023 · 1 comment
Open

serde #12

beckend opened this issue Oct 7, 2023 · 1 comment

Comments

@beckend
Copy link

beckend commented Oct 7, 2023

Reference: #1
Can this be implemented? Current workaround:

use core::fmt;
use email_address_parser::EmailAddress;
use serde::{Deserializer, Serialize, Serializer};
use std::fmt::Debug;

#[derive(Debug, Clone)]
pub struct EmailAddressWrapped(pub EmailAddress);

impl fmt::Display for EmailAddressWrapped {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.0.to_string())
  }
}

impl From<String> for EmailAddressWrapped {
  fn from(x: String) -> Self {
    Self(EmailAddress::parse(&x, None).expect("EmailAddress failed to parse."))
  }
}

impl From<&str> for EmailAddressWrapped {
  fn from(x: &str) -> Self {
    Self(EmailAddress::parse(x, None).expect("EmailAddress failed to parse."))
  }
}

impl From<EmailAddress> for EmailAddressWrapped {
  fn from(x: EmailAddress) -> Self {
    Self(x)
  }
}

impl Serialize for EmailAddressWrapped {
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: Serializer,
  {
    serializer.serialize_str(&self.to_string())
  }
}

impl<'de> serde::Deserialize<'de> for EmailAddressWrapped {
  fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
    Ok(Self(
      EmailAddress::parse(&String::deserialize(d)?, None).expect("EmailAddress failed to parse."),
    ))
  }
}
@numfin
Copy link

numfin commented Oct 24, 2023

From -> TryFrom
It is not good to panic at runtime 😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants