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