Skip to main content

jiff/fmt/
rfc2822.rs

1/*!
2Support for printing and parsing instants using the [RFC 2822] datetime format.
3
4RFC 2822 is most commonly found when dealing with email messages.
5
6Since RFC 2822 only supports specifying a complete instant in time, the parser
7and printer in this module only use [`ZonedDateTime`] and [`Timestamp`]. If you
8need inexact time, you can get it from [`ZonedDateTime`] via
9[`ZonedDateTime::datetime`].
10
11[RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
12
13# Incomplete support
14
15The RFC 2822 support in this crate is technically incomplete. Specifically,
16it does not support parsing comments within folding whitespace. It will parse
17comments after the datetime itself (including nested comments). See [Issue
18#39][issue39] for an example. If you find a real world use case for parsing
19comments within whitespace at any point in the datetime string, please file
20an issue. That is, the main reason it isn't currently supported is because
21it didn't seem worth the implementation complexity to account for it. But if
22there are real world use cases that need it, then that would be sufficient
23justification for adding it.
24
25RFC 2822 support should otherwise be complete, including support for parsing
26obsolete offsets.
27
28[issue39]: https://github.com/BurntSushi/jiff/issues/39
29
30# Warning
31
32The RFC 2822 format only supports writing a precise instant in time
33expressed via a time zone offset. It does *not* support serializing
34the time zone itself. This means that if you format a zoned datetime
35in a time zone like `America/New_York` and then deserialize it, the
36zoned datetime you get back will be a "fixed offset" zoned datetime.
37This in turn means it will not perform daylight saving time safe
38arithmetic.
39
40Basically, you should use the RFC 2822 format if it's required (for
41example, when dealing with email). But you should not choose it as a
42general interchange format for new applications.
43*/
44
45use jcore::bounds::Sign;
46
47use crate::{
48    Error, Timestamp, ZonedDateTime,
49    civil::{Date, DateTime, Time, Weekday},
50    error::{ErrorContext, fmt::rfc2822::Error as E},
51    fmt::{Parsed, Write, buffer::BorrowedBuffer},
52    tz::{Offset, TimeZone},
53    util::{b, parse},
54};
55
56/// The default date time parser that we use throughout Jiff.
57pub(crate) static DEFAULT_DATETIME_PARSER: DateTimeParser =
58    DateTimeParser::new();
59
60/// The default date time printer that we use throughout Jiff.
61pub(crate) static DEFAULT_DATETIME_PRINTER: DateTimePrinter =
62    DateTimePrinter::new();
63
64/// The maximum number bytes that can be written by the RFC 2822 printer.
65///
66/// We reserve a heap or stack buffer up front before printing, and we want to
67/// ensure we have enough space to write the longest possible RFC 2822 string.
68const PRINTER_MAX_BYTES_RFC2822: usize = 31;
69
70/// Same idea, but for RFC 9110.
71///
72/// The difference comes from always using `GMT` instead of, e.g., `-0400`.
73const PRINTER_MAX_BYTES_RFC9110: usize = 29;
74
75/// Convert a [`ZonedDateTime`] to an [RFC 2822] datetime string.
76///
77/// This is a convenience function for using [`DateTimePrinter`]. In
78/// particular, this always creates and allocates a new `String`. For writing
79/// to an existing string, or converting a [`Timestamp`] to an RFC 2822
80/// datetime string, you'll need to use `DateTimePrinter`.
81///
82/// [RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
83///
84/// # Warning
85///
86/// The RFC 2822 format only supports writing a precise instant in time
87/// expressed via a time zone offset. It does *not* support serializing
88/// the time zone itself. This means that if you format a zoned datetime
89/// in a time zone like `America/New_York` and then deserialize it, the
90/// zoned datetime you get back will be a "fixed offset" zoned datetime.
91/// This in turn means it will not perform daylight saving time safe
92/// arithmetic.
93///
94/// Basically, you should use the RFC 2822 format if it's required (for
95/// example, when dealing with email). But you should not choose it as a
96/// general interchange format for new applications.
97///
98/// # Errors
99///
100/// This returns an error if the year corresponding to this timestamp cannot be
101/// represented in the RFC 2822 format. For example, a negative year.
102///
103/// # Example
104///
105/// This example shows how to convert a zoned datetime to the RFC 2822 format:
106///
107/// ```
108/// use jiff::{civil::date, fmt::rfc2822};
109///
110/// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("Australia/Hobart")?;
111/// assert_eq!(rfc2822::to_string(&zdt)?, "Sat, 15 Jun 2024 07:00:00 +1000");
112///
113/// # Ok::<(), Box<dyn std::error::Error>>(())
114/// ```
115#[cfg(feature = "alloc")]
116#[inline]
117pub fn to_string(zdt: &ZonedDateTime) -> Result<alloc::string::String, Error> {
118    let mut buf = alloc::string::String::new();
119    DEFAULT_DATETIME_PRINTER.print_zoned_datetime(zdt, &mut buf)?;
120    Ok(buf)
121}
122
123/// Parse an [RFC 2822] datetime string into a [`ZonedDateTime`].
124///
125/// This is a convenience function for using [`DateTimeParser`]. In particular,
126/// this takes a `&str` while the `DateTimeParser` accepts a `&[u8]`.
127/// Moreover, if any configuration options are added to RFC 2822 parsing (none
128/// currently exist at time of writing), then it will be necessary to use a
129/// `DateTimeParser` to toggle them. Additionally, a `DateTimeParser` is needed
130/// for parsing into a [`Timestamp`].
131///
132/// [RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
133///
134/// # Warning
135///
136/// The RFC 2822 format only supports writing a precise instant in time
137/// expressed via a time zone offset. It does *not* support serializing
138/// the time zone itself. This means that if you format a zoned datetime
139/// in a time zone like `America/New_York` and then deserialize it, the
140/// zoned datetime you get back will be a "fixed offset" zoned datetime.
141/// This in turn means it will not perform daylight saving time safe
142/// arithmetic.
143///
144/// Basically, you should use the RFC 2822 format if it's required (for
145/// example, when dealing with email). But you should not choose it as a
146/// general interchange format for new applications.
147///
148/// # Errors
149///
150/// This returns an error if the datetime string given is invalid or if it
151/// is valid but doesn't fit in the datetime range supported by Jiff. For
152/// example, RFC 2822 supports offsets up to 99 hours and 59 minutes,
153/// but Jiff's maximum offset is 25 hours, 59 minutes and 59 seconds.
154///
155/// # Example
156///
157/// This example shows how serializing a zoned datetime to RFC 2822 format
158/// and then deserializing will drop information:
159///
160/// ```
161/// use jiff::{civil::date, fmt::rfc2822};
162///
163/// let zdt = date(2024, 7, 13)
164///     .at(15, 9, 59, 789_000_000)
165///     .in_tz("America/New_York")?;
166/// // The default format (i.e., Temporal) guarantees lossless
167/// // serialization.
168/// assert_eq!(zdt.to_string(), "2024-07-13T15:09:59.789-04:00[America/New_York]");
169///
170/// let rfc2822 = rfc2822::to_string(&zdt)?;
171/// // Notice that the time zone name and fractional seconds have been dropped!
172/// assert_eq!(rfc2822, "Sat, 13 Jul 2024 15:09:59 -0400");
173/// // And of course, if we parse it back, all that info is still lost.
174/// // Which means this `zdt` cannot do DST safe arithmetic!
175/// let zdt = rfc2822::parse(&rfc2822)?;
176/// assert_eq!(zdt.to_string(), "2024-07-13T15:09:59-04:00[-04:00]");
177///
178/// # Ok::<(), Box<dyn std::error::Error>>(())
179/// ```
180#[inline]
181pub fn parse(string: &str) -> Result<ZonedDateTime, Error> {
182    DEFAULT_DATETIME_PARSER.parse_zoned_datetime(string)
183}
184
185/// A parser for [RFC 2822] datetimes.
186///
187/// [RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
188///
189/// # Warning
190///
191/// The RFC 2822 format only supports writing a precise instant in time
192/// expressed via a time zone offset. It does *not* support serializing
193/// the time zone itself. This means that if you format a zoned datetime
194/// in a time zone like `America/New_York` and then deserialize it, the
195/// zoned datetime you get back will be a "fixed offset" zoned datetime.
196/// This in turn means it will not perform daylight saving time safe
197/// arithmetic.
198///
199/// Basically, you should use the RFC 2822 format if it's required (for
200/// example, when dealing with email). But you should not choose it as a
201/// general interchange format for new applications.
202///
203/// # Example
204///
205/// This example shows how serializing a zoned datetime to RFC 2822 format
206/// and then deserializing will drop information:
207///
208/// ```
209/// use jiff::{civil::date, fmt::rfc2822};
210///
211/// let zdt = date(2024, 7, 13)
212///     .at(15, 9, 59, 789_000_000)
213///     .in_tz("America/New_York")?;
214/// // The default format (i.e., Temporal) guarantees lossless
215/// // serialization.
216/// assert_eq!(zdt.to_string(), "2024-07-13T15:09:59.789-04:00[America/New_York]");
217///
218/// let rfc2822 = rfc2822::to_string(&zdt)?;
219/// // Notice that the time zone name and fractional seconds have been dropped!
220/// assert_eq!(rfc2822, "Sat, 13 Jul 2024 15:09:59 -0400");
221/// // And of course, if we parse it back, all that info is still lost.
222/// // Which means this `zdt` cannot do DST safe arithmetic!
223/// let zdt = rfc2822::parse(&rfc2822)?;
224/// assert_eq!(zdt.to_string(), "2024-07-13T15:09:59-04:00[-04:00]");
225///
226/// # Ok::<(), Box<dyn std::error::Error>>(())
227/// ```
228#[derive(#[automatically_derived]impl ::core::fmt::Debug for DateTimeParser {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DateTimeParser relaxed_weekday", &&self.relaxed_weekday)
    }
}Debug)]
229pub struct DateTimeParser {
230    relaxed_weekday: bool,
231}
232
233impl DateTimeParser {
234    /// Create a new RFC 2822 datetime parser with the default configuration.
235    #[inline]
236    pub const fn new() -> DateTimeParser {
237        DateTimeParser { relaxed_weekday: false }
238    }
239
240    /// When enabled, parsing will permit the weekday to be inconsistent with
241    /// the date. When enabled, the weekday is still parsed and can result in
242    /// an error if it isn't _a_ valid weekday. Only the error checking for
243    /// whether it is _the_ correct weekday for the parsed date is disabled.
244    ///
245    /// This is sometimes useful for interaction with systems that don't do
246    /// strict error checking.
247    ///
248    /// This is disabled by default. And note that RFC 2822 compliance requires
249    /// that the weekday is consistent with the date.
250    ///
251    /// # Example
252    ///
253    /// ```
254    /// use jiff::{civil::date, fmt::rfc2822};
255    ///
256    /// let string = "Sun, 13 Jul 2024 15:09:59 -0400";
257    /// // The above normally results in an error, since 2024-07-13 is a
258    /// // Saturday:
259    /// assert!(rfc2822::parse(string).is_err());
260    /// // But we can relax the error checking:
261    /// static P: rfc2822::DateTimeParser = rfc2822::DateTimeParser::new()
262    ///     .relaxed_weekday(true);
263    /// assert_eq!(
264    ///     P.parse_zoned_datetime(string)?,
265    ///     date(2024, 7, 13).at(15, 9, 59, 0).in_tz("America/New_York")?,
266    /// );
267    /// // But note that something that isn't recognized as a valid weekday
268    /// // will still result in an error:
269    /// assert!(
270    ///     P.parse_zoned_datetime("Wat, 13 Jul 2024 15:09:59 -0400")
271    ///         .is_err()
272    /// );
273    ///
274    /// # Ok::<(), Box<dyn std::error::Error>>(())
275    /// ```
276    #[inline]
277    pub const fn relaxed_weekday(self, yes: bool) -> DateTimeParser {
278        DateTimeParser { relaxed_weekday: yes, ..self }
279    }
280
281    /// Parse a datetime string into a [`ZonedDateTime`] value.
282    ///
283    /// Note that RFC 2822 does not support time zone annotations. The zoned
284    /// datetime returned will therefore always have a fixed offset time zone.
285    ///
286    /// # Warning
287    ///
288    /// The RFC 2822 format only supports writing a precise instant in time
289    /// expressed via a time zone offset. It does *not* support serializing
290    /// the time zone itself. This means that if you format a zoned datetime
291    /// in a time zone like `America/New_York` and then deserialize it, the
292    /// zoned datetime you get back will be a "fixed offset" zoned datetime.
293    /// This in turn means it will not perform daylight saving time safe
294    /// arithmetic.
295    ///
296    /// Basically, you should use the RFC 2822 format if it's required (for
297    /// example, when dealing with email). But you should not choose it as a
298    /// general interchange format for new applications.
299    ///
300    /// # Errors
301    ///
302    /// This returns an error if the datetime string given is invalid or if it
303    /// is valid but doesn't fit in the datetime range supported by Jiff. For
304    /// example, RFC 2822 supports offsets up to 99 hours and 59 minutes,
305    /// but Jiff's maximum offset is 25 hours, 59 minutes and 59 seconds.
306    ///
307    /// # Example
308    ///
309    /// This shows a basic example of parsing a `Timestamp` from an RFC 2822
310    /// datetime string.
311    ///
312    /// ```
313    /// use jiff::fmt::rfc2822::DateTimeParser;
314    ///
315    /// static PARSER: DateTimeParser = DateTimeParser::new();
316    ///
317    /// let zdt =
318    ///     PARSER.parse_zoned_datetime("Thu, 29 Feb 2024 05:34 -0500")?;
319    /// assert_eq!(zdt.to_string(), "2024-02-29T05:34:00-05:00[-05:00]");
320    ///
321    /// # Ok::<(), Box<dyn std::error::Error>>(())
322    /// ```
323    pub fn parse_zoned_datetime<I: AsRef<[u8]>>(
324        &self,
325        input: I,
326    ) -> Result<ZonedDateTime, Error> {
327        let input = input.as_ref();
328        let zdt = self
329            .parse_zoned_datetime_internal(input)
330            .context(E::FailedZonedDateTime)?
331            .into_full()?;
332        Ok(zdt)
333    }
334
335    /// Parse an RFC 2822 datetime string into a [`Timestamp`].
336    ///
337    /// # Errors
338    ///
339    /// This returns an error if the datetime string given is invalid or if it
340    /// is valid but doesn't fit in the datetime range supported by Jiff. For
341    /// example, RFC 2822 supports offsets up to 99 hours and 59 minutes,
342    /// but Jiff's maximum offset is 25 hours, 59 minutes and 59 seconds.
343    ///
344    /// # Example
345    ///
346    /// This shows a basic example of parsing a `Timestamp` from an RFC 2822
347    /// datetime string.
348    ///
349    /// ```
350    /// use jiff::fmt::rfc2822::DateTimeParser;
351    ///
352    /// static PARSER: DateTimeParser = DateTimeParser::new();
353    ///
354    /// let timestamp = PARSER.parse_timestamp("Thu, 29 Feb 2024 05:34 -0500")?;
355    /// assert_eq!(timestamp.to_string(), "2024-02-29T10:34:00Z");
356    ///
357    /// # Ok::<(), Box<dyn std::error::Error>>(())
358    /// ```
359    pub fn parse_timestamp<I: AsRef<[u8]>>(
360        &self,
361        input: I,
362    ) -> Result<Timestamp, Error> {
363        let input = input.as_ref();
364        let ts = self
365            .parse_timestamp_internal(input)
366            .context(E::FailedTimestamp)?
367            .into_full()?;
368        Ok(ts)
369    }
370
371    /// Parses an RFC 2822 datetime as a zoned datetime.
372    ///
373    /// Note that this doesn't check that the input has been completely
374    /// consumed.
375    #[cfg_attr(feature = "perf-inline", inline(always))]
376    fn parse_zoned_datetime_internal<'i>(
377        &self,
378        input: &'i [u8],
379    ) -> Result<Parsed<'i, ZonedDateTime>, Error> {
380        let Parsed { value: (dt, offset), input } =
381            self.parse_datetime_offset(input)?;
382        let ts = offset.to_timestamp(dt)?;
383        let zdt = ts.to_zoned_datetime(TimeZone::fixed(offset));
384        Ok(Parsed { value: zdt, input })
385    }
386
387    /// Parses an RFC 2822 datetime as a timestamp.
388    ///
389    /// Note that this doesn't check that the input has been completely
390    /// consumed.
391    #[cfg_attr(feature = "perf-inline", inline(always))]
392    fn parse_timestamp_internal<'i>(
393        &self,
394        input: &'i [u8],
395    ) -> Result<Parsed<'i, Timestamp>, Error> {
396        let Parsed { value: (dt, offset), input } =
397            self.parse_datetime_offset(input)?;
398        let ts = offset.to_timestamp(dt)?;
399        Ok(Parsed { value: ts, input })
400    }
401
402    /// Parse the entirety of the given input into RFC 2822 components: a civil
403    /// datetime and its offset.
404    ///
405    /// This also consumes any trailing (superfluous) whitespace.
406    #[cfg_attr(feature = "perf-inline", inline(always))]
407    fn parse_datetime_offset<'i>(
408        &self,
409        input: &'i [u8],
410    ) -> Result<Parsed<'i, (DateTime, Offset)>, Error> {
411        let input = input.as_ref();
412        let Parsed { value: dt, input } = self.parse_datetime(input)?;
413        let Parsed { value: offset, input } = self.parse_offset(input)?;
414        let Parsed { input, .. } = self.skip_whitespace(input);
415        let input = if input.is_empty() {
416            input
417        } else {
418            self.skip_comment(input)?.input
419        };
420        Ok(Parsed { value: (dt, offset), input })
421    }
422
423    /// Parses a civil datetime from an RFC 2822 string. The input may have
424    /// leading whitespace.
425    ///
426    /// This also parses and trailing whitespace, including requiring at least
427    /// one whitespace character.
428    ///
429    /// This basically parses everything except for the zone.
430    #[cfg_attr(feature = "perf-inline", inline(always))]
431    fn parse_datetime<'i>(
432        &self,
433        input: &'i [u8],
434    ) -> Result<Parsed<'i, DateTime>, Error> {
435        if input.is_empty() {
436            return Err(Error::from(E::Empty));
437        }
438        let Parsed { input, .. } = self.skip_whitespace(input);
439        if input.is_empty() {
440            return Err(Error::from(E::EmptyAfterWhitespace));
441        }
442        let Parsed { value: wd, input } = self.parse_weekday(input)?;
443        let Parsed { value: day, input } = self.parse_day(input)?;
444        let Parsed { value: month, input } = self.parse_month(input)?;
445        let Parsed { value: year, input } = self.parse_year(input)?;
446
447        let Parsed { value: hour, input } = self.parse_hour(input)?;
448        let Parsed { input, .. } = self.skip_whitespace(input);
449        let Parsed { input, .. } = self.parse_time_separator(input)?;
450        let Parsed { input, .. } = self.skip_whitespace(input);
451        let Parsed { value: minute, input } = self.parse_minute(input)?;
452
453        let Parsed { value: whitespace_after_minute, input } =
454            self.skip_whitespace(input);
455        let (second, input) = if !input.starts_with(b":") {
456            if !whitespace_after_minute {
457                return Err(Error::from(E::WhitespaceAfterTime));
458            }
459            (0, input)
460        } else {
461            let Parsed { input, .. } = self.parse_time_separator(input)?;
462            let Parsed { input, .. } = self.skip_whitespace(input);
463            let Parsed { value: second, input } = self.parse_second(input)?;
464            let Parsed { input, .. } = self.parse_whitespace(input)?;
465            (second, input)
466        };
467
468        let date = Date::new(year, month, day).context(E::InvalidDate)?;
469        // OK because hour, minute and second have been verified as being
470        // in bounds. And all combinations of such in-bound values are also
471        // valid `Time` values.
472        let time = Time::new(hour, minute, second, 0).unwrap();
473        let dt = DateTime::from_parts(date, time);
474        if let Some(wd) = wd {
475            if !self.relaxed_weekday && wd != dt.weekday() {
476                return Err(Error::from(E::InconsistentWeekday {
477                    parsed: wd,
478                    from_date: dt.weekday(),
479                }));
480            }
481        }
482        Ok(Parsed { value: dt, input })
483    }
484
485    /// Parses an optional weekday at the beginning of an RFC 2822 datetime.
486    ///
487    /// This expects that any optional whitespace preceding the start of an
488    /// optional day has been stripped and that the input has at least one
489    /// byte.
490    ///
491    /// When the first byte of the given input is a digit (or is empty), then
492    /// this returns `None`, as it implies a day is not present. But if it
493    /// isn't a digit, then we assume that it must be a weekday and return an
494    /// error based on that assumption if we couldn't recognize a weekday.
495    ///
496    /// If a weekday is parsed, then this also skips any trailing whitespace
497    /// (and requires at least one whitespace character).
498    #[cfg_attr(feature = "perf-inline", inline(always))]
499    fn parse_weekday<'i>(
500        &self,
501        input: &'i [u8],
502    ) -> Result<Parsed<'i, Option<Weekday>>, Error> {
503        // An empty input is invalid, but we let that case be
504        // handled by the caller. Otherwise, we know there MUST
505        // be a present day if the first character isn't an ASCII
506        // digit.
507        if #[allow(non_exhaustive_omitted_patterns)] match input[0] {
    b'0'..=b'9' => true,
    _ => false,
}matches!(input[0], b'0'..=b'9') {
508            return Ok(Parsed { value: None, input });
509        }
510        if let Ok(len) = u8::try_from(input.len()) {
511            if len < 4 {
512                return Err(Error::from(E::TooShortWeekday {
513                    got_non_digit: input[0],
514                    len,
515                }));
516            }
517        }
518        let b1 = input[0];
519        let b2 = input[1];
520        let b3 = input[2];
521        let wd = match &[
522            b1.to_ascii_lowercase(),
523            b2.to_ascii_lowercase(),
524            b3.to_ascii_lowercase(),
525        ] {
526            b"sun" => Weekday::Sunday,
527            b"mon" => Weekday::Monday,
528            b"tue" => Weekday::Tuesday,
529            b"wed" => Weekday::Wednesday,
530            b"thu" => Weekday::Thursday,
531            b"fri" => Weekday::Friday,
532            b"sat" => Weekday::Saturday,
533            _ => {
534                return Err(Error::from(E::InvalidWeekday {
535                    got_non_digit: input[0],
536                }));
537            }
538        };
539        let Parsed { input, .. } = self.skip_whitespace(&input[3..]);
540        let Some(should_be_comma) = input.get(0).copied() else {
541            return Err(Error::from(E::EndOfInputComma));
542        };
543        if should_be_comma != b',' {
544            return Err(Error::from(E::UnexpectedByteComma {
545                byte: should_be_comma,
546            }));
547        }
548        let Parsed { input, .. } = self.skip_whitespace(&input[1..]);
549        Ok(Parsed { value: Some(wd), input })
550    }
551
552    /// Parses a 1 or 2 digit day.
553    ///
554    /// This assumes the input starts with what must be an ASCII digit (or it
555    /// may be empty).
556    ///
557    /// This also parses at least one mandatory whitespace character after the
558    /// day.
559    #[cfg_attr(feature = "perf-inline", inline(always))]
560    fn parse_day<'i>(&self, input: &'i [u8]) -> Result<Parsed<'i, i8>, Error> {
561        if input.is_empty() {
562            return Err(Error::from(E::EndOfInputDay));
563        }
564        let mut digits = 1;
565        if input.len() >= 2 && #[allow(non_exhaustive_omitted_patterns)] match input[1] {
    b'0'..=b'9' => true,
    _ => false,
}matches!(input[1], b'0'..=b'9') {
566            digits = 2;
567        }
568        let (day, input) = input.split_at(digits);
569        let day = parse::bi64::<b::Day>(day).context(E::ParseDay)?;
570        let Parsed { input, .. } =
571            self.parse_whitespace(input).context(E::WhitespaceAfterDay)?;
572        Ok(Parsed { value: day, input })
573    }
574
575    /// Parses an abbreviated month name.
576    ///
577    /// This assumes the input starts with what must be the beginning of a
578    /// month name (or the input may be empty).
579    ///
580    /// This also parses at least one mandatory whitespace character after the
581    /// month name.
582    #[cfg_attr(feature = "perf-inline", inline(always))]
583    fn parse_month<'i>(
584        &self,
585        input: &'i [u8],
586    ) -> Result<Parsed<'i, i8>, Error> {
587        if input.is_empty() {
588            return Err(Error::from(E::EndOfInputMonth));
589        }
590        if let Ok(len) = u8::try_from(input.len()) {
591            if len < 3 {
592                return Err(Error::from(E::TooShortMonth { len }));
593            }
594        }
595        let b1 = input[0].to_ascii_lowercase();
596        let b2 = input[1].to_ascii_lowercase();
597        let b3 = input[2].to_ascii_lowercase();
598        let month = match &[b1, b2, b3] {
599            b"jan" => 1,
600            b"feb" => 2,
601            b"mar" => 3,
602            b"apr" => 4,
603            b"may" => 5,
604            b"jun" => 6,
605            b"jul" => 7,
606            b"aug" => 8,
607            b"sep" => 9,
608            b"oct" => 10,
609            b"nov" => 11,
610            b"dec" => 12,
611            _ => return Err(Error::from(E::InvalidMonth)),
612        };
613        let Parsed { input, .. } = self
614            .parse_whitespace(&input[3..])
615            .context(E::WhitespaceAfterMonth)?;
616        Ok(Parsed { value: month, input })
617    }
618
619    /// Parses a 2, 3 or 4 digit year.
620    ///
621    /// This assumes the input starts with what must be an ASCII digit (or it
622    /// may be empty).
623    ///
624    /// This also parses at least one mandatory whitespace character after the
625    /// day.
626    ///
627    /// The 2 or 3 digit years are "obsolete," which we support by following
628    /// the rules in RFC 2822:
629    ///
630    /// > Where a two or three digit year occurs in a date, the year is to be
631    /// > interpreted as follows: If a two digit year is encountered whose
632    /// > value is between 00 and 49, the year is interpreted by adding 2000,
633    /// > ending up with a value between 2000 and 2049. If a two digit year is
634    /// > encountered with a value between 50 and 99, or any three digit year
635    /// > is encountered, the year is interpreted by adding 1900.
636    #[cfg_attr(feature = "perf-inline", inline(always))]
637    fn parse_year<'i>(
638        &self,
639        input: &'i [u8],
640    ) -> Result<Parsed<'i, i16>, Error> {
641        let mut digits = 0;
642        while digits <= 3
643            && !input[digits..].is_empty()
644            && #[allow(non_exhaustive_omitted_patterns)] match input[digits] {
    b'0'..=b'9' => true,
    _ => false,
}matches!(input[digits], b'0'..=b'9')
645        {
646            digits += 1;
647        }
648        if let Ok(len) = u8::try_from(digits) {
649            if len <= 1 {
650                return Err(Error::from(E::TooShortYear { len }));
651            }
652        }
653        let (year, input) = input.split_at(digits);
654        let year = parse::bi64::<b::Year>(year).context(E::ParseYear)?;
655        let year = match digits {
656            2 if year <= 49 => year + 2000,
657            2 | 3 => year + 1900,
658            4 => year,
659            _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("digits={0} must be 2, 3 or 4", digits)));
}unreachable!("digits={digits} must be 2, 3 or 4"),
660        };
661        let Parsed { input, .. } =
662            self.parse_whitespace(input).context(E::WhitespaceAfterYear)?;
663        Ok(Parsed { value: year, input })
664    }
665
666    /// Parses a 2-digit hour. This assumes the input begins with what should
667    /// be an ASCII digit. (i.e., It doesn't trim leading whitespace.)
668    ///
669    /// This parses a mandatory trailing `:`, advancing the input to
670    /// immediately after it.
671    #[cfg_attr(feature = "perf-inline", inline(always))]
672    fn parse_hour<'i>(
673        &self,
674        input: &'i [u8],
675    ) -> Result<Parsed<'i, i8>, Error> {
676        let (hour, input) = parse::split(input, 2).ok_or(E::EndOfInputHour)?;
677        let hour = parse::bi64::<b::Hour>(hour).context(E::ParseHour)?;
678        Ok(Parsed { value: hour, input })
679    }
680
681    /// Parses a 2-digit minute. This assumes the input begins with what should
682    /// be an ASCII digit. (i.e., It doesn't trim leading whitespace.)
683    #[cfg_attr(feature = "perf-inline", inline(always))]
684    fn parse_minute<'i>(
685        &self,
686        input: &'i [u8],
687    ) -> Result<Parsed<'i, i8>, Error> {
688        let (minute, input) =
689            parse::split(input, 2).ok_or(E::EndOfInputMinute)?;
690        let minute =
691            parse::bi64::<b::Minute>(minute).context(E::ParseMinute)?;
692        Ok(Parsed { value: minute, input })
693    }
694
695    /// Parses a 2-digit second. This assumes the input begins with what should
696    /// be an ASCII digit. (i.e., It doesn't trim leading whitespace.)
697    #[cfg_attr(feature = "perf-inline", inline(always))]
698    fn parse_second<'i>(
699        &self,
700        input: &'i [u8],
701    ) -> Result<Parsed<'i, i8>, Error> {
702        let (second, input) =
703            parse::split(input, 2).ok_or(E::EndOfInputSecond)?;
704        let mut second =
705            parse::bi64::<b::LeapSecond>(second).context(E::ParseSecond)?;
706        if second == 60 {
707            second = 59;
708        }
709        Ok(Parsed { value: second, input })
710    }
711
712    /// Parses a time zone offset (including obsolete offsets like EDT).
713    ///
714    /// This assumes the offset must begin at the beginning of `input`. That
715    /// is, any leading whitespace should already have been trimmed.
716    #[cfg_attr(feature = "perf-inline", inline(always))]
717    fn parse_offset<'i>(
718        &self,
719        input: &'i [u8],
720    ) -> Result<Parsed<'i, Offset>, Error> {
721        let sign = input.get(0).copied().ok_or(E::EndOfInputOffset)?;
722        let sign = if sign == b'+' {
723            Sign::Positive
724        } else if sign == b'-' {
725            Sign::Negative
726        } else {
727            return self.parse_offset_obsolete(input);
728        };
729        let input = &input[1..];
730        let (hhmm, input) = parse::split(input, 4).ok_or(E::TooShortOffset)?;
731
732        let hh = parse::bi64::<b::OffsetHours>(&hhmm[0..2])
733            .context(E::ParseOffsetHour)?;
734        let mm = parse::bi64::<b::OffsetMinutes>(&hhmm[2..4])
735            .context(E::ParseOffsetMinute)?;
736
737        let seconds = sign * (i32::from(hh) * 3_600 + i32::from(mm) * 60);
738        // OK because we check the bounds of both hours and minutes.
739        let offset = Offset::from_seconds(seconds).unwrap();
740        Ok(Parsed { value: offset, input })
741    }
742
743    /// Parses an obsolete time zone offset.
744    #[inline(never)]
745    fn parse_offset_obsolete<'i>(
746        &self,
747        input: &'i [u8],
748    ) -> Result<Parsed<'i, Offset>, Error> {
749        let mut letters = [0; 5];
750        let mut len = 0;
751        while len <= 4
752            && !input[len..].is_empty()
753            && !is_whitespace(input[len])
754        {
755            letters[len] = input[len].to_ascii_lowercase();
756            len += 1;
757        }
758        if len == 0 {
759            return Err(Error::from(E::WhitespaceAfterTimeForObsoleteOffset));
760        }
761        let offset = match &letters[..len] {
762            b"ut" | b"gmt" | b"z" => Offset::UTC,
763            b"est" => Offset::constant(-5),
764            b"edt" => Offset::constant(-4),
765            b"cst" => Offset::constant(-6),
766            b"cdt" => Offset::constant(-5),
767            b"mst" => Offset::constant(-7),
768            b"mdt" => Offset::constant(-6),
769            b"pst" => Offset::constant(-8),
770            b"pdt" => Offset::constant(-7),
771            name => {
772                if name.len() == 1
773                    && #[allow(non_exhaustive_omitted_patterns)] match name[0] {
    b'a'..=b'i' | b'k'..=b'z' => true,
    _ => false,
}matches!(name[0], b'a'..=b'i' | b'k'..=b'z')
774                {
775                    // Section 4.3 indicates these as military time:
776                    //
777                    // > The 1 character military time zones were defined in
778                    // > a non-standard way in [RFC822] and are therefore
779                    // > unpredictable in their meaning. The original
780                    // > definitions of the military zones "A" through "I" are
781                    // > equivalent to "+0100" through "+0900" respectively;
782                    // > "K", "L", and "M" are equivalent to "+1000", "+1100",
783                    // > and "+1200" respectively; "N" through "Y" are
784                    // > equivalent to "-0100" through "-1200" respectively;
785                    // > and "Z" is equivalent to "+0000". However, because of
786                    // > the error in [RFC822], they SHOULD all be considered
787                    // > equivalent to "-0000" unless there is out-of-band
788                    // > information confirming their meaning.
789                    //
790                    // So just treat them as UTC.
791                    Offset::UTC
792                } else if name.len() >= 3
793                    && name.iter().all(|&b| #[allow(non_exhaustive_omitted_patterns)] match b {
    b'a'..=b'z' => true,
    _ => false,
}matches!(b, b'a'..=b'z'))
794                {
795                    // Section 4.3 also says that anything that _looks_ like a
796                    // zone name should just be -0000 too:
797                    //
798                    // > Other multi-character (usually between 3 and 5)
799                    // > alphabetic time zones have been used in Internet
800                    // > messages. Any such time zone whose meaning is not
801                    // > known SHOULD be considered equivalent to "-0000"
802                    // > unless there is out-of-band information confirming
803                    // > their meaning.
804                    Offset::UTC
805                } else {
806                    // But anything else we throw our hands up I guess.
807                    return Err(Error::from(E::InvalidObsoleteOffset));
808                }
809            }
810        };
811        Ok(Parsed { value: offset, input: &input[len..] })
812    }
813
814    /// Parses a time separator. This returns an error if one couldn't be
815    /// found.
816    #[cfg_attr(feature = "perf-inline", inline(always))]
817    fn parse_time_separator<'i>(
818        &self,
819        input: &'i [u8],
820    ) -> Result<Parsed<'i, ()>, Error> {
821        if input.is_empty() {
822            return Err(Error::from(E::EndOfInputTimeSeparator));
823        }
824        if input[0] != b':' {
825            return Err(Error::from(E::UnexpectedByteTimeSeparator {
826                byte: input[0],
827            }));
828        }
829        Ok(Parsed { value: (), input: &input[1..] })
830    }
831
832    /// Parses at least one whitespace character. If no whitespace was found,
833    /// then this returns an error.
834    #[cfg_attr(feature = "perf-inline", inline(always))]
835    fn parse_whitespace<'i>(
836        &self,
837        input: &'i [u8],
838    ) -> Result<Parsed<'i, ()>, Error> {
839        let Parsed { input, value: had_whitespace } =
840            self.skip_whitespace(input);
841        if !had_whitespace {
842            return Err(Error::from(E::WhitespaceAfterTime));
843        }
844        Ok(Parsed { value: (), input })
845    }
846
847    /// Skips over any ASCII whitespace at the beginning of `input`.
848    ///
849    /// This returns the input unchanged if it does not begin with whitespace.
850    /// The resulting value is `true` if any whitespace was consumed,
851    /// and `false` if none was.
852    #[cfg_attr(feature = "perf-inline", inline(always))]
853    fn skip_whitespace<'i>(&self, mut input: &'i [u8]) -> Parsed<'i, bool> {
854        let mut found_whitespace = false;
855        while input.first().map_or(false, |&b| is_whitespace(b)) {
856            input = &input[1..];
857            found_whitespace = true;
858        }
859        Parsed { value: found_whitespace, input }
860    }
861
862    /// This attempts to parse and skip any trailing "comment" in an RFC 2822
863    /// datetime.
864    ///
865    /// This is a bit more relaxed than what RFC 2822 specifies. We basically
866    /// just try to balance parenthesis and skip over escapes.
867    ///
868    /// This assumes that if a comment exists, its opening parenthesis is at
869    /// the beginning of `input`. That is, any leading whitespace has been
870    /// stripped.
871    #[inline(never)]
872    fn skip_comment<'i>(
873        &self,
874        mut input: &'i [u8],
875    ) -> Result<Parsed<'i, ()>, Error> {
876        if !input.starts_with(b"(") {
877            return Ok(Parsed { value: (), input });
878        }
879        input = &input[1..];
880        let mut depth: u8 = 1;
881        let mut escape = false;
882        for byte in input.iter().copied() {
883            input = &input[1..];
884            if escape {
885                escape = false;
886            } else if byte == b'\\' {
887                escape = true;
888            } else if byte == b')' {
889                // I believe this error case is actually impossible, since as
890                // soon as we hit 0, we break out. If there is more "comment,"
891                // then it will flag an error as unparsed input.
892                depth = depth
893                    .checked_sub(1)
894                    .ok_or(E::CommentClosingParenWithoutOpen)?;
895                if depth == 0 {
896                    break;
897                }
898            } else if byte == b'(' {
899                depth = depth
900                    .checked_add(1)
901                    .ok_or(E::CommentTooManyNestedParens)?;
902            }
903        }
904        if depth > 0 {
905            return Err(Error::from(E::CommentOpeningParenWithoutClose));
906        }
907        let Parsed { input, .. } = self.skip_whitespace(input);
908        Ok(Parsed { value: (), input })
909    }
910}
911
912/// A printer for [RFC 2822] datetimes.
913///
914/// This printer converts an in memory representation of a precise instant in
915/// time to an RFC 2822 formatted string. That is, [`ZonedDateTime`] or
916/// [`Timestamp`], since all other datetime types in Jiff are inexact.
917///
918/// [RFC 2822]: https://datatracker.ietf.org/doc/html/rfc2822
919///
920/// # Warning
921///
922/// The RFC 2822 format only supports writing a precise instant in time
923/// expressed via a time zone offset. It does *not* support serializing
924/// the time zone itself. This means that if you format a zoned datetime
925/// in a time zone like `America/New_York` and then deserialize it, the
926/// zoned datetime you get back will be a "fixed offset" zoned datetime.
927/// This in turn means it will not perform daylight saving time safe
928/// arithmetic.
929///
930/// Basically, you should use the RFC 2822 format if it's required (for
931/// example, when dealing with email). But you should not choose it as a
932/// general interchange format for new applications.
933///
934/// # Example
935///
936/// This example shows how to convert a zoned datetime to the RFC 2822 format:
937///
938/// ```
939/// use jiff::{civil::date, fmt::rfc2822::DateTimePrinter};
940///
941/// const PRINTER: DateTimePrinter = DateTimePrinter::new();
942///
943/// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("Australia/Hobart")?;
944///
945/// let mut buf = String::new();
946/// PRINTER.print_zoned_datetime(&zdt, &mut buf)?;
947/// assert_eq!(buf, "Sat, 15 Jun 2024 07:00:00 +1000");
948///
949/// # Ok::<(), Box<dyn std::error::Error>>(())
950/// ```
951///
952/// # Example: using adapters with `std::io::Write` and `std::fmt::Write`
953///
954/// By using the [`StdIoWrite`](super::StdIoWrite) and
955/// [`StdFmtWrite`](super::StdFmtWrite) adapters, one can print datetimes
956/// directly to implementations of `std::io::Write` and `std::fmt::Write`,
957/// respectively. The example below demonstrates writing to anything
958/// that implements `std::io::Write`. Similar code can be written for
959/// `std::fmt::Write`.
960///
961/// ```no_run
962/// use std::{fs::File, io::{BufWriter, Write}, path::Path};
963///
964/// use jiff::{civil::date, fmt::{StdIoWrite, rfc2822::DateTimePrinter}};
965///
966/// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("Asia/Kolkata")?;
967///
968/// let path = Path::new("/tmp/output");
969/// let mut file = BufWriter::new(File::create(path)?);
970/// DateTimePrinter::new()
971///     .print_zoned_datetime(&zdt, StdIoWrite(&mut file))
972///     .unwrap();
973/// file.flush()?;
974/// assert_eq!(
975///     std::fs::read_to_string(path)?,
976///     "Sat, 15 Jun 2024 07:00:00 +0530",
977/// );
978///
979/// # Ok::<(), Box<dyn std::error::Error>>(())
980/// ```
981#[derive(#[automatically_derived]impl ::core::fmt::Debug for DateTimePrinter {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DateTimePrinter _private", &&self._private)
    }
}Debug)]
982pub struct DateTimePrinter {
983    // The RFC 2822 printer has no configuration at present.
984    _private: (),
985}
986
987impl DateTimePrinter {
988    /// Create a new RFC 2822 datetime printer with the default configuration.
989    #[inline]
990    pub const fn new() -> DateTimePrinter {
991        DateTimePrinter { _private: () }
992    }
993
994    /// Format a `ZonedDateTime` datetime into a string.
995    ///
996    /// This never emits `-0000` as the offset in the RFC 2822 format. If you
997    /// desire a `-0000` offset, use [`DateTimePrinter::print_timestamp`] via
998    /// [`ZonedDateTime::timestamp`].
999    ///
1000    /// Moreover, since RFC 2822 does not support fractional seconds, this
1001    /// routine prints the zoned datetime as if truncating any fractional
1002    /// seconds.
1003    ///
1004    /// This is a convenience routine for
1005    /// [`DateTimePrinter::print_zoned_datetime`] with a `String`.
1006    ///
1007    /// # Warning
1008    ///
1009    /// The RFC 2822 format only supports writing a precise instant in time
1010    /// expressed via a time zone offset. It does *not* support serializing
1011    /// the time zone itself. This means that if you format a zoned datetime
1012    /// in a time zone like `America/New_York` and then deserialize it, the
1013    /// zoned datetime you get back will be a "fixed offset" zoned datetime.
1014    /// This in turn means it will not perform daylight saving time safe
1015    /// arithmetic.
1016    ///
1017    /// Basically, you should use the RFC 2822 format if it's required (for
1018    /// example, when dealing with email). But you should not choose it as a
1019    /// general interchange format for new applications.
1020    ///
1021    /// # Errors
1022    ///
1023    /// This can return an error if the year corresponding to this timestamp
1024    /// cannot be represented in the RFC 2822 format. For example, a negative
1025    /// year.
1026    ///
1027    /// # Example
1028    ///
1029    /// ```
1030    /// use jiff::{civil::date, fmt::rfc2822::DateTimePrinter};
1031    ///
1032    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1033    ///
1034    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
1035    /// assert_eq!(
1036    ///     PRINTER.zoned_datetime_to_string(&zdt)?,
1037    ///     "Sat, 15 Jun 2024 07:00:00 -0400",
1038    /// );
1039    ///
1040    /// # Ok::<(), Box<dyn std::error::Error>>(())
1041    /// ```
1042    #[cfg(feature = "alloc")]
1043    pub fn zoned_datetime_to_string(
1044        &self,
1045        zdt: &ZonedDateTime,
1046    ) -> Result<alloc::string::String, Error> {
1047        // Writing directly into the unused capacity of a `String` saves about
1048        // 40% on a micro-benchmark compared to just passing a `&mut String`
1049        // to `print_zoned_datetime`.
1050        let mut buf =
1051            alloc::string::String::with_capacity(PRINTER_MAX_BYTES_RFC2822);
1052        self.print_zoned_datetime(zdt, &mut buf)?;
1053        Ok(buf)
1054    }
1055
1056    /// Format a `Timestamp` datetime into a string.
1057    ///
1058    /// This always emits `-0000` as the offset in the RFC 2822 format. If you
1059    /// desire a `+0000` offset, use [`DateTimePrinter::print_zoned_datetime`]
1060    /// with a zoned datetime with [`TimeZone::UTC`].
1061    ///
1062    /// Moreover, since RFC 2822 does not support fractional seconds, this
1063    /// routine prints the timestamp as if truncating any fractional seconds.
1064    ///
1065    /// This is a convenience routine for [`DateTimePrinter::print_timestamp`]
1066    /// with a `String`.
1067    ///
1068    /// # Errors
1069    ///
1070    /// This returns an error if the year corresponding to this
1071    /// timestamp cannot be represented in the RFC 2822 format. For example, a
1072    /// negative year.
1073    ///
1074    /// # Example
1075    ///
1076    /// ```
1077    /// use jiff::{fmt::rfc2822::DateTimePrinter, Timestamp};
1078    ///
1079    /// let timestamp = Timestamp::from_second(1)
1080    ///     .expect("one second after Unix epoch is always valid");
1081    /// assert_eq!(
1082    ///     DateTimePrinter::new().timestamp_to_string(&timestamp)?,
1083    ///     "Thu, 1 Jan 1970 00:00:01 -0000",
1084    /// );
1085    ///
1086    /// # Ok::<(), Box<dyn std::error::Error>>(())
1087    /// ```
1088    #[cfg(feature = "alloc")]
1089    pub fn timestamp_to_string(
1090        &self,
1091        timestamp: &Timestamp,
1092    ) -> Result<alloc::string::String, Error> {
1093        let mut buf =
1094            alloc::string::String::with_capacity(PRINTER_MAX_BYTES_RFC2822);
1095        self.print_timestamp(timestamp, &mut buf)?;
1096        Ok(buf)
1097    }
1098
1099    /// Format a `Timestamp` datetime into a string in a way that is explicitly
1100    /// compatible with [RFC 9110]. This is typically useful in contexts where
1101    /// strict compatibility with HTTP is desired.
1102    ///
1103    /// This always emits `GMT` as the offset and always uses two digits for
1104    /// the day. This results in a fixed length format that always uses 29
1105    /// characters.
1106    ///
1107    /// Since neither RFC 2822 nor RFC 9110 supports fractional seconds, this
1108    /// routine prints the timestamp as if truncating any fractional seconds.
1109    ///
1110    /// This is a convenience routine for
1111    /// [`DateTimePrinter::print_timestamp_rfc9110`] with a `String`.
1112    ///
1113    /// # Errors
1114    ///
1115    /// This returns an error if the year corresponding to this timestamp
1116    /// cannot be represented in the RFC 2822 or RFC 9110 format. For example,
1117    /// a negative year.
1118    ///
1119    /// # Example
1120    ///
1121    /// ```
1122    /// use jiff::{fmt::rfc2822::DateTimePrinter, Timestamp};
1123    ///
1124    /// let timestamp = Timestamp::from_second(1)
1125    ///     .expect("one second after Unix epoch is always valid");
1126    /// assert_eq!(
1127    ///     DateTimePrinter::new().timestamp_to_rfc9110_string(&timestamp)?,
1128    ///     "Thu, 01 Jan 1970 00:00:01 GMT",
1129    /// );
1130    ///
1131    /// # Ok::<(), Box<dyn std::error::Error>>(())
1132    /// ```
1133    ///
1134    /// [RFC 9110]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.7-15
1135    #[cfg(feature = "alloc")]
1136    pub fn timestamp_to_rfc9110_string(
1137        &self,
1138        timestamp: &Timestamp,
1139    ) -> Result<alloc::string::String, Error> {
1140        let mut buf =
1141            alloc::string::String::with_capacity(PRINTER_MAX_BYTES_RFC9110);
1142        self.print_timestamp_rfc9110(timestamp, &mut buf)?;
1143        Ok(buf)
1144    }
1145
1146    /// Print a `ZonedDateTime` datetime to the given writer.
1147    ///
1148    /// This never emits `-0000` as the offset in the RFC 2822 format. If you
1149    /// desire a `-0000` offset, use [`DateTimePrinter::print_timestamp`] via
1150    /// [`ZonedDateTime::timestamp`].
1151    ///
1152    /// Moreover, since RFC 2822 does not support fractional seconds, this
1153    /// routine prints the zoned datetime as if truncating any fractional
1154    /// seconds.
1155    ///
1156    /// # Warning
1157    ///
1158    /// The RFC 2822 format only supports writing a precise instant in time
1159    /// expressed via a time zone offset. It does *not* support serializing
1160    /// the time zone itself. This means that if you format a zoned datetime
1161    /// in a time zone like `America/New_York` and then deserialize it, the
1162    /// zoned datetime you get back will be a "fixed offset" zoned datetime.
1163    /// This in turn means it will not perform daylight saving time safe
1164    /// arithmetic.
1165    ///
1166    /// Basically, you should use the RFC 2822 format if it's required (for
1167    /// example, when dealing with email). But you should not choose it as a
1168    /// general interchange format for new applications.
1169    ///
1170    /// # Errors
1171    ///
1172    /// This returns an error when writing to the given [`Write`]
1173    /// implementation would fail. Some such implementations, like for `String`
1174    /// and `Vec<u8>`, never fail (unless memory allocation fails).
1175    ///
1176    /// This can also return an error if the year corresponding to this
1177    /// timestamp cannot be represented in the RFC 2822 format. For example, a
1178    /// negative year.
1179    ///
1180    /// # Example
1181    ///
1182    /// ```
1183    /// use jiff::{civil::date, fmt::rfc2822::DateTimePrinter};
1184    ///
1185    /// const PRINTER: DateTimePrinter = DateTimePrinter::new();
1186    ///
1187    /// let zdt = date(2024, 6, 15).at(7, 0, 0, 0).in_tz("America/New_York")?;
1188    ///
1189    /// let mut buf = String::new();
1190    /// PRINTER.print_zoned_datetime(&zdt, &mut buf)?;
1191    /// assert_eq!(buf, "Sat, 15 Jun 2024 07:00:00 -0400");
1192    ///
1193    /// # Ok::<(), Box<dyn std::error::Error>>(())
1194    /// ```
1195    pub fn print_zoned_datetime<W: Write>(
1196        &self,
1197        zdt: &ZonedDateTime,
1198        mut wtr: W,
1199    ) -> Result<(), Error> {
1200        BorrowedBuffer::with_writer::<PRINTER_MAX_BYTES_RFC2822>(
1201            &mut wtr,
1202            PRINTER_MAX_BYTES_RFC2822,
1203            |bbuf| {
1204                self.print_civil_with_offset(
1205                    zdt.datetime(),
1206                    Some(zdt.offset()),
1207                    bbuf,
1208                )
1209            },
1210        )
1211    }
1212
1213    /// Print a `Timestamp` datetime to the given writer.
1214    ///
1215    /// This always emits `-0000` as the offset in the RFC 2822 format. If you
1216    /// desire a `+0000` offset, use [`DateTimePrinter::print_zoned_datetime`]
1217    /// with a zoned datetime with [`TimeZone::UTC`].
1218    ///
1219    /// Moreover, since RFC 2822 does not support fractional seconds, this
1220    /// routine prints the timestamp as if truncating any fractional seconds.
1221    ///
1222    /// # Errors
1223    ///
1224    /// This returns an error when writing to the given [`Write`]
1225    /// implementation would fail. Some such implementations, like for `String`
1226    /// and `Vec<u8>`, never fail (unless memory allocation fails).
1227    ///
1228    /// This can also return an error if the year corresponding to this
1229    /// timestamp cannot be represented in the RFC 2822 format. For example, a
1230    /// negative year.
1231    ///
1232    /// # Example
1233    ///
1234    /// ```
1235    /// use jiff::{fmt::rfc2822::DateTimePrinter, Timestamp};
1236    ///
1237    /// let timestamp = Timestamp::from_second(1)
1238    ///     .expect("one second after Unix epoch is always valid");
1239    ///
1240    /// let mut buf = String::new();
1241    /// DateTimePrinter::new().print_timestamp(&timestamp, &mut buf)?;
1242    /// assert_eq!(buf, "Thu, 1 Jan 1970 00:00:01 -0000");
1243    ///
1244    /// # Ok::<(), Box<dyn std::error::Error>>(())
1245    /// ```
1246    pub fn print_timestamp<W: Write>(
1247        &self,
1248        timestamp: &Timestamp,
1249        mut wtr: W,
1250    ) -> Result<(), Error> {
1251        let dt = TimeZone::UTC.to_datetime(*timestamp);
1252        BorrowedBuffer::with_writer::<PRINTER_MAX_BYTES_RFC2822>(
1253            &mut wtr,
1254            PRINTER_MAX_BYTES_RFC2822,
1255            |bbuf| self.print_civil_with_offset(dt, None, bbuf),
1256        )
1257    }
1258
1259    /// Print a `Timestamp` datetime to the given writer in a way that is
1260    /// explicitly compatible with [RFC 9110]. This is typically useful in
1261    /// contexts where strict compatibility with HTTP is desired.
1262    ///
1263    /// This always emits `GMT` as the offset and always uses two digits for
1264    /// the day. This results in a fixed length format that always uses 29
1265    /// characters.
1266    ///
1267    /// Since neither RFC 2822 nor RFC 9110 supports fractional seconds, this
1268    /// routine prints the timestamp as if truncating any fractional seconds.
1269    ///
1270    /// # Errors
1271    ///
1272    /// This returns an error when writing to the given [`Write`]
1273    /// implementation would fail. Some such implementations, like for `String`
1274    /// and `Vec<u8>`, never fail (unless memory allocation fails).
1275    ///
1276    /// This can also return an error if the year corresponding to this
1277    /// timestamp cannot be represented in the RFC 2822 or RFC 9110 format. For
1278    /// example, a negative year.
1279    ///
1280    /// # Example
1281    ///
1282    /// ```
1283    /// use jiff::{fmt::rfc2822::DateTimePrinter, Timestamp};
1284    ///
1285    /// let timestamp = Timestamp::from_second(1)
1286    ///     .expect("one second after Unix epoch is always valid");
1287    ///
1288    /// let mut buf = String::new();
1289    /// DateTimePrinter::new().print_timestamp_rfc9110(&timestamp, &mut buf)?;
1290    /// assert_eq!(buf, "Thu, 01 Jan 1970 00:00:01 GMT");
1291    ///
1292    /// # Ok::<(), Box<dyn std::error::Error>>(())
1293    /// ```
1294    ///
1295    /// [RFC 9110]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.7-15
1296    pub fn print_timestamp_rfc9110<W: Write>(
1297        &self,
1298        timestamp: &Timestamp,
1299        mut wtr: W,
1300    ) -> Result<(), Error> {
1301        let dt = TimeZone::UTC.to_datetime(*timestamp);
1302        BorrowedBuffer::with_writer::<PRINTER_MAX_BYTES_RFC9110>(
1303            &mut wtr,
1304            PRINTER_MAX_BYTES_RFC9110,
1305            |bbuf| self.print_civil_always_utc(dt, bbuf),
1306        )
1307    }
1308
1309    #[inline(never)]
1310    fn print_civil_with_offset(
1311        &self,
1312        dt: DateTime,
1313        offset: Option<Offset>,
1314        buf: &mut BorrowedBuffer<'_>,
1315    ) -> Result<(), Error> {
1316        if dt.year() < 0 {
1317            // RFC 2822 actually says the year must be at least 1900, but
1318            // other implementations (like Chrono) allow any positive 4-digit
1319            // year.
1320            return Err(Error::from(E::NegativeYear));
1321        }
1322
1323        buf.write_str(weekday_abbrev(dt.weekday()));
1324        buf.write_str(", ");
1325        buf.write_int(dt.day().unsigned_abs());
1326        buf.write_ascii_char(b' ');
1327        buf.write_str(month_name(dt.month()));
1328        buf.write_ascii_char(b' ');
1329        buf.write_int_pad4(dt.year().unsigned_abs());
1330        buf.write_ascii_char(b' ');
1331        buf.write_int_pad2(dt.hour().unsigned_abs());
1332        buf.write_ascii_char(b':');
1333        buf.write_int_pad2(dt.minute().unsigned_abs());
1334        buf.write_ascii_char(b':');
1335        buf.write_int_pad2(dt.second().unsigned_abs());
1336        buf.write_ascii_char(b' ');
1337
1338        let Some(offset) = offset else {
1339            buf.write_str("-0000");
1340            return Ok(());
1341        };
1342        buf.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' });
1343        let (offset_hours, offset_minutes) = offset.round_to_nearest_minute();
1344        buf.write_int_pad2(offset_hours);
1345        buf.write_int_pad2(offset_minutes);
1346
1347        Ok(())
1348    }
1349
1350    #[inline(never)]
1351    fn print_civil_always_utc(
1352        &self,
1353        dt: DateTime,
1354        buf: &mut BorrowedBuffer<'_>,
1355    ) -> Result<(), Error> {
1356        if dt.year() < 0 {
1357            // RFC 2822 actually says the year must be at least 1900, but
1358            // other implementations (like Chrono) allow any positive 4-digit
1359            // year.
1360            return Err(Error::from(E::NegativeYear));
1361        }
1362
1363        buf.write_str(weekday_abbrev(dt.weekday()));
1364        buf.write_str(", ");
1365        buf.write_int_pad2(dt.day().unsigned_abs());
1366        buf.write_str(" ");
1367        buf.write_str(month_name(dt.month()));
1368        buf.write_str(" ");
1369        buf.write_int_pad4(dt.year().unsigned_abs());
1370        buf.write_str(" ");
1371        buf.write_int_pad2(dt.hour().unsigned_abs());
1372        buf.write_str(":");
1373        buf.write_int_pad2(dt.minute().unsigned_abs());
1374        buf.write_str(":");
1375        buf.write_int_pad2(dt.second().unsigned_abs());
1376        buf.write_str(" ");
1377        buf.write_str("GMT");
1378        Ok(())
1379    }
1380}
1381
1382fn weekday_abbrev(wd: Weekday) -> &'static str {
1383    match wd {
1384        Weekday::Sunday => "Sun",
1385        Weekday::Monday => "Mon",
1386        Weekday::Tuesday => "Tue",
1387        Weekday::Wednesday => "Wed",
1388        Weekday::Thursday => "Thu",
1389        Weekday::Friday => "Fri",
1390        Weekday::Saturday => "Sat",
1391    }
1392}
1393
1394fn month_name(month: i8) -> &'static str {
1395    match month {
1396        1 => "Jan",
1397        2 => "Feb",
1398        3 => "Mar",
1399        4 => "Apr",
1400        5 => "May",
1401        6 => "Jun",
1402        7 => "Jul",
1403        8 => "Aug",
1404        9 => "Sep",
1405        10 => "Oct",
1406        11 => "Nov",
1407        12 => "Dec",
1408        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("invalid month value {0}", month)));
}unreachable!("invalid month value {month}"),
1409    }
1410}
1411
1412/// Returns true if the given byte is "whitespace" as defined by RFC 2822.
1413///
1414/// From S2.2.2:
1415///
1416/// > Many of these tokens are allowed (according to their syntax) to be
1417/// > introduced or end with comments (as described in section 3.2.3) as well
1418/// > as the space (SP, ASCII value 32) and horizontal tab (HTAB, ASCII value
1419/// > 9) characters (together known as the white space characters, WSP), and
1420/// > those WSP characters are subject to header "folding" and "unfolding" as
1421/// > described in section 2.2.3.
1422///
1423/// In other words, ASCII space or tab.
1424///
1425/// With all that said, it seems odd to limit this to just spaces or tabs, so
1426/// we relax this and let it absorb any kind of ASCII whitespace. This also
1427/// handles, I believe, most cases of "folding" whitespace. (By treating `\r`
1428/// and `\n` as whitespace.)
1429fn is_whitespace(byte: u8) -> bool {
1430    byte.is_ascii_whitespace()
1431}
1432
1433#[cfg(feature = "alloc")]
1434#[cfg(test)]
1435mod tests {
1436    use alloc::string::{String, ToString};
1437
1438    use crate::civil::date;
1439
1440    use super::*;
1441
1442    #[test]
1443    fn ok_parse_basic() {
1444        let p =
1445            |input| DateTimeParser::new().parse_zoned_datetime(input).unwrap();
1446
1447        insta::assert_debug_snapshot!(
1448            p("Wed, 10 Jan 2024 05:34:45 -0500"),
1449            @"2024-01-10T05:34:45-05:00[-05:00]",
1450        );
1451        insta::assert_debug_snapshot!(
1452            p("Tue, 9 Jan 2024 05:34:45 -0500"),
1453            @"2024-01-09T05:34:45-05:00[-05:00]",
1454        );
1455        insta::assert_debug_snapshot!(
1456            p("Tue, 09 Jan 2024 05:34:45 -0500"),
1457            @"2024-01-09T05:34:45-05:00[-05:00]",
1458        );
1459        insta::assert_debug_snapshot!(
1460            p("10 Jan 2024 05:34:45 -0500"),
1461            @"2024-01-10T05:34:45-05:00[-05:00]",
1462        );
1463        insta::assert_debug_snapshot!(
1464            p("10 Jan 2024 05:34 -0500"),
1465            @"2024-01-10T05:34:00-05:00[-05:00]",
1466        );
1467        insta::assert_debug_snapshot!(
1468            p("10 Jan 2024 05:34:45 +0500"),
1469            @"2024-01-10T05:34:45+05:00[+05:00]",
1470        );
1471        insta::assert_debug_snapshot!(
1472            p("Thu, 29 Feb 2024 05:34 -0500"),
1473            @"2024-02-29T05:34:00-05:00[-05:00]",
1474        );
1475
1476        // leap second constraining
1477        insta::assert_debug_snapshot!(
1478            p("10 Jan 2024 05:34:60 -0500"),
1479            @"2024-01-10T05:34:59-05:00[-05:00]",
1480        );
1481    }
1482
1483    #[test]
1484    fn ok_parse_obsolete_zone() {
1485        let p =
1486            |input| DateTimeParser::new().parse_zoned_datetime(input).unwrap();
1487
1488        insta::assert_debug_snapshot!(
1489            p("Wed, 10 Jan 2024 05:34:45 EST"),
1490            @"2024-01-10T05:34:45-05:00[-05:00]",
1491        );
1492        insta::assert_debug_snapshot!(
1493            p("Wed, 10 Jan 2024 05:34:45 EDT"),
1494            @"2024-01-10T05:34:45-04:00[-04:00]",
1495        );
1496        insta::assert_debug_snapshot!(
1497            p("Wed, 10 Jan 2024 05:34:45 CST"),
1498            @"2024-01-10T05:34:45-06:00[-06:00]",
1499        );
1500        insta::assert_debug_snapshot!(
1501            p("Wed, 10 Jan 2024 05:34:45 CDT"),
1502            @"2024-01-10T05:34:45-05:00[-05:00]",
1503        );
1504        insta::assert_debug_snapshot!(
1505            p("Wed, 10 Jan 2024 05:34:45 mst"),
1506            @"2024-01-10T05:34:45-07:00[-07:00]",
1507        );
1508        insta::assert_debug_snapshot!(
1509            p("Wed, 10 Jan 2024 05:34:45 mdt"),
1510            @"2024-01-10T05:34:45-06:00[-06:00]",
1511        );
1512        insta::assert_debug_snapshot!(
1513            p("Wed, 10 Jan 2024 05:34:45 pst"),
1514            @"2024-01-10T05:34:45-08:00[-08:00]",
1515        );
1516        insta::assert_debug_snapshot!(
1517            p("Wed, 10 Jan 2024 05:34:45 pdt"),
1518            @"2024-01-10T05:34:45-07:00[-07:00]",
1519        );
1520
1521        // Various things that mean UTC.
1522        insta::assert_debug_snapshot!(
1523            p("Wed, 10 Jan 2024 05:34:45 UT"),
1524            @"2024-01-10T05:34:45+00:00[UTC]",
1525        );
1526        insta::assert_debug_snapshot!(
1527            p("Wed, 10 Jan 2024 05:34:45 Z"),
1528            @"2024-01-10T05:34:45+00:00[UTC]",
1529        );
1530        insta::assert_debug_snapshot!(
1531            p("Wed, 10 Jan 2024 05:34:45 gmt"),
1532            @"2024-01-10T05:34:45+00:00[UTC]",
1533        );
1534
1535        // Even things that are unrecognized just get treated as having
1536        // an offset of 0.
1537        insta::assert_debug_snapshot!(
1538            p("Wed, 10 Jan 2024 05:34:45 XXX"),
1539            @"2024-01-10T05:34:45+00:00[UTC]",
1540        );
1541        insta::assert_debug_snapshot!(
1542            p("Wed, 10 Jan 2024 05:34:45 ABCDE"),
1543            @"2024-01-10T05:34:45+00:00[UTC]",
1544        );
1545        insta::assert_debug_snapshot!(
1546            p("Wed, 10 Jan 2024 05:34:45 FUCK"),
1547            @"2024-01-10T05:34:45+00:00[UTC]",
1548        );
1549    }
1550
1551    // whyyyyyyyyyyyyy
1552    #[test]
1553    fn ok_parse_comment() {
1554        let p =
1555            |input| DateTimeParser::new().parse_zoned_datetime(input).unwrap();
1556
1557        insta::assert_debug_snapshot!(
1558            p("Wed, 10 Jan 2024 05:34:45 -0500 (wat)"),
1559            @"2024-01-10T05:34:45-05:00[-05:00]",
1560        );
1561        insta::assert_debug_snapshot!(
1562            p("Wed, 10 Jan 2024 05:34:45 -0500 (w(a)t)"),
1563            @"2024-01-10T05:34:45-05:00[-05:00]",
1564        );
1565        insta::assert_debug_snapshot!(
1566            p(r"Wed, 10 Jan 2024 05:34:45 -0500 (w\(a\)t)"),
1567            @"2024-01-10T05:34:45-05:00[-05:00]",
1568        );
1569    }
1570
1571    #[test]
1572    fn ok_parse_whitespace() {
1573        let p =
1574            |input| DateTimeParser::new().parse_zoned_datetime(input).unwrap();
1575
1576        insta::assert_debug_snapshot!(
1577            p("Wed, 10 \t   Jan \n\r\n\n 2024       05:34:45    -0500"),
1578            @"2024-01-10T05:34:45-05:00[-05:00]",
1579        );
1580        insta::assert_debug_snapshot!(
1581            p("Wed, 10 Jan 2024 05:34:45 -0500 "),
1582            @"2024-01-10T05:34:45-05:00[-05:00]",
1583        );
1584        // Whitespace around the comma is optional
1585        insta::assert_debug_snapshot!(
1586            p("Wed,10 Jan 2024 05:34:45 -0500"),
1587            @"2024-01-10T05:34:45-05:00[-05:00]",
1588        );
1589        insta::assert_debug_snapshot!(
1590            p("Wed    ,     10 Jan 2024 05:34:45 -0500"),
1591            @"2024-01-10T05:34:45-05:00[-05:00]",
1592        );
1593        insta::assert_debug_snapshot!(
1594            p("Wed    ,10 Jan 2024 05:34:45 -0500"),
1595            @"2024-01-10T05:34:45-05:00[-05:00]",
1596        );
1597        // Whitespace is allowed around the time components
1598        insta::assert_debug_snapshot!(
1599            p("Wed, 10 Jan 2024 05   :34:  45 -0500"),
1600            @"2024-01-10T05:34:45-05:00[-05:00]",
1601        );
1602        insta::assert_debug_snapshot!(
1603            p("Wed, 10 Jan 2024 05:  34 :45 -0500"),
1604            @"2024-01-10T05:34:45-05:00[-05:00]",
1605        );
1606        insta::assert_debug_snapshot!(
1607            p("Wed, 10 Jan 2024 05 :  34 :   45 -0500"),
1608            @"2024-01-10T05:34:45-05:00[-05:00]",
1609        );
1610    }
1611
1612    #[test]
1613    fn err_parse_invalid() {
1614        let p = |input| {
1615            DateTimeParser::new()
1616                .parse_zoned_datetime(input)
1617                .unwrap_err()
1618                .to_string()
1619        };
1620
1621        insta::assert_snapshot!(
1622            p("Thu, 10 Jan 2024 05:34:45 -0500"),
1623            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: found parsed weekday of `Thursday`, but parsed datetime has weekday `Wednesday`",
1624        );
1625        insta::assert_snapshot!(
1626            p("Wed, 29 Feb 2023 05:34:45 -0500"),
1627            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: invalid date: parameter 'day' for `2023-02` is invalid, must be in range `1..=28`",
1628        );
1629        insta::assert_snapshot!(
1630            p("Mon, 31 Jun 2024 05:34:45 -0500"),
1631            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: invalid date: parameter 'day' for `2024-06` is invalid, must be in range `1..=30`",
1632        );
1633        insta::assert_snapshot!(
1634            p("Tue, 32 Jun 2024 05:34:45 -0500"),
1635            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: failed to parse day: parameter 'day' is not in the required range of 1..=31",
1636        );
1637        insta::assert_snapshot!(
1638            p("Sun, 30 Jun 2024 24:00:00 -0500"),
1639            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: failed to parse hour (expects a two digit integer): parameter 'hour' is not in the required range of 0..=23",
1640        );
1641        // No whitespace after time
1642        insta::assert_snapshot!(
1643            p("Wed, 10 Jan 2024 05:34MST"),
1644            @r###"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected whitespace after parsing time: expected at least one whitespace character (space or tab), but found none"###,
1645        );
1646    }
1647
1648    #[test]
1649    fn err_parse_incomplete() {
1650        let p = |input| {
1651            DateTimeParser::new()
1652                .parse_zoned_datetime(input)
1653                .unwrap_err()
1654                .to_string()
1655        };
1656
1657        insta::assert_snapshot!(
1658            p(""),
1659            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected RFC 2822 datetime, but got empty string",
1660        );
1661        insta::assert_snapshot!(
1662            p(" "),
1663            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected RFC 2822 datetime, but got empty string after trimming leading whitespace",
1664        );
1665        insta::assert_snapshot!(
1666            p("Wat"),
1667            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected day at beginning of RFC 2822 datetime since first non-whitespace byte, `W`, is not a digit, but given string is too short (length is 3)",
1668        );
1669        insta::assert_snapshot!(
1670            p("Wed"),
1671            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected day at beginning of RFC 2822 datetime since first non-whitespace byte, `W`, is not a digit, but given string is too short (length is 3)",
1672        );
1673        insta::assert_snapshot!(
1674            p("Wed "),
1675            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected comma after parsed weekday in RFC 2822 datetime, but found end of input instead",
1676        );
1677        insta::assert_snapshot!(
1678            p("Wed   ,"),
1679            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected numeric day, but found end of input",
1680        );
1681        insta::assert_snapshot!(
1682            p("Wed   ,   "),
1683            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected numeric day, but found end of input",
1684        );
1685        insta::assert_snapshot!(
1686            p("Wat, "),
1687            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected day at beginning of RFC 2822 datetime since first non-whitespace byte, `W`, is not a digit, but did not recognize a valid weekday abbreviation",
1688        );
1689        insta::assert_snapshot!(
1690            p("Wed, "),
1691            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected numeric day, but found end of input",
1692        );
1693        insta::assert_snapshot!(
1694            p("Wed, 1"),
1695            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected whitespace after parsing day: expected whitespace after parsing time: expected at least one whitespace character (space or tab), but found none",
1696        );
1697        insta::assert_snapshot!(
1698            p("Wed, 10"),
1699            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected whitespace after parsing day: expected whitespace after parsing time: expected at least one whitespace character (space or tab), but found none",
1700        );
1701        insta::assert_snapshot!(
1702            p("Wed, 10 J"),
1703            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected abbreviated month name, but remaining input is too short (remaining bytes is 1)",
1704        );
1705        insta::assert_snapshot!(
1706            p("Wed, 10 Wat"),
1707            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected abbreviated month name, but did not recognize a valid abbreviated month name",
1708        );
1709        insta::assert_snapshot!(
1710            p("Wed, 10 Jan"),
1711            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected whitespace after parsing abbreviated month name: expected whitespace after parsing time: expected at least one whitespace character (space or tab), but found none",
1712        );
1713        insta::assert_snapshot!(
1714            p("Wed, 10 Jan 2"),
1715            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected at least two ASCII digits for parsing a year, but only found 1",
1716        );
1717        insta::assert_snapshot!(
1718            p("Wed, 10 Jan 2024"),
1719            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected whitespace after parsing year: expected whitespace after parsing time: expected at least one whitespace character (space or tab), but found none",
1720        );
1721        insta::assert_snapshot!(
1722            p("Wed, 10 Jan 2024 05"),
1723            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected time separator of `:`, but found end of input",
1724        );
1725        insta::assert_snapshot!(
1726            p("Wed, 10 Jan 2024 053"),
1727            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected time separator of `:`, but found `3`",
1728        );
1729        insta::assert_snapshot!(
1730            p("Wed, 10 Jan 2024 05:34"),
1731            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected whitespace after parsing time: expected at least one whitespace character (space or tab), but found none",
1732        );
1733        insta::assert_snapshot!(
1734            p("Wed, 10 Jan 2024 05:34:"),
1735            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected two digit second, but found end of input",
1736        );
1737        insta::assert_snapshot!(
1738            p("Wed, 10 Jan 2024 05:34:45"),
1739            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected whitespace after parsing time: expected at least one whitespace character (space or tab), but found none",
1740        );
1741        insta::assert_snapshot!(
1742            p("Wed, 10 Jan 2024 05:34:45 J"),
1743            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: expected obsolete RFC 2822 time zone abbreviation, but did not recognize a valid abbreviation",
1744        );
1745    }
1746
1747    #[test]
1748    fn err_parse_comment() {
1749        let p = |input| {
1750            DateTimeParser::new()
1751                .parse_zoned_datetime(input)
1752                .unwrap_err()
1753                .to_string()
1754        };
1755
1756        insta::assert_snapshot!(
1757            p(r"Wed, 10 Jan 2024 05:34:45 -0500 (wa)t)"),
1758            @r###"parsed value '2024-01-10T05:34:45-05:00[-05:00]', but unparsed input "t)" remains (expected no unparsed input)"###,
1759        );
1760        insta::assert_snapshot!(
1761            p(r"Wed, 10 Jan 2024 05:34:45 -0500 (wa(t)"),
1762            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: found opening parenthesis in comment with no matching closing parenthesis",
1763        );
1764        insta::assert_snapshot!(
1765            p(r"Wed, 10 Jan 2024 05:34:45 -0500 (w"),
1766            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: found opening parenthesis in comment with no matching closing parenthesis",
1767        );
1768        insta::assert_snapshot!(
1769            p(r"Wed, 10 Jan 2024 05:34:45 -0500 ("),
1770            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: found opening parenthesis in comment with no matching closing parenthesis",
1771        );
1772        insta::assert_snapshot!(
1773            p(r"Wed, 10 Jan 2024 05:34:45 -0500 (  "),
1774            @"failed to parse RFC 2822 datetime into Jiff zoned datetime: found opening parenthesis in comment with no matching closing parenthesis",
1775        );
1776    }
1777
1778    #[test]
1779    fn ok_print_zoned_datetime() {
1780        if crate::tz::db().is_definitively_empty() {
1781            return;
1782        }
1783
1784        let p = |zdt: &ZonedDateTime| -> String {
1785            let mut buf = String::new();
1786            DateTimePrinter::new()
1787                .print_zoned_datetime(&zdt, &mut buf)
1788                .unwrap();
1789            buf
1790        };
1791
1792        let zdt = date(2024, 1, 10)
1793            .at(5, 34, 45, 0)
1794            .in_tz("America/New_York")
1795            .unwrap();
1796        insta::assert_snapshot!(p(&zdt), @"Wed, 10 Jan 2024 05:34:45 -0500");
1797
1798        let zdt = date(2024, 2, 5)
1799            .at(5, 34, 45, 0)
1800            .in_tz("America/New_York")
1801            .unwrap();
1802        insta::assert_snapshot!(p(&zdt), @"Mon, 5 Feb 2024 05:34:45 -0500");
1803
1804        let zdt = date(2024, 7, 31)
1805            .at(5, 34, 45, 0)
1806            .in_tz("America/New_York")
1807            .unwrap();
1808        insta::assert_snapshot!(p(&zdt), @"Wed, 31 Jul 2024 05:34:45 -0400");
1809
1810        let zdt = date(2024, 3, 5).at(5, 34, 45, 0).in_tz("UTC").unwrap();
1811        // Notice that this prints a +0000 offset.
1812        // But when printing a Timestamp, a -0000 offset is used.
1813        // This is because in the case of Timestamp, the "true"
1814        // offset is not known.
1815        insta::assert_snapshot!(p(&zdt), @"Tue, 5 Mar 2024 05:34:45 +0000");
1816    }
1817
1818    #[test]
1819    fn ok_print_timestamp() {
1820        if crate::tz::db().is_definitively_empty() {
1821            return;
1822        }
1823
1824        let p = |ts: Timestamp| -> String {
1825            let mut buf = String::new();
1826            DateTimePrinter::new().print_timestamp(&ts, &mut buf).unwrap();
1827            buf
1828        };
1829
1830        let ts = date(2024, 1, 10)
1831            .at(5, 34, 45, 0)
1832            .in_tz("America/New_York")
1833            .unwrap()
1834            .timestamp();
1835        insta::assert_snapshot!(p(ts), @"Wed, 10 Jan 2024 10:34:45 -0000");
1836
1837        let ts = date(2024, 2, 5)
1838            .at(5, 34, 45, 0)
1839            .in_tz("America/New_York")
1840            .unwrap()
1841            .timestamp();
1842        insta::assert_snapshot!(p(ts), @"Mon, 5 Feb 2024 10:34:45 -0000");
1843
1844        let ts = date(2024, 7, 31)
1845            .at(5, 34, 45, 0)
1846            .in_tz("America/New_York")
1847            .unwrap()
1848            .timestamp();
1849        insta::assert_snapshot!(p(ts), @"Wed, 31 Jul 2024 09:34:45 -0000");
1850
1851        let ts = date(2024, 3, 5)
1852            .at(5, 34, 45, 0)
1853            .in_tz("UTC")
1854            .unwrap()
1855            .timestamp();
1856        // Notice that this prints a +0000 offset.
1857        // But when printing a Timestamp, a -0000 offset is used.
1858        // This is because in the case of Timestamp, the "true"
1859        // offset is not known.
1860        insta::assert_snapshot!(p(ts), @"Tue, 5 Mar 2024 05:34:45 -0000");
1861    }
1862
1863    #[test]
1864    fn ok_minimum_offset_roundtrip() {
1865        let zdt = date(2025, 12, 25)
1866            .at(17, 0, 0, 0)
1867            .to_zoned_datetime(TimeZone::fixed(Offset::MIN))
1868            .unwrap();
1869        let string =
1870            DateTimePrinter::new().zoned_datetime_to_string(&zdt).unwrap();
1871        assert_eq!(string, "Thu, 25 Dec 2025 17:00:00 -2559");
1872
1873        let got: ZonedDateTime =
1874            DateTimeParser::new().parse_zoned_datetime(&string).unwrap();
1875        // Since we started with a zoned datetime with a minimal offset
1876        // (to second precision) and RFC 2822 only supports minute precision
1877        // in time zone offsets, printing the zoned datetime rounds the offset.
1878        // But this would normally result in an offset beyond Jiff's limits,
1879        // so in this case, the offset truncates to the minimum supported
1880        // value by both Jiff and RFC 2822. That's what we test for here.
1881        let expected = date(2025, 12, 25)
1882            .at(17, 0, 0, 0)
1883            .to_zoned_datetime(TimeZone::fixed(-Offset::hms(25, 59, 0)))
1884            .unwrap();
1885        assert_eq!(expected, got);
1886    }
1887
1888    #[test]
1889    fn ok_maximum_offset_roundtrip() {
1890        let zdt = date(2025, 12, 25)
1891            .at(17, 0, 0, 0)
1892            .to_zoned_datetime(TimeZone::fixed(Offset::MAX))
1893            .unwrap();
1894        let string =
1895            DateTimePrinter::new().zoned_datetime_to_string(&zdt).unwrap();
1896        assert_eq!(string, "Thu, 25 Dec 2025 17:00:00 +2559");
1897
1898        let got: ZonedDateTime =
1899            DateTimeParser::new().parse_zoned_datetime(&string).unwrap();
1900        // Since we started with a zoned datetime with a maximal offset
1901        // (to second precision) and RFC 2822 only supports minute precision
1902        // in time zone offsets, printing the zoned datetime rounds the offset.
1903        // But this would normally result in an offset beyond Jiff's limits,
1904        // so in this case, the offset truncates to the maximum supported
1905        // value by both Jiff and RFC 2822. That's what we test for here.
1906        let expected = date(2025, 12, 25)
1907            .at(17, 0, 0, 0)
1908            .to_zoned_datetime(TimeZone::fixed(Offset::hms(25, 59, 0)))
1909            .unwrap();
1910        assert_eq!(expected, got);
1911    }
1912
1913    #[test]
1914    fn ok_print_rfc9110_timestamp() {
1915        if crate::tz::db().is_definitively_empty() {
1916            return;
1917        }
1918
1919        let p = |ts: Timestamp| -> String {
1920            let mut buf = String::new();
1921            DateTimePrinter::new()
1922                .print_timestamp_rfc9110(&ts, &mut buf)
1923                .unwrap();
1924            buf
1925        };
1926
1927        let ts = date(2024, 1, 10)
1928            .at(5, 34, 45, 0)
1929            .in_tz("America/New_York")
1930            .unwrap()
1931            .timestamp();
1932        insta::assert_snapshot!(p(ts), @"Wed, 10 Jan 2024 10:34:45 GMT");
1933
1934        let ts = date(2024, 2, 5)
1935            .at(5, 34, 45, 0)
1936            .in_tz("America/New_York")
1937            .unwrap()
1938            .timestamp();
1939        insta::assert_snapshot!(p(ts), @"Mon, 05 Feb 2024 10:34:45 GMT");
1940
1941        let ts = date(2024, 7, 31)
1942            .at(5, 34, 45, 0)
1943            .in_tz("America/New_York")
1944            .unwrap()
1945            .timestamp();
1946        insta::assert_snapshot!(p(ts), @"Wed, 31 Jul 2024 09:34:45 GMT");
1947
1948        let ts = date(2024, 3, 5)
1949            .at(5, 34, 45, 0)
1950            .in_tz("UTC")
1951            .unwrap()
1952            .timestamp();
1953        // Notice that this prints a +0000 offset.
1954        // But when printing a Timestamp, a -0000 offset is used.
1955        // This is because in the case of Timestamp, the "true"
1956        // offset is not known.
1957        insta::assert_snapshot!(p(ts), @"Tue, 05 Mar 2024 05:34:45 GMT");
1958    }
1959
1960    #[test]
1961    fn err_print_zoned_datetime() {
1962        if crate::tz::db().is_definitively_empty() {
1963            return;
1964        }
1965
1966        let p = |zdt: &ZonedDateTime| -> String {
1967            let mut buf = String::new();
1968            DateTimePrinter::new()
1969                .print_zoned_datetime(&zdt, &mut buf)
1970                .unwrap_err()
1971                .to_string()
1972        };
1973
1974        let zdt = date(-1, 1, 10)
1975            .at(5, 34, 45, 0)
1976            .in_tz("America/New_York")
1977            .unwrap();
1978        insta::assert_snapshot!(p(&zdt), @"datetime has negative year, which cannot be formatted with RFC 2822");
1979    }
1980
1981    #[test]
1982    fn err_print_timestamp() {
1983        if crate::tz::db().is_definitively_empty() {
1984            return;
1985        }
1986
1987        let p = |ts: Timestamp| -> String {
1988            let mut buf = String::new();
1989            DateTimePrinter::new()
1990                .print_timestamp(&ts, &mut buf)
1991                .unwrap_err()
1992                .to_string()
1993        };
1994
1995        let ts = date(-1, 1, 10)
1996            .at(5, 34, 45, 0)
1997            .in_tz("America/New_York")
1998            .unwrap()
1999            .timestamp();
2000        insta::assert_snapshot!(p(ts), @"datetime has negative year, which cannot be formatted with RFC 2822");
2001    }
2002}