daaki-message 0.1.0

RFC 5322 email message parser and builder
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
//! Public API types for parsed and outgoing email messages.
//!
//! All types are fully owned (`String` / `Vec<u8>`) with no lifetime parameters,
//! per workspace conventions.
//!
//! # References
//! - RFC 5322 (Internet Message Format — address, date-time)
//! - RFC 2045 (MIME — Content-Transfer-Encoding)
//! - RFC 2183 (Content-Disposition)
//! - RFC 3501 Section 6.4.5 (IMAP MIME section numbers)

/// A parsed email message.
///
/// Produced by [`crate::parse_email`]. All fields are owned.
/// Missing or unparseable optional fields are `None`.
///
/// # References
/// - RFC 5322 (message structure)
/// - RFC 2045–2046 (MIME body parts)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedEmail {
    /// Message-ID with angle brackets stripped (RFC 5322 Section 3.6.4).
    pub message_id: Option<String>,
    /// First `In-Reply-To` message-id only (RFC 5322 Section 3.6.4).
    pub in_reply_to: Option<String>,
    /// All `References` message-ids, space-joined (RFC 5322 Section 3.6.4).
    pub references: Option<String>,
    /// Decoded subject (RFC 5322 Section 3.6.5, RFC 2047 encoded words decoded).
    pub subject: Option<String>,
    /// Sender address (RFC 5322 Section 3.6.2).
    pub from: Address,
    /// To recipients (RFC 5322 Section 3.6.3).
    pub to: Vec<Address>,
    /// Cc recipients (RFC 5322 Section 3.6.3).
    pub cc: Vec<Address>,
    /// Bcc recipients (RFC 5322 Section 3.6.3).
    pub bcc: Vec<Address>,
    /// Reply-To addresses (RFC 5322 Section 3.6.2).
    pub reply_to: Vec<Address>,
    /// Parsed date with original timezone offset preserved (RFC 5322 Section 3.3).
    pub date: Option<DateTime>,
    /// First `text/plain` body part, decoded to UTF-8.
    pub body_text: Option<String>,
    /// First `text/html` body part, decoded to UTF-8.
    pub body_html: Option<String>,
    /// Detected attachments with IMAP section numbers.
    pub attachments: Vec<ParsedAttachment>,
    /// Raw header bytes as a `String` (everything before the header/body separator).
    pub raw_headers: String,
    /// Total byte count of the input.
    pub size: u64,
}

/// An email address with optional display name.
///
/// # References
/// - RFC 5322 Section 3.4 (address specification)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Address {
    /// Display name, decoded from RFC 2047 encoded words if present.
    pub name: Option<String>,
    /// Email address (`addr-spec` form).
    pub email: String,
}

/// RFC 5322 specials that require a display name to be quoted.
const SPECIALS: &[char] = &[
    '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"',
];

impl std::fmt::Display for Address {
    /// Formats the address per RFC 5322 Section 3.4.
    ///
    /// - Non-ASCII display names are RFC 2047 encoded (RFC 5322 Section 2.2
    ///   requires header field bodies to be US-ASCII; RFC 2047 Section 5
    ///   defines the encoded-word mechanism for non-ASCII text).
    /// - ASCII display names containing specials are quoted per RFC 5322 Section 3.2.4.
    /// - Without display name: bare `email`
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.name {
            Some(name) if !name.is_empty() => {
                if !name.is_ascii() {
                    // RFC 5322 Section 2.2: field bodies must be US-ASCII.
                    // RFC 2047 Section 5: use encoded-words for non-ASCII text.
                    let encoded = crate::builder::encode_rfc2047_if_needed(name);
                    write!(f, "{encoded} <{}>", self.email)
                } else if name.chars().any(|c| SPECIALS.contains(&c)) {
                    let escaped = name.replace('\\', "\\\\").replace('"', "\\\"");
                    write!(f, "\"{escaped}\" <{}>", self.email)
                } else {
                    write!(f, "{name} <{}>", self.email)
                }
            }
            _ => write!(f, "{}", self.email),
        }
    }
}

impl std::str::FromStr for Address {
    type Err = crate::error::Error;

    /// Parses an address from a string (RFC 5322 Section 3.4).
    ///
    /// Accepts both `Display Name <email>` and bare `email` forms.
    /// Decodes RFC 2047 encoded words in the display name (RFC 2047 Section 5).
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        if s.is_empty() {
            return Err(crate::error::Error::InvalidAddress(
                "empty address string".into(),
            ));
        }

        // Try "Display Name <email>" form
        if let Some(angle_start) = s.rfind('<') {
            if let Some(angle_end) = s.rfind('>') {
                if angle_end > angle_start {
                    let email = s[angle_start + 1..angle_end].trim().to_string();
                    let name_part = s[..angle_start].trim();
                    let name = if name_part.is_empty() {
                        None
                    } else {
                        // Strip only the outer pair of quotes from a quoted-string
                        // (RFC 5322 Section 3.2.4). Using trim_matches('"') would
                        // greedily strip multiple quotes and corrupt escaped quotes
                        // like `\"` at the end of the display name.
                        let stripped = strip_outer_quotes(name_part);
                        let name = stripped.trim().to_string();
                        if name.is_empty() {
                            None
                        } else {
                            // Decode RFC 2047 encoded words in display name
                            // (RFC 2047 Section 5, RFC 5322 Section 2.2).
                            let unescaped = unescape_quoted_string(&name);
                            let decoded = crate::parser::decode_encoded_words(&unescaped);
                            Some(decoded)
                        }
                    };
                    if email.is_empty() {
                        return Err(crate::error::Error::InvalidAddress(
                            "empty email in angle brackets".into(),
                        ));
                    }
                    return Ok(Self { name, email });
                }
            }
        }

        // Bare email
        if s.contains('@') {
            return Ok(Self {
                name: None,
                email: s.to_string(),
            });
        }

        Err(crate::error::Error::InvalidAddress(format!(
            "cannot parse address: {s}"
        )))
    }
}

/// Strips only the outer pair of quotes from a quoted-string.
///
/// If `input` starts with `"` and ends with `"`, removes those two characters.
/// Otherwise returns the input unchanged. Unlike `trim_matches('"')`, this does
/// not greedily strip multiple consecutive quotes, which is critical when the
/// display name ends with an escaped quote like `"She said \"hello\""`.
///
/// # References
/// - RFC 5322 Section 3.2.4 (quoted-string structure)
fn strip_outer_quotes(input: &str) -> &str {
    if input.len() >= 2 && input.starts_with('"') && input.ends_with('"') {
        &input[1..input.len() - 1]
    } else {
        input
    }
}

/// Unescapes a quoted-string: removes backslash from `\\` → `\` and `\"` → `"`.
///
/// Per RFC 5322 Section 3.2.4, a `quoted-pair` is `"\" (VCHAR / WSP)`.
fn unescape_quoted_string(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            if let Some(next) = chars.next() {
                result.push(next);
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Metadata for an attachment found during parsing.
///
/// Does not contain the attachment binary data — use the `section` field
/// to fetch the content on-demand via IMAP `BODY.PEEK[section]`.
///
/// # References
/// - RFC 2183 (Content-Disposition)
/// - RFC 3501 Section 6.4.5 (MIME section numbers)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedAttachment {
    /// Filename from `Content-Disposition` or `Content-Type` name parameter.
    pub filename: Option<String>,
    /// MIME content type (e.g., `"application/pdf"`).
    pub content_type: String,
    /// Content-ID header value, stripped of angle brackets (RFC 2392).
    pub content_id: Option<String>,
    /// `true` if `Content-Disposition: inline` or has a `Content-ID`.
    pub is_inline: bool,
    /// Size of the MIME part body in bytes (if available).
    pub size: Option<u64>,
    /// IMAP MIME section number (e.g., `"2"`, `"1.2"`) for on-demand fetch.
    pub section: Option<String>,
}

/// Day-of-week abbreviations per RFC 5322 Section 3.3.
const DOW_NAMES: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

/// Month abbreviations per RFC 5322 Section 3.3.
const MONTH_NAMES: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

/// Date-time with timezone offset preserved.
///
/// # References
/// - RFC 5322 Section 3.3 (date-time specification)
#[derive(Debug, Clone)]
pub struct DateTime {
    /// Year (e.g., 2025).
    pub year: u16,
    /// Month (1–12).
    pub month: u8,
    /// Day of month (1–31).
    pub day: u8,
    /// Hour (0–23).
    pub hour: u8,
    /// Minute (0–59).
    pub minute: u8,
    /// Second (0–59).
    pub second: u8,
    /// Timezone offset from UTC in minutes (e.g., +0530 → 330, −0800 → −480).
    pub tz_offset_minutes: i16,
}

impl DateTime {
    /// Converts this date-time to a Unix timestamp (seconds since 1970-01-01T00:00:00Z).
    ///
    /// The timezone offset is applied so the result is always UTC-based.
    /// Uses the same civil-to-days algorithm as the builder.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    pub fn to_unix_timestamp(&self) -> i64 {
        let days = Self::civil_to_days(
            i32::from(self.year),
            u32::from(self.month),
            u32::from(self.day),
        );
        let secs = days * 86400
            + i64::from(self.hour) * 3600
            + i64::from(self.minute) * 60
            + i64::from(self.second);
        // Subtract timezone offset to normalize to UTC
        secs - i64::from(self.tz_offset_minutes) * 60
    }

    /// Creates a `DateTime` from a Unix timestamp (seconds since epoch) and a
    /// timezone offset in minutes.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    pub fn from_unix_timestamp(timestamp: i64, tz_offset_minutes: i16) -> Self {
        // Apply timezone offset to get local time
        let local_secs = timestamp + i64::from(tz_offset_minutes) * 60;
        let days = local_secs.div_euclid(86400);
        let time_secs = local_secs.rem_euclid(86400) as u64;

        let (year, month, day) = Self::civil_from_days(days);

        Self {
            year: year as u16,
            month: month as u8,
            day: day as u8,
            hour: (time_secs / 3600) as u8,
            minute: ((time_secs % 3600) / 60) as u8,
            second: (time_secs % 60) as u8,
            tz_offset_minutes,
        }
    }

    /// Returns the current UTC time as a `DateTime`.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    pub fn now() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};

        let secs = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        Self::from_unix_timestamp(secs as i64, 0)
    }

    /// Returns the day of week for this date.
    ///
    /// Returns 0 for Sunday, 1 for Monday, ..., 6 for Saturday.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    #[allow(clippy::cast_sign_loss)]
    pub fn weekday(&self) -> u8 {
        let days = Self::civil_to_days(
            i32::from(self.year),
            u32::from(self.month),
            u32::from(self.day),
        );
        // 1970-01-01 was Thursday (4); result is always in [0, 6]
        (((days % 7) + 4 + 7) % 7) as u8
    }

    /// Formats this date-time as an RFC 5322 date-time string.
    ///
    /// Produces the format: `day-of-week, DD Mon YYYY HH:MM:SS ±HHMM`
    /// (e.g., `"Thu, 13 Feb 2025 15:47:33 +0000"`).
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    pub fn to_rfc5322_string(&self) -> String {
        let dow = self.weekday();
        let dow_name = DOW_NAMES[dow as usize];
        // Clamp month to valid range [1, 12] to prevent index-out-of-bounds
        // panic on malformed DateTime values (RFC 5322 Section 3.3: month = 1–12).
        let month_idx = self.month.clamp(1, 12).saturating_sub(1) as usize;
        let month_name = MONTH_NAMES[month_idx];
        let (sign, tz_h, tz_m) = self.tz_parts();
        format!(
            "{dow_name}, {:02} {month_name} {:04} {:02}:{:02}:{:02} {sign}{tz_h:02}{tz_m:02}",
            self.day, self.year, self.hour, self.minute, self.second,
        )
    }

    /// Formats this date-time as an ISO 8601 / RFC 3339 string.
    ///
    /// Produces the format: `YYYY-MM-DDTHH:MM:SS±HH:MM`
    /// (e.g., `"2025-02-13T15:47:33+00:00"`).
    ///
    /// This format is widely used in JSON APIs and structured data exchange.
    ///
    /// # References
    /// - ISO 8601 (date-time representation)
    /// - RFC 3339 (date-time on the Internet)
    pub fn to_iso8601_string(&self) -> String {
        let (sign, tz_h, tz_m) = self.tz_parts();
        format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{sign}{tz_h:02}:{tz_m:02}",
            self.year, self.month, self.day, self.hour, self.minute, self.second,
        )
    }

    /// Parses an RFC 5322 date-time string into a `DateTime`.
    ///
    /// Accepts: `[day-of-week ","] day month year hour ":" minute [":" second] zone`
    ///
    /// Strips CFWS (comments and folding white space) before parsing, as
    /// allowed by the obsolete date syntax (RFC 5322 Section 4.3).
    ///
    /// Returns `None` if the input is not a valid RFC 5322 date-time.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    /// - RFC 5322 Section 4.3 (obsolete syntax)
    pub fn parse_rfc5322(input: &str) -> Option<Self> {
        crate::parser::parse_rfc5322_date(input)
    }

    /// Returns the timezone offset decomposed as `(sign, hours, minutes)`.
    ///
    /// # References
    /// - RFC 5322 Section 3.3 (zone = ("+" / "-") 4DIGIT)
    fn tz_parts(&self) -> (char, u16, u16) {
        let sign = if self.tz_offset_minutes >= 0 {
            '+'
        } else {
            '-'
        };
        let abs = self.tz_offset_minutes.unsigned_abs();
        (sign, abs / 60, abs % 60)
    }

    /// Converts days since Unix epoch to `(year, month, day)`.
    ///
    /// Algorithm from Howard Hinnant's date algorithms.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    fn civil_from_days(z: i64) -> (i32, u32, u32) {
        let z = z + 719_468;
        let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
        let doe = (z - era * 146_097) as u32;
        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
        let y = i64::from(yoe) + era * 400;
        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        let mp = (5 * doy + 2) / 153;
        let d = doy - (153 * mp + 2) / 5 + 1;
        let m = if mp < 10 { mp + 3 } else { mp - 9 };
        let y = if m <= 2 { y + 1 } else { y };
        (y as i32, m, d)
    }

    /// Converts `(year, month, day)` to days since Unix epoch.
    ///
    /// Algorithm from Howard Hinnant's date algorithms.
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_wrap)]
    fn civil_to_days(year: i32, month: u32, day: u32) -> i64 {
        let y = if month <= 2 {
            i64::from(year) - 1
        } else {
            i64::from(year)
        };
        let m = if month <= 2 { month + 9 } else { month - 3 };
        let era = (if y >= 0 { y } else { y - 399 }) / 400;
        let yoe = (y - era * 400) as u64;
        let doy = (153 * u64::from(m) + 2) / 5 + u64::from(day) - 1;
        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
        era * 146_097 + doe as i64 - 719_468
    }
}

impl PartialEq for DateTime {
    /// Compares two `DateTime` values by their UTC-normalized timestamps,
    /// consistent with the `Ord` implementation.
    ///
    /// # References
    /// - RFC 5322 Section 3.3 (date-time specification)
    fn eq(&self, other: &Self) -> bool {
        self.to_unix_timestamp() == other.to_unix_timestamp()
    }
}

impl Eq for DateTime {}

impl std::hash::Hash for DateTime {
    /// Hashes by UTC-normalized timestamp, consistent with `Eq` and `Ord`.
    ///
    /// Two `DateTime` values representing the same UTC instant (but with
    /// different timezone offsets) will produce the same hash, matching the
    /// `Eq` behavior.
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.to_unix_timestamp().hash(state);
    }
}

impl PartialOrd for DateTime {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for DateTime {
    /// Compares two `DateTime` values by their UTC-normalized timestamps.
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.to_unix_timestamp().cmp(&other.to_unix_timestamp())
    }
}

impl std::fmt::Display for DateTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (sign, tz_h, tz_m) = self.tz_parts();
        write!(
            f,
            "{:04}-{:02}-{:02} {:02}:{:02}:{:02} {sign}{tz_h:02}{tz_m:02}",
            self.year, self.month, self.day, self.hour, self.minute, self.second,
        )
    }
}

impl std::str::FromStr for DateTime {
    type Err = crate::error::Error;

    /// Parses an RFC 5322 date-time string into a `DateTime`.
    ///
    /// Accepts: `[day-of-week ","] day month year hour ":" minute [":" second] zone`
    ///
    /// This enables the ergonomic `"Thu, 13 Feb 2025 15:47:33 +0000".parse::<DateTime>()`
    /// pattern via the standard `FromStr` trait.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    /// - RFC 5322 Section 4.3 (obsolete syntax)
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_rfc5322(s).ok_or_else(|| {
            crate::error::Error::InvalidDate(format!("cannot parse RFC 5322 date: {s}"))
        })
    }
}

/// An outgoing email to be built into raw RFC 5322 bytes.
///
/// Used as input to [`crate::build_message`].
///
/// # References
/// - RFC 5322 (message format)
/// - RFC 2046 (MIME multipart)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutgoingEmail {
    /// Sender address (RFC 5322 Section 3.6.2).
    pub from: Address,
    /// To recipients (RFC 5322 Section 3.6.3).
    pub to: Vec<Address>,
    /// Cc recipients (RFC 5322 Section 3.6.3).
    pub cc: Vec<Address>,
    /// Bcc recipients — included in SMTP envelope (`RCPT TO`) but **must not**
    /// appear in message headers (RFC 5322 Section 3.6.3).
    pub bcc: Vec<Address>,
    /// Reply-To address (RFC 5322 Section 3.6.2).
    pub reply_to: Option<Address>,
    /// Subject line (RFC 5322 Section 3.6.5).
    pub subject: String,
    /// Plain text body.
    pub body_text: Option<String>,
    /// HTML body.
    pub body_html: Option<String>,
    /// In-Reply-To message ID — bare `addr-spec`, builder wraps in angle brackets.
    pub in_reply_to: Option<String>,
    /// References — space-separated bare message-ids, builder wraps each in angle brackets.
    pub references: Option<String>,
    /// File attachments.
    pub attachments: Vec<OutgoingAttachment>,
}

/// An attachment to include in an outgoing email.
///
/// # References
/// - RFC 2183 (Content-Disposition: attachment)
/// - RFC 2045 (Content-Transfer-Encoding: base64)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutgoingAttachment {
    /// Filename for the `Content-Disposition` header.
    pub filename: String,
    /// MIME content type (e.g., `"application/pdf"`).
    pub content_type: String,
    /// Raw file data — will be base64-encoded in the message.
    pub data: Vec<u8>,
}

/// The result of building an email message.
///
/// # References
/// - RFC 5322 (message format)
/// - RFC 5321 (SMTP envelope)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuiltMessage {
    /// Raw RFC 5322 message bytes (headers + body). BCC excluded from headers.
    pub raw: Vec<u8>,
    /// All envelope recipients (to + cc + bcc) for SMTP `RCPT TO`.
    pub envelope_recipients: Vec<String>,
    /// The generated Message-ID (bare `addr-spec`, no angle brackets).
    pub message_id: String,
}

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

    #[test]
    fn address_display_bare_email() {
        let addr = Address {
            name: None,
            email: "user@example.com".into(),
        };
        assert_eq!(addr.to_string(), "user@example.com");
    }

    #[test]
    fn address_display_with_name() {
        let addr = Address {
            name: Some("John Doe".into()),
            email: "john@example.com".into(),
        };
        assert_eq!(addr.to_string(), "John Doe <john@example.com>");
    }

    #[test]
    fn address_display_name_with_specials_quoted() {
        let addr = Address {
            name: Some("Doe, John".into()),
            email: "john@example.com".into(),
        };
        assert_eq!(addr.to_string(), "\"Doe, John\" <john@example.com>");
    }

    #[test]
    fn address_display_name_with_quotes_escaped() {
        let addr = Address {
            name: Some("John \"Doc\" Doe".into()),
            email: "john@example.com".into(),
        };
        assert_eq!(
            addr.to_string(),
            "\"John \\\"Doc\\\" Doe\" <john@example.com>"
        );
    }

    #[test]
    fn address_from_str_bare_email() {
        let addr: Address = "user@example.com".parse().unwrap();
        assert_eq!(addr.email, "user@example.com");
        assert!(addr.name.is_none());
    }

    #[test]
    fn address_from_str_with_name() {
        let addr: Address = "John Doe <john@example.com>".parse().unwrap();
        assert_eq!(addr.email, "john@example.com");
        assert_eq!(addr.name.as_deref(), Some("John Doe"));
    }

    #[test]
    fn address_from_str_quoted_name() {
        let addr: Address = "\"Doe, John\" <john@example.com>".parse().unwrap();
        assert_eq!(addr.email, "john@example.com");
        assert_eq!(addr.name.as_deref(), Some("Doe, John"));
    }

    #[test]
    fn address_from_str_escaped_quotes_in_name() {
        let addr: Address = "\"John \\\"Doc\\\" Doe\" <john@example.com>"
            .parse()
            .unwrap();
        assert_eq!(addr.email, "john@example.com");
        assert_eq!(addr.name.as_deref(), Some("John \"Doc\" Doe"));
    }

    #[test]
    fn address_from_str_empty_rejected() {
        let result: Result<Address, _> = "".parse();
        assert!(result.is_err());
    }

    #[test]
    fn address_from_str_no_at_rejected() {
        let result: Result<Address, _> = "not-an-email".parse();
        assert!(result.is_err());
    }

    #[test]
    fn address_round_trip_display_from_str() {
        let original = Address {
            name: Some("Doe, John".into()),
            email: "john@example.com".into(),
        };
        let displayed = original.to_string();
        let parsed: Address = displayed.parse().unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn datetime_now_returns_plausible_date() {
        let now = DateTime::now();
        // Year should be 2025 or later (test written in 2026)
        assert!(now.year >= 2025, "DateTime::now() year is {}", now.year);
        assert!((1..=12).contains(&now.month));
        assert!((1..=31).contains(&now.day));
        assert!(now.hour <= 23);
        assert!(now.minute <= 59);
        assert!(now.second <= 60);
        assert_eq!(now.tz_offset_minutes, 0, "now() should return UTC");
    }

    #[test]
    fn datetime_weekday_known_dates() {
        // 2025-02-13 is a Thursday (4)
        let dt = DateTime {
            year: 2025,
            month: 2,
            day: 13,
            hour: 0,
            minute: 0,
            second: 0,
            tz_offset_minutes: 0,
        };
        assert_eq!(dt.weekday(), 4, "2025-02-13 should be Thursday (4)");

        // 1970-01-01 is a Thursday (4)
        let epoch = DateTime::from_unix_timestamp(0, 0);
        assert_eq!(epoch.weekday(), 4, "1970-01-01 should be Thursday (4)");

        // 2025-03-16 is a Sunday (0)
        let sunday = DateTime {
            year: 2025,
            month: 3,
            day: 16,
            hour: 0,
            minute: 0,
            second: 0,
            tz_offset_minutes: 0,
        };
        assert_eq!(sunday.weekday(), 0, "2025-03-16 should be Sunday (0)");
    }

    #[test]
    fn datetime_eq_consistent_with_ord() {
        // Two DateTime values representing the same UTC instant (2025-01-15 12:00:00 UTC)
        // but with different timezone offsets.
        let utc = DateTime {
            year: 2025,
            month: 1,
            day: 15,
            hour: 12,
            minute: 0,
            second: 0,
            tz_offset_minutes: 0,
        };
        let plus_five = DateTime {
            year: 2025,
            month: 1,
            day: 15,
            hour: 17,
            minute: 0,
            second: 0,
            tz_offset_minutes: 300, // +0500
        };

        // Both should have the same UTC timestamp
        assert_eq!(utc.to_unix_timestamp(), plus_five.to_unix_timestamp());

        // Ord says they are equal
        assert_eq!(
            utc.cmp(&plus_five),
            std::cmp::Ordering::Equal,
            "cmp should consider same-UTC-instant values equal"
        );

        // PartialEq must agree with Ord — this is the Rust contract
        assert_eq!(
            utc, plus_five,
            "PartialEq must agree with Ord: same UTC instant should be =="
        );
    }

    #[test]
    fn datetime_hash_consistent_with_eq() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        fn hash_of(dt: &DateTime) -> u64 {
            let mut hasher = DefaultHasher::new();
            dt.hash(&mut hasher);
            hasher.finish()
        }

        // Two DateTime values representing the same UTC instant
        // (2025-01-15 12:00:00 UTC) but with different timezone offsets.
        let utc = DateTime {
            year: 2025,
            month: 1,
            day: 15,
            hour: 12,
            minute: 0,
            second: 0,
            tz_offset_minutes: 0,
        };
        let plus_five = DateTime {
            year: 2025,
            month: 1,
            day: 15,
            hour: 17,
            minute: 0,
            second: 0,
            tz_offset_minutes: 300,
        };

        // Eq says they are equal
        assert_eq!(utc, plus_five);

        // Hash MUST agree: equal values must produce equal hashes
        assert_eq!(
            hash_of(&utc),
            hash_of(&plus_five),
            "Hash must be consistent with Eq: same UTC instant must hash the same"
        );
    }

    #[test]
    fn datetime_to_rfc5322_string_utc() {
        let dt = DateTime {
            year: 2025,
            month: 2,
            day: 13,
            hour: 15,
            minute: 47,
            second: 33,
            tz_offset_minutes: 0,
        };
        // 2025-02-13 is a Thursday
        assert_eq!(dt.to_rfc5322_string(), "Thu, 13 Feb 2025 15:47:33 +0000");
    }

    #[test]
    fn datetime_to_rfc5322_string_positive_offset() {
        let dt = DateTime {
            year: 2025,
            month: 2,
            day: 13,
            hour: 21,
            minute: 17,
            second: 33,
            tz_offset_minutes: 330, // +0530
        };
        assert_eq!(dt.to_rfc5322_string(), "Thu, 13 Feb 2025 21:17:33 +0530");
    }

    #[test]
    fn datetime_to_rfc5322_string_negative_offset() {
        let dt = DateTime {
            year: 2025,
            month: 3,
            day: 16,
            hour: 9,
            minute: 0,
            second: 0,
            tz_offset_minutes: -480, // -0800
        };
        // 2025-03-16 is a Sunday
        assert_eq!(dt.to_rfc5322_string(), "Sun, 16 Mar 2025 09:00:00 -0800");
    }

    #[test]
    fn datetime_parse_rfc5322_basic() {
        let dt = DateTime::parse_rfc5322("Thu, 13 Feb 2025 15:47:33 +0000").unwrap();
        assert_eq!(dt.year, 2025);
        assert_eq!(dt.month, 2);
        assert_eq!(dt.day, 13);
        assert_eq!(dt.hour, 15);
        assert_eq!(dt.minute, 47);
        assert_eq!(dt.second, 33);
        assert_eq!(dt.tz_offset_minutes, 0);
    }

    #[test]
    fn datetime_parse_rfc5322_with_offset() {
        let dt = DateTime::parse_rfc5322("Fri, 14 Feb 2025 09:15:00 -0800").unwrap();
        assert_eq!(dt.year, 2025);
        assert_eq!(dt.tz_offset_minutes, -480);
    }

    #[test]
    fn datetime_parse_rfc5322_round_trip() {
        let original = DateTime {
            year: 2025,
            month: 12,
            day: 25,
            hour: 0,
            minute: 0,
            second: 0,
            tz_offset_minutes: 330,
        };
        let s = original.to_rfc5322_string();
        let parsed = DateTime::parse_rfc5322(&s).unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn datetime_parse_rfc5322_invalid() {
        assert!(DateTime::parse_rfc5322("not a date").is_none());
        assert!(DateTime::parse_rfc5322("").is_none());
    }

    #[test]
    fn datetime_to_iso8601_string_utc() {
        let dt = DateTime {
            year: 2025,
            month: 2,
            day: 13,
            hour: 15,
            minute: 47,
            second: 33,
            tz_offset_minutes: 0,
        };
        assert_eq!(dt.to_iso8601_string(), "2025-02-13T15:47:33+00:00");
    }

    #[test]
    fn datetime_to_iso8601_string_positive_offset() {
        let dt = DateTime {
            year: 2025,
            month: 2,
            day: 13,
            hour: 21,
            minute: 17,
            second: 33,
            tz_offset_minutes: 330, // +05:30
        };
        assert_eq!(dt.to_iso8601_string(), "2025-02-13T21:17:33+05:30");
    }

    #[test]
    fn datetime_to_iso8601_string_negative_offset() {
        let dt = DateTime {
            year: 2025,
            month: 3,
            day: 16,
            hour: 9,
            minute: 0,
            second: 0,
            tz_offset_minutes: -480, // -08:00
        };
        assert_eq!(dt.to_iso8601_string(), "2025-03-16T09:00:00-08:00");
    }

    /// `Address::Display` must RFC 2047 encode non-ASCII display
    /// names, since RFC 5322 Section 2.2 requires header field bodies to be
    /// US-ASCII (RFC 2047 Section 5 defines the encoded-word mechanism).
    #[test]
    fn address_display_non_ascii_is_rfc2047_encoded() {
        let addr = Address {
            name: Some("José García".into()),
            email: "jose@example.com".into(),
        };
        let displayed = addr.to_string();

        // RFC 5322 Section 2.2: field bodies must be US-ASCII
        assert!(
            displayed.is_ascii(),
            "Display output must be pure ASCII, got: {displayed}"
        );
        // RFC 2047 Base64 encoded word marker
        assert!(
            displayed.contains("=?UTF-8?B?"),
            "Non-ASCII name must be RFC 2047 encoded, got: {displayed}"
        );
        // Email must still appear in angle brackets
        assert!(
            displayed.contains("<jose@example.com>"),
            "Email must appear in angle brackets, got: {displayed}"
        );
    }

    /// ASCII display names must NOT be RFC 2047 encoded — encoding is only
    /// needed for non-ASCII characters (RFC 2047 Section 5).
    #[test]
    fn address_display_ascii_name_unchanged() {
        let addr = Address {
            name: Some("John Doe".into()),
            email: "john@example.com".into(),
        };
        let displayed = addr.to_string();
        assert_eq!(displayed, "John Doe <john@example.com>");
        // Must not contain encoded-word markers
        assert!(
            !displayed.contains("=?"),
            "ASCII name should not be RFC 2047 encoded, got: {displayed}"
        );
    }

    /// Round-trip: non-ASCII name formatted with Display, then parsed back
    /// with `FromStr`, must recover the original name (RFC 2047 encode/decode).
    #[test]
    fn address_display_non_ascii_round_trip() {
        let original = Address {
            name: Some("José García".into()),
            email: "jose@example.com".into(),
        };
        let displayed = original.to_string();
        let parsed: Address = displayed.parse().unwrap();
        assert_eq!(
            original, parsed,
            "Round-trip failed: displayed as '{displayed}', parsed name = {:?}",
            parsed.name
        );
    }

    /// `DateTime` with out-of-range month must not panic in
    /// `to_rfc5322_string()` or `weekday()` — violates "no panics" rule and
    /// RFC 5322 Section 3.3 (month is 1–12).
    #[test]
    fn datetime_invalid_month_no_panic() {
        // Month 0 (below valid range)
        let dt_zero = DateTime {
            year: 2025,
            month: 0,
            day: 15,
            hour: 12,
            minute: 0,
            second: 0,
            tz_offset_minutes: 0,
        };
        // Must not panic — should produce a clamped/fallback string
        let _ = dt_zero.to_rfc5322_string();
        let _ = dt_zero.weekday();

        // Month 13 (above valid range)
        let dt_thirteen = DateTime {
            year: 2025,
            month: 13,
            day: 15,
            hour: 12,
            minute: 0,
            second: 0,
            tz_offset_minutes: 0,
        };
        // Must not panic
        let _ = dt_thirteen.to_rfc5322_string();
        let _ = dt_thirteen.weekday();

        // Month 255 (u8::MAX)
        let dt_max = DateTime {
            year: 2025,
            month: 255,
            day: 15,
            hour: 12,
            minute: 0,
            second: 0,
            tz_offset_minutes: 0,
        };
        // Must not panic
        let _ = dt_max.to_rfc5322_string();
        let _ = dt_max.weekday();
    }

    #[test]
    fn datetime_from_str_basic() {
        let dt: DateTime = "Thu, 13 Feb 2025 15:47:33 +0000".parse().unwrap();
        assert_eq!(dt.year, 2025);
        assert_eq!(dt.month, 2);
        assert_eq!(dt.day, 13);
        assert_eq!(dt.hour, 15);
        assert_eq!(dt.minute, 47);
        assert_eq!(dt.second, 33);
        assert_eq!(dt.tz_offset_minutes, 0);
    }

    #[test]
    fn datetime_from_str_with_offset() {
        let dt: DateTime = "Fri, 14 Feb 2025 09:15:00 -0800".parse().unwrap();
        assert_eq!(dt.year, 2025);
        assert_eq!(dt.tz_offset_minutes, -480);
    }

    #[test]
    fn datetime_from_str_invalid() {
        let result: Result<DateTime, _> = "not a date".parse();
        assert!(result.is_err());
    }

    #[test]
    fn datetime_from_str_empty() {
        let result: Result<DateTime, _> = "".parse();
        assert!(result.is_err());
    }

    #[test]
    fn datetime_from_str_round_trip() {
        let original = DateTime {
            year: 2025,
            month: 7,
            day: 4,
            hour: 12,
            minute: 30,
            second: 0,
            tz_offset_minutes: -300,
        };
        let s = original.to_rfc5322_string();
        let parsed: DateTime = s.parse().unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn datetime_display_utc() {
        let dt = DateTime {
            year: 2025,
            month: 2,
            day: 13,
            hour: 15,
            minute: 47,
            second: 33,
            tz_offset_minutes: 0,
        };
        assert_eq!(dt.to_string(), "2025-02-13 15:47:33 +0000");
    }

    #[test]
    fn datetime_display_positive_offset() {
        let dt = DateTime {
            year: 2025,
            month: 2,
            day: 13,
            hour: 21,
            minute: 17,
            second: 33,
            tz_offset_minutes: 330, // +0530
        };
        assert_eq!(dt.to_string(), "2025-02-13 21:17:33 +0530");
    }

    #[test]
    fn datetime_display_negative_offset() {
        let dt = DateTime {
            year: 2025,
            month: 3,
            day: 16,
            hour: 9,
            minute: 0,
            second: 0,
            tz_offset_minutes: -480, // -0800
        };
        assert_eq!(dt.to_string(), "2025-03-16 09:00:00 -0800");
    }

    #[test]
    fn datetime_display_non_half_hour_offset() {
        // Nepal Standard Time: UTC+05:45
        let dt = DateTime {
            year: 2025,
            month: 6,
            day: 1,
            hour: 12,
            minute: 0,
            second: 0,
            tz_offset_minutes: 345, // +0545
        };
        assert_eq!(dt.to_string(), "2025-06-01 12:00:00 +0545");
    }

    #[test]
    fn datetime_display_extreme_offset() {
        // +1200 (e.g. Fiji)
        let dt = DateTime {
            year: 2025,
            month: 1,
            day: 1,
            hour: 0,
            minute: 0,
            second: 0,
            tz_offset_minutes: 720, // +1200
        };
        assert_eq!(dt.to_string(), "2025-01-01 00:00:00 +1200");

        // -1200 (Baker Island)
        let dt_neg = DateTime {
            year: 2025,
            month: 1,
            day: 1,
            hour: 0,
            minute: 0,
            second: 0,
            tz_offset_minutes: -720, // -1200
        };
        assert_eq!(dt_neg.to_string(), "2025-01-01 00:00:00 -1200");
    }

    /// Parsing `<>` must return `Err(InvalidAddress("empty email in angle brackets"))`.
    /// Covers the empty-email guard at L139-142 (RFC 5322 Section 3.4).
    #[test]
    fn address_from_str_empty_angle_brackets_rejected() {
        let result: Result<Address, _> = "<>".parse();
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("empty email in angle brackets"),
            "expected 'empty email in angle brackets' error, got: {msg}"
        );
    }

    /// Parsing `<user@example.com>` (no display name) must yield `name: None`.
    /// Covers the empty `name_part` branch at L120-121 (RFC 5322 Section 3.4).
    #[test]
    fn address_from_str_angle_brackets_no_name() {
        let addr: Address = "<user@example.com>".parse().unwrap();
        assert_eq!(addr.email, "user@example.com");
        assert!(
            addr.name.is_none(),
            "expected name to be None for bare angle-bracket address, got: {:?}",
            addr.name
        );
    }

    /// Parsing `"" <user@example.com>` (quoted empty display name) must yield `name: None`.
    /// After stripping outer quotes, the name is empty, so it becomes `None` at L129-130
    /// (RFC 5322 Section 3.2.4 — quoted-string, RFC 5322 Section 3.4).
    #[test]
    fn address_from_str_quoted_empty_name_is_none() {
        let addr: Address = "\"\" <user@example.com>".parse().unwrap();
        assert_eq!(addr.email, "user@example.com");
        assert!(
            addr.name.is_none(),
            "expected name to be None for quoted empty name, got: {:?}",
            addr.name
        );
    }

    /// Parsing `"   " <user@example.com>` (whitespace-only prefix before `<`) must
    /// yield `name: None`. The whitespace-only `name_part` is trimmed to empty at L119-121
    /// (RFC 5322 Section 3.4).
    #[test]
    fn address_from_str_whitespace_only_name_is_none() {
        let addr: Address = "   <user@example.com>".parse().unwrap();
        assert_eq!(addr.email, "user@example.com");
        assert!(
            addr.name.is_none(),
            "expected name to be None for whitespace-only prefix, got: {:?}",
            addr.name
        );
    }

    /// Parsing `<user@example.com` (unclosed angle bracket) must fall through to
    /// the bare email path or error, since `rfind('>')` fails or returns a position
    /// before `<`. Covers L116/L145-146 (RFC 5322 Section 3.4).
    #[test]
    fn address_from_str_unclosed_angle_bracket() {
        // The `>` is never found, so the angle-bracket branch is skipped.
        // The input does contain `@`, so it parses as a bare email.
        let result: Result<Address, _> = "<user@example.com".parse();
        // Either it parses as a (malformed) bare email or errors — either is acceptable.
        // It must NOT panic.
        if let Ok(addr) = result {
            // Bare email path was taken; name must be None
            assert!(addr.name.is_none());
            assert!(addr.email.contains("user@example.com"));
        }
        // Err is also acceptable — malformed input rejected
    }

    /// `Display` impl must quote and escape backslash and double-quote in
    /// display names containing RFC 5322 specials.
    /// Covers the `replace('\\', "\\\\").replace('"', "\\\"")` path at L88
    /// (RFC 5322 Section 3.2.4 — quoted-pair).
    #[test]
    fn address_display_name_with_special_chars() {
        let addr = Address {
            name: Some("O'Brien \\test".into()),
            email: "obrien@example.com".into(),
        };
        let displayed = addr.to_string();
        // Backslash is a special char, so the name must be quoted and backslash escaped
        assert!(
            displayed.contains("\\\\"),
            "backslash should be escaped in quoted name, got: {displayed}"
        );
        assert!(
            displayed.starts_with('"'),
            "name with specials should be quoted, got: {displayed}"
        );
        assert!(
            displayed.contains("<obrien@example.com>"),
            "email must appear in angle brackets, got: {displayed}"
        );
    }

    /// `unescape_quoted_string` with a trailing backslash (no following character)
    /// must preserve the backslash rather than dropping it.
    /// Covers the `else` branch at L190-192 (RFC 5322 Section 3.2.4 — quoted-pair).
    #[test]
    fn unescape_trailing_backslash() {
        let result = unescape_quoted_string("hello\\");
        assert_eq!(
            result, "hello\\",
            "trailing backslash with no following char should be preserved"
        );
    }
}