use-email-address 0.1.0

Email address and mailbox primitives for RustUse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

use core::{fmt, str::FromStr};
use std::error::Error;

/// Validation profile for address-like primitives.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AddressValidationMode {
    /// Conservative ASCII validation for common production addresses.
    #[default]
    Practical,
    /// ASCII-only validation with conservative domain-label rules.
    StrictAscii,
    /// Allows non-ASCII text while still rejecting control characters and obvious separators.
    Internationalized,
}

/// Error returned when an email address primitive fails validation.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AddressValidationError {
    /// The supplied value was empty after trimming.
    Empty,
    /// The address did not contain an at sign.
    MissingAt,
    /// The address contained more than one at sign.
    TooManyAtSigns,
    /// The local part was empty.
    EmptyLocalPart,
    /// The domain part was empty.
    EmptyDomain,
    /// The local part used syntax rejected by this crate's conservative rules.
    InvalidLocalPart,
    /// The domain part used syntax rejected by this crate's conservative rules.
    InvalidDomain,
    /// The display name used syntax rejected by this crate's conservative rules.
    InvalidDisplayName,
    /// The selected validation mode requires ASCII text.
    NonAscii,
}

impl fmt::Display for AddressValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("email address value cannot be empty"),
            Self::MissingAt => formatter.write_str("email address must contain an at sign"),
            Self::TooManyAtSigns => {
                formatter.write_str("email address must contain only one at sign")
            }
            Self::EmptyLocalPart => formatter.write_str("email local part cannot be empty"),
            Self::EmptyDomain => formatter.write_str("email domain part cannot be empty"),
            Self::InvalidLocalPart => formatter.write_str("invalid email local part"),
            Self::InvalidDomain => formatter.write_str("invalid email domain part"),
            Self::InvalidDisplayName => formatter.write_str("invalid email display name"),
            Self::NonAscii => {
                formatter.write_str("email value must be ASCII for this validation mode")
            }
        }
    }
}

impl Error for AddressValidationError {}

/// Email local-part text.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct LocalPart(String);

impl LocalPart {
    /// Creates a local part using practical validation.
    pub fn new(value: impl AsRef<str>) -> Result<Self, AddressValidationError> {
        Self::new_with_mode(value, AddressValidationMode::Practical)
    }

    /// Creates a local part using the requested validation mode.
    pub fn new_with_mode(
        value: impl AsRef<str>,
        mode: AddressValidationMode,
    ) -> Result<Self, AddressValidationError> {
        validate_local_part(value.as_ref(), mode).map(|value| Self(value.to_owned()))
    }

    /// Returns the local-part text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for LocalPart {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for LocalPart {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for LocalPart {
    type Err = AddressValidationError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for LocalPart {
    type Error = AddressValidationError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Email domain-part text.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DomainPart(String);

impl DomainPart {
    /// Creates a domain part using practical validation.
    pub fn new(value: impl AsRef<str>) -> Result<Self, AddressValidationError> {
        Self::new_with_mode(value, AddressValidationMode::Practical)
    }

    /// Creates a domain part using the requested validation mode.
    pub fn new_with_mode(
        value: impl AsRef<str>,
        mode: AddressValidationMode,
    ) -> Result<Self, AddressValidationError> {
        validate_domain_part(value.as_ref(), mode).map(|value| Self(value.to_owned()))
    }

    /// Returns the domain-part text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for DomainPart {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for DomainPart {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for DomainPart {
    type Err = AddressValidationError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for DomainPart {
    type Error = AddressValidationError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Validated email address text split into local and domain parts.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct EmailAddress {
    local_part: LocalPart,
    domain_part: DomainPart,
}

impl EmailAddress {
    /// Creates an address using practical validation.
    pub fn new(value: impl AsRef<str>) -> Result<Self, AddressValidationError> {
        Self::new_with_mode(value, AddressValidationMode::Practical)
    }

    /// Creates an address using the requested validation mode.
    pub fn new_with_mode(
        value: impl AsRef<str>,
        mode: AddressValidationMode,
    ) -> Result<Self, AddressValidationError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            return Err(AddressValidationError::Empty);
        }
        let mut parts = trimmed.split('@');
        let local = parts.next().ok_or(AddressValidationError::MissingAt)?;
        let domain = parts.next().ok_or(AddressValidationError::MissingAt)?;
        if parts.next().is_some() {
            return Err(AddressValidationError::TooManyAtSigns);
        }
        Self::from_parts_with_mode(local, domain, mode)
    }

    /// Creates an address from already separated local and domain text.
    pub fn from_parts(
        local_part: impl AsRef<str>,
        domain_part: impl AsRef<str>,
    ) -> Result<Self, AddressValidationError> {
        Self::from_parts_with_mode(local_part, domain_part, AddressValidationMode::Practical)
    }

    /// Creates an address from separated parts using the requested validation mode.
    pub fn from_parts_with_mode(
        local_part: impl AsRef<str>,
        domain_part: impl AsRef<str>,
        mode: AddressValidationMode,
    ) -> Result<Self, AddressValidationError> {
        Ok(Self {
            local_part: LocalPart::new_with_mode(local_part, mode)?,
            domain_part: DomainPart::new_with_mode(domain_part, mode)?,
        })
    }

    /// Returns the local part.
    #[must_use]
    pub const fn local_part(&self) -> &LocalPart {
        &self.local_part
    }

    /// Returns the domain part.
    #[must_use]
    pub const fn domain_part(&self) -> &DomainPart {
        &self.domain_part
    }

    /// Returns an owned address string.
    #[must_use]
    pub fn into_string(self) -> String {
        self.to_string()
    }
}

impl fmt::Display for EmailAddress {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}@{}", self.local_part, self.domain_part)
    }
}

impl FromStr for EmailAddress {
    type Err = AddressValidationError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for EmailAddress {
    type Error = AddressValidationError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Human-readable display name for a mailbox.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DisplayName(String);

impl DisplayName {
    /// Creates a display name.
    pub fn new(value: impl AsRef<str>) -> Result<Self, AddressValidationError> {
        validate_display_name(value.as_ref()).map(|value| Self(value.to_owned()))
    }

    /// Returns the display-name text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for DisplayName {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for DisplayName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for DisplayName {
    type Err = AddressValidationError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

/// A visible mailbox: optional display name plus email address.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Mailbox {
    display_name: Option<DisplayName>,
    address: EmailAddress,
}

impl Mailbox {
    /// Creates a mailbox from optional display name text and address text.
    pub fn new(
        display_name: Option<&str>,
        address: impl AsRef<str>,
    ) -> Result<Self, AddressValidationError> {
        Ok(Self {
            display_name: display_name.map(DisplayName::new).transpose()?,
            address: EmailAddress::new(address)?,
        })
    }

    /// Creates a mailbox from an already validated address.
    #[must_use]
    pub const fn from_address(address: EmailAddress) -> Self {
        Self {
            display_name: None,
            address,
        }
    }

    /// Adds a display name to the mailbox.
    pub fn with_display_name(
        mut self,
        display_name: impl AsRef<str>,
    ) -> Result<Self, AddressValidationError> {
        self.display_name = Some(DisplayName::new(display_name)?);
        Ok(self)
    }

    /// Returns the display name, when present.
    #[must_use]
    pub const fn display_name(&self) -> Option<&DisplayName> {
        self.display_name.as_ref()
    }

    /// Returns the mailbox address.
    #[must_use]
    pub const fn address(&self) -> &EmailAddress {
        &self.address
    }
}

impl fmt::Display for Mailbox {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(display_name) = &self.display_name {
            write!(
                formatter,
                "\"{}\" <{}>",
                escape_display_name(display_name.as_str()),
                self.address
            )
        } else {
            write!(formatter, "{}", self.address)
        }
    }
}

impl FromStr for Mailbox {
    type Err = AddressValidationError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err(AddressValidationError::Empty);
        }
        if let Some(start) = trimmed.rfind('<') {
            let end = trimmed
                .rfind('>')
                .ok_or(AddressValidationError::InvalidLocalPart)?;
            if end <= start {
                return Err(AddressValidationError::InvalidLocalPart);
            }
            let display = trimmed[..start].trim().trim_matches('"').trim();
            let address = trimmed[start + 1..end].trim();
            let display_name = if display.is_empty() {
                None
            } else {
                Some(display)
            };
            Self::new(display_name, address)
        } else {
            Self::new(None, trimmed)
        }
    }
}

/// A comma-rendered list of visible mailboxes.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MailboxList {
    mailboxes: Vec<Mailbox>,
}

impl MailboxList {
    /// Creates an empty mailbox list.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            mailboxes: Vec::new(),
        }
    }

    /// Adds a mailbox and returns the updated list.
    #[must_use]
    pub fn with_mailbox(mut self, mailbox: Mailbox) -> Self {
        self.mailboxes.push(mailbox);
        self
    }

    /// Appends a mailbox.
    pub fn push(&mut self, mailbox: Mailbox) {
        self.mailboxes.push(mailbox);
    }

    /// Returns the mailboxes.
    #[must_use]
    pub fn as_slice(&self) -> &[Mailbox] {
        &self.mailboxes
    }

    /// Returns the number of mailboxes.
    #[must_use]
    pub fn len(&self) -> usize {
        self.mailboxes.len()
    }

    /// Returns true when the list is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.mailboxes.is_empty()
    }
}

impl fmt::Display for MailboxList {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (index, mailbox) in self.mailboxes.iter().enumerate() {
            if index > 0 {
                formatter.write_str(", ")?;
            }
            write!(formatter, "{mailbox}")?;
        }
        Ok(())
    }
}

/// A named group of visible mailboxes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AddressGroup {
    name: DisplayName,
    members: MailboxList,
}

impl AddressGroup {
    /// Creates an address group.
    pub fn new(
        name: impl AsRef<str>,
        members: MailboxList,
    ) -> Result<Self, AddressValidationError> {
        Ok(Self {
            name: DisplayName::new(name)?,
            members,
        })
    }

    /// Returns the group name.
    #[must_use]
    pub const fn name(&self) -> &DisplayName {
        &self.name
    }

    /// Returns the group members.
    #[must_use]
    pub const fn members(&self) -> &MailboxList {
        &self.members
    }
}

impl fmt::Display for AddressGroup {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}: {};", self.name, self.members)
    }
}

fn validate_local_part(
    value: &str,
    mode: AddressValidationMode,
) -> Result<&str, AddressValidationError> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(AddressValidationError::EmptyLocalPart);
    }
    if mode != AddressValidationMode::Internationalized && !trimmed.is_ascii() {
        return Err(AddressValidationError::NonAscii);
    }
    if trimmed.starts_with('.') || trimmed.ends_with('.') || trimmed.contains("..") {
        return Err(AddressValidationError::InvalidLocalPart);
    }
    if trimmed.chars().any(|character| {
        character.is_control()
            || character.is_whitespace()
            || matches!(character, '@' | '<' | '>' | ',' | ';')
            || (mode != AddressValidationMode::Internationalized && !is_local_ascii(character))
    }) {
        return Err(AddressValidationError::InvalidLocalPart);
    }
    Ok(trimmed)
}

fn validate_domain_part(
    value: &str,
    mode: AddressValidationMode,
) -> Result<&str, AddressValidationError> {
    let trimmed = value.trim().trim_end_matches('.');
    if trimmed.is_empty() {
        return Err(AddressValidationError::EmptyDomain);
    }
    if mode != AddressValidationMode::Internationalized && !trimmed.is_ascii() {
        return Err(AddressValidationError::NonAscii);
    }
    if trimmed.starts_with('.') || trimmed.contains("..") {
        return Err(AddressValidationError::InvalidDomain);
    }
    for label in trimmed.split('.') {
        if label.is_empty() || label.starts_with('-') || label.ends_with('-') {
            return Err(AddressValidationError::InvalidDomain);
        }
        if label.chars().any(|character| {
            character.is_control()
                || character.is_whitespace()
                || matches!(character, '@' | '<' | '>' | ',' | ';' | '_')
                || (mode != AddressValidationMode::Internationalized && !is_domain_ascii(character))
        }) {
            return Err(AddressValidationError::InvalidDomain);
        }
    }
    Ok(trimmed)
}

fn validate_display_name(value: &str) -> Result<&str, AddressValidationError> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(AddressValidationError::Empty);
    }
    if trimmed
        .chars()
        .any(|character| character.is_control() || matches!(character, '<' | '>' | '\r' | '\n'))
    {
        return Err(AddressValidationError::InvalidDisplayName);
    }
    Ok(trimmed)
}

fn is_local_ascii(character: char) -> bool {
    character.is_ascii_alphanumeric()
        || matches!(
            character,
            '!' | '#'
                | '$'
                | '%'
                | '&'
                | '\''
                | '*'
                | '+'
                | '-'
                | '/'
                | '='
                | '?'
                | '^'
                | '_'
                | '`'
                | '{'
                | '|'
                | '}'
                | '~'
                | '.'
        )
}

fn is_domain_ascii(character: char) -> bool {
    character.is_ascii_alphanumeric() || matches!(character, '-' | '.')
}

fn escape_display_name(value: &str) -> String {
    let mut escaped = String::new();
    for character in value.chars() {
        if matches!(character, '\\' | '"') {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}

#[cfg(test)]
mod tests {
    use super::{
        AddressGroup, AddressValidationError, AddressValidationMode, EmailAddress, Mailbox,
        MailboxList,
    };

    #[test]
    fn parses_practical_addresses() -> Result<(), AddressValidationError> {
        let address: EmailAddress = "jane.doe+notes@example.com".parse()?;

        assert_eq!(address.local_part().as_str(), "jane.doe+notes");
        assert_eq!(address.domain_part().as_str(), "example.com");
        assert_eq!(address.to_string(), "jane.doe+notes@example.com");
        Ok(())
    }

    #[test]
    fn validation_modes_are_explicit() {
        assert_eq!(
            EmailAddress::new_with_mode("jane@exämple.test", AddressValidationMode::StrictAscii),
            Err(AddressValidationError::NonAscii)
        );
        assert!(
            EmailAddress::new_with_mode(
                "jane@exämple.test",
                AddressValidationMode::Internationalized
            )
            .is_ok()
        );
    }

    #[test]
    fn renders_mailbox_lists_and_groups() -> Result<(), AddressValidationError> {
        let jane = Mailbox::new(Some("Jane Doe"), "jane@example.com")?;
        let ada: Mailbox = "Ada <ada@example.com>".parse()?;
        let list = MailboxList::new().with_mailbox(jane).with_mailbox(ada);
        let group = AddressGroup::new("Team", list)?;

        assert_eq!(
            group.to_string(),
            "Team: \"Jane Doe\" <jane@example.com>, \"Ada\" <ada@example.com>;"
        );
        Ok(())
    }

    #[test]
    fn rejects_obvious_invalid_addresses() {
        assert_eq!(
            EmailAddress::new("jane.example.com"),
            Err(AddressValidationError::MissingAt)
        );
        assert_eq!(
            EmailAddress::new("jane@@example.com"),
            Err(AddressValidationError::TooManyAtSigns)
        );
        assert_eq!(
            EmailAddress::new("jane@-example.com"),
            Err(AddressValidationError::InvalidDomain)
        );
    }
}