Skip to main content

jiff/fmt/strtime/
printer.rs

1use crate::{
2    Error,
3    error::{
4        ErrorContext,
5        fmt::strtime::{Error as E, FormatError as FE},
6    },
7    fmt::{
8        buffer::BorrowedWriter,
9        strtime::{
10            BrokenDownTime, Config, Custom, Extension, Flag, Meridiem,
11            month_name_abbrev, month_name_full, weekday_name_abbrev,
12            weekday_name_full,
13        },
14    },
15    tz::Offset,
16    util::utf8,
17};
18
19enum Item {
20    AlreadyFormatted,
21    Integer(ItemInteger),
22    Fraction(ItemFraction),
23    String(ItemString),
24    Offset(ItemOffset),
25}
26
27struct ItemInteger {
28    pad_byte: u8,
29    pad_width: u8,
30    number: i64,
31}
32
33impl ItemInteger {
34    fn new(pad_byte: u8, pad_width: u8, n: impl Into<i64>) -> ItemInteger {
35        ItemInteger { pad_byte, pad_width, number: n.into() }
36    }
37}
38
39struct ItemFraction {
40    width: Option<u8>,
41    dot: bool,
42    subsec: u32,
43}
44
45struct ItemString {
46    case: Case,
47    string: &'static str,
48}
49
50impl ItemString {
51    fn new(case: Case, string: &'static str) -> ItemString {
52        ItemString { case, string }
53    }
54}
55
56struct ItemOffset {
57    offset: Offset,
58    colon: bool,
59    minute: bool,
60    second: bool,
61}
62
63impl ItemOffset {
64    fn new(
65        offset: Offset,
66        colon: bool,
67        minute: bool,
68        second: bool,
69    ) -> ItemOffset {
70        ItemOffset { offset, colon, minute, second }
71    }
72}
73
74pub(super) struct Formatter<
75    'config,
76    'fmt,
77    'tm,
78    'writer,
79    'buffer,
80    'data,
81    'write,
82> {
83    pub(super) config: &'config Config<dyn Custom + 'config>,
84    pub(super) fmt: &'fmt [u8],
85    pub(super) tm: &'tm BrokenDownTime,
86    pub(super) wtr: &'writer mut BorrowedWriter<'buffer, 'data, 'write>,
87}
88
89impl<'config, 'fmt, 'tm, 'writer, 'buffer, 'data, 'write>
90    Formatter<'config, 'fmt, 'tm, 'writer, 'buffer, 'data, 'write>
91{
92    #[inline(never)]
93    pub(super) fn format(&mut self) -> Result<(), Error> {
94        while !self.fmt.is_empty() {
95            if self.f() != b'%' {
96                if self.f().is_ascii() {
97                    self.wtr.write_ascii_char(self.f())?;
98                    self.bump_fmt();
99                } else {
100                    let ch = self.utf8_decode_and_bump()?;
101                    self.wtr.write_char(ch)?;
102                }
103                continue;
104            }
105            if !self.bump_fmt() {
106                if self.config.lenient {
107                    self.wtr.write_ascii_char(b'%')?;
108                    break;
109                }
110                return Err(E::UnexpectedEndAfterPercent.into());
111            }
112            let orig = self.fmt;
113            if let Err(err) =
114                self.parse_extension().and_then(|ext| self.format_one(&ext))
115            {
116                if !self.config.lenient {
117                    return Err(err);
118                }
119                // `orig` is whatever failed to parse immediately after a `%`.
120                // Since it failed, we write out the `%` and then proceed to
121                // handle what failed to parse literally.
122                self.wtr.write_ascii_char(b'%')?;
123                // Reset back to right after parsing the `%`.
124                self.fmt = orig;
125            }
126        }
127        Ok(())
128    }
129
130    #[cfg_attr(feature = "perf-inline", inline(always))]
131    fn format_one(&mut self, ext: &Extension) -> Result<(), Error> {
132        let i = |item: ItemInteger| Item::Integer(item);
133        let s = |item: ItemString| Item::String(item);
134        let o = |item: ItemOffset| Item::Offset(item);
135        let failc =
136            |directive, colons| E::DirectiveFailure { directive, colons };
137        let fail = |directive| failc(directive, 0);
138
139        // Parse extensions like padding/case options and padding width.
140        let mut directive = self.f();
141        let item = match directive {
142            b'%' => self.fmt_literal("%").map(s).context(fail(b'%')),
143            b'A' => self.fmt_weekday_full().map(s).context(fail(b'A')),
144            b'a' => self.fmt_weekday_abbrev().map(s).context(fail(b'a')),
145            b'B' => self.fmt_month_full().map(s).context(fail(b'B')),
146            b'b' => self.fmt_month_abbrev().map(s).context(fail(b'b')),
147            b'C' => self.fmt_century().map(i).context(fail(b'C')),
148            b'c' => self.fmt_datetime(ext).context(fail(b'c')),
149            b'D' => self.fmt_american_date().context(fail(b'D')),
150            b'd' => self.fmt_day_zero().map(i).context(fail(b'd')),
151            b'e' => self.fmt_day_space().map(i).context(fail(b'e')),
152            b'F' => self.fmt_iso_date().context(fail(b'F')),
153            b'f' => self.fmt_fractional(ext).context(fail(b'f')),
154            b'G' => self.fmt_iso_week_year().map(i).context(fail(b'G')),
155            b'g' => self.fmt_iso_week_year2().map(i).context(fail(b'g')),
156            b'H' => self.fmt_hour24_zero().map(i).context(fail(b'H')),
157            b'h' => self.fmt_month_abbrev().map(s).context(fail(b'b')),
158            b'I' => self.fmt_hour12_zero().map(i).context(fail(b'H')),
159            b'j' => self.fmt_day_of_year().map(i).context(fail(b'j')),
160            b'k' => self.fmt_hour24_space().map(i).context(fail(b'k')),
161            b'l' => self.fmt_hour12_space().map(i).context(fail(b'l')),
162            b'M' => self.fmt_minute().map(i).context(fail(b'M')),
163            b'm' => self.fmt_month().map(i).context(fail(b'm')),
164            b'N' => self.fmt_nanoseconds(ext).context(fail(b'N')),
165            b'n' => self.fmt_literal("\n").map(s).context(fail(b'n')),
166            b'P' => self.fmt_ampm_lower().map(s).context(fail(b'P')),
167            b'p' => self.fmt_ampm_upper(ext).map(s).context(fail(b'p')),
168            b'Q' => match ext.colons {
169                0 => self.fmt_iana_nocolon().context(fail(b'Q')),
170                1 => self.fmt_iana_colon().context(failc(b'Q', 1)),
171                _ => return Err(E::ColonCount { directive: b'Q' }.into()),
172            },
173            b'q' => self.fmt_quarter().map(i).context(fail(b'q')),
174            b'R' => self.fmt_clock_nosecs().context(fail(b'R')),
175            b'r' => self.fmt_12hour_time(ext).context(fail(b'r')),
176            b'S' => self.fmt_second().map(i).context(fail(b'S')),
177            b's' => self.fmt_timestamp().map(i).context(fail(b's')),
178            b'T' => self.fmt_clock_secs().context(fail(b'T')),
179            b't' => self.fmt_literal("\t").map(s).context(fail(b't')),
180            b'U' => self.fmt_week_sun().map(i).context(fail(b'U')),
181            b'u' => self.fmt_weekday_mon().map(i).context(fail(b'u')),
182            b'V' => self.fmt_week_iso().map(i).context(fail(b'V')),
183            b'W' => self.fmt_week_mon().map(i).context(fail(b'W')),
184            b'w' => self.fmt_weekday_sun().map(i).context(fail(b'w')),
185            b'X' => self.fmt_time(ext).context(fail(b'X')),
186            b'x' => self.fmt_date(ext).context(fail(b'x')),
187            b'Y' => self.fmt_year().map(i).context(fail(b'Y')),
188            b'y' => self.fmt_year2().map(i).context(fail(b'y')),
189            b'Z' => self.fmt_tzabbrev(ext).context(fail(b'Z')),
190            b'z' => match ext.colons {
191                0 => self.fmt_offset_nocolon().map(o).context(fail(b'z')),
192                1 => self.fmt_offset_colon().map(o).context(failc(b'z', 1)),
193                2 => self.fmt_offset_colon2().map(o).context(failc(b'z', 2)),
194                3 => self.fmt_offset_colon3().map(o).context(failc(b'z', 3)),
195                _ => return Err(E::ColonCount { directive: b'z' }.into()),
196            },
197            b'.' => {
198                if !self.bump_fmt() {
199                    return Err(E::UnexpectedEndAfterDot.into());
200                }
201                // Parse precision settings after the `.`, effectively
202                // overriding any digits that came before it.
203                let ext =
204                    &Extension { width: self.parse_width()?, ..ext.clone() };
205                directive = self.f();
206                match directive {
207                    b'f' => self
208                        .fmt_dot_fractional(ext)
209                        .context(E::DirectiveFailureDot { directive }),
210                    _ => {
211                        return Err(Error::from(
212                            E::UnknownDirectiveAfterDot { directive },
213                        ));
214                    }
215                }
216            }
217            _ => return Err(Error::from(E::UnknownDirective { directive })),
218        }?;
219        self.write_item(ext, &item).context(fail(directive))?;
220        self.bump_fmt();
221        Ok(())
222    }
223
224    /// Returns the byte at the current position of the format string.
225    ///
226    /// # Panics
227    ///
228    /// This panics when the entire format string has been consumed.
229    fn f(&self) -> u8 {
230        self.fmt[0]
231    }
232
233    /// Bumps the position of the format string.
234    ///
235    /// This returns true in precisely the cases where `self.f()` will not
236    /// panic. i.e., When the end of the format string hasn't been reached yet.
237    fn bump_fmt(&mut self) -> bool {
238        self.fmt = &self.fmt[1..];
239        !self.fmt.is_empty()
240    }
241
242    /// Decodes a Unicode scalar value from the beginning of `fmt` and advances
243    /// the parser accordingly.
244    ///
245    /// If a Unicode scalar value could not be decoded, then an error is
246    /// returned.
247    ///
248    /// It would be nice to just pass through bytes as-is instead of doing
249    /// actual UTF-8 decoding, but since the `Write` trait only represents
250    /// Unicode-accepting buffers, we need to actually do decoding here.
251    ///
252    /// # Errors
253    ///
254    /// Unless lenient parsing is enabled, this returns an error if UTF-8
255    /// decoding failed. When lenient parsing is enabled, decoding errors
256    /// are turned into the Unicode replacement codepoint via the
257    /// "substitution of maximal subparts" strategy.
258    ///
259    /// # Panics
260    ///
261    /// When `self.fmt` is empty. i.e., Only call this when you know there is
262    /// some remaining bytes to parse.
263    #[cold]
264    #[inline(never)]
265    fn utf8_decode_and_bump(&mut self) -> Result<char, FE> {
266        match utf8::decode(self.fmt).expect("non-empty fmt") {
267            Ok(ch) => {
268                self.fmt = &self.fmt[ch.len_utf8()..];
269                return Ok(ch);
270            }
271            Err(err) if self.config.lenient => {
272                self.fmt = &self.fmt[err.len()..];
273                return Ok(char::REPLACEMENT_CHARACTER);
274            }
275            Err(_) => Err(FE::InvalidUtf8),
276        }
277    }
278
279    /// Parses optional extensions before a specifier directive. That is, right
280    /// after the `%`. If any extensions are parsed, the parser is bumped
281    /// to the next byte. (If no next byte exists, then an error is returned.)
282    #[cfg_attr(feature = "perf-inline", inline(always))]
283    fn parse_extension(&mut self) -> Result<Extension, Error> {
284        if self.f().is_ascii_alphabetic() {
285            return Ok(Extension { flag: None, width: None, colons: 0 });
286        }
287        let flag = self.parse_flag()?;
288        let width = self.parse_width()?;
289        let colons = self.parse_colons()?;
290        Ok(Extension { flag, width, colons })
291    }
292
293    /// Parses an optional flag. And if one is parsed, the parser is bumped
294    /// to the next byte. (If no next byte exists, then an error is returned.)
295    #[cfg_attr(feature = "perf-inline", inline(always))]
296    fn parse_flag(&mut self) -> Result<Option<Flag>, Error> {
297        let (flag, fmt) = Extension::parse_flag(self.fmt)?;
298        self.fmt = fmt;
299        Ok(flag)
300    }
301
302    /// Parses an optional width that comes after a (possibly absent) flag and
303    /// before the specifier directive itself. And if a width is parsed, the
304    /// parser is bumped to the next byte. (If no next byte exists, then an
305    /// error is returned.)
306    ///
307    /// Note that this is also used to parse precision settings for `%f` and
308    /// `%.f`. In the former case, the width is just re-interpreted as a
309    /// precision setting. In the latter case, something like `%5.9f` is
310    /// technically valid, but the `5` is ignored.
311    #[cfg_attr(feature = "perf-inline", inline(always))]
312    fn parse_width(&mut self) -> Result<Option<u8>, Error> {
313        let (width, fmt) = Extension::parse_width(self.fmt)?;
314        self.fmt = fmt;
315        Ok(width)
316    }
317
318    /// Parses an optional number of colons (up to 3) immediately before a
319    /// conversion specifier.
320    #[cfg_attr(feature = "perf-inline", inline(always))]
321    fn parse_colons(&mut self) -> Result<u8, Error> {
322        let (colons, fmt) = Extension::parse_colons(self.fmt)?;
323        self.fmt = fmt;
324        Ok(colons)
325    }
326
327    #[cfg_attr(feature = "perf-inline", inline(always))]
328    fn write_item(
329        &mut self,
330        ext: &Extension,
331        item: &Item,
332    ) -> Result<(), Error> {
333        match *item {
334            Item::AlreadyFormatted => Ok(()),
335            Item::Integer(ref item) => ext.write_int(
336                item.pad_byte,
337                item.pad_width,
338                item.number,
339                self.wtr,
340            ),
341            Item::Fraction(ItemFraction { width, dot, subsec }) => {
342                if dot {
343                    self.wtr.write_ascii_char(b'.')?;
344                }
345                self.wtr.write_fraction(width, subsec)
346            }
347            Item::String(ref item) => {
348                ext.write_str(item.case, item.string, self.wtr)
349            }
350            Item::Offset(ref item) => write_offset(
351                item.offset,
352                item.colon,
353                item.minute,
354                item.second,
355                self.wtr,
356            ),
357        }
358    }
359
360    // These are the formatting functions. They are pretty much responsible
361    // for getting what they need for the broken down time and reporting a
362    // decent failure mode if what they need couldn't be found. And then,
363    // of course, doing the actual formatting.
364
365    /// %P
366    fn fmt_ampm_lower(&self) -> Result<ItemString, Error> {
367        let meridiem = match self.tm.meridiem() {
368            Some(meridiem) => meridiem,
369            None => {
370                let hour = self.tm.hour().ok_or(FE::RequiresTime)?;
371                if hour < 12 { Meridiem::AM } else { Meridiem::PM }
372            }
373        };
374        let s = match meridiem {
375            Meridiem::AM => "am",
376            Meridiem::PM => "pm",
377        };
378        Ok(ItemString::new(Case::AsIs, s))
379    }
380
381    /// %p
382    fn fmt_ampm_upper(&self, ext: &Extension) -> Result<ItemString, Error> {
383        let meridiem = match self.tm.meridiem() {
384            Some(meridiem) => meridiem,
385            None => {
386                let hour = self.tm.hour().ok_or(FE::RequiresTime)?;
387                if hour < 12 { Meridiem::AM } else { Meridiem::PM }
388            }
389        };
390        // Manually specialize this case to avoid hitting `write_str_cold`.
391        let s = if #[allow(non_exhaustive_omitted_patterns)] match ext.flag {
    Some(Flag::Swapcase) => true,
    _ => false,
}matches!(ext.flag, Some(Flag::Swapcase)) {
392            match meridiem {
393                Meridiem::AM => "am",
394                Meridiem::PM => "pm",
395            }
396        } else {
397            match meridiem {
398                Meridiem::AM => "AM",
399                Meridiem::PM => "PM",
400            }
401        };
402        Ok(ItemString::new(Case::AsIs, s))
403    }
404
405    /// %D
406    fn fmt_american_date(&mut self) -> Result<Item, Error> {
407        let ItemInteger { number, .. } = self.fmt_month()?;
408        self.wtr.write_int_pad2(number.unsigned_abs())?;
409        self.wtr.write_ascii_char(b'/')?;
410        let ItemInteger { number, .. } = self.fmt_day_zero()?;
411        self.wtr.write_int_pad2(number.unsigned_abs())?;
412        self.wtr.write_ascii_char(b'/')?;
413        let ItemInteger { number, .. } = self.fmt_year2()?;
414        if number < 0 {
415            self.wtr.write_ascii_char(b'-')?;
416        }
417        self.wtr.write_int_pad2(number.unsigned_abs())?;
418        Ok(Item::AlreadyFormatted)
419    }
420
421    /// %R
422    fn fmt_clock_nosecs(&mut self) -> Result<Item, Error> {
423        let ItemInteger { number, .. } = self.fmt_hour24_zero()?;
424        self.wtr.write_int_pad2(number.unsigned_abs())?;
425        self.wtr.write_ascii_char(b':')?;
426        let ItemInteger { number, .. } = self.fmt_minute()?;
427        self.wtr.write_int_pad2(number.unsigned_abs())?;
428        Ok(Item::AlreadyFormatted)
429    }
430
431    /// %T
432    fn fmt_clock_secs(&mut self) -> Result<Item, Error> {
433        let ItemInteger { number, .. } = self.fmt_hour24_zero()?;
434        self.wtr.write_int_pad2(number.unsigned_abs())?;
435        self.wtr.write_ascii_char(b':')?;
436        let ItemInteger { number, .. } = self.fmt_minute()?;
437        self.wtr.write_int_pad2(number.unsigned_abs())?;
438        self.wtr.write_ascii_char(b':')?;
439        let ItemInteger { number, .. } = self.fmt_second()?;
440        self.wtr.write_int_pad2(number.unsigned_abs())?;
441        Ok(Item::AlreadyFormatted)
442    }
443
444    /// %F
445    fn fmt_iso_date(&mut self) -> Result<Item, Error> {
446        let ItemInteger { number, .. } = self.fmt_year()?;
447        if number < 0 {
448            self.wtr.write_ascii_char(b'-')?;
449        }
450        self.wtr.write_int_pad4(number.unsigned_abs())?;
451        self.wtr.write_ascii_char(b'-')?;
452        let ItemInteger { number, .. } = self.fmt_month()?;
453        self.wtr.write_int_pad2(number.unsigned_abs())?;
454        self.wtr.write_ascii_char(b'-')?;
455        let ItemInteger { number, .. } = self.fmt_day_zero()?;
456        self.wtr.write_int_pad2(number.unsigned_abs())?;
457        Ok(Item::AlreadyFormatted)
458    }
459
460    /// %d
461    fn fmt_day_zero(&self) -> Result<ItemInteger, Error> {
462        let day = self
463            .tm
464            .day()
465            .or_else(|| self.tm.to_date().ok().map(|d| d.day()))
466            .ok_or(FE::RequiresDate)?;
467        Ok(ItemInteger::new(b'0', 2, day))
468    }
469
470    /// %e
471    fn fmt_day_space(&self) -> Result<ItemInteger, Error> {
472        let day = self
473            .tm
474            .day()
475            .or_else(|| self.tm.to_date().ok().map(|d| d.day()))
476            .ok_or(FE::RequiresDate)?;
477        Ok(ItemInteger::new(b' ', 2, day))
478    }
479
480    /// %I
481    fn fmt_hour12_zero(&self) -> Result<ItemInteger, Error> {
482        let mut hour = self.tm.hour().ok_or(FE::RequiresTime)?;
483        if hour == 0 {
484            hour = 12;
485        } else if hour > 12 {
486            hour -= 12;
487        }
488        Ok(ItemInteger::new(b'0', 2, hour))
489    }
490
491    /// %H
492    fn fmt_hour24_zero(&self) -> Result<ItemInteger, Error> {
493        let hour = self.tm.hour().ok_or(FE::RequiresTime)?;
494        Ok(ItemInteger::new(b'0', 2, hour))
495    }
496
497    /// %l
498    fn fmt_hour12_space(&self) -> Result<ItemInteger, Error> {
499        let mut hour = self.tm.hour().ok_or(FE::RequiresTime)?;
500        if hour == 0 {
501            hour = 12;
502        } else if hour > 12 {
503            hour -= 12;
504        }
505        Ok(ItemInteger::new(b' ', 2, hour))
506    }
507
508    /// %k
509    fn fmt_hour24_space(&self) -> Result<ItemInteger, Error> {
510        let hour = self.tm.hour().ok_or(FE::RequiresTime)?;
511        Ok(ItemInteger::new(b' ', 2, hour))
512    }
513
514    /// %M
515    fn fmt_minute(&self) -> Result<ItemInteger, Error> {
516        let minute = self.tm.minute().ok_or(FE::RequiresTime)?;
517        Ok(ItemInteger::new(b'0', 2, minute))
518    }
519
520    /// %m
521    fn fmt_month(&self) -> Result<ItemInteger, Error> {
522        let month = self
523            .tm
524            .month()
525            .or_else(|| self.tm.to_date().ok().map(|d| d.month()))
526            .ok_or(FE::RequiresDate)?;
527        Ok(ItemInteger::new(b'0', 2, month))
528    }
529
530    /// %B
531    fn fmt_month_full(&self) -> Result<ItemString, Error> {
532        let month = self
533            .tm
534            .month()
535            .or_else(|| self.tm.to_date().ok().map(|d| d.month()))
536            .ok_or(FE::RequiresDate)?;
537        Ok(ItemString::new(Case::AsIs, month_name_full(month)))
538    }
539
540    /// %b, %h
541    fn fmt_month_abbrev(&self) -> Result<ItemString, Error> {
542        let month = self
543            .tm
544            .month()
545            .or_else(|| self.tm.to_date().ok().map(|d| d.month()))
546            .ok_or(FE::RequiresDate)?;
547        Ok(ItemString::new(Case::AsIs, month_name_abbrev(month)))
548    }
549
550    /// %Q
551    fn fmt_iana_nocolon(&mut self) -> Result<Item, Error> {
552        let Some(iana) = self.tm.iana_time_zone() else {
553            let offset = self.tm.offset.ok_or(FE::RequiresTimeZoneOrOffset)?;
554            return Ok(Item::Offset(ItemOffset::new(
555                offset, false, true, false,
556            )));
557        };
558        self.wtr.write_str(iana)?;
559        Ok(Item::AlreadyFormatted)
560    }
561
562    /// %:Q
563    fn fmt_iana_colon(&mut self) -> Result<Item, Error> {
564        let Some(iana) = self.tm.iana_time_zone() else {
565            let offset = self.tm.offset.ok_or(FE::RequiresTimeZoneOrOffset)?;
566            return Ok(Item::Offset(ItemOffset::new(
567                offset, true, true, false,
568            )));
569        };
570        self.wtr.write_str(iana)?;
571        Ok(Item::AlreadyFormatted)
572    }
573
574    /// %z
575    fn fmt_offset_nocolon(&self) -> Result<ItemOffset, Error> {
576        let offset = self.tm.offset.ok_or(FE::RequiresOffset)?;
577        Ok(ItemOffset::new(offset, false, true, false))
578    }
579
580    /// %:z
581    fn fmt_offset_colon(&self) -> Result<ItemOffset, Error> {
582        let offset = self.tm.offset.ok_or(FE::RequiresOffset)?;
583        Ok(ItemOffset::new(offset, true, true, false))
584    }
585
586    /// %::z
587    fn fmt_offset_colon2(&self) -> Result<ItemOffset, Error> {
588        let offset = self.tm.offset.ok_or(FE::RequiresOffset)?;
589        Ok(ItemOffset::new(offset, true, true, true))
590    }
591
592    /// %:::z
593    fn fmt_offset_colon3(&self) -> Result<ItemOffset, Error> {
594        let offset = self.tm.offset.ok_or(FE::RequiresOffset)?;
595        Ok(ItemOffset::new(offset, true, false, false))
596    }
597
598    /// %S
599    fn fmt_second(&self) -> Result<ItemInteger, Error> {
600        let second = self.tm.second().ok_or(FE::RequiresTime)?;
601        Ok(ItemInteger::new(b'0', 2, second))
602    }
603
604    /// %s
605    fn fmt_timestamp(&self) -> Result<ItemInteger, Error> {
606        let timestamp =
607            self.tm.to_timestamp().map_err(|_| FE::RequiresInstant)?;
608        Ok(ItemInteger::new(b' ', 0, timestamp.as_second()))
609    }
610
611    /// %f
612    fn fmt_fractional(&self, ext: &Extension) -> Result<Item, Error> {
613        let subsec = self.tm.subsec.ok_or(FE::RequiresTime)?;
614        let subsec = i32::from(subsec).unsigned_abs();
615        // For %f, we always want to emit at least one digit. The only way we
616        // wouldn't is if our fractional component is zero. One exception to
617        // this is when the width is `0` (which looks like `%00f`), in which
618        // case, we emit an error. We could allow it to emit an empty string,
619        // but this seems very odd. And an empty string cannot be parsed by
620        // `%f`.
621        if ext.width == Some(0) {
622            return Err(Error::from(FE::ZeroPrecisionFloat));
623        }
624        if subsec == 0 && ext.width.is_none() {
625            return Ok(Item::String(ItemString::new(Case::AsIs, "0")));
626        }
627        Ok(Item::Fraction(ItemFraction {
628            width: ext.width,
629            dot: false,
630            subsec,
631        }))
632    }
633
634    /// %.f
635    fn fmt_dot_fractional(&self, ext: &Extension) -> Result<Item, Error> {
636        let Some(subsec) = self.tm.subsec else {
637            return Ok(Item::AlreadyFormatted);
638        };
639        let subsec = i32::from(subsec).unsigned_abs();
640        if subsec == 0 && ext.width.is_none() || ext.width == Some(0) {
641            return Ok(Item::AlreadyFormatted);
642        }
643        Ok(Item::Fraction(ItemFraction {
644            width: ext.width,
645            dot: true,
646            subsec,
647        }))
648    }
649
650    /// %N
651    fn fmt_nanoseconds(&self, ext: &Extension) -> Result<Item, Error> {
652        let subsec = self.tm.subsec.ok_or(FE::RequiresTime)?;
653        if ext.width == Some(0) {
654            return Err(Error::from(FE::ZeroPrecisionNano));
655        }
656        let subsec = i32::from(subsec).unsigned_abs();
657        // Since `%N` is actually an alias for `%9f`, when the precision
658        // is missing, we default to 9.
659        if ext.width.is_none() {
660            return Ok(Item::Fraction(ItemFraction {
661                width: Some(9),
662                dot: false,
663                subsec,
664            }));
665        }
666        Ok(Item::Fraction(ItemFraction {
667            width: ext.width,
668            dot: false,
669            subsec,
670        }))
671    }
672
673    /// %Z
674    fn fmt_tzabbrev(&mut self, ext: &Extension) -> Result<Item, Error> {
675        let tz = self.tm.tz.as_ref().ok_or(FE::RequiresTimeZone)?;
676        let ts = self.tm.to_timestamp().map_err(|_| FE::RequiresInstant)?;
677        let oinfo = tz.to_offset_info(ts);
678        ext.write_str(Case::Upper, oinfo.abbreviation(), self.wtr)?;
679        Ok(Item::AlreadyFormatted)
680    }
681
682    /// %A
683    fn fmt_weekday_full(&self) -> Result<ItemString, Error> {
684        let weekday = self
685            .tm
686            .weekday
687            .or_else(|| self.tm.to_date().ok().map(|d| d.weekday()))
688            .ok_or(FE::RequiresDate)?;
689        Ok(ItemString::new(Case::AsIs, weekday_name_full(weekday)))
690    }
691
692    /// %a
693    fn fmt_weekday_abbrev(&self) -> Result<ItemString, Error> {
694        let weekday = self
695            .tm
696            .weekday
697            .or_else(|| self.tm.to_date().ok().map(|d| d.weekday()))
698            .ok_or(FE::RequiresDate)?;
699        Ok(ItemString::new(Case::AsIs, weekday_name_abbrev(weekday)))
700    }
701
702    /// %u
703    fn fmt_weekday_mon(&self) -> Result<ItemInteger, Error> {
704        let weekday = self
705            .tm
706            .weekday
707            .or_else(|| self.tm.to_date().ok().map(|d| d.weekday()))
708            .ok_or(FE::RequiresDate)?;
709        Ok(ItemInteger::new(b' ', 0, weekday.to_monday_one_offset()))
710    }
711
712    /// %w
713    fn fmt_weekday_sun(&self) -> Result<ItemInteger, Error> {
714        let weekday = self
715            .tm
716            .weekday
717            .or_else(|| self.tm.to_date().ok().map(|d| d.weekday()))
718            .ok_or(FE::RequiresDate)?;
719        Ok(ItemInteger::new(b' ', 0, weekday.to_sunday_zero_offset()))
720    }
721
722    /// %U
723    fn fmt_week_sun(&self) -> Result<ItemInteger, Error> {
724        // Short circuit if the week number was explicitly set.
725        if let Some(weeknum) = self.tm.week_sun {
726            return Ok(ItemInteger::new(b'0', 2, weeknum));
727        }
728        let day = self
729            .tm
730            .day_of_year()
731            .or_else(|| self.tm.to_date().ok().map(|d| d.day_of_year()))
732            .ok_or(FE::RequiresDate)?;
733        let weekday = self
734            .tm
735            .weekday
736            .or_else(|| self.tm.to_date().ok().map(|d| d.weekday()))
737            .ok_or(FE::RequiresDate)?
738            .to_sunday_zero_offset();
739        // Example: 2025-01-05 is the first Sunday in 2025, and thus the start
740        // of week 1. This means that 2025-01-04 (Saturday) is in week 0.
741        //
742        // So for 2025-01-05, day=5 and weekday=0. Thus we get 11/7 = 1.
743        // For 2025-01-04, day=4 and weekday=6. Thus we get 4/7 = 0.
744        let weeknum = (day + 6 - i16::from(weekday)) / 7;
745        Ok(ItemInteger::new(b'0', 2, weeknum))
746    }
747
748    /// %V
749    fn fmt_week_iso(&self) -> Result<ItemInteger, Error> {
750        let weeknum = self
751            .tm
752            .iso_week()
753            .or_else(|| {
754                self.tm.to_date().ok().map(|d| d.iso_week_date().week())
755            })
756            .ok_or(FE::RequiresDate)?;
757        Ok(ItemInteger::new(b'0', 2, weeknum))
758    }
759
760    /// %W
761    fn fmt_week_mon(&self) -> Result<ItemInteger, Error> {
762        // Short circuit if the week number was explicitly set.
763        if let Some(weeknum) = self.tm.week_mon {
764            return Ok(ItemInteger::new(b'0', 2, weeknum));
765        }
766        let day = self
767            .tm
768            .day_of_year()
769            .or_else(|| self.tm.to_date().ok().map(|d| d.day_of_year()))
770            .ok_or(FE::RequiresDate)?;
771        let weekday = self
772            .tm
773            .weekday
774            .or_else(|| self.tm.to_date().ok().map(|d| d.weekday()))
775            .ok_or(FE::RequiresDate)?
776            .to_sunday_zero_offset();
777        // Example: 2025-01-06 is the first Monday in 2025, and thus the start
778        // of week 1. This means that 2025-01-05 (Sunday) is in week 0.
779        //
780        // So for 2025-01-06, day=6 and weekday=1. Thus we get 12/7 = 1.
781        // For 2025-01-05, day=5 and weekday=7. Thus we get 5/7 = 0.
782        let weeknum = (day + 6 - ((i16::from(weekday) + 6) % 7)) / 7;
783        Ok(ItemInteger::new(b'0', 2, weeknum))
784    }
785
786    /// %Y
787    fn fmt_year(&self) -> Result<ItemInteger, Error> {
788        let year = self
789            .tm
790            .year()
791            .or_else(|| self.tm.to_date().ok().map(|d| d.year()))
792            .ok_or(FE::RequiresDate)?;
793        Ok(ItemInteger::new(b'0', 4, year))
794    }
795
796    /// %y
797    fn fmt_year2(&self) -> Result<ItemInteger, Error> {
798        let year = self
799            .tm
800            .year()
801            .or_else(|| self.tm.to_date().ok().map(|d| d.year()))
802            .ok_or(FE::RequiresDate)?;
803        let year = year % 100;
804        Ok(ItemInteger::new(b'0', 2, year))
805    }
806
807    /// %C
808    fn fmt_century(&self) -> Result<ItemInteger, Error> {
809        let year = self
810            .tm
811            .year()
812            .or_else(|| self.tm.to_date().ok().map(|d| d.year()))
813            .ok_or(FE::RequiresDate)?;
814        let century = year / 100;
815        Ok(ItemInteger::new(b' ', 0, century))
816    }
817
818    /// %G
819    fn fmt_iso_week_year(&self) -> Result<ItemInteger, Error> {
820        let year = self
821            .tm
822            .iso_week_year()
823            .or_else(|| {
824                self.tm.to_date().ok().map(|d| d.iso_week_date().year())
825            })
826            .ok_or(FE::RequiresDate)?;
827        Ok(ItemInteger::new(b'0', 4, year))
828    }
829
830    /// %g
831    fn fmt_iso_week_year2(&self) -> Result<ItemInteger, Error> {
832        let year = self
833            .tm
834            .iso_week_year()
835            .or_else(|| {
836                self.tm.to_date().ok().map(|d| d.iso_week_date().year())
837            })
838            .ok_or(FE::RequiresDate)?;
839        let year = year % 100;
840        Ok(ItemInteger::new(b'0', 2, year))
841    }
842
843    /// %q
844    fn fmt_quarter(&self) -> Result<ItemInteger, Error> {
845        let month = self
846            .tm
847            .month()
848            .or_else(|| self.tm.to_date().ok().map(|d| d.month()))
849            .ok_or(FE::RequiresDate)?;
850        let quarter = match month {
851            1..=3 => 1,
852            4..=6 => 2,
853            7..=9 => 3,
854            10..=12 => 4,
855            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
856        };
857        Ok(ItemInteger::new(b'0', 0, quarter))
858    }
859
860    /// %j
861    fn fmt_day_of_year(&self) -> Result<ItemInteger, Error> {
862        let day = self
863            .tm
864            .day_of_year()
865            .or_else(|| self.tm.to_date().ok().map(|d| d.day_of_year()))
866            .ok_or(FE::RequiresDate)?;
867        Ok(ItemInteger::new(b'0', 3, day))
868    }
869
870    /// %n, %t
871    fn fmt_literal(&self, literal: &'static str) -> Result<ItemString, Error> {
872        Ok(ItemString::new(Case::AsIs, literal))
873    }
874
875    /// %c
876    fn fmt_datetime(&mut self, ext: &Extension) -> Result<Item, Error> {
877        self.config.custom.format_datetime(
878            self.config,
879            ext,
880            self.tm,
881            self.wtr,
882        )?;
883        Ok(Item::AlreadyFormatted)
884    }
885
886    /// %x
887    fn fmt_date(&mut self, ext: &Extension) -> Result<Item, Error> {
888        self.config.custom.format_date(self.config, ext, self.tm, self.wtr)?;
889        Ok(Item::AlreadyFormatted)
890    }
891
892    /// %X
893    fn fmt_time(&mut self, ext: &Extension) -> Result<Item, Error> {
894        self.config.custom.format_time(self.config, ext, self.tm, self.wtr)?;
895        Ok(Item::AlreadyFormatted)
896    }
897
898    /// %r
899    fn fmt_12hour_time(&mut self, ext: &Extension) -> Result<Item, Error> {
900        self.config.custom.format_12hour_time(
901            self.config,
902            ext,
903            self.tm,
904            self.wtr,
905        )?;
906        Ok(Item::AlreadyFormatted)
907    }
908}
909
910/// Writes the given time zone offset to the writer.
911///
912/// When `colon` is true, the hour, minute and optional second components are
913/// delimited by a colon. Otherwise, no delimiter is used.
914///
915/// When `minute` is true, the minute component is always printed. When
916/// false, the minute component is only printed when it is non-zero (or if
917/// the second component is non-zero).
918///
919/// When `second` is true, the second component is always printed. When false,
920/// the second component is only printed when it is non-zero.
921#[cfg_attr(feature = "perf-inline", inline(always))]
922fn write_offset(
923    offset: Offset,
924    colon: bool,
925    minute: bool,
926    second: bool,
927    wtr: &mut BorrowedWriter<'_, '_, '_>,
928) -> Result<(), Error> {
929    let total_seconds = offset.seconds().unsigned_abs();
930    let hours = (total_seconds / (60 * 60)) as u8;
931    let minutes = ((total_seconds / 60) % 60) as u8;
932    let seconds = (total_seconds % 60) as u8;
933
934    wtr.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' })?;
935    wtr.write_int_pad2(hours)?;
936    if minute || minutes != 0 || seconds != 0 {
937        if colon {
938            wtr.write_ascii_char(b':')?;
939        }
940        wtr.write_int_pad2(minutes)?;
941        if second || seconds != 0 {
942            if colon {
943                wtr.write_ascii_char(b':')?;
944            }
945            wtr.write_int_pad2(seconds)?;
946        }
947    }
948    Ok(())
949}
950
951impl Extension {
952    /// Writes the given string using the default case rule provided, unless
953    /// an option in this extension config overrides the default case.
954    #[cfg_attr(feature = "perf-inline", inline(always))]
955    fn write_str(
956        &self,
957        default: Case,
958        string: &str,
959        wtr: &mut BorrowedWriter<'_, '_, '_>,
960    ) -> Result<(), Error> {
961        if self.flag.is_none() && #[allow(non_exhaustive_omitted_patterns)] match default {
    Case::AsIs => true,
    _ => false,
}matches!(default, Case::AsIs) {
962            return wtr.write_str(string);
963        }
964        self.write_str_cold(default, string, wtr)
965    }
966
967    #[cold]
968    #[inline(never)]
969    fn write_str_cold(
970        &self,
971        default: Case,
972        string: &str,
973        wtr: &mut BorrowedWriter<'_, '_, '_>,
974    ) -> Result<(), Error> {
975        let case = match self.flag {
976            Some(Flag::Uppercase) => Case::Upper,
977            Some(Flag::Swapcase) => default.swap(),
978            _ => default,
979        };
980        match case {
981            Case::AsIs => {
982                wtr.write_str(string)?;
983            }
984            Case::Upper | Case::Lower => {
985                for ch in string.chars() {
986                    wtr.write_char(if #[allow(non_exhaustive_omitted_patterns)] match case {
    Case::Upper => true,
    _ => false,
}matches!(case, Case::Upper) {
987                        ch.to_ascii_uppercase()
988                    } else {
989                        ch.to_ascii_lowercase()
990                    })?;
991                }
992            }
993        }
994        Ok(())
995    }
996
997    /// Writes the given integer using the given padding width and byte, unless
998    /// an option in this extension config overrides a default setting.
999    #[cfg_attr(feature = "perf-inline", inline(always))]
1000    fn write_int(
1001        &self,
1002        pad_byte: u8,
1003        pad_width: u8,
1004        number: impl Into<i64>,
1005        wtr: &mut BorrowedWriter<'_, '_, '_>,
1006    ) -> Result<(), Error> {
1007        let number = number.into();
1008        let pad_byte = match self.flag {
1009            Some(Flag::PadZero) => b'0',
1010            Some(Flag::PadSpace) => b' ',
1011            _ => pad_byte,
1012        };
1013        let pad_width = if #[allow(non_exhaustive_omitted_patterns)] match self.flag {
    Some(Flag::NoPad) => true,
    _ => false,
}matches!(self.flag, Some(Flag::NoPad)) {
1014            0
1015        } else {
1016            self.width.unwrap_or(pad_width)
1017        };
1018        if number < 0 {
1019            // Special case formatting a negative integer with non-zero
1020            // padding. This case isn't handled by the `BorrowedWriter`
1021            // API, so just handle it specially instead of bloating up
1022            // the hot path.
1023            if pad_width > 0 {
1024                return Self::write_negative_int(
1025                    pad_byte,
1026                    pad_width,
1027                    number.unsigned_abs(),
1028                    wtr,
1029                );
1030            }
1031            wtr.write_ascii_char(b'-')?;
1032        }
1033        let number = number.unsigned_abs();
1034        match (pad_byte, pad_width) {
1035            (b'0', 2) if number <= 99 => wtr.write_int_pad2(number),
1036            (b' ', 2) if number <= 99 => wtr.write_int_pad2_space(number),
1037            (b'0', 4) if number <= 9999 => wtr.write_int_pad4(number),
1038            _ => wtr.write_int_pad(number, pad_byte, pad_width),
1039        }
1040    }
1041
1042    /// Writes a negative integer with explicit width, where sign is part of
1043    /// total width.
1044    #[cold]
1045    #[inline(never)]
1046    fn write_negative_int(
1047        pad_byte: u8,
1048        pad_width: u8,
1049        number: u64,
1050        wtr: &mut BorrowedWriter<'_, '_, '_>,
1051    ) -> Result<(), Error> {
1052        // The sign is part of the total width, so offset the
1053        // padding to account for it.
1054        let mut pad_width = pad_width.saturating_sub(1);
1055        // When padding to spaces, we want the padding first
1056        // and then the `-` sign. So handle the padding here
1057        // explicitly. For padding to zeros, we handle it
1058        // normally (other than offsetting the padding width
1059        // above).
1060        if pad_byte == b' ' {
1061            let d = 1 + number.checked_ilog10().unwrap_or(0) as u8;
1062            for _ in 0..pad_width.saturating_sub(d) {
1063                wtr.write_ascii_char(b' ')?;
1064            }
1065            // Don't do any padding to the call below.
1066            // We could instead add a `BorrowedWriter::write_int`
1067            // routine, but I don't think it's worth doing for
1068            // this case.
1069            pad_width = 0;
1070        }
1071        wtr.write_ascii_char(b'-')?;
1072        wtr.write_int_pad(number, pad_byte, pad_width)
1073    }
1074}
1075
1076/// The case to use when printing a string like weekday or TZ abbreviation.
1077#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Case {
}
#[automatically_derived]impl ::core::clone::Clone for Case {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Case { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Case {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Case::AsIs => "AsIs",
                Case::Upper => "Upper",
                Case::Lower => "Lower",
            })
    }
}Debug)]
1078enum Case {
1079    AsIs,
1080    Upper,
1081    Lower,
1082}
1083
1084impl Case {
1085    /// Swap upper to lowercase, and lower to uppercase.
1086    fn swap(self) -> Case {
1087        match self {
1088            Case::AsIs => Case::AsIs,
1089            Case::Upper => Case::Lower,
1090            Case::Lower => Case::Upper,
1091        }
1092    }
1093}
1094
1095#[cfg(feature = "alloc")]
1096#[cfg(test)]
1097mod tests {
1098    use alloc::string::ToString;
1099
1100    use crate::{
1101        Timestamp, ZonedDateTime,
1102        civil::{Date, DateTime, Time, date, time},
1103        fmt::strtime::{BrokenDownTime, Config, PosixCustom, format},
1104        tz::Offset,
1105    };
1106
1107    #[test]
1108    fn ok_format_american_date() {
1109        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1110
1111        insta::assert_snapshot!(f("%D", date(2024, 7, 9)), @"07/09/24");
1112        insta::assert_snapshot!(f("%-D", date(2024, 7, 9)), @"07/09/24");
1113        insta::assert_snapshot!(f("%3D", date(2024, 7, 9)), @"07/09/24");
1114        insta::assert_snapshot!(f("%03D", date(2024, 7, 9)), @"07/09/24");
1115    }
1116
1117    #[test]
1118    fn ok_format_ampm() {
1119        let f = |fmt: &str, time: Time| format(fmt, time).unwrap();
1120
1121        insta::assert_snapshot!(f("%H%P", time(9, 0, 0, 0)), @"09am");
1122        insta::assert_snapshot!(f("%H%P", time(11, 0, 0, 0)), @"11am");
1123        insta::assert_snapshot!(f("%H%P", time(23, 0, 0, 0)), @"23pm");
1124        insta::assert_snapshot!(f("%H%P", time(0, 0, 0, 0)), @"00am");
1125
1126        insta::assert_snapshot!(f("%H%p", time(9, 0, 0, 0)), @"09AM");
1127        insta::assert_snapshot!(f("%H%p", time(11, 0, 0, 0)), @"11AM");
1128        insta::assert_snapshot!(f("%H%p", time(23, 0, 0, 0)), @"23PM");
1129        insta::assert_snapshot!(f("%H%p", time(0, 0, 0, 0)), @"00AM");
1130
1131        insta::assert_snapshot!(f("%H%#p", time(9, 0, 0, 0)), @"09am");
1132    }
1133
1134    #[test]
1135    fn ok_format_clock() {
1136        let f = |fmt: &str, time: Time| format(fmt, time).unwrap();
1137
1138        insta::assert_snapshot!(f("%R", time(23, 59, 8, 0)), @"23:59");
1139        insta::assert_snapshot!(f("%T", time(23, 59, 8, 0)), @"23:59:08");
1140    }
1141
1142    #[test]
1143    fn ok_format_day() {
1144        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1145
1146        insta::assert_snapshot!(f("%d", date(2024, 7, 9)), @"09");
1147        insta::assert_snapshot!(f("%0d", date(2024, 7, 9)), @"09");
1148        insta::assert_snapshot!(f("%-d", date(2024, 7, 9)), @"9");
1149        insta::assert_snapshot!(f("%_d", date(2024, 7, 9)), @" 9");
1150
1151        insta::assert_snapshot!(f("%e", date(2024, 7, 9)), @" 9");
1152        insta::assert_snapshot!(f("%0e", date(2024, 7, 9)), @"09");
1153        insta::assert_snapshot!(f("%-e", date(2024, 7, 9)), @"9");
1154        insta::assert_snapshot!(f("%_e", date(2024, 7, 9)), @" 9");
1155    }
1156
1157    #[test]
1158    fn ok_format_iso_date() {
1159        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1160
1161        insta::assert_snapshot!(f("%F", date(2024, 7, 9)), @"2024-07-09");
1162        insta::assert_snapshot!(f("%-F", date(2024, 7, 9)), @"2024-07-09");
1163        insta::assert_snapshot!(f("%3F", date(2024, 7, 9)), @"2024-07-09");
1164        insta::assert_snapshot!(f("%03F", date(2024, 7, 9)), @"2024-07-09");
1165    }
1166
1167    #[test]
1168    fn ok_format_hour() {
1169        let f = |fmt: &str, time: Time| format(fmt, time).unwrap();
1170
1171        insta::assert_snapshot!(f("%H", time(9, 0, 0, 0)), @"09");
1172        insta::assert_snapshot!(f("%H", time(11, 0, 0, 0)), @"11");
1173        insta::assert_snapshot!(f("%H", time(23, 0, 0, 0)), @"23");
1174        insta::assert_snapshot!(f("%H", time(0, 0, 0, 0)), @"00");
1175
1176        insta::assert_snapshot!(f("%I", time(9, 0, 0, 0)), @"09");
1177        insta::assert_snapshot!(f("%I", time(11, 0, 0, 0)), @"11");
1178        insta::assert_snapshot!(f("%I", time(23, 0, 0, 0)), @"11");
1179        insta::assert_snapshot!(f("%I", time(0, 0, 0, 0)), @"12");
1180
1181        insta::assert_snapshot!(f("%k", time(9, 0, 0, 0)), @" 9");
1182        insta::assert_snapshot!(f("%k", time(11, 0, 0, 0)), @"11");
1183        insta::assert_snapshot!(f("%k", time(23, 0, 0, 0)), @"23");
1184        insta::assert_snapshot!(f("%k", time(0, 0, 0, 0)), @" 0");
1185
1186        insta::assert_snapshot!(f("%l", time(9, 0, 0, 0)), @" 9");
1187        insta::assert_snapshot!(f("%l", time(11, 0, 0, 0)), @"11");
1188        insta::assert_snapshot!(f("%l", time(23, 0, 0, 0)), @"11");
1189        insta::assert_snapshot!(f("%l", time(0, 0, 0, 0)), @"12");
1190    }
1191
1192    #[test]
1193    fn ok_format_minute() {
1194        let f = |fmt: &str, time: Time| format(fmt, time).unwrap();
1195
1196        insta::assert_snapshot!(f("%M", time(0, 9, 0, 0)), @"09");
1197        insta::assert_snapshot!(f("%M", time(0, 11, 0, 0)), @"11");
1198        insta::assert_snapshot!(f("%M", time(0, 23, 0, 0)), @"23");
1199        insta::assert_snapshot!(f("%M", time(0, 0, 0, 0)), @"00");
1200    }
1201
1202    #[test]
1203    fn ok_format_month() {
1204        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1205
1206        insta::assert_snapshot!(f("%m", date(2024, 7, 14)), @"07");
1207        insta::assert_snapshot!(f("%m", date(2024, 12, 14)), @"12");
1208        insta::assert_snapshot!(f("%0m", date(2024, 7, 14)), @"07");
1209        insta::assert_snapshot!(f("%0m", date(2024, 12, 14)), @"12");
1210        insta::assert_snapshot!(f("%-m", date(2024, 7, 14)), @"7");
1211        insta::assert_snapshot!(f("%-m", date(2024, 12, 14)), @"12");
1212        insta::assert_snapshot!(f("%_m", date(2024, 7, 14)), @" 7");
1213        insta::assert_snapshot!(f("%_m", date(2024, 12, 14)), @"12");
1214    }
1215
1216    #[test]
1217    fn ok_format_month_name() {
1218        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1219
1220        insta::assert_snapshot!(f("%B", date(2024, 7, 14)), @"July");
1221        insta::assert_snapshot!(f("%b", date(2024, 7, 14)), @"Jul");
1222        insta::assert_snapshot!(f("%h", date(2024, 7, 14)), @"Jul");
1223
1224        insta::assert_snapshot!(f("%#B", date(2024, 7, 14)), @"July");
1225        insta::assert_snapshot!(f("%^B", date(2024, 7, 14)), @"JULY");
1226    }
1227
1228    #[test]
1229    fn ok_format_offset_from_zoned() {
1230        if crate::tz::db().is_definitively_empty() {
1231            return;
1232        }
1233
1234        let f = |fmt: &str, zdt: &ZonedDateTime| format(fmt, zdt).unwrap();
1235
1236        let zdt = date(2024, 7, 14)
1237            .at(22, 24, 0, 0)
1238            .in_tz("America/New_York")
1239            .unwrap();
1240        insta::assert_snapshot!(f("%z", &zdt), @"-0400");
1241        insta::assert_snapshot!(f("%:z", &zdt), @"-04:00");
1242
1243        let zdt = zdt.checked_add(crate::Span::new().months(5)).unwrap();
1244        insta::assert_snapshot!(f("%z", &zdt), @"-0500");
1245        insta::assert_snapshot!(f("%:z", &zdt), @"-05:00");
1246    }
1247
1248    #[test]
1249    fn ok_format_offset_plain() {
1250        let o = |h: i8, m: i8, s: i8| -> Offset { Offset::hms(h, m, s) };
1251        let f = |fmt: &str, offset: Offset| {
1252            let mut tm = BrokenDownTime::default();
1253            tm.set_offset(Some(offset));
1254            tm.to_string(fmt).unwrap()
1255        };
1256
1257        insta::assert_snapshot!(f("%z", o(0, 0, 0)), @"+0000");
1258        insta::assert_snapshot!(f("%:z", o(0, 0, 0)), @"+00:00");
1259        insta::assert_snapshot!(f("%::z", o(0, 0, 0)), @"+00:00:00");
1260        insta::assert_snapshot!(f("%:::z", o(0, 0, 0)), @"+00");
1261
1262        insta::assert_snapshot!(f("%z", -o(4, 0, 0)), @"-0400");
1263        insta::assert_snapshot!(f("%:z", -o(4, 0, 0)), @"-04:00");
1264        insta::assert_snapshot!(f("%::z", -o(4, 0, 0)), @"-04:00:00");
1265        insta::assert_snapshot!(f("%:::z", -o(4, 0, 0)), @"-04");
1266
1267        insta::assert_snapshot!(f("%z", o(5, 30, 0)), @"+0530");
1268        insta::assert_snapshot!(f("%:z", o(5, 30, 0)), @"+05:30");
1269        insta::assert_snapshot!(f("%::z", o(5, 30, 0)), @"+05:30:00");
1270        insta::assert_snapshot!(f("%:::z", o(5, 30, 0)), @"+05:30");
1271
1272        insta::assert_snapshot!(f("%z", o(5, 30, 15)), @"+053015");
1273        insta::assert_snapshot!(f("%:z", o(5, 30, 15)), @"+05:30:15");
1274        insta::assert_snapshot!(f("%::z", o(5, 30, 15)), @"+05:30:15");
1275        insta::assert_snapshot!(f("%:::z", o(5, 30, 15)), @"+05:30:15");
1276
1277        insta::assert_snapshot!(f("%z", o(5, 0, 15)), @"+050015");
1278        insta::assert_snapshot!(f("%:z", o(5, 0, 15)), @"+05:00:15");
1279        insta::assert_snapshot!(f("%::z", o(5, 0, 15)), @"+05:00:15");
1280        insta::assert_snapshot!(f("%:::z", o(5, 0, 15)), @"+05:00:15");
1281    }
1282
1283    #[test]
1284    fn ok_format_second() {
1285        let f = |fmt: &str, time: Time| format(fmt, time).unwrap();
1286
1287        insta::assert_snapshot!(f("%S", time(0, 0, 9, 0)), @"09");
1288        insta::assert_snapshot!(f("%S", time(0, 0, 11, 0)), @"11");
1289        insta::assert_snapshot!(f("%S", time(0, 0, 23, 0)), @"23");
1290        insta::assert_snapshot!(f("%S", time(0, 0, 0, 0)), @"00");
1291    }
1292
1293    #[test]
1294    fn ok_format_subsec_nanosecond() {
1295        let f = |fmt: &str, time: Time| format(fmt, time).unwrap();
1296        let mk = |subsec| time(0, 0, 0, subsec);
1297
1298        insta::assert_snapshot!(f("%f", mk(123_000_000)), @"123");
1299        insta::assert_snapshot!(f("%f", mk(0)), @"0");
1300        insta::assert_snapshot!(f("%3f", mk(0)), @"000");
1301        insta::assert_snapshot!(f("%3f", mk(123_000_000)), @"123");
1302        insta::assert_snapshot!(f("%6f", mk(123_000_000)), @"123000");
1303        insta::assert_snapshot!(f("%9f", mk(123_000_000)), @"123000000");
1304        insta::assert_snapshot!(f("%255f", mk(123_000_000)), @"123000000");
1305
1306        insta::assert_snapshot!(f("%.f", mk(123_000_000)), @".123");
1307        insta::assert_snapshot!(f("%.f", mk(0)), @"");
1308        insta::assert_snapshot!(f("%3.f", mk(0)), @"");
1309        insta::assert_snapshot!(f("%.3f", mk(0)), @".000");
1310        insta::assert_snapshot!(f("%.3f", mk(123_000_000)), @".123");
1311        insta::assert_snapshot!(f("%.6f", mk(123_000_000)), @".123000");
1312        insta::assert_snapshot!(f("%.9f", mk(123_000_000)), @".123000000");
1313        insta::assert_snapshot!(f("%.255f", mk(123_000_000)), @".123000000");
1314
1315        insta::assert_snapshot!(f("%3f", mk(123_456_789)), @"123");
1316        insta::assert_snapshot!(f("%6f", mk(123_456_789)), @"123456");
1317        insta::assert_snapshot!(f("%9f", mk(123_456_789)), @"123456789");
1318
1319        insta::assert_snapshot!(f("%.0f", mk(123_456_789)), @"");
1320        insta::assert_snapshot!(f("%.3f", mk(123_456_789)), @".123");
1321        insta::assert_snapshot!(f("%.6f", mk(123_456_789)), @".123456");
1322        insta::assert_snapshot!(f("%.9f", mk(123_456_789)), @".123456789");
1323
1324        insta::assert_snapshot!(f("%N", mk(123_000_000)), @"123000000");
1325        insta::assert_snapshot!(f("%N", mk(0)), @"000000000");
1326        insta::assert_snapshot!(f("%N", mk(000_123_000)), @"000123000");
1327        insta::assert_snapshot!(f("%3N", mk(0)), @"000");
1328        insta::assert_snapshot!(f("%3N", mk(123_000_000)), @"123");
1329        insta::assert_snapshot!(f("%6N", mk(123_000_000)), @"123000");
1330        insta::assert_snapshot!(f("%9N", mk(123_000_000)), @"123000000");
1331        insta::assert_snapshot!(f("%255N", mk(123_000_000)), @"123000000");
1332    }
1333
1334    #[test]
1335    fn ok_format_tzabbrev() {
1336        if crate::tz::db().is_definitively_empty() {
1337            return;
1338        }
1339
1340        let f = |fmt: &str, zdt: &ZonedDateTime| format(fmt, zdt).unwrap();
1341
1342        let zdt = date(2024, 7, 14)
1343            .at(22, 24, 0, 0)
1344            .in_tz("America/New_York")
1345            .unwrap();
1346        insta::assert_snapshot!(f("%Z", &zdt), @"EDT");
1347        insta::assert_snapshot!(f("%^Z", &zdt), @"EDT");
1348        insta::assert_snapshot!(f("%#Z", &zdt), @"edt");
1349
1350        let zdt = zdt.checked_add(crate::Span::new().months(5)).unwrap();
1351        insta::assert_snapshot!(f("%Z", &zdt), @"EST");
1352    }
1353
1354    #[test]
1355    fn ok_format_tzabbrev_timestamp() {
1356        let ts: Timestamp = "2024-07-14T22:24:00-04".parse().unwrap();
1357        for ts in [Timestamp::MIN, Timestamp::UNIX_EPOCH, Timestamp::MAX, ts] {
1358            assert_eq!(ts.strftime("%Z").to_string(), "UTC");
1359            assert_eq!(format("%Z", ts).unwrap(), "UTC");
1360            assert_eq!(format("%^Z", ts).unwrap(), "UTC");
1361            assert_eq!(format("%#Z", ts).unwrap(), "utc");
1362        }
1363        insta::assert_snapshot!(
1364            format("%F %T %Z %z", ts).unwrap(),
1365            @"2024-07-15 02:24:00 UTC +0000",
1366        );
1367    }
1368
1369    #[test]
1370    fn ok_format_iana() {
1371        if crate::tz::db().is_definitively_empty() {
1372            return;
1373        }
1374
1375        let f = |fmt: &str, zdt: &ZonedDateTime| format(fmt, zdt).unwrap();
1376
1377        let zdt = date(2024, 7, 14)
1378            .at(22, 24, 0, 0)
1379            .in_tz("America/New_York")
1380            .unwrap();
1381        insta::assert_snapshot!(f("%Q", &zdt), @"America/New_York");
1382        insta::assert_snapshot!(f("%:Q", &zdt), @"America/New_York");
1383
1384        let zdt = date(2024, 7, 14)
1385            .at(22, 24, 0, 0)
1386            .to_zoned_datetime(crate::tz::offset(-4).to_time_zone())
1387            .unwrap();
1388        insta::assert_snapshot!(f("%Q", &zdt), @"-0400");
1389        insta::assert_snapshot!(f("%:Q", &zdt), @"-04:00");
1390
1391        let zdt = date(2024, 7, 14)
1392            .at(22, 24, 0, 0)
1393            .to_zoned_datetime(crate::tz::TimeZone::UTC)
1394            .unwrap();
1395        insta::assert_snapshot!(f("%Q", &zdt), @"UTC");
1396        insta::assert_snapshot!(f("%:Q", &zdt), @"UTC");
1397    }
1398
1399    #[test]
1400    fn ok_format_weekday_name() {
1401        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1402
1403        insta::assert_snapshot!(f("%A", date(2024, 7, 14)), @"Sunday");
1404        insta::assert_snapshot!(f("%a", date(2024, 7, 14)), @"Sun");
1405
1406        insta::assert_snapshot!(f("%#A", date(2024, 7, 14)), @"Sunday");
1407        insta::assert_snapshot!(f("%^A", date(2024, 7, 14)), @"SUNDAY");
1408
1409        insta::assert_snapshot!(f("%u", date(2024, 7, 14)), @"7");
1410        insta::assert_snapshot!(f("%w", date(2024, 7, 14)), @"0");
1411    }
1412
1413    #[test]
1414    fn ok_format_year() {
1415        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1416
1417        insta::assert_snapshot!(f("%Y", date(2024, 7, 14)), @"2024");
1418        insta::assert_snapshot!(f("%Y", date(24, 7, 14)), @"0024");
1419        insta::assert_snapshot!(f("%Y", date(-24, 7, 14)), @"-024");
1420
1421        insta::assert_snapshot!(f("%C", date(2024, 7, 14)), @"20");
1422        insta::assert_snapshot!(f("%C", date(1815, 7, 14)), @"18");
1423        insta::assert_snapshot!(f("%C", date(915, 7, 14)), @"9");
1424        insta::assert_snapshot!(f("%C", date(1, 7, 14)), @"0");
1425        insta::assert_snapshot!(f("%C", date(0, 7, 14)), @"0");
1426        insta::assert_snapshot!(f("%C", date(-1, 7, 14)), @"0");
1427        insta::assert_snapshot!(f("%C", date(-2024, 7, 14)), @"-20");
1428        insta::assert_snapshot!(f("%C", date(-1815, 7, 14)), @"-18");
1429        insta::assert_snapshot!(f("%C", date(-915, 7, 14)), @"-9");
1430    }
1431
1432    #[test]
1433    fn ok_format_year_negative_padded() {
1434        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1435
1436        insta::assert_snapshot!(f("%06Y", date(-2025, 1, 13)), @"-02025");
1437        insta::assert_snapshot!(f("%06Y", date(-25, 1, 13)), @"-00025");
1438        insta::assert_snapshot!(f("%06Y", date(-1, 1, 13)), @"-00001");
1439        insta::assert_snapshot!(f("%08Y", date(-2025, 1, 13)), @"-0002025");
1440        insta::assert_snapshot!(f("%_6Y", date(-2025, 1, 13)), @" -2025");
1441        insta::assert_snapshot!(f("%_6Y", date(-25, 1, 13)), @"   -25");
1442        insta::assert_snapshot!(f("%_6Y", date(-1, 1, 13)), @"    -1");
1443        insta::assert_snapshot!(f("%_8Y", date(-2025, 1, 13)), @"   -2025");
1444        insta::assert_snapshot!(f("%06Y", date(2025, 1, 13)), @"002025");
1445        insta::assert_snapshot!(f("%_6Y", date(2025, 1, 13)), @"  2025");
1446        insta::assert_snapshot!(f("%Y", date(-2025, 1, 13)), @"-2025");
1447        insta::assert_snapshot!(f("%Y", date(-25, 1, 13)), @"-025");
1448        insta::assert_snapshot!(f("%_Y", date(-2025, 1, 13)), @"-2025");
1449        insta::assert_snapshot!(f("%_Y", date(-25, 1, 13)), @" -25");
1450        insta::assert_snapshot!(f("%03Y", date(-2025, 1, 13)), @"-2025");
1451        insta::assert_snapshot!(f("%_3Y", date(-2025, 1, 13)), @"-2025");
1452        insta::assert_snapshot!(f("%-6Y", date(-2025, 1, 13)), @"-2025");
1453        insta::assert_snapshot!(f("%04Y", date(-2025, 1, 13)), @"-2025");
1454        insta::assert_snapshot!(f("%05Y", date(-2025, 1, 13)), @"-2025");
1455    }
1456
1457    #[test]
1458    fn ok_format_default_locale() {
1459        let f = |fmt: &str, date: DateTime| format(fmt, date).unwrap();
1460
1461        insta::assert_snapshot!(
1462            f("%c", date(2024, 7, 14).at(0, 0, 0, 0)),
1463            @"2024 M07 14, Sun 00:00:00",
1464        );
1465        insta::assert_snapshot!(
1466            f("%c", date(24, 7, 14).at(0, 0, 0, 0)),
1467            @"0024 M07 14, Sun 00:00:00",
1468        );
1469        insta::assert_snapshot!(
1470            f("%c", date(-24, 7, 14).at(0, 0, 0, 0)),
1471            @"-024 M07 14, Wed 00:00:00",
1472        );
1473        insta::assert_snapshot!(
1474            f("%c", date(2024, 7, 14).at(17, 31, 59, 123_456_789)),
1475            @"2024 M07 14, Sun 17:31:59",
1476        );
1477
1478        insta::assert_snapshot!(
1479            f("%r", date(2024, 7, 14).at(8, 30, 0, 0)),
1480            @"8:30:00 AM",
1481        );
1482        insta::assert_snapshot!(
1483            f("%r", date(2024, 7, 14).at(17, 31, 59, 123_456_789)),
1484            @"5:31:59 PM",
1485        );
1486
1487        insta::assert_snapshot!(
1488            f("%x", date(2024, 7, 14).at(0, 0, 0, 0)),
1489            @"2024 M07 14",
1490        );
1491
1492        insta::assert_snapshot!(
1493            f("%X", date(2024, 7, 14).at(8, 30, 0, 0)),
1494            @"08:30:00",
1495        );
1496        insta::assert_snapshot!(
1497            f("%X", date(2024, 7, 14).at(17, 31, 59, 123_456_789)),
1498            @"17:31:59",
1499        );
1500    }
1501
1502    #[test]
1503    fn ok_format_compound_uppercase() {
1504        let f = |fmt: &str, date: DateTime| format(fmt, date).unwrap();
1505
1506        insta::assert_snapshot!(
1507            f("%^c", date(2024, 7, 14).at(0, 0, 0, 0)),
1508            @"2024 M07 14, SUN 00:00:00",
1509        );
1510        insta::assert_snapshot!(
1511            f("%^x", date(2024, 7, 14).at(0, 0, 0, 0)),
1512            @"2024 M07 14",
1513        );
1514        insta::assert_snapshot!(
1515            f("%^X", date(2024, 7, 14).at(8, 30, 0, 0)),
1516            @"08:30:00",
1517        );
1518        insta::assert_snapshot!(
1519            f("%^r", date(2024, 7, 14).at(8, 30, 0, 0)),
1520            @"8:30:00 AM",
1521        );
1522    }
1523
1524    #[test]
1525    fn ok_format_posix_locale() {
1526        let f = |fmt: &str, date: DateTime| {
1527            let config = Config::new().custom(PosixCustom::default());
1528            let tm = BrokenDownTime::from(date);
1529            tm.to_string_with_config(&config, fmt).unwrap()
1530        };
1531
1532        insta::assert_snapshot!(
1533            f("%c", date(2024, 7, 14).at(0, 0, 0, 0)),
1534            @"Sun Jul 14 00:00:00 2024",
1535        );
1536        insta::assert_snapshot!(
1537            f("%c", date(24, 7, 14).at(0, 0, 0, 0)),
1538            @"Sun Jul 14 00:00:00 0024",
1539        );
1540        insta::assert_snapshot!(
1541            f("%c", date(-24, 7, 14).at(0, 0, 0, 0)),
1542            @"Wed Jul 14 00:00:00 -024",
1543        );
1544        insta::assert_snapshot!(
1545            f("%c", date(2024, 7, 14).at(17, 31, 59, 123_456_789)),
1546            @"Sun Jul 14 17:31:59 2024",
1547        );
1548
1549        insta::assert_snapshot!(
1550            f("%r", date(2024, 7, 14).at(8, 30, 0, 0)),
1551            @"08:30:00 AM",
1552        );
1553        insta::assert_snapshot!(
1554            f("%r", date(2024, 7, 14).at(17, 31, 59, 123_456_789)),
1555            @"05:31:59 PM",
1556        );
1557
1558        insta::assert_snapshot!(
1559            f("%x", date(2024, 7, 14).at(0, 0, 0, 0)),
1560            @"07/14/24",
1561        );
1562
1563        insta::assert_snapshot!(
1564            f("%X", date(2024, 7, 14).at(8, 30, 0, 0)),
1565            @"08:30:00",
1566        );
1567        insta::assert_snapshot!(
1568            f("%X", date(2024, 7, 14).at(17, 31, 59, 123_456_789)),
1569            @"17:31:59",
1570        );
1571    }
1572
1573    #[test]
1574    fn ok_format_year_2digit() {
1575        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1576
1577        insta::assert_snapshot!(f("%y", date(2024, 7, 14)), @"24");
1578        insta::assert_snapshot!(f("%y", date(2001, 7, 14)), @"01");
1579        insta::assert_snapshot!(f("%-y", date(2001, 7, 14)), @"1");
1580        insta::assert_snapshot!(f("%5y", date(2001, 7, 14)), @"00001");
1581        insta::assert_snapshot!(f("%-5y", date(2001, 7, 14)), @"1");
1582        insta::assert_snapshot!(f("%05y", date(2001, 7, 14)), @"00001");
1583        insta::assert_snapshot!(f("%_y", date(2001, 7, 14)), @" 1");
1584        insta::assert_snapshot!(f("%_5y", date(2001, 7, 14)), @"    1");
1585
1586        insta::assert_snapshot!(f("%y", date(1824, 7, 14)), @"24");
1587        insta::assert_snapshot!(f("%g", date(1824, 7, 14)), @"24");
1588    }
1589
1590    #[test]
1591    fn ok_format_iso_week_year() {
1592        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1593
1594        insta::assert_snapshot!(f("%G", date(2019, 11, 30)), @"2019");
1595        insta::assert_snapshot!(f("%G", date(19, 11, 30)), @"0019");
1596        insta::assert_snapshot!(f("%G", date(-19, 11, 30)), @"-019");
1597
1598        // tricksy
1599        insta::assert_snapshot!(f("%G", date(2019, 12, 30)), @"2020");
1600    }
1601
1602    #[test]
1603    fn ok_format_week_num() {
1604        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1605
1606        insta::assert_snapshot!(f("%U", date(2025, 1, 4)), @"00");
1607        insta::assert_snapshot!(f("%U", date(2025, 1, 5)), @"01");
1608
1609        insta::assert_snapshot!(f("%W", date(2025, 1, 5)), @"00");
1610        insta::assert_snapshot!(f("%W", date(2025, 1, 6)), @"01");
1611    }
1612
1613    #[test]
1614    fn ok_format_timestamp() {
1615        let f = |fmt: &str, ts: Timestamp| format(fmt, ts).unwrap();
1616
1617        let ts = "1970-01-01T00:00Z".parse().unwrap();
1618        insta::assert_snapshot!(f("%s", ts), @"0");
1619        insta::assert_snapshot!(f("%3s", ts), @"  0");
1620        insta::assert_snapshot!(f("%03s", ts), @"000");
1621        insta::assert_snapshot!(f("%2s", ts), @" 0");
1622
1623        let ts = "2025-01-20T13:09-05[America/New_York]".parse().unwrap();
1624        insta::assert_snapshot!(f("%s", ts), @"1737396540");
1625    }
1626
1627    #[test]
1628    fn ok_format_quarter() {
1629        let f = |fmt: &str, date: Date| format(fmt, date).unwrap();
1630
1631        insta::assert_snapshot!(f("%q", date(2024, 3, 31)), @"1");
1632        insta::assert_snapshot!(f("%q", date(2024, 4, 1)), @"2");
1633        insta::assert_snapshot!(f("%q", date(2024, 7, 14)), @"3");
1634        insta::assert_snapshot!(f("%q", date(2024, 12, 31)), @"4");
1635
1636        insta::assert_snapshot!(f("%2q", date(2024, 3, 31)), @"01");
1637        insta::assert_snapshot!(f("%02q", date(2024, 3, 31)), @"01");
1638        insta::assert_snapshot!(f("%_2q", date(2024, 3, 31)), @" 1");
1639    }
1640
1641    #[test]
1642    fn err_format_subsec_nanosecond() {
1643        let f = |fmt: &str, time: Time| format(fmt, time).unwrap_err();
1644        let mk = |subsec| time(0, 0, 0, subsec);
1645
1646        insta::assert_snapshot!(
1647            f("%00f", mk(123_456_789)),
1648            @"strftime formatting failed: %f failed: zero precision with %f is not allowed",
1649        );
1650    }
1651
1652    #[test]
1653    fn err_format_timestamp() {
1654        let f = |fmt: &str, dt: DateTime| format(fmt, dt).unwrap_err();
1655
1656        let dt = date(2025, 1, 20).at(13, 9, 0, 0);
1657        insta::assert_snapshot!(
1658            f("%s", dt),
1659            @"strftime formatting failed: %s failed: requires instant (a timestamp or a date, time and offset)",
1660        );
1661    }
1662
1663    #[test]
1664    fn err_invalid_utf8() {
1665        let d = date(2025, 1, 20);
1666        insta::assert_snapshot!(
1667            format("abc %F xyz", d).unwrap(),
1668            @"abc 2025-01-20 xyz",
1669        );
1670        insta::assert_snapshot!(
1671            format(b"abc %F \xFFxyz", d).unwrap_err(),
1672            @"strftime formatting failed: invalid format string, it must be valid UTF-8",
1673        );
1674    }
1675
1676    #[test]
1677    fn lenient() {
1678        fn f(
1679            fmt: impl AsRef<[u8]>,
1680            tm: impl Into<BrokenDownTime>,
1681        ) -> alloc::string::String {
1682            let config = Config::new().lenient(true);
1683            tm.into().to_string_with_config(&config, fmt).unwrap()
1684        }
1685
1686        insta::assert_snapshot!(f("%z", date(2024, 7, 9)), @"%z");
1687        insta::assert_snapshot!(f("%:z", date(2024, 7, 9)), @"%:z");
1688        insta::assert_snapshot!(f("%Q", date(2024, 7, 9)), @"%Q");
1689        insta::assert_snapshot!(f("%+", date(2024, 7, 9)), @"%+");
1690        insta::assert_snapshot!(f("%F", date(2024, 7, 9)), @"2024-07-09");
1691        insta::assert_snapshot!(f("%T", date(2024, 7, 9)), @"%T");
1692        insta::assert_snapshot!(f("%F%", date(2024, 7, 9)), @"2024-07-09%");
1693        insta::assert_snapshot!(
1694            f(b"abc %F \xFFxyz", date(2024, 7, 9)),
1695            @"abc 2024-07-09 �xyz",
1696        );
1697        // Demonstrates substitution of maximal subparts.
1698        // Namely, `\xF0\x9F\x92` is a prefix of a valid
1699        // UTF-8 encoding of a codepoint, such as `💩`.
1700        // So the entire prefix should get substituted with
1701        // a single replacement character...
1702        insta::assert_snapshot!(
1703            f(b"%F\xF0\x9F\x92%Y", date(2024, 7, 9)),
1704            @"2024-07-09�2024",
1705        );
1706        // ... but \xFF is never part of a valid encoding.
1707        // So each instance gets its own replacement
1708        // character.
1709        insta::assert_snapshot!(
1710            f(b"%F\xFF\xFF\xFF%Y", date(2024, 7, 9)),
1711            @"2024-07-09���2024",
1712        );
1713    }
1714
1715    // Regression test for a failed optimization where we would
1716    // inappropriately call `write_int_pad2` without checking that
1717    // the number to format was two digits.
1718    //
1719    // See: https://github.com/BurntSushi/jiff/issues/497
1720    #[test]
1721    fn regression_timestamp_2s() {
1722        use alloc::string::ToString;
1723
1724        let ts: Timestamp = "2024-07-09T20:24:00Z".parse().unwrap();
1725        assert_eq!(ts.strftime("%2s").to_string(), "1720556640");
1726
1727        let ts: Timestamp = "2024-07-09T20:24:00Z".parse().unwrap();
1728        assert_eq!(ts.strftime("%_2s").to_string(), "1720556640");
1729
1730        let ts: Timestamp = "2024-07-09T20:24:00Z".parse().unwrap();
1731        assert_eq!(ts.strftime("%02s").to_string(), "1720556640");
1732
1733        let ts: Timestamp = "2024-07-09T20:24:00Z".parse().unwrap();
1734        assert_eq!(ts.strftime("%04s").to_string(), "1720556640");
1735    }
1736}