Skip to main content

qsv_dateparser/
datetime.rs

1#![allow(deprecated)]
2use crate::timezone;
3use anyhow::{Result, anyhow};
4use chrono::format::{Item, ParseResult, Parsed, parse as parse_items};
5use chrono::prelude::*;
6
7/// Compiles a regex literal once per process and hands each thread its own
8/// clone, as a `&'static LocalKey<Regex>` used via `.with(|re| ...)`.
9///
10/// A shared `Regex` gives only its first-using thread the lock-free cache fast
11/// path; every other thread takes a mutex-protected cache stack. Under a
12/// parallel caller (e.g. `qsv stats --infer-dates` on 16 threads) that
13/// contention nearly doubled the CPU cost of date parsing. `Regex::clone`
14/// shares the compiled program but builds a fresh cache pool, so each thread
15/// becomes the owner of its own pool. Thread-local (not leaked) so a long-lived
16/// process that churns threads doesn't accumulate caches.
17macro_rules! regex {
18    ($re:literal $(,)?) => {{
19        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
20        thread_local! {
21            static TL: regex::Regex = RE
22                .get_or_init(|| {
23                    regex::RegexBuilder::new($re)
24                        .unicode(false)
25                        .build()
26                        .expect("invalid regex literal")
27                })
28                .clone();
29        }
30        &TL
31    }};
32}
33
34/// Compiles a strftime format literal into `chrono` format items exactly once,
35/// mirroring [`regex!`].
36///
37/// `chrono`'s `parse_from_str` / `datetime_from_str` convenience methods walk
38/// the format string through `StrftimeItems` on *every* call. Since every
39/// format in this file is a literal, that walk is pure repeated work, and it is
40/// paid several times per input because the parsers try formats in an
41/// `or_else` chain. Hoisting it into a `OnceLock` leaves the parse itself
42/// untouched: each method below reduces to exactly the same
43/// `parse(&mut Parsed, input, items)` plus `Parsed::to_*` that the chrono
44/// convenience method performs internally.
45///
46/// The format is a literal, so the resulting items borrow `'static` and the
47/// `expect` is checked once at first use rather than per call.
48macro_rules! fmt_items {
49    ($fmt:literal $(,)?) => {{
50        static ITEMS: std::sync::OnceLock<Vec<chrono::format::Item<'static>>> =
51            std::sync::OnceLock::new();
52        ITEMS
53            .get_or_init(|| {
54                chrono::format::StrftimeItems::new($fmt)
55                    .parse()
56                    .expect("invalid strftime literal")
57            })
58            .as_slice()
59    }};
60}
61/// Lookup table of bytes that may legally appear in an accepted date format:
62/// ASCII alphanumerics, ASCII whitespace (`\s` under `unicode(false)` =
63/// space, `\t`, `\n`, `\x0B`, `\x0C`, `\r`), and the separators `- + / : . ,`.
64const fn build_date_byte_table() -> [bool; 256] {
65    let mut table = [false; 256];
66    let mut i = 0usize;
67    while i < 256 {
68        let b = i as u8;
69        table[i] = b.is_ascii_alphanumeric()
70            || matches!(b, b' ' | 0x09..=0x0D)
71            || matches!(b, b'-' | b'+' | b'/' | b':' | b'.' | b',');
72        i += 1;
73    }
74    table
75}
76
77static DATE_BYTE: [bool; 256] = build_date_byte_table();
78
79/// Bytes matched by `\s` in these patterns, which are all built with
80/// `unicode(false)`: space plus `\t \n \v \f \r`.
81///
82/// `u8::is_ascii_whitespace` is not a substitute — it omits `\v` (0x0B), so
83/// using it here would silently disagree with the regexes.
84const fn build_ws_table() -> [bool; 256] {
85    let mut table = [false; 256];
86    let mut i = 0usize;
87    while i < 256 {
88        table[i] = matches!(i as u8, b' ' | 0x09..=0x0D);
89        i += 1;
90    }
91    table
92}
93
94static DATE_WS: [bool; 256] = build_ws_table();
95
96/// Cheap structural pre-filter run before the regex dispatch chain.
97///
98/// Any byte outside [`DATE_BYTE`] (e.g. `_`, `#`, `(`, or any non-ASCII byte)
99/// means the input cannot be a date, so we can bail before running 5-6 failing
100/// regex probes. This is the common, hot case for non-date string columns. It is
101/// intentionally conservative: it rejects nothing that currently parses.
102/// The table collapses the per-byte test to a single load + branch.
103#[inline]
104fn cannot_be_date(input: &str) -> bool {
105    input.bytes().any(|b| !DATE_BYTE[b as usize])
106}
107
108/// Extracts the trailing timezone token without asking the regex engine for
109/// capture positions.
110///
111/// The `_z` parsers used a `(?P<tz>…)` group purely to locate this token, but
112/// capture tracking forces the regex crate onto a much slower engine: on
113/// `month_mdy_hms_z`'s pattern, `captures()` costs 188 ns against 18 ns for
114/// `is_match()` or `find()`, and a reused `capture_locations` buffer only gets
115/// it to 179 ns — so it is the engine, not the allocation.
116///
117/// Instead the caller runs a prefix regex (the same pattern minus the tz
118/// group) with `find()`, and passes the match end here. `prefix_end` is where
119/// the greedy prefix stopped, so the rest of the input is the timezone.
120///
121/// Returns `None` whenever the remainder is not unambiguously a timezone
122/// token, which is the caller's signal to fall back to the original
123/// capture-based path. Because the fallback still runs the full pattern, this
124/// cannot change any result: it either produces exactly what the capture group
125/// would have, or declines and lets the slow path decide.
126///
127/// `require_ws` mirrors the difference between the two tz groups: `\s*` in
128/// `ymd_hms_z` versus `\s+` in `month_mdy_hms_z`. It matters because the
129/// prefix's own trailing `\s*` may already have eaten the separator, and the
130/// caller trims the token anyway, so the whitespace has to be accounted for
131/// here rather than inferred from the remainder alone.
132#[inline]
133fn tz_suffix(input: &str, prefix_end: usize, require_ws: bool) -> Option<&str> {
134    let bytes = input.as_bytes();
135    let rest = input.get(prefix_end..)?;
136
137    if require_ws {
138        let leading_ws = rest
139            .as_bytes()
140            .first()
141            .is_some_and(|&b| DATE_WS[b as usize]);
142        let trailing_ws = prefix_end
143            .checked_sub(1)
144            .is_some_and(|i| DATE_WS[bytes[i] as usize]);
145        if !leading_ws && !trailing_ws {
146            return None;
147        }
148    }
149
150    // `\s*` then 3-6 of `[+-:a-zA-Z0-9]`, and nothing else.
151    let token = rest.trim_start_matches(|c: char| (c as u32) < 128 && DATE_WS[c as usize]);
152    if !(3..=6).contains(&token.len()) {
153        return None;
154    }
155    token
156        .bytes()
157        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b':'))
158        .then_some(token)
159}
160
161/// Scratch space for the month-name parsers, which must strip separators from
162/// the input before handing it to chrono.
163///
164/// Comfortably covers every shape those regexes accept in practice — the
165/// longest realistic input, `September 17, 2012 at 10:09am PST`, is 33 bytes.
166/// The patterns allow unbounded runs of whitespace, so a pathological input can
167/// still exceed this; that falls back to allocating, which makes the size a
168/// performance choice rather than a correctness one.
169const NORMALIZE_SCRATCH: usize = 64;
170
171/// Copies `input` into `buf`, dropping every byte in `strip`, and then removes
172/// the first `"at"` when `drop_at` is set.
173///
174/// This replaces `String::replace`, whose allocation cost 56 ns of
175/// `month_mdy_hms_z` — comparable to the entire format parse. Returns `None`
176/// when the input does not fit, leaving the caller to allocate as before.
177///
178/// The `"at"` removal deliberately mirrors `String::find`, which matches the
179/// first occurrence anywhere rather than only a standalone word. No month name
180/// or abbreviation contains a lowercase `at`, so the two agree on every input
181/// the callers' regexes admit, but keeping the behaviour identical avoids
182/// having to prove that separately.
183#[inline]
184fn normalize_into<'b>(
185    input: &str,
186    buf: &'b mut [u8; NORMALIZE_SCRATCH],
187    strip: &[u8],
188    drop_at: bool,
189) -> Option<&'b str> {
190    if input.len() > buf.len() {
191        return None;
192    }
193
194    let mut n = 0;
195    for &b in input.as_bytes() {
196        if !strip.contains(&b) {
197            buf[n] = b;
198            n += 1;
199        }
200    }
201
202    if drop_at && let Some(pos) = buf[..n].windows(2).position(|w| w == b"at") {
203        buf.copy_within(pos + 2..n, pos);
204        n -= 2;
205    }
206
207    // Only whole ASCII bytes are ever dropped, so this cannot split a
208    // multi-byte character; the check is a cheap way to say so without unsafe.
209    std::str::from_utf8(&buf[..n]).ok()
210}
211
212/// Which format a date-time input's time-of-day portion dispatches to.
213///
214/// These are parse-dispatch buckets, not an exhaustive account of what the
215/// family regexes admit. `\d{1,2}:\d{2}(?::\d{2})?(?:\.\d{1,9})?\s*(?:am|pm|AM|PM)?`
216/// also admits a fraction with no seconds field — `hh:mm.fff`, with or without
217/// an AM/PM marker — which buckets as [`Self::Hm`] or [`Self::ImP`] and then
218/// fails against that format. It is malformed rather than a real shape, and
219/// `unsupported_shapes_still_fail` pins it as unsupported.
220///
221/// Each bucket is matched by at most one format string per family, so
222/// classifying up front replaces a chain of up to five trial parses — all but
223/// the last guaranteed to fail — with a single attempt.
224#[derive(Clone, Copy, PartialEq, Eq)]
225enum TimeShape {
226    /// `hh:mm`
227    Hm,
228    /// `hh:mm:ss`
229    Hms,
230    /// `hh:mm:ss.fff`
231    HmsF,
232    /// `hh:mm AM/PM`
233    ImP,
234    /// `hh:mm:ss AM/PM`
235    ImsP,
236    /// `hh:mm:ss.fff AM/PM`.
237    ///
238    /// Families whose regex admits both a fraction and an AM/PM marker parse
239    /// this with the same `%I:%M:%S%.f %P` they use for [`Self::ImsP`], since
240    /// `%.f` consumes nothing when there is no period. The two month-name
241    /// families reject it at their regex gate and map it to `None`.
242    HmsFP,
243}
244
245/// Classifies the time-of-day portion of an input that has already passed a
246/// family regex, from a single byte scan.
247///
248/// Callers pass the exact string they are about to hand to the parser, not the
249/// raw input. `month_mdy_hms` strips both `,` and `.` beforehand, so
250/// classifying the raw input would mistake the period in `Sept. 17, 2012` for
251/// fractional seconds. `month_dmy_hms` strips only `,` — it must keep a
252/// fractional-seconds period for [`TimeShape::HmsF`] to be reachable.
253///
254/// A colon count of 2 distinguishes `%H:%M:%S` from `%H:%M`; the callers'
255/// regexes cap the time at two colons and admit none anywhere else. The AM/PM
256/// marker can only ever be the final two bytes, and chrono's `%P` is
257/// case-insensitive, so a single `| 32` comparison covers `am`/`AM`/`Am`.
258#[inline]
259fn time_shape(input: &str) -> TimeShape {
260    let bytes = input.as_bytes();
261
262    let ampm = bytes.len() >= 2 && {
263        let [.., ap, m] = bytes else { unreachable!() };
264        m | 32 == b'm' && matches!(ap | 32, b'a' | b'p')
265    };
266
267    let mut colons = 0_u8;
268    let mut fraction = false;
269    for &b in bytes {
270        match b {
271            b':' => colons += 1,
272            b'.' => fraction = true,
273            _ => {}
274        }
275    }
276
277    match (colons >= 2, fraction, ampm) {
278        (true, true, true) => TimeShape::HmsFP,
279        (true, true, false) => TimeShape::HmsF,
280        (true, false, true) => TimeShape::ImsP,
281        (true, false, false) => TimeShape::Hms,
282        (false, _, true) => TimeShape::ImP,
283        (false, _, false) => TimeShape::Hm,
284    }
285}
286
287/// Returns true when the year field of a slash-separated date (the digits
288/// after the second `/`) is exactly 2 digits wide. Callers' regexes guarantee
289/// the `d{1,2}/d{1,2}/d{2,4}` shape, but the scan is panic-free regardless.
290///
291/// Used to dispatch between the `%y` and `%Y` chrono format families: `%y`
292/// consumes at most 2 digits, so it always fails on 3-4 digit years, and `%Y`
293/// is never reached on a 2-digit year that `%y` accepts (both families apply
294/// identical date-validity rules), so picking one family by year width is
295/// result-preserving and halves the trial-parse chain.
296#[inline]
297fn slash_year_is_two_digits(bytes: &[u8]) -> bool {
298    let mut slashes = 0u8;
299    let mut year_len = 0usize;
300    for &b in bytes {
301        if b == b'/' {
302            slashes += 1;
303        } else if slashes == 2 {
304            if b.is_ascii_digit() {
305                year_len += 1;
306            } else {
307                break;
308            }
309        }
310    }
311    year_len == 2
312}
313
314/// Parse struct has methods implemented parsers for accepted formats.
315pub struct Parse<'z, Tz2> {
316    tz: &'z Tz2,
317    default_time: NaiveTime,
318    prefer_dmy: bool,
319}
320
321impl<'z, Tz2> Parse<'z, Tz2>
322where
323    Tz2: TimeZone,
324{
325    /// Create a new instance of [`Parse`] with a custom parsing timezone that handles the
326    /// datetime string without time offset.
327    pub const fn new(tz: &'z Tz2, default_time: NaiveTime) -> Self {
328        Self {
329            tz,
330            default_time,
331            prefer_dmy: false,
332        }
333    }
334
335    pub const fn prefer_dmy(&mut self, yes: bool) -> &Self {
336        self.prefer_dmy = yes;
337        self
338    }
339
340    /// Create a new instance of [`Parse`] with a custom parsing timezone that handles the
341    /// datetime string without time offset, and the date parsing preference.
342    pub const fn new_with_preference(
343        tz: &'z Tz2,
344        default_time: NaiveTime,
345        prefer_dmy: bool,
346    ) -> Self {
347        Self {
348            tz,
349            default_time,
350            prefer_dmy,
351        }
352    }
353
354    /// Drop-in replacement for `Tz::datetime_from_str` taking pre-compiled items.
355    ///
356    /// Note that `Parsed` **must** be constructed fresh for every attempt.
357    /// `Parsed::set_*` returns `Err` when a field is set twice to conflicting
358    /// values, so reusing one `Parsed` across the `or_else` chains below would
359    /// produce silently wrong results rather than a compile error.
360    #[inline]
361    fn dt_from_items(&self, input: &str, items: &[Item<'static>]) -> ParseResult<DateTime<Tz2>> {
362        let mut parsed = Parsed::new();
363        parse_items(&mut parsed, input, items.iter())?;
364        parsed.to_datetime_with_timezone(self.tz)
365    }
366
367    /// Drop-in replacement for `NaiveDateTime::parse_from_str` taking
368    /// pre-compiled items. See [`Self::dt_from_items`] on `Parsed` reuse.
369    #[inline]
370    fn naive_dt_from_items(input: &str, items: &[Item<'static>]) -> ParseResult<NaiveDateTime> {
371        let mut parsed = Parsed::new();
372        parse_items(&mut parsed, input, items.iter())?;
373        parsed.to_naive_datetime_with_offset(0)
374    }
375
376    /// Drop-in replacement for `NaiveDate::parse_from_str` taking pre-compiled
377    /// items. See [`Self::dt_from_items`] on `Parsed` reuse.
378    #[inline]
379    fn naive_date_from_items(input: &str, items: &[Item<'static>]) -> ParseResult<NaiveDate> {
380        let mut parsed = Parsed::new();
381        parse_items(&mut parsed, input, items.iter())?;
382        parsed.to_naive_date()
383    }
384
385    /// This method tries to parse the input datetime string with a list of accepted formats. See
386    /// more examples from [`Parse`], [`crate::parse()`] and [`crate::parse_with_timezone()`].
387    ///
388    /// Order rationale: the regex-gated families are tried first because their
389    /// `is_match` gate rejects non-matching inputs cheaply. The two parsers
390    /// without a family regex gate — `unix_timestamp` (runs `fast_float2`) and
391    /// `rfc2822` (runs `parse_from_rfc2822`) — are tried last to avoid paying
392    /// their cost on the common ISO/slash dates. Each still applies its own cheap
393    /// byte pre-filter before the heavy parse (`unix_timestamp` checks the first
394    /// byte against the leads `fast_float2` accepts; `rfc2822` requires a `:`).
395    ///
396    /// This reorder is result-preserving:
397    /// - A `fast_float2`-parseable input (a pure finite number; `inf`/`nan` are
398    ///   rejected as non-finite) matches no family gate (they all require `/`,
399    ///   an interior `-`, or a letters+space shape a bare number lacks), so it
400    ///   still reaches `unix_timestamp`.
401    /// - An `rfc2822` input always carries a timezone, which makes the
402    ///   `$`-anchored `month_dmy_*` regexes fail; conversely `month_dmy_*` only
403    ///   succeeds without a timezone, which makes `rfc2822` fail. The two are
404    ///   mutually exclusive, so deferring `rfc2822` cannot change any result.
405    ///
406    /// Within that order, the first byte selects which families can match at
407    /// all. Every family gate is `^`-anchored on either a digit or a letter, so
408    /// a letter-leading input cannot match any of the numeric families and vice
409    /// versa. Running them anyway costs roughly 5-10 ns each in regex startup
410    /// even when the first byte rejects immediately, which is most of the cost
411    /// of a non-date word — the dominant input in a `qsv stats --infer-dates`
412    /// run over a text column.
413    ///
414    /// `rfc2822` stays in the digit branch as well as the letter branch: the
415    /// day-of-week is optional in RFC 2822, so `02 Jun 2021 06:31:39 GMT`
416    /// parses and leads with a digit.
417    #[inline]
418    pub fn parse(&self, input: &str) -> Result<DateTime<Utc>> {
419        if cannot_be_date(input) {
420            return Err(anyhow!("{input} did not match any formats."));
421        }
422        let Some(&first) = input.as_bytes().first() else {
423            return Err(anyhow!("{input} did not match any formats."));
424        };
425
426        let parsed = if first.is_ascii_digit() {
427            self.slash_mdy_family(input)
428                .or_else(|| self.slash_ymd_family(input))
429                .or_else(|| self.ymd_family(input))
430                .or_else(|| self.month_ymd(input))
431                .or_else(|| self.month_dmy_family(input))
432                .or_else(|| self.unix_timestamp(input))
433                .or_else(|| self.rfc2822(input))
434        } else if first.is_ascii_alphabetic() {
435            // `month_mdy_family` is the only letter-anchored gate.
436            // `unix_timestamp` is excluded by its own lead-byte pre-filter.
437            self.month_mdy_family(input).or_else(|| self.rfc2822(input))
438        } else {
439            // `+`, `-`, `.` and the separators that survive `cannot_be_date`.
440            // No family gate can match, but a signed or bare-decimal timestamp
441            // can; `rfc2822` is kept for its own leading-whitespace handling.
442            self.unix_timestamp(input).or_else(|| self.rfc2822(input))
443        };
444
445        parsed.unwrap_or_else(|| Err(anyhow!("{input} did not match any formats.")))
446    }
447
448    #[inline]
449    fn ymd_family(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
450        let re = regex! {
451            r"^\d{4}-\d{2}"
452
453        };
454
455        if !re.with(|r| r.is_match(input)) {
456            return None;
457        }
458        self.rfc3339(input)
459            .or_else(|| self.ymd_hms(input))
460            .or_else(|| self.ymd_hms_z(input))
461            .or_else(|| self.ymd(input))
462            .or_else(|| self.ymd_z(input))
463    }
464
465    #[inline]
466    fn month_mdy_family(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
467        let re = regex! {
468            r"^[a-zA-Z]{3,9}\.?\s+\d{1,2}"
469        };
470
471        if !re.with(|r| r.is_match(input)) {
472            return None;
473        }
474        self.month_mdy_hms(input)
475            .or_else(|| self.month_mdy_hms_z(input))
476            .or_else(|| self.month_mdy(input))
477    }
478
479    #[inline]
480    fn month_dmy_family(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
481        let re = regex! {r"^\d{1,2}\s+[a-zA-Z]{3,9}"
482        };
483
484        if !re.with(|r| r.is_match(input)) {
485            return None;
486        }
487        self.month_dmy_hms(input).or_else(|| self.month_dmy(input))
488    }
489
490    #[inline]
491    fn slash_mdy_family(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
492        let re = regex! {r"^\d{1,2}/\d{1,2}"
493        };
494        if !re.with(|r| r.is_match(input)) {
495            return None;
496        }
497        if self.prefer_dmy {
498            self.slash_dmy_hms(input)
499                .or_else(|| self.slash_dmy(input))
500                .or_else(|| self.slash_mdy_hms(input))
501                .or_else(|| self.slash_mdy(input))
502        } else {
503            self.slash_mdy_hms(input)
504                .or_else(|| self.slash_mdy(input))
505                .or_else(|| self.slash_dmy_hms(input))
506                .or_else(|| self.slash_dmy(input))
507        }
508    }
509
510    #[inline]
511    fn slash_ymd_family(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
512        let re = regex! {r"^[0-9]{4}/[0-9]{1,2}"};
513        if !re.with(|r| r.is_match(input)) {
514            return None;
515        }
516        self.slash_ymd_hms(input).or_else(|| self.slash_ymd(input))
517    }
518
519    // unix timestamp
520    // - 0
521    // - -770172300
522    // - 1671673426.123456789
523    #[inline]
524    fn unix_timestamp(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
525        // Cheap pre-filter before the heavier float parse: only finite numbers
526        // are accepted, so the first byte must be a digit, sign, or dot
527        // (`fast_float2` rejects leading whitespace and empty input; bare
528        // `inf`/`nan` are excluded here, matching the non-finite check below).
529        // This is the last-resort numeric parser, so most inputs reaching it
530        // are non-numeric.
531        let &b0 = input.as_bytes().first()?;
532        if !(b0.is_ascii_digit() || matches!(b0, b'+' | b'-' | b'.')) {
533            return None;
534        }
535
536        let ts_sec_val: f64 = if let Ok(val) = fast_float2::parse(input) {
537            val
538        } else {
539            return None;
540        };
541
542        // Reject non-finite values (`+inf`, `-nan`, … pass the lead-byte filter
543        // above): the `as i64` cast below would otherwise turn `nan` into 0
544        // (1970-01-01) and `inf` into i64::MAX nanos (2262-04-11) — never the
545        // intended reading of the input.
546        if !ts_sec_val.is_finite() {
547            return None;
548        }
549
550        // convert the timestamp seconds value to nanoseconds
551        let ts_ns_val = ts_sec_val * 1_000_000_000_f64;
552
553        let result = Utc.timestamp_nanos(ts_ns_val as i64).with_timezone(&Utc);
554        Some(Ok(result))
555    }
556
557    // rfc3339
558    // - 2021-05-01T01:17:02.604456Z
559    // - 2017-11-25T22:34:50Z
560    #[inline]
561    fn rfc3339(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
562        DateTime::parse_from_rfc3339(input)
563            .ok()
564            .map(|parsed| parsed.with_timezone(&Utc))
565            .map(Ok)
566    }
567
568    // rfc2822
569    // - Wed, 02 Jun 2021 06:31:39 GMT
570    #[inline]
571    fn rfc2822(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
572        // Fast pre-filter: every RFC2822 datetime carries a time-of-day
573        // (`hour ":" minute`), so it always contains ':'. Skip the
574        // `parse_from_rfc2822` attempt for colon-free inputs. This is the
575        // last-resort parser, so most inputs reaching it are non-rfc2822.
576        if !input.as_bytes().contains(&b':') {
577            return None;
578        }
579        DateTime::parse_from_rfc2822(input)
580            .ok()
581            .map(|parsed| parsed.with_timezone(&Utc))
582            .map(Ok)
583    }
584
585    // yyyy-mm-dd hh:mm:ss  (separator is space OR ISO 8601 'T')
586    // - 2014-04-26 05:24:37 PM
587    // - 2021-04-30 21:14
588    // - 2021-04-30 21:14:10
589    // - 2021-04-30 21:14:10.052282
590    // - 2014-04-26 17:24:37.123
591    // - 2014-04-26 17:24:37.3186369
592    // - 2012-08-03 18:31:59.257000000
593    // - 2020-01-15T08:00
594    // - 2020-01-15T08:00:00
595    // - 2020-01-15T08:00:00.123456
596    // - 2012-03-19 10:11:59.318 PM
597    #[inline]
598    fn ymd_hms(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
599        let re = regex! {
600                r"^\d{4}-\d{2}-\d{2}[T\s]+\d{2}:\d{2}(?::\d{2})?(?:\.\d{1,9})?\s*(?:am|pm|AM|PM)?$"
601
602        };
603        if !re.with(|r| r.is_match(input)) {
604            return None;
605        }
606
607        // Byte 10 is the date/time separator. The regex guarantees the input
608        // has at least 16 bytes and that byte 10 is either 'T' or ASCII
609        // whitespace, so the single byte picks the format family.
610        let items = match (input.as_bytes()[10] == b'T', time_shape(input)) {
611            (true, TimeShape::Hms) => fmt_items!("%Y-%m-%dT%H:%M:%S"),
612            (true, TimeShape::Hm) => fmt_items!("%Y-%m-%dT%H:%M"),
613            (true, TimeShape::HmsF) => fmt_items!("%Y-%m-%dT%H:%M:%S%.f"),
614            (true, TimeShape::ImsP | TimeShape::HmsFP) => {
615                fmt_items!("%Y-%m-%dT%I:%M:%S%.f %P")
616            }
617            (true, TimeShape::ImP) => fmt_items!("%Y-%m-%dT%I:%M %P"),
618            (false, TimeShape::Hms) => fmt_items!("%Y-%m-%d %H:%M:%S"),
619            (false, TimeShape::Hm) => fmt_items!("%Y-%m-%d %H:%M"),
620            (false, TimeShape::HmsF) => fmt_items!("%Y-%m-%d %H:%M:%S%.f"),
621            (false, TimeShape::ImsP | TimeShape::HmsFP) => {
622                fmt_items!("%Y-%m-%d %I:%M:%S%.f %P")
623            }
624            (false, TimeShape::ImP) => fmt_items!("%Y-%m-%d %I:%M %P"),
625        };
626
627        self.dt_from_items(input, items)
628            .ok()
629            .map(|parsed| parsed.with_timezone(&Utc))
630            .map(Ok)
631    }
632
633    // yyyy-mm-dd hh:mm:ss z
634    // - 2017-11-25 13:31:15 PST
635    // - 2017-11-25 13:31 PST
636    // - 2014-12-16 06:20:00 UTC
637    // - 2014-12-16 06:20:00 GMT
638    // - 2014-04-26 13:13:43 +0800
639    // - 2014-04-26 13:13:44 +09:00
640    // - 2012-08-03 18:31:59.257000000 +0000
641    // - 2015-09-30 18:48:56.35272715 UTC
642    #[inline]
643    fn ymd_hms_z(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
644        // Fast pre-filter: bare dates "YYYY-MM-DD" are 10 chars; valid inputs need space + time
645        if input.len() < 17 || !input.as_bytes()[10].is_ascii_whitespace() {
646            return None;
647        }
648        // Fast path: locate the timezone with `find()` on the pattern minus the
649        // tz group, which keeps the regex engine off the capture-tracking path.
650        // See `tz_suffix` — on failure this falls through to the original
651        // capture-based match, so no input can change meaning.
652        let prefix = regex! {r"^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(?::\d{2})?(?:\.\d{1,9})?"};
653        let fast_tz = prefix
654            .with(|r| r.find(input))
655            .and_then(|m| tz_suffix(input, m.end(), false));
656
657        let re = regex! {
658                r"^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(?::\d{2})?(?:\.\d{1,9})?(?P<tz>\s*[+-:a-zA-Z0-9]{3,6})$"
659        };
660
661        if let Some(tz) = fast_tz.or_else(|| {
662            re.with(|r| r.captures(input))
663                .and_then(|caps| caps.name("tz").map(|m| m.as_str().trim()))
664        }) {
665            let parse_from_str = Self::naive_dt_from_items;
666            return match timezone::parse(tz) {
667                Ok(offset) => parse_from_str(input, fmt_items!("%Y-%m-%d %H:%M:%S %Z"))
668                    .or_else(|_| parse_from_str(input, fmt_items!("%Y-%m-%d %H:%M %Z")))
669                    .or_else(|_| parse_from_str(input, fmt_items!("%Y-%m-%d %H:%M:%S%.f %Z")))
670                    .ok()
671                    .and_then(|parsed| offset.from_local_datetime(&parsed).single())
672                    .map(|datetime| datetime.with_timezone(&Utc))
673                    .map(Ok),
674                Err(err) => Some(Err(err)),
675            };
676        }
677        None
678    }
679
680    // yyyy-mm-dd
681    // - 2021-02-21
682    #[inline]
683    fn ymd(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
684        let re = regex! {r"^\d{4}-\d{2}-\d{2}$"
685        };
686
687        if !re.with(|r| r.is_match(input)) {
688            return None;
689        }
690        let now = Utc::now()
691            .date()
692            .and_time(self.default_time)?
693            .with_timezone(self.tz);
694        Self::naive_date_from_items(input, fmt_items!("%Y-%m-%d"))
695            .ok()
696            .map(|parsed| parsed.and_time(now.time()))
697            .and_then(|datetime| self.tz.from_local_datetime(&datetime).single())
698            .map(|at_tz| at_tz.with_timezone(&Utc))
699            .map(Ok)
700    }
701
702    // yyyy-mm-dd z
703    // - 2021-02-21 PST
704    // - 2021-02-21 UTC
705    // - 2020-07-20+08:00 (yyyy-mm-dd-07:00)
706    #[inline]
707    fn ymd_z(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
708        // Fast pre-filter: bare date "YYYY-MM-DD" is exactly 10 chars; timezone appended = longer
709        if input.len() <= 10 {
710            return None;
711        }
712        let re = regex! {r"^\d{4}-\d{2}-\d{2}(?P<tz>\s*[+-:a-zA-Z0-9]{3,6})$"
713        };
714        if let Some(caps) = re.with(|r| r.captures(input))
715            && let Some(matched_tz) = caps.name("tz")
716        {
717            return match timezone::parse(matched_tz.as_str().trim()) {
718                Ok(offset) => {
719                    let now = Utc::now()
720                        .date()
721                        .and_time(self.default_time)?
722                        .with_timezone(&offset);
723                    Self::naive_date_from_items(input, fmt_items!("%Y-%m-%d %Z"))
724                        .ok()
725                        .map(|parsed| parsed.and_time(now.time()))
726                        .and_then(|datetime| offset.from_local_datetime(&datetime).single())
727                        .map(|at_tz| at_tz.with_timezone(&Utc))
728                        .map(Ok)
729                }
730                Err(err) => Some(Err(err)),
731            };
732        }
733        None
734    }
735
736    // yyyy-mon-dd
737    // - 2021-Feb-21
738    #[inline]
739    fn month_ymd(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
740        let re = regex! {r"^\d{4}-\w{3,9}-\d{2}$"
741        };
742        if !re.with(|r| r.is_match(input)) {
743            return None;
744        }
745
746        let now = Utc::now()
747            .date()
748            .and_time(self.default_time)?
749            .with_timezone(self.tz);
750        Self::naive_date_from_items(input, fmt_items!("%Y-%m-%d"))
751            .or_else(|_| Self::naive_date_from_items(input, fmt_items!("%Y-%b-%d")))
752            .ok()
753            .map(|parsed| parsed.and_time(now.time()))
754            .and_then(|datetime| self.tz.from_local_datetime(&datetime).single())
755            .map(|at_tz| at_tz.with_timezone(&Utc))
756            .map(Ok)
757    }
758
759    // Mon dd, yyyy, hh:mm:ss
760    // - May 8, 2009 5:57:51 PM
761    // - September 17, 2012 10:09am
762    // - September 17, 2012, 10:10:09
763    #[inline]
764    fn month_mdy_hms(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
765        let re = regex! {
766                r"^[a-zA-Z]{3,9}\.?\s+\d{1,2},\s+\d{2,4},?\s+\d{1,2}:\d{2}(?::\d{2})?\s*(?:am|pm|AM|PM)?$"
767        };
768        if !re.with(|r| r.is_match(input)) {
769            return None;
770        }
771
772        // The regex above enforces \s+ after any comma or period, so removing bare ',' or '.'
773        // is equivalent to the previous `replace(", ", " ").replace(". ", " ")` for all
774        // inputs that reach this point — marginally-malformed inputs (e.g. "May 27,2012 …")
775        // still fail to parse after stripping because the digits run together.
776        let mut buf = [0_u8; NORMALIZE_SCRATCH];
777        let fallback;
778        let dt = if let Some(s) = normalize_into(input, &mut buf, b",.", false) {
779            s
780        } else {
781            fallback = input.replace([',', '.'], "");
782            fallback.as_str()
783        };
784        // Classify `dt`, not `input`: the regex admits a period after an
785        // abbreviated month ("Sept. 17, 2012"), which would otherwise read as
786        // fractional seconds. This family's regex has no fractional-seconds
787        // group at all, and the strip removes any period regardless, so the
788        // two fraction-bearing shapes cannot occur — and never had a format.
789        let items = match time_shape(dt) {
790            TimeShape::Hms => fmt_items!("%B %d %Y %H:%M:%S"),
791            TimeShape::Hm => fmt_items!("%B %d %Y %H:%M"),
792            TimeShape::ImsP => fmt_items!("%B %d %Y %I:%M:%S %P"),
793            TimeShape::ImP => fmt_items!("%B %d %Y %I:%M %P"),
794            TimeShape::HmsF | TimeShape::HmsFP => return None,
795        };
796        self.dt_from_items(dt, items)
797            .ok()
798            .map(|at_tz| at_tz.with_timezone(&Utc))
799            .map(Ok)
800    }
801
802    // Mon dd, yyyy hh:mm:ss z
803    // - May 02, 2021 15:51:31 UTC
804    // - May 02, 2021 15:51 UTC
805    // - May 26, 2021, 12:49 AM PDT
806    // - September 17, 2012 at 10:09am PST
807    #[inline]
808    fn month_mdy_hms_z(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
809        // Fast pre-filter: must contain an isolated 4-digit year — eliminates "May 27 02:45:27".
810        // Skip the O(n) scan entirely for inputs too short to hold a valid month+day+year+time+tz.
811        if input.len() < 20 {
812            return None;
813        }
814        let bytes = input.as_bytes();
815        let has_year = (0..bytes.len().saturating_sub(3)).any(|i| {
816            bytes[i..i + 4].iter().all(u8::is_ascii_digit)
817                && (i == 0 || !bytes[i - 1].is_ascii_digit())
818                && bytes.get(i + 4).is_none_or(|b| !b.is_ascii_digit())
819        });
820        if !has_year {
821            return None;
822        }
823        // Fast path — see the twin comment in ymd_hms_z. This pattern's tz
824        // group requires whitespace (`\s+`), but the prefix's own trailing
825        // `\s*` may already have consumed it, so `tz_suffix` is told to accept
826        // the separator on either side of the boundary.
827        let prefix = regex! {
828                r"^[a-zA-Z]{3,9}\s+\d{1,2},?\s+\d{4}\s*,?(?:at)?\s+\d{2}:\d{2}(?::\d{2})?\s*(?:am|pm|AM|PM)?"
829        };
830        let fast_tz = prefix
831            .with(|r| r.find(input))
832            .and_then(|m| tz_suffix(input, m.end(), true));
833
834        let re = regex! {
835                r"^[a-zA-Z]{3,9}\s+\d{1,2},?\s+\d{4}\s*,?(?:at)?\s+\d{2}:\d{2}(?::\d{2})?\s*(?:am|pm|AM|PM)?(?P<tz>\s+[+-:a-zA-Z0-9]{3,6})$",
836        };
837        if let Some(tz) = fast_tz.or_else(|| {
838            re.with(|r| r.captures(input))
839                .and_then(|caps| caps.name("tz").map(|m| m.as_str().trim()))
840        }) {
841            let parse_from_str = Self::naive_dt_from_items;
842            return match timezone::parse(tz) {
843                Ok(offset) => {
844                    let mut buf = [0_u8; NORMALIZE_SCRATCH];
845                    let fallback;
846                    let dt: &str = if let Some(s) = normalize_into(input, &mut buf, b",", true) {
847                        s
848                    } else {
849                        let mut owned = input.replace(',', "");
850                        if let Some(pos) = owned.find("at") {
851                            owned.replace_range(pos..pos + 2, "");
852                        }
853                        fallback = owned;
854                        fallback.as_str()
855                    };
856                    parse_from_str(dt, fmt_items!("%B %d %Y %H:%M:%S %Z"))
857                        .or_else(|_| parse_from_str(dt, fmt_items!("%B %d %Y %H:%M %Z")))
858                        .or_else(|_| parse_from_str(dt, fmt_items!("%B %d %Y %I:%M:%S %P %Z")))
859                        .or_else(|_| parse_from_str(dt, fmt_items!("%B %d %Y %I:%M %P %Z")))
860                        .ok()
861                        .and_then(|parsed| offset.from_local_datetime(&parsed).single())
862                        .map(|datetime| datetime.with_timezone(&Utc))
863                        .map(Ok)
864                }
865                Err(err) => Some(Err(err)),
866            };
867        }
868        None
869    }
870
871    // Mon dd, yyyy
872    // - May 25, 2021
873    // - oct 7, 1970
874    // - oct 7, 70
875    // - oct. 7, 1970
876    // - oct. 7, 70
877    // - October 7, 1970
878    #[inline]
879    fn month_mdy(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
880        let re = regex! {r"^[a-zA-Z]{3,9}\.?\s+\d{1,2},\s+\d{2,4}$"
881        };
882        if !re.with(|r| r.is_match(input)) {
883            return None;
884        }
885
886        let now = Utc::now()
887            .date()
888            .and_time(self.default_time)?
889            .with_timezone(self.tz);
890        // The regex above enforces \s+ after any comma or period, so removing bare ',' or '.'
891        // is equivalent to the previous `replace(", ", " ").replace(". ", " ")` for all
892        // inputs that reach this point.
893        let mut buf = [0_u8; NORMALIZE_SCRATCH];
894        let fallback;
895        let dt = if let Some(s) = normalize_into(input, &mut buf, b",.", false) {
896            s
897        } else {
898            fallback = input.replace([',', '.'], "");
899            fallback.as_str()
900        };
901        Self::naive_date_from_items(dt, fmt_items!("%B %d %y"))
902            .or_else(|_| Self::naive_date_from_items(dt, fmt_items!("%B %d %Y")))
903            .ok()
904            .map(|parsed| parsed.and_time(now.time()))
905            .and_then(|datetime| self.tz.from_local_datetime(&datetime).single())
906            .map(|at_tz| at_tz.with_timezone(&Utc))
907            .map(Ok)
908    }
909
910    // dd Mon yyyy hh:mm:ss
911    // - 12 Feb 2006, 19:17
912    // - 12 Feb 2006 19:17
913    // - 14 May 2019 19:11:40.164
914    #[inline]
915    fn month_dmy_hms(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
916        // Fast pre-filter: time component always contains ':', skip regex for date-only inputs.
917        if !input.as_bytes().contains(&b':') {
918            return None;
919        }
920        let re = regex! {
921                r"^\d{1,2}\s+[a-zA-Z]{3,9}\s+\d{2,4},?\s+\d{1,2}:[0-9]{2}(?::[0-9]{2})?(?:\.[0-9]{1,9})?$"
922        };
923        if !re.with(|r| r.is_match(input)) {
924            return None;
925        }
926
927        let mut buf = [0_u8; NORMALIZE_SCRATCH];
928        let fallback;
929        let dt = if let Some(s) = normalize_into(input, &mut buf, b",", false) {
930            s
931        } else {
932            fallback = input.replace(',', "");
933            fallback.as_str()
934        };
935        // This family's regex has no am/pm alternative, so the AM/PM shapes
936        // cannot occur here. The chain previously ended in `%I:%M:%S %P` and
937        // `%I:%M %P`, which were therefore unreachable; dropping them changes
938        // no result.
939        let items = match time_shape(dt) {
940            TimeShape::Hms => fmt_items!("%d %B %Y %H:%M:%S"),
941            TimeShape::Hm => fmt_items!("%d %B %Y %H:%M"),
942            TimeShape::HmsF => fmt_items!("%d %B %Y %H:%M:%S%.f"),
943            TimeShape::ImP | TimeShape::ImsP | TimeShape::HmsFP => return None,
944        };
945        self.dt_from_items(dt, items)
946            .ok()
947            .map(|at_tz| at_tz.with_timezone(&Utc))
948            .map(Ok)
949    }
950
951    // dd Mon yyyy
952    // - 7 oct 70
953    // - 7 oct 1970
954    // - 03 February 2013
955    // - 1 July 2013
956    #[inline]
957    fn month_dmy(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
958        let re = regex! {r"^\d{1,2}\s+[a-zA-Z]{3,9}\s+\d{2,4}$"
959        };
960        if !re.with(|r| r.is_match(input)) {
961            return None;
962        }
963
964        let now = Utc::now()
965            .date()
966            .and_time(self.default_time)?
967            .with_timezone(self.tz);
968        // Fast path: if the last 4 bytes are all digits and preceded by a space, it's a
969        // 4-digit year — skip the always-failing %d %B %y (2-digit year) attempt.
970        let bytes = input.as_bytes();
971        let len = bytes.len();
972        let four_digit_year = len >= 5
973            && bytes[len - 4..].iter().all(u8::is_ascii_digit)
974            && bytes[len - 5].is_ascii_whitespace();
975        let parsed = if four_digit_year {
976            Self::naive_date_from_items(input, fmt_items!("%d %B %Y"))
977        } else {
978            Self::naive_date_from_items(input, fmt_items!("%d %B %y"))
979                .or_else(|_| Self::naive_date_from_items(input, fmt_items!("%d %B %Y")))
980        };
981        parsed
982            .ok()
983            .map(|parsed| parsed.and_time(now.time()))
984            .and_then(|datetime| self.tz.from_local_datetime(&datetime).single())
985            .map(|at_tz| at_tz.with_timezone(&Utc))
986            .map(Ok)
987    }
988
989    // mm/dd/yyyy hh:mm:ss
990    // - 4/8/2014 22:05
991    // - 04/08/2014 22:05
992    // - 4/8/14 22:05
993    // - 04/2/2014 03:00:51
994    // - 8/8/1965 12:00:00 AM
995    // - 8/8/1965 01:00:01 PM
996    // - 8/8/1965 01:00 PM
997    // - 8/8/1965 1:00 PM
998    // - 8/8/1965 12:00 AM
999    // - 4/02/2014 03:00:51
1000    // - 03/19/2012 10:11:59
1001    // - 03/19/2012 10:11:59.3186369
1002    // - 03/19/2012 10:11:59.318 PM
1003    #[inline]
1004    fn slash_mdy_hms(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
1005        let re = regex! {
1006                r"^\d{1,2}/\d{1,2}/\d{2,4}\s+\d{1,2}:\d{2}(?::\d{2})?(?:\.\d{1,9})?\s*(?:am|pm|AM|PM)?$"
1007        };
1008        if !re.with(|r| r.is_match(input)) {
1009            return None;
1010        }
1011
1012        // Dispatch on year width (see slash_year_is_two_digits) and on the
1013        // time shape (see time_shape) instead of trying all 10 formats. This
1014        // picks the one format that can match, so `MM/DD/YYYY hh:mm:ss AM/PM`
1015        // no longer burns three guaranteed-failing attempts before the fourth.
1016        let items = match (
1017            slash_year_is_two_digits(input.as_bytes()),
1018            time_shape(input),
1019        ) {
1020            (true, TimeShape::Hms) => fmt_items!("%m/%d/%y %H:%M:%S"),
1021            (true, TimeShape::Hm) => fmt_items!("%m/%d/%y %H:%M"),
1022            (true, TimeShape::HmsF) => fmt_items!("%m/%d/%y %H:%M:%S%.f"),
1023            (true, TimeShape::ImsP | TimeShape::HmsFP) => {
1024                fmt_items!("%m/%d/%y %I:%M:%S%.f %P")
1025            }
1026            (true, TimeShape::ImP) => fmt_items!("%m/%d/%y %I:%M %P"),
1027            (false, TimeShape::Hms) => fmt_items!("%m/%d/%Y %H:%M:%S"),
1028            (false, TimeShape::Hm) => fmt_items!("%m/%d/%Y %H:%M"),
1029            (false, TimeShape::HmsF) => fmt_items!("%m/%d/%Y %H:%M:%S%.f"),
1030            (false, TimeShape::ImsP | TimeShape::HmsFP) => {
1031                fmt_items!("%m/%d/%Y %I:%M:%S%.f %P")
1032            }
1033            (false, TimeShape::ImP) => fmt_items!("%m/%d/%Y %I:%M %P"),
1034        };
1035        self.dt_from_items(input, items)
1036            .ok()
1037            .map(|at_tz| at_tz.with_timezone(&Utc))
1038            .map(Ok)
1039    }
1040
1041    // dd/mm/yyyy hh:mm:ss
1042    // - 8/4/2014 22:05
1043    // - 08/04/2014 22:05
1044    // - 8/4/14 22:05
1045    // - 2/04/2014 03:00:51
1046    // - 8/8/1965 12:00:00 AM
1047    // - 8/8/1965 01:00:01 PM
1048    // - 8/8/1965 01:00 PM
1049    // - 8/8/1965 1:00 PM
1050    // - 8/8/1965 12:00 AM
1051    // - 02/4/2014 03:00:51
1052    // - 19/03/2012 10:11:59
1053    // - 19/03/2012 10:11:59.3186369
1054    // - 19/03/2012 10:11:59.318 PM
1055    #[inline]
1056    fn slash_dmy_hms(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
1057        let re = regex! {
1058                r"^\d{1,2}/\d{1,2}/\d{2,4}\s+\d{1,2}:\d{2}(?::\d{2})?(?:\.\d{1,9})?\s*(?:am|pm|AM|PM)?$"
1059        };
1060        if !re.with(|r| r.is_match(input)) {
1061            return None;
1062        }
1063
1064        // Dispatch on year width and time shape — see the twin comment in
1065        // slash_mdy_hms.
1066        let items = match (
1067            slash_year_is_two_digits(input.as_bytes()),
1068            time_shape(input),
1069        ) {
1070            (true, TimeShape::Hms) => fmt_items!("%d/%m/%y %H:%M:%S"),
1071            (true, TimeShape::Hm) => fmt_items!("%d/%m/%y %H:%M"),
1072            (true, TimeShape::HmsF) => fmt_items!("%d/%m/%y %H:%M:%S%.f"),
1073            (true, TimeShape::ImsP | TimeShape::HmsFP) => {
1074                fmt_items!("%d/%m/%y %I:%M:%S%.f %P")
1075            }
1076            (true, TimeShape::ImP) => fmt_items!("%d/%m/%y %I:%M %P"),
1077            (false, TimeShape::Hms) => fmt_items!("%d/%m/%Y %H:%M:%S"),
1078            (false, TimeShape::Hm) => fmt_items!("%d/%m/%Y %H:%M"),
1079            (false, TimeShape::HmsF) => fmt_items!("%d/%m/%Y %H:%M:%S%.f"),
1080            (false, TimeShape::ImsP | TimeShape::HmsFP) => {
1081                fmt_items!("%d/%m/%Y %I:%M:%S%.f %P")
1082            }
1083            (false, TimeShape::ImP) => fmt_items!("%d/%m/%Y %I:%M %P"),
1084        };
1085        self.dt_from_items(input, items)
1086            .ok()
1087            .map(|at_tz| at_tz.with_timezone(&Utc))
1088            .map(Ok)
1089    }
1090
1091    // mm/dd/yyyy
1092    // - 3/31/2014
1093    // - 03/31/2014
1094    // - 08/21/71
1095    // - 8/1/71
1096    #[inline]
1097    fn slash_mdy(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
1098        let re = regex! {r"^\d{1,2}/\d{1,2}/\d{2,4}$"
1099        };
1100        if !re.with(|r| r.is_match(input)) {
1101            return None;
1102        }
1103
1104        let now = Utc::now()
1105            .date()
1106            .and_time(self.default_time)?
1107            .with_timezone(self.tz);
1108        let fmt = if slash_year_is_two_digits(input.as_bytes()) {
1109            fmt_items!("%m/%d/%y")
1110        } else {
1111            fmt_items!("%m/%d/%Y")
1112        };
1113        Self::naive_date_from_items(input, fmt)
1114            .ok()
1115            .map(|parsed| parsed.and_time(now.time()))
1116            .and_then(|datetime| self.tz.from_local_datetime(&datetime).single())
1117            .map(|at_tz| at_tz.with_timezone(&Utc))
1118            .map(Ok)
1119    }
1120
1121    // dd/mm/yyyy
1122    // - 31/3/2014
1123    // - 31/03/2014
1124    // - 21/08/71
1125    // - 1/8/71
1126    #[inline]
1127    fn slash_dmy(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
1128        let re = regex! {r"^[0-9]{1,2}/[0-9]{1,2}/[0-9]{2,4}$"
1129        };
1130        if !re.with(|r| r.is_match(input)) {
1131            return None;
1132        }
1133
1134        let now = Utc::now()
1135            .date()
1136            .and_time(self.default_time)?
1137            .with_timezone(self.tz);
1138        let fmt = if slash_year_is_two_digits(input.as_bytes()) {
1139            fmt_items!("%d/%m/%y")
1140        } else {
1141            fmt_items!("%d/%m/%Y")
1142        };
1143        Self::naive_date_from_items(input, fmt)
1144            .ok()
1145            .map(|parsed| parsed.and_time(now.time()))
1146            .and_then(|datetime| self.tz.from_local_datetime(&datetime).single())
1147            .map(|at_tz| at_tz.with_timezone(&Utc))
1148            .map(Ok)
1149    }
1150
1151    // yyyy/mm/dd hh:mm:ss
1152    // - 2014/4/8 22:05
1153    // - 2014/04/08 22:05
1154    // - 2014/04/2 03:00:51
1155    // - 2014/4/02 03:00:51
1156    // - 2012/03/19 10:11:59
1157    // - 2012/03/19 10:11:59.3186369
1158    // - 2012/03/19 10:11:59.318 PM
1159    #[inline]
1160    fn slash_ymd_hms(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
1161        let re = regex! {
1162                r"^[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}\s+[0-9]{1,2}:[0-9]{2}(?::[0-9]{2})?(?:\.[0-9]{1,9})?\s*(?:am|pm|AM|PM)?$"
1163        };
1164        if !re.with(|r| r.is_match(input)) {
1165            return None;
1166        }
1167
1168        let items = match time_shape(input) {
1169            TimeShape::Hms => fmt_items!("%Y/%m/%d %H:%M:%S"),
1170            TimeShape::Hm => fmt_items!("%Y/%m/%d %H:%M"),
1171            TimeShape::HmsF => fmt_items!("%Y/%m/%d %H:%M:%S%.f"),
1172            TimeShape::ImsP | TimeShape::HmsFP => fmt_items!("%Y/%m/%d %I:%M:%S%.f %P"),
1173            TimeShape::ImP => fmt_items!("%Y/%m/%d %I:%M %P"),
1174        };
1175        self.dt_from_items(input, items)
1176            .ok()
1177            .map(|at_tz| at_tz.with_timezone(&Utc))
1178            .map(Ok)
1179    }
1180
1181    // yyyy/mm/dd
1182    // - 2014/3/31
1183    // - 2014/03/31
1184    #[inline]
1185    fn slash_ymd(&self, input: &str) -> Option<Result<DateTime<Utc>>> {
1186        let re = regex! {r"^[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}$"
1187        };
1188        if !re.with(|r| r.is_match(input)) {
1189            return None;
1190        }
1191
1192        let now = Utc::now()
1193            .date()
1194            .and_time(self.default_time)?
1195            .with_timezone(self.tz);
1196        Self::naive_date_from_items(input, fmt_items!("%Y/%m/%d"))
1197            .ok()
1198            .map(|parsed| parsed.and_time(now.time()))
1199            .and_then(|datetime| self.tz.from_local_datetime(&datetime).single())
1200            .map(|at_tz| at_tz.with_timezone(&Utc))
1201            .map(Ok)
1202    }
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use super::*;
1208    use regex::Regex;
1209
1210    #[test]
1211    fn unix_timestamp() {
1212        let parse = Parse::new(&Utc, Utc::now().time());
1213
1214        let test_cases = vec![
1215            ("0", Utc.ymd(1970, 1, 1).and_hms(0, 0, 0)),
1216            ("0000000000", Utc.ymd(1970, 1, 1).and_hms(0, 0, 0)),
1217            ("0000000000000", Utc.ymd(1970, 1, 1).and_hms(0, 0, 0)),
1218            ("0000000000000000000", Utc.ymd(1970, 1, 1).and_hms(0, 0, 0)),
1219            ("-770172300", Utc.ymd(1945, 8, 5).and_hms(23, 15, 0)),
1220            (
1221                "1671673426.123456789",
1222                Utc.ymd(2022, 12, 22).and_hms_nano(1, 43, 46, 123456768),
1223            ),
1224            ("1511648546", Utc.ymd(2017, 11, 25).and_hms(22, 22, 26)),
1225            (
1226                "1620036248.420",
1227                Utc.ymd(2021, 5, 3).and_hms_milli(10, 4, 8, 420),
1228            ),
1229            (
1230                "1620036248.717915136",
1231                Utc.ymd(2021, 5, 3).and_hms_nano(10, 4, 8, 717915136),
1232            ),
1233        ];
1234
1235        for &(input, want) in test_cases.iter() {
1236            assert_eq!(
1237                parse.unix_timestamp(input).unwrap().unwrap(),
1238                want,
1239                "unix_timestamp/{}",
1240                input
1241            )
1242        }
1243        assert!(parse.unix_timestamp("15116").is_some());
1244        assert!(
1245            parse
1246                .unix_timestamp("16200248727179150001620024872717915000") //DevSkim: ignore DS173237
1247                .is_some()
1248        );
1249        assert!(parse.unix_timestamp("not-a-ts").is_none());
1250        // Non-finite floats must be rejected, whether caught by the lead-byte
1251        // pre-filter (bare `inf`/`nan`) or the is_finite check (signed forms).
1252        for input in [
1253            "inf", "nan", "INF", "NaN", "infinity", "+inf", "-inf", "-nan",
1254        ] {
1255            assert!(
1256                parse.unix_timestamp(input).is_none(),
1257                "unix_timestamp must reject non-finite {input}"
1258            );
1259        }
1260    }
1261
1262    #[test]
1263    fn rfc3339() {
1264        let parse = Parse::new(&Utc, Utc::now().time());
1265
1266        let test_cases = [
1267            (
1268                "2021-05-01T01:17:02.604456Z",
1269                Utc.ymd(2021, 5, 1).and_hms_nano(1, 17, 2, 604456000),
1270            ),
1271            (
1272                "2017-11-25T22:34:50Z",
1273                Utc.ymd(2017, 11, 25).and_hms(22, 34, 50),
1274            ),
1275        ];
1276
1277        for &(input, want) in test_cases.iter() {
1278            assert_eq!(
1279                parse.rfc3339(input).unwrap().unwrap(),
1280                want,
1281                "rfc3339/{}",
1282                input
1283            )
1284        }
1285        assert!(parse.rfc3339("2017-11-25 22:34:50").is_none());
1286        assert!(parse.rfc3339("not-date-time").is_none());
1287    }
1288
1289    #[test]
1290    fn rfc2822() {
1291        let parse = Parse::new(&Utc, Utc::now().time());
1292
1293        let test_cases = [
1294            (
1295                "Wed, 02 Jun 2021 06:31:39 GMT",
1296                Utc.ymd(2021, 6, 2).and_hms(6, 31, 39),
1297            ),
1298            (
1299                "Wed, 02 Jun 2021 06:31:39 PDT",
1300                Utc.ymd(2021, 6, 2).and_hms(13, 31, 39),
1301            ),
1302        ];
1303
1304        for &(input, want) in test_cases.iter() {
1305            assert_eq!(
1306                parse.rfc2822(input).unwrap().unwrap(),
1307                want,
1308                "rfc2822/{}",
1309                input
1310            )
1311        }
1312        assert!(parse.rfc2822("02 Jun 2021 06:31:39").is_none());
1313        assert!(parse.rfc2822("not-date-time").is_none());
1314    }
1315
1316    #[test]
1317    fn ymd_hms() {
1318        let parse = Parse::new(&Utc, Utc::now().time());
1319
1320        let test_cases = [
1321            ("2021-04-30 21:14", Utc.ymd(2021, 4, 30).and_hms(21, 14, 0)),
1322            (
1323                "2021-04-30 21:14:10",
1324                Utc.ymd(2021, 4, 30).and_hms(21, 14, 10),
1325            ),
1326            (
1327                "2021-04-30 21:14:10.052282",
1328                Utc.ymd(2021, 4, 30).and_hms_micro(21, 14, 10, 52282),
1329            ),
1330            (
1331                "2014-04-26 05:24:37 PM",
1332                Utc.ymd(2014, 4, 26).and_hms(17, 24, 37),
1333            ),
1334            (
1335                "2014-04-26 17:24:37.123",
1336                Utc.ymd(2014, 4, 26).and_hms_milli(17, 24, 37, 123),
1337            ),
1338            (
1339                "2014-04-26 17:24:37.3186369",
1340                Utc.ymd(2014, 4, 26).and_hms_nano(17, 24, 37, 318636900),
1341            ),
1342            (
1343                "2012-08-03 18:31:59.257000000",
1344                Utc.ymd(2012, 8, 3).and_hms_nano(18, 31, 59, 257000000),
1345            ),
1346            // ISO 8601 with 'T' separator and no timezone (naive wall-clock).
1347            // Must agree with the space-separated form on the same wall-clock instant.
1348            ("2020-01-15T08:00", Utc.ymd(2020, 1, 15).and_hms(8, 0, 0)),
1349            ("2020-01-15T08:00:00", Utc.ymd(2020, 1, 15).and_hms(8, 0, 0)),
1350            (
1351                "2020-01-15T08:00:00.123",
1352                Utc.ymd(2020, 1, 15).and_hms_milli(8, 0, 0, 123),
1353            ),
1354            (
1355                "2020-01-15T08:00:00.123456",
1356                Utc.ymd(2020, 1, 15).and_hms_micro(8, 0, 0, 123456),
1357            ),
1358            (
1359                "2020-01-15T08:00:00.123456789",
1360                Utc.ymd(2020, 1, 15).and_hms_nano(8, 0, 0, 123456789),
1361            ),
1362        ];
1363
1364        for &(input, want) in test_cases.iter() {
1365            assert_eq!(
1366                parse.ymd_hms(input).unwrap().unwrap(),
1367                want,
1368                "ymd_hms/{}",
1369                input
1370            )
1371        }
1372        assert!(parse.ymd_hms("not-date-time").is_none());
1373
1374        // T and space separators must produce the same instant.
1375        let t_form = parse.ymd_hms("2020-01-15T08:00:00").unwrap().unwrap();
1376        let space_form = parse.ymd_hms("2020-01-15 08:00:00").unwrap().unwrap();
1377        assert_eq!(t_form, space_form, "T-separator vs space disagree");
1378    }
1379
1380    #[test]
1381    fn ymd_hms_z() {
1382        let parse = Parse::new(&Utc, Utc::now().time());
1383
1384        let test_cases = [
1385            (
1386                "2017-11-25 13:31:15 PST",
1387                Utc.ymd(2017, 11, 25).and_hms(21, 31, 15),
1388            ),
1389            (
1390                "2017-11-25 13:31 PST",
1391                Utc.ymd(2017, 11, 25).and_hms(21, 31, 0),
1392            ),
1393            (
1394                "2014-12-16 06:20:00 UTC",
1395                Utc.ymd(2014, 12, 16).and_hms(6, 20, 0),
1396            ),
1397            (
1398                "2014-12-16 06:20:00 GMT",
1399                Utc.ymd(2014, 12, 16).and_hms(6, 20, 0),
1400            ),
1401            (
1402                "2014-04-26 13:13:43 +0800",
1403                Utc.ymd(2014, 4, 26).and_hms(5, 13, 43),
1404            ),
1405            (
1406                "2014-04-26 13:13:44 +09:00",
1407                Utc.ymd(2014, 4, 26).and_hms(4, 13, 44),
1408            ),
1409            (
1410                "2012-08-03 18:31:59.257000000 +0000",
1411                Utc.ymd(2012, 8, 3).and_hms_nano(18, 31, 59, 257000000),
1412            ),
1413            (
1414                "2015-09-30 18:48:56.35272715 UTC",
1415                Utc.ymd(2015, 9, 30).and_hms_nano(18, 48, 56, 352727150),
1416            ),
1417        ];
1418
1419        for &(input, want) in test_cases.iter() {
1420            assert_eq!(
1421                parse.ymd_hms_z(input).unwrap().unwrap(),
1422                want,
1423                "ymd_hms_z/{}",
1424                input
1425            )
1426        }
1427        assert!(parse.ymd_hms_z("not-date-time").is_none());
1428        // Pre-filter boundary: exactly 16 chars is rejected by length guard (< 17)
1429        assert!(parse.ymd_hms_z("2021-04-30 21:14").is_none()); // 16 chars, rejected by length guard
1430        // 17 chars but byte[10] is not whitespace — rejected by whitespace check
1431        assert!(parse.ymd_hms_z("2021-04-30X21:14Z").is_none()); // 17 chars, byte[10]='X' not space
1432        // 17 chars with whitespace at byte[10] proceeds to regex but regex rejects malformed input
1433        assert!(parse.ymd_hms_z("2021-04-30 21:1XZ").is_none()); // 17 chars, byte[10]=' ', regex rejects
1434    }
1435
1436    #[test]
1437    fn ymd() {
1438        let parse = Parse::new(&Utc, Utc::now().time());
1439
1440        let test_cases = [(
1441            "2021-02-21",
1442            Utc.ymd(2021, 2, 21).and_time(Utc::now().time()),
1443        )];
1444
1445        for &(input, want) in test_cases.iter() {
1446            assert_eq!(
1447                parse
1448                    .ymd(input)
1449                    .unwrap()
1450                    .unwrap()
1451                    .trunc_subsecs(0)
1452                    .with_second(0)
1453                    .unwrap(),
1454                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1455                "ymd/{}",
1456                input
1457            )
1458        }
1459        assert!(parse.ymd("not-date-time").is_none());
1460    }
1461
1462    #[test]
1463    fn ymd_z() {
1464        let parse = Parse::new(&Utc, Utc::now().time());
1465        let now_at_pst = Utc::now().with_timezone(&FixedOffset::west(8 * 3600));
1466        let now_at_cst = Utc::now().with_timezone(&FixedOffset::east(8 * 3600));
1467
1468        let test_cases = [
1469            (
1470                "2021-02-21 PST",
1471                FixedOffset::west(8 * 3600)
1472                    .ymd(2021, 2, 21)
1473                    .and_time(now_at_pst.time())
1474                    .map(|dt| dt.with_timezone(&Utc)),
1475            ),
1476            (
1477                "2021-02-21 UTC",
1478                FixedOffset::west(0)
1479                    .ymd(2021, 2, 21)
1480                    .and_time(Utc::now().time())
1481                    .map(|dt| dt.with_timezone(&Utc)),
1482            ),
1483            (
1484                "2020-07-20+08:00",
1485                FixedOffset::east(8 * 3600)
1486                    .ymd(2020, 7, 20)
1487                    .and_time(now_at_cst.time())
1488                    .map(|dt| dt.with_timezone(&Utc)),
1489            ),
1490        ];
1491
1492        for &(input, want) in test_cases.iter() {
1493            assert_eq!(
1494                parse
1495                    .ymd_z(input)
1496                    .unwrap()
1497                    .unwrap()
1498                    .trunc_subsecs(0)
1499                    .with_second(0)
1500                    .unwrap(),
1501                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1502                "ymd_z/{}",
1503                input
1504            )
1505        }
1506        assert!(parse.ymd_z("not-date-time").is_none());
1507        // Pre-filter boundary: exactly 10 chars (bare date) is rejected (<= 10 guard), 11+ proceeds
1508        assert!(parse.ymd_z("2021-02-21").is_none()); // exactly 10 chars, rejected
1509        assert!(parse.ymd_z("2021-02-21X").is_none()); // 11 chars, proceeds to regex but regex rejects
1510    }
1511
1512    #[test]
1513    fn month_ymd() {
1514        let parse = Parse::new(&Utc, Utc::now().time());
1515
1516        let test_cases = [(
1517            "2021-Feb-21",
1518            Utc.ymd(2021, 2, 21).and_time(Utc::now().time()),
1519        )];
1520
1521        for &(input, want) in test_cases.iter() {
1522            assert_eq!(
1523                parse
1524                    .month_ymd(input)
1525                    .unwrap()
1526                    .unwrap()
1527                    .trunc_subsecs(0)
1528                    .with_second(0)
1529                    .unwrap(),
1530                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1531                "month_ymd/{}",
1532                input
1533            )
1534        }
1535        assert!(parse.month_ymd("not-date-time").is_none());
1536    }
1537
1538    #[test]
1539    fn month_mdy_hms() {
1540        let parse = Parse::new(&Utc, Utc::now().time());
1541
1542        let test_cases = [
1543            (
1544                "May 8, 2009 5:57:51 PM",
1545                Utc.ymd(2009, 5, 8).and_hms(17, 57, 51),
1546            ),
1547            (
1548                "September 17, 2012 10:09am",
1549                Utc.ymd(2012, 9, 17).and_hms(10, 9, 0),
1550            ),
1551            (
1552                "September 17, 2012, 10:10:09",
1553                Utc.ymd(2012, 9, 17).and_hms(10, 10, 9),
1554            ),
1555        ];
1556
1557        for &(input, want) in test_cases.iter() {
1558            assert_eq!(
1559                parse.month_mdy_hms(input).unwrap().unwrap(),
1560                want,
1561                "month_mdy_hms/{}",
1562                input
1563            )
1564        }
1565        assert!(parse.month_mdy_hms("not-date-time").is_none());
1566    }
1567
1568    #[test]
1569    fn month_mdy_hms_z() {
1570        let parse = Parse::new(&Utc, Utc::now().time());
1571
1572        let test_cases = [
1573            (
1574                "May 02, 2021 15:51:31 UTC",
1575                Utc.ymd(2021, 5, 2).and_hms(15, 51, 31),
1576            ),
1577            (
1578                "May 02, 2021 15:51 UTC",
1579                Utc.ymd(2021, 5, 2).and_hms(15, 51, 0),
1580            ),
1581            (
1582                "May 26, 2021, 12:49 AM PDT",
1583                Utc.ymd(2021, 5, 26).and_hms(7, 49, 0),
1584            ),
1585            (
1586                "September 17, 2012 at 10:09am PST",
1587                Utc.ymd(2012, 9, 17).and_hms(18, 9, 0),
1588            ),
1589        ];
1590
1591        for &(input, want) in test_cases.iter() {
1592            assert_eq!(
1593                parse.month_mdy_hms_z(input).unwrap().unwrap(),
1594                want,
1595                "month_mdy_hms_z/{}",
1596                input
1597            )
1598        }
1599        assert!(parse.month_mdy_hms_z("not-date-time").is_none());
1600        // Pre-filter: 20+ chars required; no isolated 4-digit year → has_year=false, rejected
1601        assert!(parse.month_mdy_hms_z("May 27, 02:45:27 XX PST").is_none()); // 23 chars, no 4-digit year
1602        // Pre-filter: 20+ chars with isolated 4-digit sequence → has_year=true, regex rejects format
1603        assert!(parse.month_mdy_hms_z("May 27 1234 something PST").is_none()); // 25 chars, has_year=true but regex rejects
1604    }
1605
1606    #[test]
1607    fn month_mdy() {
1608        let parse = Parse::new(&Utc, Utc::now().time());
1609
1610        let test_cases = [
1611            (
1612                "May 25, 2021",
1613                Utc.ymd(2021, 5, 25).and_time(Utc::now().time()),
1614            ),
1615            (
1616                "oct 7, 1970",
1617                Utc.ymd(1970, 10, 7).and_time(Utc::now().time()),
1618            ),
1619            (
1620                "oct 7, 70",
1621                Utc.ymd(1970, 10, 7).and_time(Utc::now().time()),
1622            ),
1623            (
1624                "oct. 7, 1970",
1625                Utc.ymd(1970, 10, 7).and_time(Utc::now().time()),
1626            ),
1627            (
1628                "oct. 7, 70",
1629                Utc.ymd(1970, 10, 7).and_time(Utc::now().time()),
1630            ),
1631            (
1632                "October 7, 1970",
1633                Utc.ymd(1970, 10, 7).and_time(Utc::now().time()),
1634            ),
1635        ];
1636
1637        for &(input, want) in test_cases.iter() {
1638            assert_eq!(
1639                parse
1640                    .month_mdy(input)
1641                    .unwrap()
1642                    .unwrap()
1643                    .trunc_subsecs(0)
1644                    .with_second(0)
1645                    .unwrap(),
1646                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1647                "month_mdy/{}",
1648                input
1649            )
1650        }
1651        assert!(parse.month_mdy("not-date-time").is_none());
1652    }
1653
1654    #[test]
1655    fn month_dmy_hms() {
1656        let parse = Parse::new(&Utc, Utc::now().time());
1657
1658        let test_cases = [
1659            (
1660                "12 Feb 2006, 19:17",
1661                Utc.ymd(2006, 2, 12).and_hms(19, 17, 0),
1662            ),
1663            ("12 Feb 2006 19:17", Utc.ymd(2006, 2, 12).and_hms(19, 17, 0)),
1664            (
1665                "14 May 2019 19:11:40.164",
1666                Utc.ymd(2019, 5, 14).and_hms_milli(19, 11, 40, 164),
1667            ),
1668        ];
1669
1670        for &(input, want) in test_cases.iter() {
1671            assert_eq!(
1672                parse.month_dmy_hms(input).unwrap().unwrap(),
1673                want,
1674                "month_dmy_hms/{}",
1675                input
1676            )
1677        }
1678        assert!(parse.month_dmy_hms("not-date-time").is_none());
1679    }
1680
1681    #[test]
1682    fn month_dmy() {
1683        let parse = Parse::new(&Utc, Utc::now().time());
1684
1685        let test_cases = [
1686            ("7 oct 70", Utc.ymd(1970, 10, 7).and_time(Utc::now().time())),
1687            (
1688                "7 oct 1970",
1689                Utc.ymd(1970, 10, 7).and_time(Utc::now().time()),
1690            ),
1691            (
1692                "03 February 2013",
1693                Utc.ymd(2013, 2, 3).and_time(Utc::now().time()),
1694            ),
1695            (
1696                "1 July 2013",
1697                Utc.ymd(2013, 7, 1).and_time(Utc::now().time()),
1698            ),
1699        ];
1700
1701        for &(input, want) in test_cases.iter() {
1702            assert_eq!(
1703                parse
1704                    .month_dmy(input)
1705                    .unwrap()
1706                    .unwrap()
1707                    .trunc_subsecs(0)
1708                    .with_second(0)
1709                    .unwrap(),
1710                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1711                "month_dmy/{}",
1712                input
1713            )
1714        }
1715        assert!(parse.month_dmy("not-date-time").is_none());
1716    }
1717
1718    // Explicitly tests the `four_digit_year` fast path in `month_dmy` (skips `%d %B %y`) and
1719    // the else-branch fallback that tries `%d %B %y` first then `%d %B %Y`.
1720    #[test]
1721    fn month_dmy_year_fast_path() {
1722        let parse = Parse::new(&Utc, Utc::now().time());
1723
1724        // Fast path: 4-digit year — `four_digit_year` is true, goes directly to `%d %B %Y`
1725        let four_digit = parse.month_dmy("14 May 2019").unwrap().unwrap();
1726        assert_eq!(four_digit.year(), 2019);
1727        assert_eq!(four_digit.month(), 5);
1728        assert_eq!(four_digit.day(), 14);
1729
1730        // Else-branch: 2-digit year — `four_digit_year` is false, tries `%d %B %y` first
1731        // chrono %y: 00–68 → 2000–2068, so "19" → 2019 (not 1919)
1732        let two_digit = parse.month_dmy("14 May 19").unwrap().unwrap();
1733        assert_eq!(two_digit.year(), 2019);
1734        assert_eq!(two_digit.month(), 5);
1735        assert_eq!(two_digit.day(), 14);
1736    }
1737
1738    #[test]
1739    fn slash_mdy_hms() {
1740        let parse = Parse::new(&Utc, Utc::now().time());
1741
1742        let test_cases = vec![
1743            ("4/8/2014 22:05", Utc.ymd(2014, 4, 8).and_hms(22, 5, 0)),
1744            ("04/08/2014 22:05", Utc.ymd(2014, 4, 8).and_hms(22, 5, 0)),
1745            ("4/8/14 22:05", Utc.ymd(2014, 4, 8).and_hms(22, 5, 0)),
1746            ("04/2/2014 03:00:51", Utc.ymd(2014, 4, 2).and_hms(3, 0, 51)),
1747            ("8/8/1965 12:00:00 AM", Utc.ymd(1965, 8, 8).and_hms(0, 0, 0)),
1748            (
1749                "8/8/1965 01:00:01 PM",
1750                Utc.ymd(1965, 8, 8).and_hms(13, 0, 1),
1751            ),
1752            ("8/8/1965 01:00 PM", Utc.ymd(1965, 8, 8).and_hms(13, 0, 0)),
1753            ("8/8/1965 1:00 PM", Utc.ymd(1965, 8, 8).and_hms(13, 0, 0)),
1754            ("8/8/1965 12:00 AM", Utc.ymd(1965, 8, 8).and_hms(0, 0, 0)),
1755            ("4/02/2014 03:00:51", Utc.ymd(2014, 4, 2).and_hms(3, 0, 51)),
1756            (
1757                "03/19/2012 10:11:59",
1758                Utc.ymd(2012, 3, 19).and_hms(10, 11, 59),
1759            ),
1760            (
1761                "03/19/2012 10:11:59.3186369",
1762                Utc.ymd(2012, 3, 19).and_hms_nano(10, 11, 59, 318636900),
1763            ),
1764        ];
1765
1766        for &(input, want) in test_cases.iter() {
1767            assert_eq!(
1768                parse.slash_mdy_hms(input).unwrap().unwrap(),
1769                want,
1770                "slash_mdy_hms/{}",
1771                input
1772            )
1773        }
1774        assert!(parse.slash_mdy_hms("not-date-time").is_none());
1775    }
1776
1777    #[test]
1778    fn slash_mdy() {
1779        let parse = Parse::new(&Utc, Utc::now().time());
1780
1781        let test_cases = [
1782            (
1783                "3/31/2014",
1784                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()),
1785            ),
1786            (
1787                "03/31/2014",
1788                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()),
1789            ),
1790            ("08/21/71", Utc.ymd(1971, 8, 21).and_time(Utc::now().time())),
1791            ("8/1/71", Utc.ymd(1971, 8, 1).and_time(Utc::now().time())),
1792        ];
1793
1794        for &(input, want) in test_cases.iter() {
1795            assert_eq!(
1796                parse
1797                    .slash_mdy(input)
1798                    .unwrap()
1799                    .unwrap()
1800                    .trunc_subsecs(0)
1801                    .with_second(0)
1802                    .unwrap(),
1803                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1804                "slash_mdy/{}",
1805                input
1806            )
1807        }
1808        assert!(parse.slash_mdy("not-date-time").is_none());
1809    }
1810
1811    #[test]
1812    fn slash_dmy() {
1813        let mut parse = Parse::new(&Utc, Utc::now().time());
1814
1815        let test_cases = [
1816            (
1817                "31/3/2014",
1818                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()),
1819            ),
1820            (
1821                "13/11/2014",
1822                Utc.ymd(2014, 11, 13).and_time(Utc::now().time()),
1823            ),
1824            ("21/08/71", Utc.ymd(1971, 8, 21).and_time(Utc::now().time())),
1825            ("1/8/71", Utc.ymd(1971, 8, 1).and_time(Utc::now().time())),
1826        ];
1827
1828        for &(input, want) in test_cases.iter() {
1829            assert_eq!(
1830                parse
1831                    .prefer_dmy(true)
1832                    .slash_dmy(input)
1833                    .unwrap()
1834                    .unwrap()
1835                    .trunc_subsecs(0)
1836                    .with_second(0)
1837                    .unwrap(),
1838                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1839                "slash_dmy/{}",
1840                input
1841            )
1842        }
1843        assert!(parse.slash_dmy("not-date-time").is_none());
1844    }
1845
1846    #[test]
1847    fn slash_ymd_hms() {
1848        let parse = Parse::new(&Utc, Utc::now().time());
1849
1850        let test_cases = [
1851            ("2014/4/8 22:05", Utc.ymd(2014, 4, 8).and_hms(22, 5, 0)),
1852            ("2014/04/08 22:05", Utc.ymd(2014, 4, 8).and_hms(22, 5, 0)),
1853            ("2014/04/2 03:00:51", Utc.ymd(2014, 4, 2).and_hms(3, 0, 51)),
1854            ("2014/4/02 03:00:51", Utc.ymd(2014, 4, 2).and_hms(3, 0, 51)),
1855            (
1856                "2012/03/19 10:11:59",
1857                Utc.ymd(2012, 3, 19).and_hms(10, 11, 59),
1858            ),
1859            (
1860                "2012/03/19 10:11:59.3186369",
1861                Utc.ymd(2012, 3, 19).and_hms_nano(10, 11, 59, 318636900),
1862            ),
1863        ];
1864
1865        for &(input, want) in test_cases.iter() {
1866            assert_eq!(
1867                parse.slash_ymd_hms(input).unwrap().unwrap(),
1868                want,
1869                "slash_ymd_hms/{}",
1870                input
1871            )
1872        }
1873        assert!(parse.slash_ymd_hms("not-date-time").is_none());
1874    }
1875
1876    #[test]
1877    fn slash_ymd() {
1878        let parse = Parse::new(&Utc, Utc::now().time());
1879
1880        let test_cases = [
1881            (
1882                "2014/3/31",
1883                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()),
1884            ),
1885            (
1886                "2014/03/31",
1887                Utc.ymd(2014, 3, 31).and_time(Utc::now().time()),
1888            ),
1889        ];
1890
1891        for &(input, want) in test_cases.iter() {
1892            assert_eq!(
1893                parse
1894                    .slash_ymd(input)
1895                    .unwrap()
1896                    .unwrap()
1897                    .trunc_subsecs(0)
1898                    .with_second(0)
1899                    .unwrap(),
1900                want.unwrap().trunc_subsecs(0).with_second(0).unwrap(),
1901                "slash_ymd/{}",
1902                input
1903            )
1904        }
1905        assert!(parse.slash_ymd("not-date-time").is_none());
1906    }
1907
1908    #[test]
1909    fn time_shape_classification() {
1910        use TimeShape::{Hm, Hms, HmsF, HmsFP, ImP, ImsP};
1911
1912        let cases = [
1913            ("2021-04-30 21:14", Hm),
1914            ("2021-04-30T21:14", Hm),
1915            ("2021-04-30 21:14:10", Hms),
1916            ("2021-04-30 21:14:10.052282", HmsF),
1917            ("8/8/1965 12:00 AM", ImP),
1918            ("8/8/1965 12:00am", ImP),
1919            ("8/8/1965 01:00:01 PM", ImsP),
1920            ("September 17 2012 10:09am", ImP),
1921            ("03/19/2012 10:11:59.318 PM", HmsFP),
1922            // A one-colon time with a fraction has no format either; it lands
1923            // in a shape whose format still rejects it, so it keeps failing.
1924            ("03/19/2012 10:11.123", Hm),
1925        ];
1926        for (input, want) in cases {
1927            assert!(
1928                time_shape(input) == want,
1929                "time_shape misclassified {input}"
1930            );
1931        }
1932    }
1933
1934    /// Every `fmt_items!` literal in this file must be a valid strftime format.
1935    ///
1936    /// The macro compiles its literal lazily on first use and `expect`s the
1937    /// result, so an invalid format would panic the first time some input
1938    /// happened to reach that particular link of an `or_else` chain — possibly
1939    /// only in production. The literals are extracted from this file's own
1940    /// source rather than re-listed here, so the check cannot drift out of
1941    /// sync as parsers are added or reworked.
1942    #[test]
1943    fn every_fmt_items_literal_is_valid() {
1944        let src = include_str!("datetime.rs");
1945        // Matches uses, not the macro definition (which has no `!`).
1946        let call = Regex::new(r#"fmt_items!\("([^"]*)"\)"#).unwrap();
1947
1948        let mut checked = 0_usize;
1949        for caps in call.captures_iter(src) {
1950            let fmt = &caps[1];
1951            assert!(
1952                chrono::format::StrftimeItems::new(fmt).parse().is_ok(),
1953                "invalid strftime literal: {fmt}"
1954            );
1955            checked += 1;
1956        }
1957        // Guard against the extraction silently matching nothing.
1958        assert!(
1959            checked >= 50,
1960            "expected to check every fmt_items! literal, only found {checked}"
1961        );
1962    }
1963
1964    /// Fractional seconds combined with an AM/PM marker (issue #12).
1965    ///
1966    /// The four families whose regex admits both a fraction and an AM/PM
1967    /// marker parse this with `%I:%M:%S%.f %P`. That one format also covers
1968    /// the fraction-less `ImsP` shape, because `%.f` consumes nothing when
1969    /// there is no period, so it replaced `%I:%M:%S %P` rather than joining
1970    /// it — which is why the plain AM/PM cases are re-asserted here too.
1971    #[test]
1972    fn fractional_seconds_with_ampm() {
1973        let parse = Parse::new(&Utc, Utc::now().time());
1974
1975        let cases = [
1976            (
1977                "03/19/2012 10:11:59.318 PM",
1978                Utc.ymd(2012, 3, 19).and_hms_milli(22, 11, 59, 318),
1979            ),
1980            (
1981                "3/19/2012 1:11:59.318 am",
1982                Utc.ymd(2012, 3, 19).and_hms_milli(1, 11, 59, 318),
1983            ),
1984            (
1985                "03/19/12 10:11:59.318 PM",
1986                Utc.ymd(2012, 3, 19).and_hms_milli(22, 11, 59, 318),
1987            ),
1988            (
1989                "2012/03/19 10:11:59.318 PM",
1990                Utc.ymd(2012, 3, 19).and_hms_milli(22, 11, 59, 318),
1991            ),
1992            (
1993                "2012-03-19 10:11:59.318 PM",
1994                Utc.ymd(2012, 3, 19).and_hms_milli(22, 11, 59, 318),
1995            ),
1996            (
1997                "2012-03-19T10:11:59.318 PM",
1998                Utc.ymd(2012, 3, 19).and_hms_milli(22, 11, 59, 318),
1999            ),
2000            (
2001                "2012-03-19 10:11:59.3186369 PM",
2002                Utc.ymd(2012, 3, 19).and_hms_nano(22, 11, 59, 318636900),
2003            ),
2004            // Unchanged by the format swap: no period, so `%.f` matches empty.
2005            (
2006                "03/19/2012 10:11:59 PM",
2007                Utc.ymd(2012, 3, 19).and_hms(22, 11, 59),
2008            ),
2009            (
2010                "2012-03-19 10:11:59 PM",
2011                Utc.ymd(2012, 3, 19).and_hms(22, 11, 59),
2012            ),
2013        ];
2014
2015        for (input, want) in cases {
2016            assert_eq!(parse.parse(input).unwrap(), want, "parse/{input}");
2017        }
2018
2019        // slash_dmy_hms's arms are only reached day-first, so the cases above
2020        // never exercise them. Both year widths, since the parser dispatches
2021        // on year width before it dispatches on time shape.
2022        let dmy = Parse::new_with_preference(&Utc, Utc::now().time(), true);
2023        let dmy_cases = [
2024            (
2025                "19/03/2012 10:11:59.318 PM",
2026                Utc.ymd(2012, 3, 19).and_hms_milli(22, 11, 59, 318),
2027            ),
2028            (
2029                "19/03/12 10:11:59.318 PM",
2030                Utc.ymd(2012, 3, 19).and_hms_milli(22, 11, 59, 318),
2031            ),
2032            (
2033                "9/3/2012 1:11:59.318 am",
2034                Utc.ymd(2012, 3, 9).and_hms_milli(1, 11, 59, 318),
2035            ),
2036            // Fraction-less, to pin that the format swap left it alone.
2037            (
2038                "19/03/2012 10:11:59 PM",
2039                Utc.ymd(2012, 3, 19).and_hms(22, 11, 59),
2040            ),
2041        ];
2042
2043        for (input, want) in dmy_cases {
2044            assert_eq!(dmy.parse(input).unwrap(), want, "prefer_dmy/{input}");
2045        }
2046    }
2047
2048    /// Inputs that resemble an accepted shape but do not parse. Pinned so that
2049    /// format-chain refactors stay result-preserving: a classifier that newly
2050    /// accepts any of these has widened the accepted input set, which is a
2051    /// behavior change rather than a performance optimization.
2052    ///
2053    /// These are independent gaps, not one gap. Some are turned away by their
2054    /// family regex before any format is tried; others clear the regex and
2055    /// then match no format. Each case carries its own reason below.
2056    #[test]
2057    fn unsupported_shapes_still_fail() {
2058        let parse = Parse::new(&Utc, Utc::now().time());
2059
2060        for input in [
2061            // Rejected at the regex gate: month_mdy_hms has no
2062            // fractional-seconds group at all, and strips `.` before parsing.
2063            "May 8, 2009 5:57:51.123 PM",
2064            // Rejected at the regex gate: month_dmy_hms has no am/pm
2065            // alternative, which is also why that chain's two `%I ... %P`
2066            // formats were unreachable and have been removed. Note the first
2067            // of these carries no fractional seconds — it is the missing
2068            // am/pm alternative alone that rejects it.
2069            "14 May 2019 07:11:40 PM",
2070            "14 May 2019 07:11:40.164 PM",
2071            // Clears the regex, matches no format: a fraction with no seconds
2072            // field. The optional groups admit it, but it buckets as Hm/ImP
2073            // and fails there. Malformed rather than a real shape. Note the
2074            // first two carry no AM/PM marker.
2075            "03/19/2012 10:11.123",
2076            "2021-04-30 21:14.052282",
2077            "03/19/2012 10:11.123 PM",
2078            // Clears the regex, matches no format: `%I` only accepts a 1-12
2079            // hour, so a 24-hour reading cannot carry an AM/PM marker.
2080            "03/19/2012 22:11:59.318 PM",
2081        ] {
2082            assert!(
2083                parse.parse(input).is_err(),
2084                "{input} is expected to remain unsupported"
2085            );
2086        }
2087    }
2088}