daaki-message 0.2.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
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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
#![allow(clippy::unwrap_used)]
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);
}

/// Regression test: Display for Address must quote display names containing
/// `=?` to prevent the parser from mis-decoding them as RFC 2047
/// encoded-words (RFC 2047 Section 5).
#[test]
fn address_display_quotes_encoded_word_syntax() {
    let addr = Address {
        name: Some("=?UTF-8?B?SGVsbG8=?=".into()),
        email: "user@example.com".into(),
    };
    let formatted = addr.to_string();
    // The display name must be wrapped in a quoted-string so the `=?`
    // is not interpreted as an encoded-word prefix.
    assert!(
        formatted.starts_with('"'),
        "display name containing =? must be quoted, got: {formatted}"
    );
    assert_eq!(formatted, "\"=?UTF-8?B?SGVsbG8=?=\" <user@example.com>");
}

/// Regression test: round-trip through Display -> `FromStr` must preserve a
/// display name that literally contains `=?` (RFC 2047 Section 5).
#[test]
fn address_round_trip_encoded_word_syntax_preserved() {
    let original = Address {
        name: Some("=?UTF-8?B?SGVsbG8=?=".into()),
        email: "user@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"
    );
}

/// Whitespace-only display names are not valid phrases under RFC 5322
/// Section 3.4 (`phrase = 1*word`, where `word = atom / quoted-string`).
/// `Display for Address` must treat them as absent and emit a bare email.
#[test]
fn address_display_whitespace_only_name_treated_as_absent() {
    let addr = Address {
        name: Some("   ".to_string()),
        email: "test@example.com".into(),
    };
    assert_eq!(addr.to_string(), "test@example.com");
}

/// RFC 5322 Section 3.3 allows second=60 (leap second).  Unix timestamps
/// do not represent leap seconds, so `to_unix_timestamp()` must clamp 60→59
/// to avoid producing a timestamp 1 second into the next minute.
///
/// Additionally, 23:59:60 UTC and 00:00:00 UTC of the next day represent
/// the same real-world instant.  `Eq`/`Ord` (which compare by timestamp)
/// must treat them as equal.
#[test]
fn datetime_leap_second_clamped_in_timestamp() {
    let leap = DateTime {
        year: 2016,
        month: 12,
        day: 31,
        hour: 23,
        minute: 59,
        second: 60, // leap second
        tz_offset_minutes: 0,
    };
    let clamped = DateTime {
        year: 2016,
        month: 12,
        day: 31,
        hour: 23,
        minute: 59,
        second: 59,
        tz_offset_minutes: 0,
    };

    // Leap second timestamp must equal the clamped (second=59) timestamp,
    // NOT spill into the next minute.
    assert_eq!(
        leap.to_unix_timestamp(),
        clamped.to_unix_timestamp(),
        "leap second (60) must clamp to 59 in timestamp calculation"
    );

    // Eq/Ord must agree
    assert_eq!(
        leap, clamped,
        "leap second DateTime must be equal to the clamped form"
    );
}

#[test]
fn datetime_rfc5322_string_clamps_invalid_time_fields() {
    let dt = DateTime {
        year: 2025,
        month: 1,
        day: 15,
        hour: 25,
        minute: 61,
        second: 99,
        tz_offset_minutes: 0,
    };
    let s = dt.to_rfc5322_string();
    // RFC 5322 Section 3.3: hour 00-23, minute 00-59, second 00-60
    assert!(
        s.contains("23:59:60"),
        "Invalid time fields must be clamped, got: {s}"
    );
}

#[test]
fn datetime_weekday_consistent_with_clamped_month() {
    let dt = DateTime {
        year: 2025,
        month: 0,
        day: 15,
        hour: 12,
        minute: 0,
        second: 0,
        tz_offset_minutes: 0,
    };
    let s = dt.to_rfc5322_string();
    // month 0 is clamped to 1 (Jan), so 2025-01-15 = Wednesday
    assert!(
        s.starts_with("Wed,"),
        "Weekday must match clamped date, got: {s}"
    );
}

/// `DateTime::Display` must clamp fields the same way as
/// `to_rfc5322_string()` and `to_iso8601_string()` to ensure
/// consistent output for out-of-range field values.
#[test]
fn datetime_display_clamps_fields() {
    let dt = DateTime {
        year: 2025,
        month: 0,
        day: 15,
        hour: 99,
        minute: 0,
        second: 0,
        tz_offset_minutes: 0,
    };
    let display = dt.to_string();
    // month 0 should be clamped to 1, hour 99 to 23
    assert!(
        display.contains("-01-") && display.contains(" 23:"),
        "Display must clamp fields like to_rfc5322_string: {display:?}"
    );
}

/// `DateTime::to_unix_timestamp` must clamp hour/minute/second the
/// same way as `to_rfc5322_string()` to produce a timestamp
/// consistent with the string representation.
#[test]
fn datetime_to_unix_timestamp_clamps_hour_minute() {
    let dt = DateTime {
        year: 2025,
        month: 1,
        day: 1,
        hour: 25,
        minute: 0,
        second: 0,
        tz_offset_minutes: 0,
    };
    // After clamping, hour=23 → 2025-01-01 23:00:00 UTC
    let clamped = DateTime {
        year: 2025,
        month: 1,
        day: 1,
        hour: 23,
        minute: 0,
        second: 0,
        tz_offset_minutes: 0,
    };
    assert_eq!(
        dt.to_unix_timestamp(),
        clamped.to_unix_timestamp(),
        "to_unix_timestamp must clamp hour to 0-23 for consistency with formatters"
    );
}

/// `DateTime::from_unix_timestamp` must clamp the year to 0–9999
/// so that negative years from `civil_from_days` (BCE dates) or years
/// exceeding the RFC 5322 range do not silently wrap when cast to `u16`.
///
/// Without the clamp, `i32` year −1 wraps to `u16` 65535, corrupting
/// the date and breaking the `from_unix_timestamp → to_unix_timestamp`
/// round-trip.
///
/// # References
/// - RFC 5322 Section 3.3 (year = 4*DIGIT)
#[test]
fn datetime_from_unix_timestamp_clamps_extreme_years() {
    // Very far in the past: civil_from_days produces a negative year.
    // Before the fix, `year as u16` would wrap (e.g., −1 → 65535).
    let ancient = DateTime::from_unix_timestamp(-62_200_000_000, 0);
    assert!(
        ancient.year <= 9999,
        "Negative year must be clamped, got {}",
        ancient.year
    );
    assert_eq!(ancient.year, 0, "Years before 0 CE should clamp to year 0");

    // Very far in the future: year exceeds u16::MAX.
    // 253_402_300_800 is roughly year 9999; go well beyond.
    let distant = DateTime::from_unix_timestamp(253_402_300_800 * 100, 0);
    assert!(
        distant.year <= 9999,
        "Years above 9999 must be clamped, got {}",
        distant.year
    );
    assert_eq!(distant.year, 9999, "Years above 9999 should clamp to 9999");

    // Normal timestamp round-trips correctly (sanity check).
    let ts = 1_700_000_000_i64; // ~2023-11-14
    let dt = DateTime::from_unix_timestamp(ts, 0);
    assert_eq!(
        dt.to_unix_timestamp(),
        ts,
        "Normal timestamps must round-trip"
    );
}

/// RFC 2047 Section 5: encoded-words MUST NOT appear inside a
/// quoted-string. When the display name is a quoted-string containing
/// literal encoded-word syntax (e.g., `"=?UTF-8?B?SGVsbG8=?="`), the
/// parser must preserve the literal text — not decode it.
///
/// `Address::from_str` must match the behavior of `parse_single_address`
/// (parser.rs) which correctly distinguishes quoted-string vs unquoted
/// phrase contexts.
#[test]
fn address_from_str_quoted_string_encoded_word_not_decoded() {
    // A quoted-string display name that contains literal RFC 2047
    // encoded-word syntax — this must NOT be decoded.
    let addr: Address = "\"=?UTF-8?B?SGVsbG8=?=\" <user@example.com>"
        .parse()
        .unwrap();
    assert_eq!(addr.email, "user@example.com");
    // RFC 2047 Section 5: the encoded-word inside the quoted-string
    // is literal text, not an encoding to be decoded.
    assert_eq!(
        addr.name.as_deref(),
        Some("=?UTF-8?B?SGVsbG8=?="),
        "encoded-word inside quoted-string must be preserved literally \
         (RFC 2047 Section 5)"
    );
}

/// RFC 5322 Section 3.4.1: `addr-spec = local-part "@" domain` — both
/// local-part and domain MUST be non-empty.  Bare emails with a missing
/// side of the `@` must be rejected.
#[test]
fn address_from_str_rejects_empty_local_part() {
    let result: Result<Address, _> = "@example.com".parse();
    assert!(
        result.is_err(),
        "bare email with empty local-part must be rejected (RFC 5322 Section 3.4.1)"
    );
}

#[test]
fn address_from_str_rejects_empty_domain() {
    let result: Result<Address, _> = "user@".parse();
    assert!(
        result.is_err(),
        "bare email with empty domain must be rejected (RFC 5322 Section 3.4.1)"
    );
}

#[test]
fn address_from_str_rejects_bare_at() {
    let result: Result<Address, _> = "@".parse();
    assert!(
        result.is_err(),
        "bare '@' must be rejected (RFC 5322 Section 3.4.1)"
    );
}

/// RFC 5322 Section 3.4.1: `addr-spec` does not permit embedded
/// whitespace in the local-part or domain. The public parser must reject
/// the same invalid addresses that the builder refuses to emit.
#[test]
fn address_from_str_rejects_whitespace_in_addr_spec() {
    for raw in [
        "user @example.com",
        "user@ example.com",
        "user@example .com",
        "Display Name <user @example.com>",
    ] {
        let result: Result<Address, _> = raw.parse();
        assert!(
            result.is_err(),
            "embedded whitespace in addr-spec must be rejected: {raw}"
        );
    }
}

/// RFC 5322 Section 3.4 / Section 3.2.2: after the closing `>` of a
/// `name-addr`, only CFWS is allowed. Arbitrary trailing atoms must be
/// rejected by the public parser.
#[test]
fn address_from_str_rejects_trailing_garbage_after_angle_addr() {
    let result: Result<Address, _> = "Alice <user@example.com> garbage".parse();
    assert!(
        result.is_err(),
        "trailing non-CFWS text after angle-addr must be rejected \
         (RFC 5322 Section 3.4 / Section 3.2.2)"
    );
}

#[test]
fn address_from_str_accepts_trailing_comment_after_angle_addr() {
    let addr: Address = "Alice <user@example.com> (Team Inbox)".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(addr.name.as_deref(), Some("Alice"));
}

/// RFC 5322 Section 3.2.2: comments inside a `display-name` are CFWS and
/// semantically invisible. Parsing must strip them instead of returning
/// the literal parenthesized text.
#[test]
fn address_from_str_strips_comments_from_name_addr_display_name() {
    let addr: Address = "John (Boss) Doe <user@example.com>".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(addr.name.as_deref(), Some("John Doe"));
}

/// RFC 5322 Section 3.2.5: a `display-name` is a phrase, so quoted-string
/// words may be mixed with atoms. The parser must unquote only the quoted
/// word instead of preserving the literal quote characters.
#[test]
fn address_from_str_unquotes_mixed_phrase_words() {
    let addr: Address = "\"John\" Doe <user@example.com>".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(addr.name.as_deref(), Some("John Doe"));
}

#[test]
fn address_from_str_rejects_trailing_garbage_after_addr_spec_comment() {
    let result: Result<Address, _> = "user@example.com (Team Inbox) garbage".parse();
    assert!(
        result.is_err(),
        "trailing non-CFWS text after addr-spec comment must be rejected \
         (RFC 5322 Section 3.4.1 / Section 3.2.2)"
    );
}

/// `clamped_fields()` must respect per-month day limits, not a flat 1-31
/// (RFC 5322 Section 3.3). Months with fewer than 31 days must clamp
/// the day to the actual maximum for that month and year.
#[test]
fn test_clamped_fields_respects_days_in_month() {
    // Feb 31 in leap year 2024 -> should clamp to Feb 29
    let dt_feb_leap = DateTime {
        year: 2024,
        month: 2,
        day: 31,
        hour: 12,
        minute: 0,
        second: 0,
        tz_offset_minutes: 0,
    };
    let s = dt_feb_leap.to_rfc5322_string();
    assert!(
        s.contains("29 Feb 2024"),
        "Feb 31 in leap year 2024 should clamp to 29 Feb, got: {s}"
    );

    // Feb 31 in non-leap year 2023 -> should clamp to Feb 28
    let dt_feb_non_leap = DateTime {
        year: 2023,
        month: 2,
        day: 31,
        hour: 12,
        minute: 0,
        second: 0,
        tz_offset_minutes: 0,
    };
    let s = dt_feb_non_leap.to_rfc5322_string();
    assert!(
        s.contains("28 Feb 2023"),
        "Feb 31 in non-leap year 2023 should clamp to 28 Feb, got: {s}"
    );

    // Apr 31 -> should clamp to Apr 30
    let dt_apr = DateTime {
        year: 2024,
        month: 4,
        day: 31,
        hour: 12,
        minute: 0,
        second: 0,
        tz_offset_minutes: 0,
    };
    let s = dt_apr.to_rfc5322_string();
    assert!(
        s.contains("30 Apr 2024"),
        "Apr 31 should clamp to 30 Apr, got: {s}"
    );
}

/// Regression test: `tz_parts()` must clamp `tz_offset_minutes` to the
/// valid RFC 5322 range [-1439, +1439] so that `to_rfc5322_string()`
/// never produces an HHMM zone with hours > 23 or minutes > 59.
///
/// Without the clamp, offset 1500 produces `+2500` which the parser
/// rightfully rejects, causing round-trip data loss.
///
/// # References
/// - RFC 5322 Section 3.3 (zone = ("+" / "-") 4DIGIT, HHMM)
#[test]
fn test_tz_offset_clamped_for_rfc5322_round_trip() {
    // Positive overflow: 1500 minutes = 25h00m, exceeds max +23:59 (+1439 min)
    let dt = DateTime {
        year: 2025,
        month: 6,
        day: 15,
        hour: 12,
        minute: 0,
        second: 0,
        tz_offset_minutes: 1500,
    };
    let formatted = dt.to_rfc5322_string();
    let parsed = DateTime::parse_rfc5322(&formatted);
    assert!(
        parsed.is_some(),
        "to_rfc5322_string() with tz_offset_minutes=1500 must produce parseable output, got: {formatted}"
    );
    // Clamped to +1439 = +23:59
    let parsed = parsed.unwrap();
    assert_eq!(
        parsed.tz_offset_minutes, 1439,
        "tz_offset_minutes should clamp to 1439, got: {}",
        parsed.tz_offset_minutes
    );

    // Negative overflow: -1500 minutes
    let dt_neg = DateTime {
        year: 2025,
        month: 6,
        day: 15,
        hour: 12,
        minute: 0,
        second: 0,
        tz_offset_minutes: -1500,
    };
    let formatted_neg = dt_neg.to_rfc5322_string();
    let parsed_neg = DateTime::parse_rfc5322(&formatted_neg);
    assert!(
        parsed_neg.is_some(),
        "to_rfc5322_string() with tz_offset_minutes=-1500 must produce parseable output, got: {formatted_neg}"
    );
    let parsed_neg = parsed_neg.unwrap();
    assert_eq!(
        parsed_neg.tz_offset_minutes, -1439,
        "tz_offset_minutes should clamp to -1439, got: {}",
        parsed_neg.tz_offset_minutes
    );
}

/// Regression test: `Address::from_str` must handle the RFC 5322 Section
/// 3.4.1 `addr-spec (display-name)` form where a parenthesized comment
/// follows the bare address.
///
/// Before the fix, `"user@example.com (John Doe)".parse::<Address>()`
/// produced `email = "user@example.com (John Doe)"` (comment included in
/// email) and `name = None`.
///
/// # References
/// - RFC 5322 Section 3.4.1 (addr-spec)
/// - RFC 5322 Section 3.2.2 (comment / CFWS)
#[test]
fn test_address_from_str_parenthesized_comment() {
    let addr: Address = "user@example.com (John Doe)".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(addr.name.as_deref(), Some("John Doe"));
}

/// Regression test: parenthesized comment with nested parens.
///
/// # References
/// - RFC 5322 Section 3.2.2 (nested comments)
#[test]
fn test_address_from_str_nested_parenthesized_comment() {
    let addr: Address = "user@example.com (John (Jack) Doe)".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(addr.name.as_deref(), Some("John (Jack) Doe"));
}

/// Regression test: bare email with no parenthesized comment should
/// still work unchanged.
#[test]
fn test_address_from_str_bare_email_unchanged() {
    let addr: Address = "user@example.com".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(addr.name, None);
}

/// Regression: `Address::from_str("(Name) user@example.com")` returned an
/// error because the code assumed parenthesized comments always follow the
/// addr-spec. When the comment precedes the address, `addr_part` (text
/// before `(`) is empty, causing the local-part/domain validation to fail.
///
/// RFC 5322 Section 3.2.2 allows CFWS (including comments) before
/// the addr-spec. The parser's `parse_single_address` already handles
/// this correctly; `Address::from_str` must match that behavior.
#[test]
fn test_address_from_str_leading_comment() {
    let addr: Address = "(John Doe) user@example.com".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(
        addr.name.as_deref(),
        Some("John Doe"),
        "leading comment should be used as display name (RFC 5322 Section 3.2.2)"
    );
}

/// Leading comment with nested parens must parse correctly.
#[test]
fn test_address_from_str_leading_comment_nested() {
    let addr: Address = "(John (Jack) Doe) user@example.com".parse().unwrap();
    assert_eq!(addr.email, "user@example.com");
    assert_eq!(addr.name.as_deref(), Some("John (Jack) Doe"));
}

/// Regression: `Address::Display` emitted control characters raw.
///
/// RFC 5322 Section 3.2.3: `atext` only includes printable ASCII
/// characters. Control characters (0x00-0x1F, 0x7F) are not valid
/// in atom, qtext, or any wire-safe context and must be encoded.
#[test]
fn address_display_encodes_control_chars() {
    // RFC 5322 Section 3.2.3: control characters are not valid atext.
    let addr = Address {
        name: Some("Hello\x7FWorld".into()),
        email: "user@example.com".into(),
    };
    let displayed = addr.to_string();
    // Control chars must be encoded, not emitted raw
    assert!(
        !displayed.contains('\x7F'),
        "DEL char must not appear raw in output"
    );
    assert!(
        displayed.contains("=?"),
        "Control chars should trigger RFC 2047 encoding"
    );
}

/// Regression: comment content was not unescaped for quoted-pairs.
///
/// RFC 5322 Section 3.2.2: comments support quoted-pair escaping
/// (`\(` → `(`). When extracting semantic content from a comment,
/// escape sequences must be resolved.
#[test]
fn address_from_str_comment_unescapes_quoted_pairs() {
    // RFC 5322 Section 3.2.2: comments support quoted-pair escaping.
    let addr: Address = "(John \\(Jack\\) Doe) user@example.com".parse().unwrap();
    assert_eq!(addr.name.as_deref(), Some("John (Jack) Doe"));
}

/// Regression: unquoted display names had backslash consumed as escape.
///
/// RFC 5322 Section 3.2.4: quoted-pair (`\X` → `X`) is only defined inside
/// quoted-strings and comments. In an unquoted phrase (atom sequence),
/// backslash is a literal character.
#[test]
fn address_from_str_unquoted_preserves_backslash() {
    // RFC 5322 Section 3.2.4: quoted-pair is only valid inside
    // quoted-strings and comments, not in unquoted phrase context.
    let addr: Address = "John \\Doe <user@example.com>".parse().unwrap();
    assert_eq!(addr.name.as_deref(), Some("John \\Doe"));
}

/// RFC 5322 Section 3.4.1 / RFC 5321 Section 4.1.2: a quoted local-part
/// may contain `@` as literal qtext. Public address parsing must keep the
/// full addr-spec intact instead of splitting at the first `@`.
#[test]
fn address_from_str_quoted_local_part_with_at_sign() {
    let addr: Address = "\"user@inner\"@example.com".parse().unwrap();
    assert_eq!(addr.email, "\"user@inner\"@example.com");
    assert_eq!(addr.name, None);
}

/// RFC 5322 Section 3.2.4 / Section 3.4.1: parentheses inside a quoted
/// local-part are qtext, not comment delimiters. The parser must not
/// misinterpret them as CFWS around the addr-spec.
#[test]
fn address_from_str_quoted_local_part_with_parentheses() {
    let addr: Address = "\"user(comment)\"@example.com".parse().unwrap();
    assert_eq!(addr.email, "\"user(comment)\"@example.com");
    assert_eq!(addr.name, None);
}

/// Regression: `Address::from_str("(@")` panicked because the `@` index
/// from the original string `s` was used to slice `addr_part`, which is
/// a shorter substring after stripping the comment. The `@` was inside
/// the comment (not in the address part), so `addr_part` was empty and
/// the index was out of bounds.
///
/// Discovered by cargo-fuzz on the `address_from_str` target.
#[test]
fn fuzz_address_from_str_paren_at_no_panic() {
    // Must return Err, not panic.
    assert!("(@".parse::<Address>().is_err());
    assert!("(@)".parse::<Address>().is_err());
    assert!("(user@host)".parse::<Address>().is_err());
}

// ── HeaderName tests ──────────────────────────────────────────────

/// RFC 5322 Section 2.2: valid ftext characters are accepted.
#[test]
fn header_name_valid() {
    let h = HeaderName::new("X-Custom-Header").unwrap();
    assert_eq!(h.as_str(), "X-Custom-Header");
    assert_eq!(h.to_string(), "X-Custom-Header");
}

#[test]
fn header_name_empty_rejected() {
    assert!(HeaderName::new("").is_err());
}

#[test]
fn header_name_colon_rejected() {
    assert!(HeaderName::new("X-Bad:Name").is_err());
}

#[test]
fn header_name_space_rejected() {
    assert!(HeaderName::new("X Bad").is_err());
}

#[test]
fn header_name_control_char_rejected() {
    assert!(HeaderName::new("X-Bad\x01").is_err());
}

#[test]
fn header_name_non_ascii_rejected() {
    // Non-ASCII bytes are outside the ftext range (33..=126).
    assert!(HeaderName::new("X-Caf\u{00E9}").is_err());
}

#[test]
fn header_name_try_from_string() {
    let h: Result<HeaderName, _> = "X-Valid".to_string().try_into();
    assert!(h.is_ok());
    assert_eq!(h.unwrap().as_str(), "X-Valid");
}

#[test]
fn header_name_try_from_str() {
    let h: Result<HeaderName, _> = "X-Valid".try_into();
    assert!(h.is_ok());
}

#[test]
fn header_name_unchecked_allows_anything() {
    // new_unchecked doesn't validate — Postel's law for parser use.
    let h = HeaderName::new_unchecked("bad: name");
    assert_eq!(h.as_str(), "bad: name");
}

#[test]
fn header_name_as_ref() {
    let h = HeaderName::new("X-Test").unwrap();
    let s: &str = h.as_ref();
    assert_eq!(s, "X-Test");
}

#[test]
fn header_name_into_inner() {
    let h = HeaderName::new("X-Test").unwrap();
    let s: String = h.into_inner();
    assert_eq!(s, "X-Test");
}

#[test]
fn header_name_equality_is_case_insensitive() {
    let upper = HeaderName::new("Subject").unwrap();
    let lower = HeaderName::new("subject").unwrap();
    assert_eq!(
        upper, lower,
        "header field names must compare case-insensitively"
    );
}

#[test]
fn header_name_hash_is_case_insensitive() {
    let mut set = std::collections::HashSet::new();
    set.insert(HeaderName::new("X-Trace").unwrap());
    set.insert(HeaderName::new("x-trace").unwrap());
    assert_eq!(
        set.len(),
        1,
        "header field names that differ only by ASCII case must hash identically"
    );
}

// ── MessageId tests ───────────────────────────────────────────────

/// RFC 5322 Section 3.6.4: valid bare message-ID accepted.
#[test]
fn message_id_valid() {
    let m = MessageId::new("abc123@example.com").unwrap();
    assert_eq!(m.as_str(), "abc123@example.com");
    assert_eq!(m.to_string(), "abc123@example.com");
}

/// RFC 5322 Section 3.6.4 limits generated `msg-id` values to
/// `dot-atom-text` on the left-hand side. RFC 5322 Appendix A notes that
/// `no-fold-quote` was removed from modern `msg-id` syntax, so the public
/// outbound validator must reject it even though parsers may still recover
/// obsolete `obs-id-left` forms from inbound mail.
#[test]
fn message_id_quoted_id_left_rejected_for_public_api() {
    assert!(MessageId::new("\"user@inner\"@example.com").is_err());
}

#[test]
fn message_id_empty_rejected() {
    assert!(MessageId::new("").is_err());
}

#[test]
fn message_id_no_at_rejected() {
    assert!(MessageId::new("no-at-sign").is_err());
}

#[test]
fn message_id_multiple_at_rejected() {
    assert!(MessageId::new("a@b@c").is_err());
}

#[test]
fn message_id_empty_id_left_rejected() {
    assert!(MessageId::new("@example.com").is_err());
}

#[test]
fn message_id_empty_id_right_rejected() {
    assert!(MessageId::new("abc@").is_err());
}

#[test]
fn message_id_whitespace_rejected() {
    assert!(MessageId::new("abc @example.com").is_err());
}

#[test]
fn message_id_angle_brackets_rejected() {
    assert!(MessageId::new("<abc@example.com>").is_err());
}

#[test]
fn message_id_control_char_rejected() {
    assert!(MessageId::new("abc\x01@example.com").is_err());
}

/// RFC 5322 Section 3.2.3: `dot-atom-text` forbids leading, trailing,
/// and consecutive dots in both `id-left` and dot-atom `id-right`.
#[test]
fn message_id_invalid_dot_atom_rejected() {
    assert!(MessageId::new(".user@example.com").is_err());
    assert!(MessageId::new("user.@example.com").is_err());
    assert!(MessageId::new("user..name@example.com").is_err());
    assert!(MessageId::new("user@.example.com").is_err());
    assert!(MessageId::new("user@example.com.").is_err());
    assert!(MessageId::new("user@example..com").is_err());
}

/// RFC 5322 Section 3.6.4: `id-right` may be a `no-fold-literal`.
#[test]
fn message_id_no_fold_literal_id_right_accepted() {
    let m = MessageId::new("user@[127.0.0.1]");
    assert!(m.is_ok(), "no-fold-literal id-right should be accepted");
}

#[test]
fn message_id_try_from_string() {
    let m: Result<MessageId, _> = "valid@host.com".to_string().try_into();
    assert!(m.is_ok());
}

#[test]
fn message_id_try_from_str() {
    let m: Result<MessageId, _> = "valid@host.com".try_into();
    assert!(m.is_ok());
}

#[test]
fn message_id_unchecked_allows_anything() {
    // new_unchecked doesn't validate — Postel's law for parser use.
    let m = MessageId::new_unchecked("no-at");
    assert_eq!(m.as_str(), "no-at");
}

#[test]
fn message_id_as_ref() {
    let m = MessageId::new("test@host.com").unwrap();
    let s: &str = m.as_ref();
    assert_eq!(s, "test@host.com");
}

#[test]
fn message_id_into_inner() {
    let m = MessageId::new("test@host.com").unwrap();
    let s: String = m.into_inner();
    assert_eq!(s, "test@host.com");
}

/// RFC 6532 Section 3.2: non-ASCII characters are valid in
/// internationalized message-IDs (they pass the no-whitespace,
/// no-angle-bracket, no-control check).
#[test]
fn message_id_non_ascii_accepted() {
    let m = MessageId::new("réponse@example.com");
    assert!(
        m.is_ok(),
        "Non-ASCII message-ID should be accepted per RFC 6532"
    );
}

// --- ParsedEmail::validated_extra_headers ---

/// Valid header names (RFC 5322 Section 2.2 ftext) are converted to
/// `HeaderName` and paired with their values.
#[test]
fn validated_extra_headers_converts_valid_names() {
    let email = ParsedEmail {
        extra_headers: vec![
            ("X-Mailer".into(), "TestApp/1.0".into()),
            ("X-Priority".into(), "3".into()),
        ],
        ..Default::default()
    };
    let result = email.validated_extra_headers();
    assert_eq!(result.len(), 2);
    assert_eq!(result[0].0.as_ref(), "X-Mailer");
    assert_eq!(result[0].1, "TestApp/1.0");
    assert_eq!(result[1].0.as_ref(), "X-Priority");
    assert_eq!(result[1].1, "3");
}

/// Headers with names that violate RFC 5322 Section 2.2 ftext syntax
/// (e.g. containing spaces or colons) are silently dropped.
#[test]
fn validated_extra_headers_drops_invalid_names() {
    let email = ParsedEmail {
        extra_headers: vec![
            ("X-Valid".into(), "keep".into()),
            ("Bad Header".into(), "space in name".into()),
            ("Also:Bad".into(), "colon in name".into()),
            (String::new(), "empty name".into()),
            ("X-Also-Valid".into(), "also keep".into()),
        ],
        ..Default::default()
    };
    let result = email.validated_extra_headers();
    assert_eq!(result.len(), 2);
    assert_eq!(result[0].0.as_ref(), "X-Valid");
    assert_eq!(result[0].1, "keep");
    assert_eq!(result[1].0.as_ref(), "X-Also-Valid");
    assert_eq!(result[1].1, "also keep");
}

/// An empty `extra_headers` list produces an empty result.
#[test]
fn validated_extra_headers_empty_input() {
    let email = ParsedEmail::default();
    assert!(email.validated_extra_headers().is_empty());
}

// ── ValidationError ────────────────────────────────────────────────

#[test]
fn validation_error_message_returns_inner_string() {
    let err = ValidationError::new("bad input");
    assert_eq!(err.message(), "bad input");
}

#[test]
fn validation_error_message_matches_display() {
    let err = ValidationError::new("something went wrong");
    assert_eq!(err.message(), err.to_string());
}