1use chrono::{Datelike, FixedOffset, Offset, TimeZone, Timelike};
2use kumo_chrono_helper::DateTime;
3
4const SHORT_WEEKDAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
5const SHORT_MONTHS: [&str; 12] = [
6 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
7];
8
9pub fn format_rfc2822_date<Tz: TimeZone>(date: DateTime<Tz>) -> String {
15 let zero = FixedOffset::east_opt(0).expect("zero is a valid offset");
16 let raw_offset = date.offset().fix();
17 #[allow(clippy::disallowed_methods)]
21 let (local, offset) = match date.naive_utc().checked_add_offset(raw_offset) {
22 Some(local) => (local, raw_offset),
23 None => (date.naive_utc(), zero),
26 };
27
28 let weekday = SHORT_WEEKDAYS[local.weekday().num_days_from_sunday() as usize];
29 let month = SHORT_MONTHS[local.month0() as usize];
30 let year = local.year().max(0);
31 let day = local.day();
32 let hour = local.hour();
33 let minute = local.minute();
34 let second = local.second() + local.nanosecond() / 1_000_000_000;
37
38 let offset_seconds = offset.local_minus_utc();
39 let (sign, offset_seconds) = if offset_seconds < 0 {
40 ('-', -offset_seconds)
41 } else {
42 ('+', offset_seconds)
43 };
44 let offset_hours = offset_seconds / 3600;
45 let offset_minutes = (offset_seconds % 3600) / 60;
46
47 format!(
48 "{weekday}, {day} {month} {year:04} \
49 {hour:02}:{minute:02}:{second:02} \
50 {sign}{offset_hours:02}{offset_minutes:02}"
51 )
52}
53
54#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
73pub fn parse_rfc2822_date(
74 input: &str,
75) -> Result<DateTime<FixedOffset>, chrono::format::ParseError> {
76 chrono::DateTime::parse_from_rfc2822(input)
77 .or_else(|err| {
78 if let Some(rewritten) = rewrite_unknown_alphabetic_zone(input) {
79 if let Ok(date) = chrono::DateTime::parse_from_rfc2822(&rewritten) {
80 return Ok(date);
81 }
82 }
83 Err(err)
84 })
85 .map(DateTime::from)
86}
87
88fn rewrite_unknown_alphabetic_zone(input: &str) -> Option<String> {
96 let cleaned = crate::rfc5322_parser::strip_cfws(input)?;
97 let (head, zone) = cleaned.rsplit_once(' ')?;
100 if !zone.bytes().all(|b| b.is_ascii_alphabetic()) {
101 return None;
102 }
103 let offset = named_zone_offset(zone).unwrap_or("-0000");
104 Some(format!("{head} {offset}"))
105}
106
107fn named_zone_offset(zone: &str) -> Option<&'static str> {
112 crate::zone_offsets::ZONE_OFFSETS
113 .get(zone.to_ascii_uppercase().as_str())
114 .copied()
115}
116
117#[cfg(test)]
118mod test {
119 use super::*;
120
121 #[test]
122 fn obsolete_utc_zone() {
123 let ses = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 UTC").unwrap();
124 let canonical = parse_rfc2822_date("Thu, 02 Jul 2026 18:55:38 +0000").unwrap();
125 k9::assert_equal!(ses, canonical);
126 }
127
128 #[test]
129 fn recognized_zones_keep_their_offset() {
130 let eastern = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 EST").unwrap();
132 k9::assert_equal!(eastern.to_rfc3339(), "2026-07-02T18:55:38-05:00");
133
134 let numeric = parse_rfc2822_date("Tue, 1 Jul 2003 10:52:37 +0200").unwrap();
135 k9::assert_equal!(numeric.to_rfc3339(), "2003-07-01T10:52:37+02:00");
136 }
137
138 #[test]
139 fn regional_zone_resolves_to_its_offset() {
140 let cest = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 CEST").unwrap();
142 k9::assert_equal!(cest.to_rfc3339(), "2026-07-02T18:55:38+02:00");
143
144 let jst = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 JST").unwrap();
145 k9::assert_equal!(jst.to_rfc3339(), "2026-07-02T18:55:38+09:00");
146 }
147
148 #[test]
149 fn ambiguous_zone_becomes_unknown_offset() {
150 let ist = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 IST").unwrap();
156 let utc = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 UTC").unwrap();
157 k9::assert_equal!(ist, utc);
158 }
159
160 #[test]
161 fn trailing_zone_comment_is_ignored() {
162 let with_comment = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 UTC (Coordinated)").unwrap();
163 let canonical = parse_rfc2822_date("Thu, 02 Jul 2026 18:55:38 +0000").unwrap();
164 k9::assert_equal!(with_comment, canonical);
165 }
166
167 #[test]
168 fn garbage_still_errors() {
169 parse_rfc2822_date("not a date").unwrap_err();
170 }
171
172 #[test]
173 fn format_representable_date() {
174 let date = parse_rfc2822_date("Tue, 1 Jul 2003 10:52:37 +0200").unwrap();
175 k9::assert_equal!(format_rfc2822_date(date), "Tue, 1 Jul 2003 10:52:37 +0200");
176 }
177
178 #[test]
179 fn format_matches_chrono_for_representable_dates() {
180 let utc = FixedOffset::east_opt(0).unwrap();
185 let east = FixedOffset::east_opt(2 * 3600).unwrap();
186 let west = FixedOffset::west_opt(5 * 3600).unwrap();
187 let samples = [
188 east.with_ymd_and_hms(2003, 7, 1, 10, 52, 37).unwrap(),
189 utc.with_ymd_and_hms(2026, 7, 2, 18, 55, 38).unwrap(),
190 west.with_ymd_and_hms(2026, 7, 2, 18, 55, 38).unwrap(),
191 utc.with_ymd_and_hms(9999, 12, 31, 23, 59, 59).unwrap(),
192 utc.with_ymd_and_hms(1, 1, 1, 0, 0, 0).unwrap(),
193 ];
194 for date in samples {
195 #[allow(clippy::disallowed_methods)]
197 let expected = date.to_rfc2822();
198 k9::assert_equal!(format_rfc2822_date(date.into()), expected);
199 }
200 }
201
202 #[test]
203 fn format_far_future_year_keeps_all_digits() {
204 let far_future = chrono::Utc.with_ymd_and_hms(60123, 1, 1, 0, 0, 0).unwrap();
207 k9::assert_equal!(
208 format_rfc2822_date(far_future.into()),
209 "Fri, 1 Jan 60123 00:00:00 +0000"
210 );
211 }
212
213 #[test]
214 fn format_negative_year_clamps_to_zero() {
215 let ancient = chrono::Utc.with_ymd_and_hms(-44, 3, 15, 12, 0, 0).unwrap();
216 k9::assert_equal!(
217 format_rfc2822_date(ancient.into()),
218 "Thu, 15 Mar 0000 12:00:00 +0000"
219 );
220 }
221
222 #[test]
223 fn format_offset_overflow_falls_back_to_utc() {
224 let max_utc = DateTime::<chrono::Utc>::MAX_UTC;
230 let shifted = max_utc.with_timezone(&FixedOffset::east_opt(5 * 3600).unwrap());
231 k9::assert_equal!(format_rfc2822_date(shifted), format_rfc2822_date(max_utc));
232 }
233}