email-message 0.7.0

Typed outbound email message and address model
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
use std::fmt::Display;
use std::str::FromStr;
use std::sync::OnceLock;

use crate::email::{EmailAddress, EmailAddressParseError};

static ADDRESS_PARSER: OnceLock<mail_parser::MessageParser> = OnceLock::new();

/// A mailbox address with optional display name.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Mailbox {
    name: Option<String>,
    email: EmailAddress,
}

impl Mailbox {
    /// Returns the optional display name.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

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

impl From<EmailAddress> for Mailbox {
    fn from(email: EmailAddress) -> Self {
        Self { name: None, email }
    }
}

impl From<(String, EmailAddress)> for Mailbox {
    fn from((name, email): (String, EmailAddress)) -> Self {
        Self {
            name: Some(name),
            email,
        }
    }
}

impl From<(Option<String>, EmailAddress)> for Mailbox {
    fn from((name, email): (Option<String>, EmailAddress)) -> Self {
        Self { name, email }
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum MailboxParseError {
    #[error("expected a single mailbox, found {found} address item(s)")]
    ExpectedSingleMailbox { found: usize },
    #[error("expected mailbox but found group")]
    UnexpectedAddressKind,
    #[error("mailbox list contains group entries")]
    ContainsGroupEntry,
    #[error("mailbox parse backend failed")]
    Backend {
        #[source]
        source: AddressBackendError,
    },
}

impl FromStr for Mailbox {
    type Err = MailboxParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(email) = EmailAddress::from_str(s) {
            return Ok(Self::from(email));
        }

        let addresses =
            parse_address_items(s).map_err(|source| MailboxParseError::Backend { source })?;
        if addresses.len() != 1 {
            return Err(MailboxParseError::ExpectedSingleMailbox {
                found: addresses.len(),
            });
        }

        match addresses.into_iter().next() {
            Some(Address::Mailbox(mailbox)) => Ok(mailbox),
            _ => Err(MailboxParseError::UnexpectedAddressKind),
        }
    }
}

impl TryFrom<&str> for Mailbox {
    type Error = MailboxParseError;

    /// Parses a single mailbox from a string slice.
    ///
    /// ```rust
    /// use email_message::Mailbox;
    ///
    /// let mailbox = Mailbox::try_from("Mary Smith <mary@x.test>").unwrap();
    /// assert_eq!(mailbox.name(), Some("Mary Smith"));
    /// assert_eq!(mailbox.email().as_str(), "mary@x.test");
    /// ```
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::from_str(value)
    }
}

/// Renders the mailbox as `"display name" <email>` or just `email` if no
/// display name is set.
///
/// The output is **UTF-8-direct**: a non-ASCII display name is emitted
/// verbatim (e.g. `"José" <jose@example.com>`). This is the right shape
/// for HTTP-API consumers (Postmark, Resend, Mailgun, Loops) which
/// JSON-encode UTF-8 strings natively.
///
/// **Do not use the result directly as an RFC 5322 header value.** SMTP
/// headers are 7-bit and require RFC 2047 encoded-word wrapping for
/// non-ASCII display names; the wire renderer
/// (`email_message_wire::render_rfc822`) applies that encoding
/// separately. Routing `Mailbox::to_string()` straight into a `From:`
/// or `To:` header would emit a malformed RFC 5322 line.
impl Display for Mailbox {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.name() {
            Some(name) => {
                write_quoted(name, f)?;
                f.write_str(" <")?;
                self.email.fmt(f)?;
                f.write_str(">")
            }
            None => self.email.fmt(f),
        }
    }
}

#[cfg(feature = "serde")]
#[derive(serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
enum AddressKind {
    Mailbox,
    Group,
}

#[cfg(feature = "schemars")]
fn mailbox_typed_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
    let email = generator.subschema_for::<EmailAddress>();
    schemars::json_schema!({
        "type": "object",
        "properties": {
            "type": {"const": "mailbox"},
            "name": {"type": ["string", "null"]},
            "email": email
        },
        "required": ["type", "email"]
    })
}

#[cfg(feature = "serde")]
impl serde::Serialize for Mailbox {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct as _;

        let len = 2 + usize::from(self.name.is_some());
        let mut value = serializer.serialize_struct("Mailbox", len)?;
        value.serialize_field("type", "mailbox")?;
        if let Some(name) = &self.name {
            value.serialize_field("name", name)?;
        }
        value.serialize_field("email", &self.email)?;
        value.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Mailbox {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        struct RawMailbox {
            #[serde(rename = "type")]
            type_: AddressKind,
            #[serde(default)]
            name: Option<String>,
            email: EmailAddress,
        }

        fn from_raw<E>(raw: RawMailbox) -> Result<Mailbox, E>
        where
            E: serde::de::Error,
        {
            if raw.type_ != AddressKind::Mailbox {
                return Err(E::custom("expected mailbox address type"));
            }
            Ok(Mailbox {
                name: raw.name,
                email: raw.email,
            })
        }

        #[cfg(feature = "rfc5322-string-compat")]
        {
            // A bespoke `Visitor` (rather than `#[serde(untagged)]`) so
            // typed-shape errors keep their field-level provenance, e.g.
            // `missing field "type"` instead of the generic "did not match
            // any variant" produced by `untagged`.
            struct MailboxVisitor;

            impl<'de> serde::de::Visitor<'de> for MailboxVisitor {
                type Value = Mailbox;

                fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.write_str("a typed mailbox object or an RFC 5322 mailbox string")
                }

                fn visit_str<E>(self, value: &str) -> Result<Mailbox, E>
                where
                    E: serde::de::Error,
                {
                    value.parse().map_err(E::custom)
                }

                fn visit_string<E>(self, value: String) -> Result<Mailbox, E>
                where
                    E: serde::de::Error,
                {
                    value.parse().map_err(E::custom)
                }

                fn visit_map<A>(self, map: A) -> Result<Mailbox, A::Error>
                where
                    A: serde::de::MapAccess<'de>,
                {
                    let raw = <RawMailbox as serde::Deserialize<'de>>::deserialize(
                        serde::de::value::MapAccessDeserializer::new(map),
                    )?;
                    from_raw(raw)
                }
            }

            deserializer.deserialize_any(MailboxVisitor)
        }

        #[cfg(not(feature = "rfc5322-string-compat"))]
        from_raw(RawMailbox::deserialize(deserializer)?)
    }
}

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Mailbox {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Mailbox".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::Mailbox").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let typed = mailbox_typed_schema(generator);

        #[cfg(feature = "rfc5322-string-compat")]
        {
            schemars::json_schema!({
                "oneOf": [
                    typed,
                    {
                        "type": "string",
                        "description": "RFC 5322 mailbox string"
                    }
                ]
            })
        }

        #[cfg(not(feature = "rfc5322-string-compat"))]
        typed
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Mailbox {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let email = EmailAddress::arbitrary(u)?;
        if bool::arbitrary(u)? {
            let name = format!("User {}", u8::arbitrary(u)?);
            Ok(Self {
                name: Some(name),
                email,
            })
        } else {
            Ok(Self { name: None, email })
        }
    }
}

/// A named address group containing mailbox members.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Group {
    name: String,
    members: Vec<Mailbox>,
}

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

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

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GroupParseError {
    #[error("expected a single group, found {found} address item(s)")]
    ExpectedSingleGroup { found: usize },
    #[error("expected group but found mailbox")]
    UnexpectedAddressKind,
    #[error("group parse backend failed")]
    Backend {
        #[source]
        source: AddressBackendError,
    },
}

impl FromStr for Group {
    type Err = GroupParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let addresses =
            parse_address_items(s).map_err(|source| GroupParseError::Backend { source })?;
        if addresses.len() != 1 {
            return Err(GroupParseError::ExpectedSingleGroup {
                found: addresses.len(),
            });
        }

        match addresses.into_iter().next() {
            Some(Address::Group(group)) => Ok(group),
            _ => Err(GroupParseError::UnexpectedAddressKind),
        }
    }
}

impl TryFrom<&str> for Group {
    type Error = GroupParseError;

    /// Parses a single group from a string slice.
    ///
    /// ```rust
    /// use email_message::Group;
    ///
    /// let group = Group::try_from("Undisclosed recipients:;").unwrap();
    /// assert_eq!(group.name(), "Undisclosed recipients");
    /// assert!(group.members().is_empty());
    /// ```
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::from_str(value)
    }
}

/// Renders the group as `"display name": member1, member2, ...;`.
///
/// Same UTF-8-direct caveat as [`Display for Mailbox`]: suitable for
/// HTTP-API consumers, not directly safe as an RFC 5322 header value.
impl Display for Group {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write_quoted(self.name(), f)?;
        f.write_str(":")?;
        for (idx, member) in self.members().iter().enumerate() {
            if idx > 0 {
                f.write_str(", ")?;
            }
            member.fmt(f)?;
        }
        f.write_str(";")
    }
}

#[cfg(feature = "schemars")]
fn group_typed_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
    let members = <Vec<Mailbox> as schemars::JsonSchema>::json_schema(generator);
    schemars::json_schema!({
        "type": "object",
        "properties": {
            "type": {"const": "group"},
            "name": {"type": "string"},
            "members": members
        },
        "required": ["type", "name"]
    })
}

#[cfg(feature = "serde")]
impl serde::Serialize for Group {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct as _;

        let len = 2 + usize::from(!self.members.is_empty());
        let mut value = serializer.serialize_struct("Group", len)?;
        value.serialize_field("type", "group")?;
        value.serialize_field("name", &self.name)?;
        if !self.members.is_empty() {
            value.serialize_field("members", &self.members)?;
        }
        value.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Group {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        struct RawGroup {
            #[serde(rename = "type")]
            type_: AddressKind,
            name: String,
            #[serde(default)]
            members: Vec<Mailbox>,
        }

        fn from_raw<E>(raw: RawGroup) -> Result<Group, E>
        where
            E: serde::de::Error,
        {
            if raw.type_ != AddressKind::Group {
                return Err(E::custom("expected group address type"));
            }
            Ok(Group {
                name: raw.name,
                members: raw.members,
            })
        }

        #[cfg(feature = "rfc5322-string-compat")]
        {
            struct GroupVisitor;

            impl<'de> serde::de::Visitor<'de> for GroupVisitor {
                type Value = Group;

                fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.write_str("a typed group object or an RFC 5322 group string")
                }

                fn visit_str<E>(self, value: &str) -> Result<Group, E>
                where
                    E: serde::de::Error,
                {
                    value.parse().map_err(E::custom)
                }

                fn visit_string<E>(self, value: String) -> Result<Group, E>
                where
                    E: serde::de::Error,
                {
                    value.parse().map_err(E::custom)
                }

                fn visit_map<A>(self, map: A) -> Result<Group, A::Error>
                where
                    A: serde::de::MapAccess<'de>,
                {
                    let raw = <RawGroup as serde::Deserialize<'de>>::deserialize(
                        serde::de::value::MapAccessDeserializer::new(map),
                    )?;
                    from_raw(raw)
                }
            }

            deserializer.deserialize_any(GroupVisitor)
        }

        #[cfg(not(feature = "rfc5322-string-compat"))]
        from_raw(RawGroup::deserialize(deserializer)?)
    }
}

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Group {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Group".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::Group").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let typed = group_typed_schema(generator);

        #[cfg(feature = "rfc5322-string-compat")]
        {
            schemars::json_schema!({
                "oneOf": [
                    typed,
                    {
                        "type": "string",
                        "description": "RFC 5322 group string"
                    }
                ]
            })
        }

        #[cfg(not(feature = "rfc5322-string-compat"))]
        typed
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Group {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let member_count = usize::from(u.int_in_range::<u8>(0..=3)?);
        let mut members = Vec::with_capacity(member_count);
        for _ in 0..member_count {
            members.push(Mailbox::arbitrary(u)?);
        }
        Ok(Self {
            name: format!("Group {}", u8::arbitrary(u)?),
            members,
        })
    }
}

/// A single address item: either a mailbox or a group.
///
/// Deliberately *not* `#[non_exhaustive]`. RFC 5322 §3.4 closes the
/// address grammar to exactly `mailbox / group`; the kernel cannot
/// honestly add a third variant without an RFC update. The
/// derive-required exhaustive `match` lets downstream callers branch
/// on every variant without an `_ =>` arm, useful when an extension
/// crate wants type-safe coverage of the address space.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Address {
    Mailbox(Mailbox),
    Group(Group),
}

impl From<Mailbox> for Address {
    fn from(value: Mailbox) -> Self {
        Self::Mailbox(value)
    }
}

impl From<Group> for Address {
    fn from(value: Group) -> Self {
        Self::Group(value)
    }
}

impl Address {
    /// Returns the mailbox entries represented by this address item.
    pub fn mailboxes(&self) -> impl Iterator<Item = &Mailbox> {
        match self {
            Self::Mailbox(mailbox) => std::slice::from_ref(mailbox).iter(),
            Self::Group(group) => group.members().iter(),
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AddressParseError {
    #[error("expected a single address, found {found} address item(s)")]
    ExpectedSingleAddress { found: usize },
    #[error("address parse backend failed")]
    Backend {
        #[source]
        source: AddressBackendError,
    },
}

impl FromStr for Address {
    type Err = AddressParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(email) = EmailAddress::from_str(s) {
            return Ok(Self::Mailbox(Mailbox::from(email)));
        }

        let addresses =
            parse_address_items(s).map_err(|source| AddressParseError::Backend { source })?;
        if addresses.len() != 1 {
            return Err(AddressParseError::ExpectedSingleAddress {
                found: addresses.len(),
            });
        }

        addresses
            .into_iter()
            .next()
            .ok_or(AddressParseError::ExpectedSingleAddress { found: 0 })
    }
}

impl TryFrom<&str> for Address {
    type Error = AddressParseError;

    /// Parses a single address (mailbox or group) from a string slice.
    ///
    /// ```rust
    /// use email_message::Address;
    ///
    /// let address = Address::try_from("jdoe@one.test").unwrap();
    /// assert_eq!(address.to_string(), "jdoe@one.test");
    /// ```
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::from_str(value)
    }
}

/// Forwards to the underlying [`Display for Mailbox`] or
/// [`Display for Group`]; same UTF-8-direct caveat applies.
impl Display for Address {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Mailbox(mailbox) => mailbox.fmt(f),
            Self::Group(group) => group.fmt(f),
        }
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Address {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Mailbox(mailbox) => serde::Serialize::serialize(mailbox, serializer),
            Self::Group(group) => serde::Serialize::serialize(group, serializer),
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Address {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        #[serde(tag = "type", rename_all = "snake_case")]
        enum RawAddress {
            Mailbox {
                #[serde(default)]
                name: Option<String>,
                email: EmailAddress,
            },
            Group {
                name: String,
                #[serde(default)]
                members: Vec<Mailbox>,
            },
        }

        fn from_raw(raw: RawAddress) -> Address {
            match raw {
                RawAddress::Mailbox { name, email } => Address::Mailbox(Mailbox { name, email }),
                RawAddress::Group { name, members } => Address::Group(Group { name, members }),
            }
        }

        #[cfg(feature = "rfc5322-string-compat")]
        {
            struct AddressVisitor;

            impl<'de> serde::de::Visitor<'de> for AddressVisitor {
                type Value = Address;

                fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.write_str("a typed address object or an RFC 5322 address string")
                }

                fn visit_str<E>(self, value: &str) -> Result<Address, E>
                where
                    E: serde::de::Error,
                {
                    value.parse().map_err(E::custom)
                }

                fn visit_string<E>(self, value: String) -> Result<Address, E>
                where
                    E: serde::de::Error,
                {
                    value.parse().map_err(E::custom)
                }

                fn visit_map<A>(self, map: A) -> Result<Address, A::Error>
                where
                    A: serde::de::MapAccess<'de>,
                {
                    let raw = <RawAddress as serde::Deserialize<'de>>::deserialize(
                        serde::de::value::MapAccessDeserializer::new(map),
                    )?;
                    Ok(from_raw(raw))
                }
            }

            deserializer.deserialize_any(AddressVisitor)
        }

        #[cfg(not(feature = "rfc5322-string-compat"))]
        Ok(from_raw(RawAddress::deserialize(deserializer)?))
    }
}

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Address {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Address".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::Address").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let mailbox = mailbox_typed_schema(generator);
        let group = group_typed_schema(generator);

        #[cfg(feature = "rfc5322-string-compat")]
        {
            schemars::json_schema!({
                "oneOf": [
                    mailbox,
                    group,
                    {
                        "type": "string",
                        "description": "RFC 5322 address string"
                    }
                ]
            })
        }

        #[cfg(not(feature = "rfc5322-string-compat"))]
        schemars::json_schema!({"oneOf": [mailbox, group]})
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Address {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        if bool::arbitrary(u)? {
            Ok(Self::Mailbox(Mailbox::arbitrary(u)?))
        } else {
            Ok(Self::Group(Group::arbitrary(u)?))
        }
    }
}

macro_rules! impl_address_collection {
    ($(#[$meta:meta])* $name:ident, $item:ty, $error:ty, $parse_fn:expr) => {
        $(#[$meta])*
        #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
        pub struct $name {
            items: Vec<$item>,
        }

        #[cfg(feature = "schemars")]
        impl schemars::JsonSchema for $name {
            fn inline_schema() -> bool {
                true
            }

            fn schema_name() -> std::borrow::Cow<'static, str> {
                stringify!($name).into()
            }

            fn schema_id() -> std::borrow::Cow<'static, str> {
                concat!(module_path!(), "::", stringify!($name)).into()
            }

            fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
                let typed = <Vec<$item> as schemars::JsonSchema>::json_schema(generator);

                #[cfg(feature = "rfc5322-string-compat")]
                {
                    schemars::json_schema!({
                        "oneOf": [
                            typed,
                            {
                                "type": "string",
                                "description": "RFC 5322 comma-separated address list string"
                            }
                        ]
                    })
                }

                #[cfg(not(feature = "rfc5322-string-compat"))]
                typed
            }
        }

        impl $name {
            #[must_use]
            pub fn len(&self) -> usize {
                self.items.len()
            }

            #[must_use]
            pub fn is_empty(&self) -> bool {
                self.items.is_empty()
            }

            pub fn iter(&self) -> std::slice::Iter<'_, $item> {
                self.items.iter()
            }

            pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, $item> {
                self.items.iter_mut()
            }

            #[must_use]
            pub fn as_slice(&self) -> &[$item] {
                self.items.as_slice()
            }

            #[must_use]
            pub fn into_vec(self) -> Vec<$item> {
                self.items
            }
        }

        impl From<Vec<$item>> for $name {
            fn from(items: Vec<$item>) -> Self {
                Self { items }
            }
        }

        impl From<$name> for Vec<$item> {
            fn from(value: $name) -> Self {
                value.items
            }
        }

        impl FromStr for $name {
            type Err = $error;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                let items = ($parse_fn)(s)?;
                Ok(Self { items })
            }
        }

        impl TryFrom<&str> for $name {
            type Error = $error;

            /// Parses a list from a string slice.
            fn try_from(value: &str) -> Result<Self, Self::Error> {
                Self::from_str(value)
            }
        }

        impl IntoIterator for $name {
            type Item = $item;
            type IntoIter = std::vec::IntoIter<$item>;

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

        impl<'a> IntoIterator for &'a $name {
            type Item = &'a $item;
            type IntoIter = std::slice::Iter<'a, $item>;

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

        impl<'a> IntoIterator for &'a mut $name {
            type Item = &'a mut $item;
            type IntoIter = std::slice::IterMut<'a, $item>;

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

        impl AsRef<[$item]> for $name {
            fn as_ref(&self) -> &[$item] {
                self.items.as_slice()
            }
        }

        impl std::iter::FromIterator<$item> for $name {
            fn from_iter<T: IntoIterator<Item = $item>>(iter: T) -> Self {
                Self {
                    items: iter.into_iter().collect(),
                }
            }
        }

        impl Extend<$item> for $name {
            fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
                self.items.extend(iter);
            }
        }

        impl Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                for (idx, item) in self.items.iter().enumerate() {
                    if idx > 0 {
                        f.write_str(", ")?;
                    }
                    item.fmt(f)?;
                }
                Ok(())
            }
        }

        #[cfg(feature = "serde")]
        impl serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serde::Serialize::serialize(&self.items, serializer)
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                #[cfg(feature = "rfc5322-string-compat")]
                {
                    struct CollectionVisitor;

                    impl<'de> serde::de::Visitor<'de> for CollectionVisitor {
                        type Value = $name;

                        fn expecting(
                            &self,
                            f: &mut std::fmt::Formatter<'_>,
                        ) -> std::fmt::Result {
                            f.write_str(concat!(
                                "a ",
                                stringify!($name),
                                " array or an RFC 5322 list string",
                            ))
                        }

                        fn visit_str<E>(self, value: &str) -> Result<$name, E>
                        where
                            E: serde::de::Error,
                        {
                            value.parse().map_err(E::custom)
                        }

                        fn visit_string<E>(self, value: String) -> Result<$name, E>
                        where
                            E: serde::de::Error,
                        {
                            value.parse().map_err(E::custom)
                        }

                        fn visit_seq<A>(self, mut seq: A) -> Result<$name, A::Error>
                        where
                            A: serde::de::SeqAccess<'de>,
                        {
                            let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0));
                            while let Some(item) = seq.next_element::<$item>()? {
                                items.push(item);
                            }
                            Ok($name { items })
                        }
                    }

                    deserializer.deserialize_any(CollectionVisitor)
                }

                #[cfg(not(feature = "rfc5322-string-compat"))]
                {
                    let items = <Vec<$item> as serde::Deserialize>::deserialize(deserializer)?;
                    Ok(Self { items })
                }
            }
        }

        #[cfg(feature = "arbitrary")]
        impl<'a> arbitrary::Arbitrary<'a> for $name {
            fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
                let len = usize::from(u.int_in_range::<u8>(0..=4)?);
                let mut items = Vec::with_capacity(len);
                for _ in 0..len {
                    items.push(<$item>::arbitrary(u)?);
                }
                Ok(Self { items })
            }
        }
    };
}

impl_address_collection!(
    /// A parsed list of address items.
    ///
    /// This is used instead of `Vec<Address>` for `FromStr`, because Rust's orphan
    /// rules do not allow implementing foreign traits for foreign types.
    AddressList,
    Address,
    AddressParseError,
    |s| parse_address_items(s).map_err(|source| AddressParseError::Backend { source })
);

impl<'a> TryFrom<Vec<&'a str>> for AddressList {
    type Error = AddressParseError;

    fn try_from(value: Vec<&'a str>) -> Result<Self, Self::Error> {
        value
            .into_iter()
            .map(Address::from_str)
            .collect::<Result<Vec<_>, _>>()
            .map(Self::from)
    }
}

impl<'a> TryFrom<&'a [&'a str]> for AddressList {
    type Error = AddressParseError;

    fn try_from(value: &'a [&'a str]) -> Result<Self, Self::Error> {
        value
            .iter()
            .copied()
            .map(Address::from_str)
            .collect::<Result<Vec<_>, _>>()
            .map(Self::from)
    }
}

impl<'a> TryFrom<Vec<&'a str>> for MailboxList {
    type Error = MailboxParseError;

    fn try_from(value: Vec<&'a str>) -> Result<Self, Self::Error> {
        value
            .into_iter()
            .map(Mailbox::from_str)
            .collect::<Result<Vec<_>, _>>()
            .map(Self::from)
    }
}

impl<'a> TryFrom<&'a [&'a str]> for MailboxList {
    type Error = MailboxParseError;

    fn try_from(value: &'a [&'a str]) -> Result<Self, Self::Error> {
        value
            .iter()
            .copied()
            .map(Mailbox::from_str)
            .collect::<Result<Vec<_>, _>>()
            .map(Self::from)
    }
}

impl_address_collection!(
    /// A parsed list of mailbox items.
    ///
    /// Group entries are rejected when parsing into `MailboxList`.
    MailboxList,
    Mailbox,
    MailboxParseError,
    |s| {
        let addresses = parse_address_items(s).map_err(|source| MailboxParseError::Backend { source })?;
        let mut items = Vec::with_capacity(addresses.len());

        for address in addresses {
            match address {
                Address::Mailbox(mailbox) => items.push(mailbox),
                Address::Group(_) => return Err(MailboxParseError::ContainsGroupEntry),
            }
        }

        Ok(items)
    }
);

/// Maximum byte length accepted by the address-list parser before
/// rejecting outright. 64 KiB is far above any realistic header value
///, RFC 5322 caps physical lines at 998 bytes; even a header folded
/// across hundreds of continuation lines stays well under this. The
/// cap exists to prevent the `format!("To: {input}\r\n\r\n")`
/// allocation amplification on adversarial multi-megabyte input.
pub const MAX_ADDRESS_INPUT_BYTES: usize = 64 * 1024;

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AddressBackendError {
    #[error("address input contains raw newline characters")]
    InputContainsRawNewlines,
    #[error("address input is {len} bytes, exceeding maximum of {max}")]
    #[non_exhaustive]
    InputTooLong { len: usize, max: usize },
    #[error("failed to parse address header")]
    HeaderParse,
    #[error("parsed header did not contain address data")]
    MissingAddress,
    #[error("mailbox is missing addr-spec")]
    MissingAddrSpec,
    #[error("invalid addr-spec `{input}`")]
    InvalidAddrSpec {
        input: String,
        #[source]
        source: EmailAddressParseError,
    },
    #[error("group member at index {index} is missing addr-spec")]
    GroupMemberMissingAddrSpec { index: usize },
    #[error("invalid group member addr-spec `{input}` at index {index}")]
    InvalidGroupMemberAddrSpec {
        index: usize,
        input: String,
        #[source]
        source: EmailAddressParseError,
    },
    #[error("group is missing a name")]
    GroupMissingName,
}

fn write_quoted(value: &str, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str("\"")?;
    for ch in value.chars() {
        if ch == '\\' || ch == '"' {
            f.write_str("\\")?;
        }
        f.write_str(ch.encode_utf8(&mut [0; 4]))?;
    }
    f.write_str("\"")
}

/// Parse-side address-list extractor.
///
/// # Byte discipline at the parser
///
/// This parser deliberately accepts more than the message-level gate
/// rejects. Specifically: it rejects raw CR / LF (which would let an
/// attacker inject a new header line at the parser layer) and
/// inputs over [`MAX_ADDRESS_INPUT_BYTES`]; it does **not** reject
/// NUL or other non-tab ASCII control characters in display-name
/// content.
///
/// The asymmetry is intentional. The kernel's stricter byte-
/// discipline lives at [`crate::Message::validate_basic`] and fires
/// when an outbound `OutboundMessage` is built; inbound parsing is
/// best-effort and used in forensic / archival / replay workflows
/// where rejecting BEL / VT / ESC in display names from real-world
/// malformed-but-recoverable mail loses information. A `Mailbox`
/// carrying questionable bytes is fine *as a parsed value*; it
/// cannot reach an outbound wire renderer because the message-level
/// gate catches it first.
///
/// Callers handing a `Mailbox.name()` directly to a logging sink or
/// non-validated downstream consumer are responsible for their own
/// byte-discipline check.
fn parse_address_items(input: &str) -> Result<Vec<Address>, AddressBackendError> {
    if input.len() > MAX_ADDRESS_INPUT_BYTES {
        return Err(AddressBackendError::InputTooLong {
            len: input.len(),
            max: MAX_ADDRESS_INPUT_BYTES,
        });
    }
    if input.contains('\r') || input.contains('\n') {
        return Err(AddressBackendError::InputContainsRawNewlines);
    }

    let raw = format!("To: {input}\r\n\r\n");
    let parser =
        ADDRESS_PARSER.get_or_init(|| mail_parser::MessageParser::new().with_address_headers());
    let message = parser
        .parse_headers(raw.as_bytes())
        .ok_or(AddressBackendError::HeaderParse)?;
    let parsed = message.to().ok_or(AddressBackendError::MissingAddress)?;

    match parsed {
        mail_parser::Address::List(list) => list
            .iter()
            .map(convert_mailbox)
            .map(|result| result.map(Address::Mailbox))
            .collect(),
        // mail_parser switches the whole header to the `Group` shape as soon
        // as any group syntax appears, and wraps flat mailboxes that appear
        // before/between/after named groups into a synthetic
        // `Group { name: None, ... }`. Flatten those back to `Mailbox`
        // entries so a mixed header like
        // `alice@example.com, Team: bob@team.com;, dave@example.com`
        // produces three items in order rather than a parse error.
        mail_parser::Address::Group(groups) => {
            let mut items = Vec::with_capacity(groups.len());
            for group in groups {
                if group.name.is_some() {
                    items.push(Address::Group(convert_group(group)?));
                } else {
                    for addr in group.addresses.iter() {
                        items.push(Address::Mailbox(convert_mailbox(addr)?));
                    }
                }
            }
            Ok(items)
        }
    }
}

fn convert_mailbox(value: &mail_parser::Addr<'_>) -> Result<Mailbox, AddressBackendError> {
    let raw_email = value
        .address()
        .ok_or(AddressBackendError::MissingAddrSpec)?;
    let email = EmailAddress::from_str(raw_email).map_err(|source| {
        AddressBackendError::InvalidAddrSpec {
            input: raw_email.to_owned(),
            source,
        }
    })?;

    Ok(match value.name() {
        Some(name) => Mailbox::from((name.to_owned(), email)),
        None => Mailbox::from(email),
    })
}

fn convert_group(value: &mail_parser::Group<'_>) -> Result<Group, AddressBackendError> {
    let name = value
        .name
        .as_deref()
        .ok_or(AddressBackendError::GroupMissingName)?
        .to_owned();
    let mut members = Vec::with_capacity(value.addresses.len());
    for (index, member) in value.addresses.iter().enumerate() {
        let mailbox = convert_mailbox(member).map_err(|error| match error {
            AddressBackendError::MissingAddrSpec => {
                AddressBackendError::GroupMemberMissingAddrSpec { index }
            }
            AddressBackendError::InvalidAddrSpec { input, source } => {
                AddressBackendError::InvalidGroupMemberAddrSpec {
                    index,
                    input,
                    source,
                }
            }
            other => other,
        })?;
        members.push(mailbox);
    }

    Ok(Group { name, members })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn mailbox_from_str_accepts_rfc_examples() {
        let parsed = "Mary Smith <mary@x.test>".parse::<Mailbox>();
        assert!(parsed.is_ok(), "expected valid mailbox");

        let parsed = "jdoe@one.test".parse::<Mailbox>();
        assert!(parsed.is_ok(), "expected valid mailbox");
    }

    #[test]
    fn mailbox_from_str_rejects_group() {
        let parsed = "Undisclosed recipients:;".parse::<Mailbox>();
        assert!(matches!(
            parsed,
            Err(MailboxParseError::UnexpectedAddressKind)
        ));
    }

    #[test]
    fn group_from_str_accepts_rfc_examples() {
        let parsed =
            "A Group:Ed Jones <c@a.test>,joe@where.test,John <jdoe@one.test>;".parse::<Group>();
        assert!(parsed.is_ok(), "expected valid group");

        let parsed = "Undisclosed recipients:;".parse::<Group>();
        assert!(parsed.is_ok(), "expected valid group");
    }

    #[test]
    fn address_list_roundtrip() {
        let list = "Mary Smith <mary@x.test>, jdoe@one.test"
            .parse::<AddressList>()
            .expect("address list should parse");
        let rendered = list.to_string();
        let reparsed = rendered
            .parse::<AddressList>()
            .expect("rendered address list should parse");
        assert_eq!(reparsed.as_slice(), list.as_slice());
    }

    #[test]
    fn mailbox_from_str_rejects_input_with_raw_newline() {
        let parsed = "Mary Smith <mary@x.test>\nBcc: victim@example.com".parse::<Mailbox>();
        assert!(matches!(
            parsed,
            Err(MailboxParseError::Backend {
                source: AddressBackendError::InputContainsRawNewlines,
            })
        ));
    }
}