Skip to content

Commit

Permalink
Merge pull request #11 from techhazard/add-tryfrom-str
Browse files Browse the repository at this point in the history
add FromStr method for EmailAddress
  • Loading branch information
Sayan751 committed May 31, 2023
2 parents 8e2159f + 763ac22 commit 8c27262
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions rust-lib/src/email_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ extern crate pest_derive;
use pest::{iterators::Pairs, Parser};
use std::fmt;
use std::hash::Hash;
use std::str::FromStr;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

Expand Down Expand Up @@ -33,6 +34,34 @@ impl Default for ParsingOptions {
}
}

/// Allows conversion from string slices (&str) to EmailAddress using the FromStr trait.
/// This wraps around `EmailAddress::parse` using the default `ParsingOptions`.
///
/// # Examples
/// ```
/// use email_address_parser::EmailAddress;
/// use std::str::FromStr;
///
/// const input_address : &str = "[email protected]";
///
/// let myaddr : EmailAddress = input_address.parse().expect("could not parse str into EmailAddress");
/// let myotheraddr = EmailAddress::from_str(input_address).expect("could create EmailAddress from str");
///
/// assert_eq!(myaddr, myotheraddr);
/// ```
impl FromStr for EmailAddress {
type Err = fmt::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let opts = ParsingOptions::default();
if let Some(email) = EmailAddress::parse(s, Some(opts)) {
Ok(email)
} else {
Err(fmt::Error)
}
}
}

#[derive(Parser)]
#[grammar = "rfc5322.pest"]
struct RFC5322;
Expand Down

0 comments on commit 8c27262

Please sign in to comment.