diff --git a/src/datetime/mod.rs b/src/datetime/mod.rs index e82b19e78a..854383109e 100644 --- a/src/datetime/mod.rs +++ b/src/datetime/mod.rs @@ -600,8 +600,10 @@ where #[cfg(any(feature = "alloc", feature = "std", test))] #[cfg_attr(docsrs, doc(cfg(any(feature = "alloc", feature = "std"))))] pub fn to_rfc2822(&self) -> String { - const ITEMS: &[Item<'static>] = &[Item::Fixed(Fixed::RFC2822)]; - self.format_with_items(ITEMS.iter()).to_string() + let mut result = String::with_capacity(32); + crate::format::write_rfc2822(&mut result, self.naive_local(), self.offset.fix()) + .expect("writing rfc2822 datetime to string should never fail"); + result } /// Returns an RFC 3339 and ISO 8601 date and time string such as `1996-12-19T16:39:57-08:00`. diff --git a/src/format/mod.rs b/src/format/mod.rs index 7aae7a8699..8ceb4d7342 100644 --- a/src/format/mod.rs +++ b/src/format/mod.rs @@ -700,19 +700,7 @@ fn format_inner<'a>( // same as `%a, %d %b %Y %H:%M:%S %z` { if let (Some(d), Some(t), Some(&(_, off))) = (date, time, off) { - let sec = t.second() + t.nanosecond() / 1_000_000_000; - write!( - result, - "{}, {:02} {} {:04} {:02}:{:02}:{:02} ", - locale.short_weekdays[d.weekday().num_days_from_sunday() as usize], - d.day(), - locale.short_months[d.month0() as usize], - d.year(), - t.hour(), - t.minute(), - sec - )?; - Some(write_local_minus_utc(result, off, false, Colons::None)) + Some(write_rfc2822_inner(result, d, t, off, locale)) } else { None } @@ -783,6 +771,40 @@ pub(crate) fn write_rfc3339( write_local_minus_utc(result, off, false, Colons::Single) } +#[cfg(any(feature = "alloc", feature = "std", test))] +/// write datetimes like `Tue, 1 Jul 2003 10:52:37 +0200`, same as `%a, %d %b %Y %H:%M:%S %z` +pub(crate) fn write_rfc2822( + result: &mut String, + dt: crate::NaiveDateTime, + off: FixedOffset, +) -> fmt::Result { + write_rfc2822_inner(result, &dt.date(), &dt.time(), off, Locales::new(None)) +} + +#[cfg(any(feature = "alloc", feature = "std", test))] +/// write datetimes like `Tue, 1 Jul 2003 10:52:37 +0200`, same as `%a, %d %b %Y %H:%M:%S %z` +fn write_rfc2822_inner( + result: &mut String, + d: &NaiveDate, + t: &NaiveTime, + off: FixedOffset, + locale: Locales, +) -> fmt::Result { + let sec = t.second() + t.nanosecond() / 1_000_000_000; + write!( + result, + "{}, {:02} {} {:04} {:02}:{:02}:{:02} ", + locale.short_weekdays[d.weekday().num_days_from_sunday() as usize], + d.day(), + locale.short_months[d.month0() as usize], + d.year(), + t.hour(), + t.minute(), + sec + )?; + write_local_minus_utc(result, off, false, Colons::None) +} + /// Tries to format given arguments with given formatting items. /// Internally used by `DelayedFormat`. #[cfg(any(feature = "alloc", feature = "std", test))]