email-address-list 0.3.0

Pest based parser for address-lists in email headers like to/from/cc/etc.
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
use std::cmp::PartialEq;
use std::fmt;
use std::iter::{FromIterator, IntoIterator, Iterator};
use std::ops::Deref;

#[cfg(feature = "mailparse-conversions")]
use super::error::Error;
#[cfg(feature = "mailparse-conversions")]
use std::convert::TryInto;

/// Check if all fields are the same rather than just a subset ("deep equals")
pub trait DeepEq<Rhs = Self> {
    fn deep_eq(&self, other: &Rhs) -> bool;
    fn deep_ne(&self, other: &Rhs) -> bool {
        !self.deep_eq(other)
    }
}

/// Unified interface for all contact types
pub trait Contactish {
    fn email(&self) -> Option<&String>;
    fn name(&self) -> Option<&String>;
    fn comment(&self) -> Option<&String>;
    fn new<T>(required: T) -> Self
    where
        T: AsRef<str>;
    fn set_name<T>(self, name: T) -> Self
    where
        T: AsRef<str>;
    fn set_email<T>(self, email: T) -> Self
    where
        T: AsRef<str>;
    fn set_comment<T>(self, comment: T) -> Self
    where
        T: AsRef<str>;
    fn to_contact(self) -> Contact;
}

/// For everything that has contacts
pub trait Contactsish {
    fn len(&self) -> usize;
    fn is_empty(&self) -> bool;
    fn to_contacts(self) -> Contacts;
    fn add<C>(&mut self, contact: C)
    where
        C: Contactish;
    fn contains(&self, contact: &Contact) -> bool;
}

/// A contact with at least an email address
#[derive(Debug, Clone, Default)]
pub struct EmailContact {
    email: String,
    name: Option<String>,
    comment: Option<String>,
}

impl Contactish for EmailContact {
    fn email(&self) -> Option<&String> {
        Some(&self.email)
    }

    fn name(&self) -> Option<&String> {
        self.name.as_ref()
    }

    fn comment(&self) -> Option<&String> {
        self.comment.as_ref()
    }

    fn new<T>(email: T) -> Self
    where
        T: AsRef<str>,
    {
        EmailContact {
            email: email.as_ref().into(),
            name: None,
            comment: None,
        }
    }

    fn set_name<T>(mut self, name: T) -> Self
    where
        T: AsRef<str>,
    {
        let name = name.as_ref().trim();
        if !name.is_empty() {
            self.name = Some(name.into());
        }
        self
    }

    fn set_email<T>(mut self, email: T) -> Self
    where
        T: AsRef<str>,
    {
        self.email = email.as_ref().into();
        self
    }

    fn set_comment<T>(mut self, comment: T) -> Self
    where
        T: AsRef<str>,
    {
        let comment = comment.as_ref();
        if !comment.is_empty() {
            self.comment = Some(comment.into());
        }
        self
    }

    fn to_contact(self) -> Contact {
        Contact::from(self)
    }
}

/// Check if the email field is the same
impl PartialEq for EmailContact {
    fn eq(&self, other: &EmailContact) -> bool {
        self.email == other.email
    }
}

/// Check if all fields are the same (PartialEq only checks if email is the
/// same)
impl DeepEq for EmailContact {
    fn deep_eq(&self, other: &EmailContact) -> bool {
        self.email == other.email && self.name == other.name && self.comment == other.comment
    }
}

impl fmt::Display for EmailContact {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(n) = &self.name {
            write!(f, "\"{}\" ", n.replace('\\', "\\\\").replace('"', "\\\""))?;
            if let Some(c) = &self.comment {
                write!(f, "({}) ", c)?;
            }
        }
        write!(
            f,
            "<{}>",
            self.email.replace('\\', "\\\\").replace('"', "\\\""),
        )
    }
}

/// A string that we couldn't parse into an [`EmailContact`] but implements
/// the [`Contactish`] trait regardless
///
/// [`EmailContact`]: struct.EmailContact.html
/// [`Contactish`]: trait.Contactish.html
#[derive(Debug, Clone, Default)]
pub struct GarbageContact(String);

impl Contactish for GarbageContact {
    /// Since we are garbage, we don't have an email address
    fn email(&self) -> Option<&String> {
        None
    }

    /// Since we are garbage, we don't have a name
    fn name(&self) -> Option<&String> {
        None
    }

    /// Returns the actual string we couldn't interpret as [`EmailContact`]
    ///
    /// [`EmailContact`]: struct.EmailContact.html
    fn comment(&self) -> Option<&String> {
        Some(&self.0)
    }

    fn new<T>(garbage: T) -> Self
    where
        T: AsRef<str>,
    {
        GarbageContact(garbage.as_ref().into())
    }

    fn set_comment<T>(mut self, garbage: T) -> Self
    where
        T: AsRef<str>,
    {
        self.0 = garbage.as_ref().into();
        self
    }

    fn set_email<T>(self, _: T) -> Self {
        self
    }

    fn set_name<T>(self, _: T) -> Self {
        self
    }

    fn to_contact(self) -> Contact {
        Contact::from(self)
    }
}

impl From<String> for GarbageContact {
    fn from(string: String) -> Self {
        GarbageContact(string)
    }
}

/// Either an [`EmailContact`] we could successfully parse or a
/// [`GarbageContact`] we didn't want to throw away
///
/// [`EmailContact`]: struct.EmailContact.html
/// [`GarbageContact`]: struct.GarbageContact.html
#[derive(Clone)]
pub enum Contact {
    Email(EmailContact),
    Garbage(GarbageContact),
}

impl Contact {
    pub fn is_garbage(&self) -> bool {
        matches!(self, Contact::Garbage(_))
    }
}

/// Will be handed down on our variants' contents, which implement the same
/// trait
///
/// The exception to the rule is the [`::new`] method.
///
/// **Please note:** the current implementation does not (yet?) magically change
/// a `Contact::Garbage` variant into a `Contact::Email` one if you try to call
/// `::set_email`. It merely returns an unchanged `Self`.
///
/// [`::new`]: enum.Contact.html#method.new
impl Contactish for Contact {
    fn name(&self) -> Option<&String> {
        match self {
            Contact::Email(c) => c.name(),
            Contact::Garbage(_) => None,
        }
    }

    fn email(&self) -> Option<&String> {
        match self {
            Contact::Email(c) => c.email(),
            Contact::Garbage(_) => None,
        }
    }

    fn comment(&self) -> Option<&String> {
        match self {
            Contact::Email(c) => c.comment(),
            Contact::Garbage(c) => c.comment(),
        }
    }

    /// By default we create a new `Contact::Email` variant, since
    /// `Contact::Garbage` is merely a fallback
    fn new<T>(email: T) -> Self
    where
        T: AsRef<str>,
    {
        EmailContact::new(email).into()
    }

    fn set_name<T>(self, name: T) -> Self
    where
        T: AsRef<str>,
    {
        match self {
            Contact::Email(c) => c.set_name(name).into(),
            Contact::Garbage(g) => g.set_name(name).into(),
        }
    }

    fn set_comment<T>(self, comment: T) -> Self
    where
        T: AsRef<str>,
    {
        match self {
            Contact::Email(c) => c.set_comment(comment).into(),
            Contact::Garbage(g) => g.set_comment(comment).into(),
        }
    }

    fn set_email<T>(self, email: T) -> Self
    where
        T: AsRef<str>,
    {
        match self {
            Contact::Email(c) => c.set_email(email).into(),
            Contact::Garbage(g) => g.set_email(email).into(),
        }
    }

    fn to_contact(self) -> Self {
        self
    }
}

impl PartialEq for Contact {
    fn eq(&self, other: &Contact) -> bool {
        self.email() == other.email()
    }
}

impl DeepEq for Contact {
    fn deep_eq(&self, other: &Contact) -> bool {
        self.email() == other.email()
            || self.name() == other.name()
            || self.comment() == other.comment()
    }
}

impl fmt::Debug for Contact {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Contact({}{}{})",
            match self.name() {
                Some(n) => format!("\"{}\" ", n),
                None => "".into(),
            },
            match self.comment() {
                Some(c) => {
                    if !self.is_garbage() {
                        format!("({}) ", c)
                    } else {
                        format!("Garbage: \"{}\"", c)
                    }
                }
                None => "".into(),
            },
            match self.email() {
                Some(e) => format!("<{}>", e),
                None => "".into(),
            }
        )
    }
}

impl fmt::Display for Contact {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Contact::Garbage(_) => write!(f, ""),
            Contact::Email(e) => write!(f, "{}", e),
        }
    }
}

impl From<GarbageContact> for Contact {
    fn from(garbage: GarbageContact) -> Contact {
        Contact::Garbage(garbage)
    }
}

impl From<EmailContact> for Contact {
    fn from(contact: EmailContact) -> Contact {
        Contact::Email(contact)
    }
}

#[cfg(feature = "mailparse-conversions")]
impl TryInto<mailparse::MailAddr> for Contact {
    type Error = Error;

    fn try_into(self) -> Result<mailparse::MailAddr, Error> {
        match self {
            Contact::Garbage(_) => Err(Error::UnexpectedError(
                "Can't convert Garbage into MailAddr".into(),
            )),
            Contact::Email(_) => Ok(mailparse::MailAddr::Single(self.try_into()?)),
        }
    }
}

#[cfg(feature = "mailparse-conversions")]
impl TryInto<mailparse::SingleInfo> for Contact {
    type Error = Error;

    fn try_into(self) -> Result<mailparse::SingleInfo, Error> {
        match self {
            Contact::Garbage(_) => Err(Error::UnexpectedError(
                "Can't convert Garbage into SingleInfo".into(),
            )),
            Contact::Email(e) => Ok(mailparse::SingleInfo {
                display_name: e.name,
                addr: e.email,
            }),
        }
    }
}

/// Container for [`Contact`]s
///
/// [`Contact`]: enum.Contact.html
///
#[derive(Debug, Clone, Default)]
pub struct Contacts {
    pub contacts: Vec<Contact>,
}

impl Contacts {
    pub fn new() -> Self {
        Self {
            contacts: Vec::new(),
        }
    }
}

impl Contactsish for Vec<Contact> {
    fn len(&self) -> usize {
        self.len()
    }

    fn is_empty(&self) -> bool {
        self.is_empty()
    }

    fn to_contacts(self) -> Contacts {
        Contacts::from(self)
    }

    fn add<C>(&mut self, contact: C)
    where
        C: Contactish,
    {
        self.push(contact.to_contact());
    }

    fn contains(&self, contact: &Contact) -> bool {
        self.iter().any(|y| y == contact)
    }
}

impl Contactsish for Contacts {
    fn len(&self) -> usize {
        self.contacts.len()
    }

    fn is_empty(&self) -> bool {
        self.contacts.is_empty()
    }

    fn to_contacts(self) -> Contacts {
        self
    }

    fn add<C>(&mut self, contact: C)
    where
        C: Contactish,
    {
        self.contacts.push(contact.to_contact());
    }

    fn contains(&self, contact: &Contact) -> bool {
        self.contacts.contains(contact)
    }
}

impl Deref for Contacts {
    type Target = [Contact];

    fn deref(&self) -> &[Contact] {
        self.contacts.as_slice()
    }
}

impl<'a> IntoIterator for &'a Contacts {
    type Item = &'a Contact;
    type IntoIter = std::slice::Iter<'a, Contact>;

    fn into_iter(self) -> Self::IntoIter {
        self.contacts.iter()
    }
}

impl IntoIterator for Contacts {
    type Item = Contact;
    type IntoIter = std::vec::IntoIter<Contact>;

    fn into_iter(self) -> Self::IntoIter {
        self.contacts.into_iter()
    }
}

impl FromIterator<Contact> for Contacts {
    fn from_iter<I: IntoIterator<Item = Contact>>(iter: I) -> Contacts {
        let mut contacts = Contacts::new();
        contacts.contacts = Vec::<Contact>::from_iter(iter);
        contacts
    }
}

impl From<Vec<Contact>> for Contacts {
    fn from(s: Vec<Contact>) -> Self {
        Self { contacts: s }
    }
}

impl fmt::Display for Contacts {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let trim: &[_] = &[' ', ','];
        write!(
            f,
            "{}",
            self.contacts
                .iter()
                .map(|c| format!("{}", c))
                .collect::<Vec<String>>()
                .join(", ")
                .trim_matches(trim),
        )
    }
}

#[cfg(feature = "mailparse-conversions")]
impl TryInto<Vec<mailparse::SingleInfo>> for Contacts {
    type Error = Error;

    fn try_into(self) -> Result<Vec<mailparse::SingleInfo>, Error> {
        self.into_iter().map(|c| c.try_into()).collect()
    }
}

/// A group with a name and [`Contacts`]
///
/// [`Contacts`]: struct.Contacts.html
#[derive(Debug, Clone, Default)]
pub struct Group {
    pub name: String,
    pub contacts: Contacts,
}

impl Group {
    pub fn new<T>(name: T) -> Self
    where
        T: AsRef<str>,
    {
        Self {
            name: name.as_ref().into(),
            ..Default::default()
        }
    }

    pub fn set_contacts<T>(mut self, contacts: T) -> Self
    where
        T: Contactsish,
    {
        self.contacts = contacts.to_contacts();
        self
    }
}

impl PartialEq for Group {
    fn eq(&self, other: &Group) -> bool {
        if self.name != other.name || self.contacts.len() != other.contacts.len() {
            return false;
        }
        for (i, contact) in self.contacts.iter().enumerate() {
            if contact != &other.contacts[i] {
                return false;
            }
        }
        true
    }
}

impl DeepEq for Group {
    fn deep_eq(&self, other: &Group) -> bool {
        if self.name != other.name || self.contacts.len() != other.contacts.len() {
            return false;
        }
        for (i, contact) in self.contacts.iter().enumerate() {
            if !contact.deep_eq(&other.contacts[i]) {
                return false;
            }
        }
        true
    }
}

impl<T> From<T> for Group
where
    T: AsRef<str>,
{
    fn from(string: T) -> Self {
        Self {
            name: string.as_ref().into(),
            contacts: Contacts::new(),
        }
    }
}

impl Contactsish for Group {
    fn len(&self) -> usize {
        self.contacts.len()
    }

    fn is_empty(&self) -> bool {
        self.contacts.is_empty()
    }

    fn to_contacts(self) -> Contacts {
        self.contacts
    }

    fn add<C>(&mut self, contact: C)
    where
        C: Contactish,
    {
        self.contacts.add(contact.to_contact());
    }

    fn contains(&self, contact: &Contact) -> bool {
        self.contacts.contains(contact)
    }
}

#[cfg(feature = "mailparse-conversions")]
impl TryInto<mailparse::MailAddr> for Group {
    type Error = Error;

    fn try_into(self) -> Result<mailparse::MailAddr, Error> {
        Ok(mailparse::MailAddr::Group(mailparse::GroupInfo {
            group_name: self.name,
            addrs: self
                .contacts
                .into_iter()
                .map(|c| c.try_into())
                .collect::<Result<Vec<_>, Error>>()?,
        }))
    }
}

impl fmt::Display for Group {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "\"{}\": {};",
            self.name.replace('\\', "\\\\").replace('"', "\\\""),
            self.contacts
        )
    }
}

/// All forms which email headers like `To`, `From`, `Cc`, etc. can take
///
/// # Examples
///
/// ```rust
/// # use email_address_list::*;
/// let latvian: AddressList = vec![Contact::new("piemērs@example.org")].into();
/// assert!(latvian.contacts()[0].email().unwrap() == "piemērs@example.org");
///
/// let sudanese: AddressList = Group::new("Conto").into();
/// assert!(sudanese.group_name() == Some(&"Conto".to_string()));
/// ```
#[derive(Debug, Clone)]
pub enum AddressList {
    Contacts(Contacts),
    Group(Group),
}

impl AddressList {
    /// Check if this address list is a group
    pub fn is_group(&self) -> bool {
        matches!(self, AddressList::Group(_))
    }

    /// Get the group name if it is a group
    pub fn group_name(&self) -> Option<&String> {
        match self {
            AddressList::Group(g) => Some(&g.name),
            _ => None,
        }
    }

    /// Get the contacts regardless of our variant
    pub fn contacts(&self) -> &Contacts {
        match self {
            AddressList::Contacts(c) => c,
            AddressList::Group(g) => &g.contacts,
        }
    }
}

impl fmt::Display for AddressList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AddressList::Contacts(c) => write!(f, "{}", c),
            AddressList::Group(g) => write!(f, "{}", g),
        }
    }
}

impl PartialEq for AddressList {
    fn eq(&self, other: &AddressList) -> bool {
        if self.is_group() != other.is_group() {
            return false;
        }
        match self {
            AddressList::Group(g) => {
                if let AddressList::Group(o) = other {
                    g == o
                } else {
                    false
                }
            }
            AddressList::Contacts(c) => {
                if let AddressList::Contacts(o) = other {
                    if c.len() != o.len() {
                        return false;
                    }
                    for (i, contact) in c.iter().enumerate() {
                        if contact != &o[i] {
                            return false;
                        }
                    }
                    true
                } else {
                    false
                }
            }
        }
    }
}

impl DeepEq for AddressList {
    fn deep_eq(&self, other: &AddressList) -> bool {
        if self.is_group() != other.is_group() {
            return false;
        }
        match self {
            AddressList::Group(g) => {
                if let AddressList::Group(o) = other {
                    g.deep_eq(o)
                } else {
                    false
                }
            }
            AddressList::Contacts(c) => {
                if let AddressList::Contacts(o) = other {
                    if c.len() != o.len() {
                        return false;
                    }
                    for (i, contact) in c.iter().enumerate() {
                        if !contact.deep_eq(&o[i]) {
                            return false;
                        }
                    }
                    true
                } else {
                    false
                }
            }
        }
    }
}

impl From<Vec<Contact>> for AddressList {
    fn from(s: Vec<Contact>) -> Self {
        Self::Contacts(Contacts { contacts: s })
    }
}

impl Contactsish for AddressList {
    fn len(&self) -> usize {
        match self {
            Self::Contacts(c) => c.len(),
            Self::Group(g) => g.contacts.len(),
        }
    }

    fn is_empty(&self) -> bool {
        match self {
            Self::Contacts(c) => c.is_empty(),
            Self::Group(g) => g.contacts.is_empty(),
        }
    }

    fn to_contacts(self) -> Contacts {
        match self {
            Self::Contacts(c) => c,
            Self::Group(g) => g.contacts,
        }
    }

    fn add<C>(&mut self, contact: C)
    where
        C: Contactish,
    {
        match self {
            Self::Contacts(c) => c.add(contact),
            Self::Group(g) => g.add(contact),
        }
    }

    fn contains(&self, contact: &Contact) -> bool {
        match self {
            Self::Contacts(c) => c.contains(contact),
            Self::Group(g) => g.contains(contact),
        }
    }
}

impl From<Contacts> for AddressList {
    fn from(contacts: Contacts) -> Self {
        Self::Contacts(contacts)
    }
}

impl From<Group> for AddressList {
    fn from(group: Group) -> AddressList {
        Self::Group(group)
    }
}

#[cfg(feature = "mailparse-conversions")]
impl TryInto<Vec<mailparse::MailAddr>> for AddressList {
    type Error = Error;

    fn try_into(self) -> Result<Vec<mailparse::MailAddr>, Error> {
        match self {
            Self::Group(g) => Ok(vec![g.try_into()?]),
            Self::Contacts(c) => c.into_iter().map(|ic| ic.try_into()).collect(),
        }
    }
}