email/email/envelope/
address.rs

1//! Module dedicated to email envelope addresses.
2//!
3//! This core concept of this module is the [Address] structure, which
4//! represents an email envelope address.
5
6use std::hash::{Hash, Hasher};
7
8/// The email envelope address.
9///
10/// An address is composed of an optional name and
11/// an email address.
12#[derive(Clone, Debug, Default, Eq, Ord, PartialOrd)]
13pub struct Address {
14    pub name: Option<String>,
15    pub addr: String,
16}
17
18impl Hash for Address {
19    fn hash<H: Hasher>(&self, state: &mut H) {
20        self.addr.hash(state);
21    }
22}
23
24/// Two addresses are considered equal when their email addresses are
25/// equal.
26impl PartialEq for Address {
27    fn eq(&self, other: &Self) -> bool {
28        self.addr == other.addr
29    }
30}
31
32impl ToString for Address {
33    fn to_string(&self) -> String {
34        match &self.name {
35            Some(name) => format!("{name} <{}>", self.addr),
36            None => self.addr.clone(),
37        }
38    }
39}
40
41impl Address {
42    /// Builds a new address from an optional name and an email
43    /// address.
44    pub fn new(name: Option<impl ToString>, address: impl ToString) -> Self {
45        Self {
46            name: name.map(|name| name.to_string()),
47            addr: address.to_string(),
48        }
49    }
50
51    /// Builds a new address from an email address only.
52    pub fn new_nameless(address: impl ToString) -> Self {
53        Self::new(Option::<String>::None, address)
54    }
55}