Skip to main content

dateoxide_core/
fast_path.rs

1use crate::locale::{fold_diacritics, normalize_digits_and_lower, CompiledLocale, LocaleRegistry};
2use crate::settings::{
3    DateOrder, DatePart, ParserKind, Period, PreferDatesFrom, PreferMonthOfYear, Settings,
4    StrictDateOrder,
5};
6use crate::timezone::{extract_trailing_timezone_with_abbrevs, TzSpec};
7use chrono::format::{parse as chrono_parse, Parsed, StrftimeItems};
8use chrono::{DateTime, Datelike, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Weekday};
9
10#[derive(Debug, Clone)]
11pub struct FastPathMatch {
12    pub naive: NaiveDateTime,
13    pub tz: Option<TzSpec>,
14    pub period: Period,
15    pub has_time: bool,
16    pub parts: Vec<&'static str>,
17    pub locale: Option<String>,
18}
19
20const ENG_MONTHS_FULL: [&str; 12] = [
21    "January",
22    "February",
23    "March",
24    "April",
25    "May",
26    "June",
27    "July",
28    "August",
29    "September",
30    "October",
31    "November",
32    "December",
33];
34
35const ENG_MONTHS_ABBR: [&str; 12] = [
36    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
37];
38
39const ENG_WEEKDAYS_FULL: [&str; 7] = [
40    "Monday",
41    "Tuesday",
42    "Wednesday",
43    "Thursday",
44    "Friday",
45    "Saturday",
46    "Sunday",
47];
48
49const ENG_WEEKDAYS_ABBR: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
50
51fn try_strptime_any(
52    s: &str,
53    fmt: &str,
54    locale: Option<String>,
55    settings: &Settings,
56) -> Option<FastPathMatch> {
57    let eff_fmt_owned: String;
58    let eff_fmt: &str = if fmt.contains(".%f") {
59        if !s.contains('.') {
60            return None;
61        }
62        eff_fmt_owned = fmt.replace(".%f", "%.f");
63        &eff_fmt_owned
64    } else {
65        fmt
66    };
67
68    if let Ok(dt) = DateTime::parse_from_str(s, eff_fmt) {
69        return Some(FastPathMatch {
70            naive: dt.naive_local(),
71            tz: Some(TzSpec::Fixed(*dt.offset())),
72            period: Period::Day,
73            has_time: true,
74            parts: vec!["year", "month", "day", "time"],
75            locale,
76        });
77    }
78    if let Ok(ndt) = NaiveDateTime::parse_from_str(s, eff_fmt) {
79        return Some(FastPathMatch {
80            naive: ndt,
81            tz: None,
82            period: Period::Day,
83            has_time: true,
84            parts: vec!["year", "month", "day", "time"],
85            locale,
86        });
87    }
88    if let Ok(nd) = NaiveDate::parse_from_str(s, eff_fmt) {
89        return Some(FastPathMatch {
90            naive: nd.and_hms_opt(0, 0, 0)?,
91            tz: None,
92            period: Period::Day,
93            has_time: false,
94            parts: vec!["year", "month", "day"],
95            locale,
96        });
97    }
98
99    // Partial strptime fallback via chrono::format::Parsed (e.g. "%B %Y", "%Y-%m", "%d %B", "%H:%M", "%Y-%j")
100    let mut parsed = Parsed::new();
101    chrono_parse(&mut parsed, s, StrftimeItems::new(eff_fmt)).ok()?;
102
103    let has_year = parsed.year.is_some();
104    let has_month = parsed.month.is_some();
105    let has_day = parsed.day.is_some();
106    let has_ordinal = parsed.ordinal.is_some();
107    let has_time = parsed.hour_div_12.is_some()
108        || parsed.hour_mod_12.is_some()
109        || parsed.minute.is_some()
110        || parsed.second.is_some();
111
112    if !has_year && !has_month && !has_day && !has_ordinal && !has_time {
113        return None;
114    }
115
116    if settings.strict_parsing && (!has_year || (!(has_month && has_day) && !has_ordinal)) {
117        return None;
118    }
119    if settings.require_parts.contains(&DatePart::Year) && !has_year {
120        return None;
121    }
122    if settings.require_parts.contains(&DatePart::Month) && !has_month && !has_ordinal {
123        return None;
124    }
125    if settings.require_parts.contains(&DatePart::Day) && !has_day && !has_ordinal {
126        return None;
127    }
128
129    let time = if has_time {
130        if parsed.minute.is_none() {
131            parsed.minute = Some(0);
132        }
133        if parsed.second.is_none() {
134            parsed.second = Some(0);
135        }
136        parsed.to_naive_time().ok()?
137    } else {
138        NaiveTime::from_hms_opt(0, 0, 0)?
139    };
140
141    let base = settings.effective_base();
142    let nd = if has_ordinal {
143        let y = parsed.year.unwrap_or(base.year());
144        if !(1..=9999).contains(&y) {
145            return None;
146        }
147        NaiveDate::from_yo_opt(y, parsed.ordinal?)?
148    } else if !has_year && !has_month && !has_day && has_time {
149        resolve_time_only_date(time, settings)
150    } else {
151        let mut y = parsed.year.unwrap_or(base.year());
152        if !(1..=9999).contains(&y) {
153            return None;
154        }
155        let m = parsed.month.unwrap_or_else(|| match settings.prefer_month_of_year {
156            PreferMonthOfYear::First => 1,
157            PreferMonthOfYear::Last => 12,
158            PreferMonthOfYear::Current => base.month(),
159        });
160        if !(1..=12).contains(&m) {
161            return None;
162        }
163        let d = parsed
164            .day
165            .unwrap_or_else(|| resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month));
166        if d < 1 || d > days_in_month(y, m) {
167            return None;
168        }
169        if !has_year {
170            if let Some(cand) = NaiveDate::from_ymd_opt(y, m, d) {
171                match settings.prefer_dates_from {
172                    PreferDatesFrom::Past if cand > base.date() => y -= 1,
173                    PreferDatesFrom::Future if cand < base.date() => y += 1,
174                    _ => {}
175                }
176            }
177        }
178        let final_d = d.min(days_in_month(y, m));
179        NaiveDate::from_ymd_opt(y, m, final_d)?
180    };
181
182    let tz = parsed.offset.and_then(FixedOffset::east_opt).map(TzSpec::Fixed);
183    let period = if has_day || has_ordinal || (!has_year && !has_month && has_time) {
184        Period::Day
185    } else if has_month {
186        Period::Month
187    } else {
188        Period::Year
189    };
190
191    let mut parts = Vec::with_capacity(4);
192    if has_year {
193        parts.push("year");
194    }
195    if has_month || has_ordinal {
196        parts.push("month");
197    }
198    if has_day || has_ordinal {
199        parts.push("day");
200    }
201    if has_time {
202        parts.push("time");
203    }
204
205    Some(FastPathMatch {
206        naive: nd.and_time(time),
207        tz,
208        period,
209        has_time,
210        parts,
211        locale,
212    })
213}
214
215fn translate_input_for_strptime(
216    norm: &str,
217    fmt: &str,
218    loc: &CompiledLocale,
219    use_folded: bool,
220) -> Option<String> {
221    let want_full_month = fmt.contains("%B");
222    let want_abbr_month = fmt.contains("%b") || fmt.contains("%h");
223    let want_full_wd = fmt.contains("%A");
224    let want_abbr_wd = fmt.contains("%a");
225    let want_ampm = fmt.contains("%p") || fmt.contains("%P");
226
227    if !want_full_month && !want_abbr_month && !want_full_wd && !want_abbr_wd && !want_ampm {
228        return None;
229    }
230
231    let mut pairs: Vec<(&str, &'static str)> = Vec::new();
232    if want_full_month || want_abbr_month {
233        let map = if use_folded { &loc.folded_months } else { &loc.months };
234        for (name, &m) in map {
235            if (1..=12).contains(&m) {
236                let idx = (m - 1) as usize;
237                let rep = if want_full_month {
238                    ENG_MONTHS_FULL[idx]
239                } else {
240                    ENG_MONTHS_ABBR[idx]
241                };
242                pairs.push((name.as_str(), rep));
243            }
244        }
245    }
246    if want_full_wd || want_abbr_wd {
247        let map = if use_folded {
248            &loc.folded_weekdays
249        } else {
250            &loc.weekdays
251        };
252        for (name, &w) in map {
253            if (w as usize) < 7 {
254                let rep = if want_full_wd {
255                    ENG_WEEKDAYS_FULL[w as usize]
256                } else {
257                    ENG_WEEKDAYS_ABBR[w as usize]
258                };
259                pairs.push((name.as_str(), rep));
260            }
261        }
262    }
263    if want_ampm && !use_folded {
264        for name in &loc.am {
265            pairs.push((name.as_str(), "AM"));
266        }
267        for name in &loc.pm {
268            pairs.push((name.as_str(), "PM"));
269        }
270    }
271
272    if pairs.is_empty() {
273        return None;
274    }
275    pairs.sort_unstable_by(|a, b| b.0.len().cmp(&a.0.len()));
276
277    let mut out = String::with_capacity(norm.len() + 8);
278    let mut pos = 0usize;
279    let mut changed = false;
280
281    while pos < norm.len() {
282        let prev_is_alpha = norm[..pos]
283            .chars()
284            .next_back()
285            .map(|c| c.is_alphabetic())
286            .unwrap_or(false);
287
288        let mut matched: Option<(usize, &str)> = None;
289        if !prev_is_alpha {
290            let rest = &norm[pos..];
291            for &(pat, rep) in &pairs {
292                if let Some(after) = rest.strip_prefix(pat) {
293                    let next_is_alpha = after.chars().next().map(|c| c.is_alphabetic()).unwrap_or(false);
294                    if !next_is_alpha {
295                        matched = Some((pat.len(), rep));
296                        break;
297                    }
298                }
299            }
300        }
301
302        if let Some((plen, rep)) = matched {
303            out.push_str(rep);
304            pos += plen;
305            changed = true;
306        } else {
307            let ch = norm[pos..].chars().next().unwrap();
308            out.push(ch);
309            pos += ch.len_utf8();
310        }
311    }
312
313    if changed {
314        Some(out)
315    } else {
316        None
317    }
318}
319
320/// Try explicit user-provided strptime formats (`date_formats`).
321pub fn try_custom_formats(input: &str, settings: &Settings) -> Option<FastPathMatch> {
322    if !settings.allows_parser(ParserKind::CustomFormats) {
323        return None;
324    }
325    let formats = settings.date_formats.as_deref()?;
326    if formats.is_empty() {
327        return None;
328    }
329    let s = input.trim();
330    for fmt in formats {
331        if let Some(m) = try_strptime_any(s, fmt, Some("en".to_string()), settings) {
332            return Some(m);
333        }
334    }
335
336    // Localized strptime fallback when formats use locale-dependent directives (%B/%b/%A/%a/%p)
337    let needs_locale = formats.iter().any(|f| {
338        f.contains("%B")
339            || f.contains("%b")
340            || f.contains("%h")
341            || f.contains("%A")
342            || f.contains("%a")
343            || f.contains("%p")
344            || f.contains("%P")
345    });
346    if !needs_locale {
347        return None;
348    }
349
350    let norm = normalize_digits_and_lower(s);
351    if norm.is_empty() {
352        return None;
353    }
354
355    // Fast retry for Unicode digits in case format had numeric-only mismatch? No, focus on localized names.
356    let registry = LocaleRegistry::global();
357    let tokens: Vec<&str> = norm
358        .split(|c: char| {
359            c.is_whitespace() || c == ',' || c == '/' || c == '-' || c == '.' || c == '[' || c == ']'
360        })
361        .map(|t| t.trim_matches(|c: char| c == '.' || c == '(' || c == ')'))
362        .filter(|t| !t.is_empty())
363        .collect();
364    let candidates = registry.detect_candidates(
365        &norm,
366        &tokens,
367        settings.languages.as_deref(),
368        &settings.default_languages,
369        settings.normalize,
370        settings.use_given_language_order,
371    );
372
373    let folded_norm = if settings.normalize {
374        Some(fold_diacritics(&norm))
375    } else {
376        None
377    };
378
379    for &lid in &candidates {
380        let loc = &registry.locales[lid];
381        for fmt in formats {
382            if let Some(translated) = translate_input_for_strptime(&norm, fmt, loc, false) {
383                if let Some(m) = try_strptime_any(&translated, fmt, Some(loc.code.clone()), settings) {
384                    return Some(m);
385                }
386            }
387            if let Some(ref fn_s) = folded_norm {
388                if let Some(translated) = translate_input_for_strptime(fn_s, fmt, loc, true) {
389                    if let Some(m) = try_strptime_any(&translated, fmt, Some(loc.code.clone()), settings) {
390                        return Some(m);
391                    }
392                }
393            }
394        }
395    }
396
397    None
398}
399
400/// Zero-regex, zero-allocation fast path for ISO-8601 (extended & compact), RFC-2822/3339,
401/// delimited numeric dates, standalone times, Unix timestamps, and compact YYYYMMDD dates.
402pub fn try_fast_path(input: &str, settings: &Settings) -> Option<FastPathMatch> {
403    let s = input.trim();
404    if s.is_empty() || s.len() > 80 {
405        return None;
406    }
407
408    let allow_base = settings.allows_parser(ParserKind::BaseFormats)
409        || settings.allows_parser(ParserKind::AbsoluteTime);
410
411    // 1. RFC 2822 (e.g., "Thu, 26 Nov 2026 15:30:00 +0300")
412    if allow_base && s.len() >= 16 && s.contains(',') {
413        if let Ok(dt) = DateTime::parse_from_rfc2822(s) {
414            return Some(FastPathMatch {
415                naive: dt.naive_local(),
416                tz: Some(TzSpec::Fixed(*dt.offset())),
417                period: Period::Day,
418                has_time: true,
419                parts: vec!["year", "month", "day", "time"],
420                locale: None,
421            });
422        }
423    }
424
425    // 2. RFC 3339 (e.g., "2026-11-26T15:30:00Z" or "2026-11-26T15:30:00.123+03:00")
426    if allow_base
427        && s.len() >= 19
428        && s.as_bytes().get(4) == Some(&b'-')
429        && s.as_bytes().get(7) == Some(&b'-')
430    {
431        if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
432            return Some(FastPathMatch {
433                naive: dt.naive_local(),
434                tz: Some(TzSpec::Fixed(*dt.offset())),
435                period: Period::Day,
436                has_time: true,
437                parts: vec!["year", "month", "day", "time"],
438                locale: None,
439            });
440        }
441    }
442
443    // Peel off optional trailing timezone (including custom abbreviations) before numeric checks
444    let (core, tz) = extract_trailing_timezone_with_abbrevs(s, &settings.timezone_abbreviations);
445    if core.is_empty() {
446        return None;
447    }
448
449    // 3. Compact ISO-8601 basic format: YYYYMMDDTHHMMSS[.frac] (e.g., "20261126T153000Z")
450    if allow_base {
451        if let Some(m) = try_compact_iso_datetime(core, tz) {
452            return Some(m);
453        }
454        if let Some(m) = try_iso_week_date(core, tz, settings) {
455            return Some(m);
456        }
457    }
458
459    // 3b. Negative Unix timestamp (only when "negative-timestamp" is explicitly in PARSERS)
460    if core.starts_with('-') && settings.allows_parser(ParserKind::NegativeTimestamp) {
461        if let Some(m) = try_negative_timestamp(core, tz, settings) {
462            return Some(m);
463        }
464    }
465
466    // 4. Pure ASCII digits (Unix timestamp or compact YYYYMMDD)
467    if core.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
468        if let Some(m) = try_timestamp_or_compact(core, tz, settings) {
469            return Some(m);
470        }
471    }
472
473    // 5. ISO-like & delimited numeric dates / standalone times
474    if allow_base && core.as_bytes()[0].is_ascii_digit() {
475        if let Some(m) = try_numeric_datetime(core, tz, settings) {
476            return Some(m);
477        }
478    }
479
480    // 6. Prefixed standalone times ("at 5:30 PM", "saat 14:30", "alle 18:00")
481    if allow_base {
482        if let Some(m) = try_prefixed_time_only(core, tz, settings) {
483            return Some(m);
484        }
485    }
486
487    None
488}
489
490fn try_prefixed_time_only(
491    core: &str,
492    tz: Option<TzSpec>,
493    settings: &Settings,
494) -> Option<FastPathMatch> {
495    if settings.strict_parsing
496        || settings.require_parts.contains(&DatePart::Year)
497        || settings.require_parts.contains(&DatePart::Month)
498        || settings.require_parts.contains(&DatePart::Day)
499    {
500        return None;
501    }
502
503    let lower = core.to_ascii_lowercase();
504    let prefixes = [
505        "a las ",
506        "alle ",
507        "saat ",
508        "klo ",
509        "kl. ",
510        "at ",
511        "um ",
512        "om ",
513        "kl ",
514        "às ",
515        "à ",
516        "в ",
517        "о ",
518    ];
519    let mut rest: Option<&str> = None;
520    for p in prefixes {
521        if lower.starts_with(p) {
522            let sliced = core[p.len()..].trim();
523            if !sliced.is_empty() {
524                rest = Some(sliced);
525                break;
526            }
527        }
528    }
529    let time_s = rest?;
530    let tl = time_s.to_ascii_lowercase();
531    let looks_like_time = time_s.contains(':')
532        || ((time_s.contains('h') || time_s.contains('H'))
533            && time_s.as_bytes().first().map(|b| b.is_ascii_digit()).unwrap_or(false))
534        || time_s.contains('시')
535        || time_s.contains('時')
536        || time_s.contains('时')
537        || time_s.contains('点')
538        || tl.ends_with("am")
539        || tl.ends_with("pm")
540        || tl.ends_with("a.m.")
541        || tl.ends_with("p.m.")
542        || tl.ends_with("a.m")
543        || tl.ends_with("p.m");
544    if !looks_like_time {
545        return None;
546    }
547    let time = parse_time_str(time_s)?;
548    let date = resolve_time_only_date(time, settings);
549    Some(FastPathMatch {
550        naive: date.and_time(time),
551        tz,
552        period: Period::Day,
553        has_time: true,
554        parts: vec!["time"],
555        locale: None,
556    })
557}
558
559fn try_negative_timestamp(
560    core: &str,
561    tz: Option<TzSpec>,
562    settings: &Settings,
563) -> Option<FastPathMatch> {
564    if settings.strict_parsing {
565        return None;
566    }
567    let abs_str = core.strip_prefix('-')?;
568    if abs_str.is_empty() || !abs_str.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
569        return None;
570    }
571    let dt = if let Some((int_part, frac_part)) = abs_str.split_once('.') {
572        if !(5..=10).contains(&int_part.len())
573            || frac_part.is_empty()
574            || frac_part.len() > 9
575            || !int_part.bytes().all(|b| b.is_ascii_digit())
576            || !frac_part.bytes().all(|b| b.is_ascii_digit())
577        {
578            return None;
579        }
580        let secs: i64 = int_part.parse().ok()?;
581        let mut nanos_str = frac_part.to_string();
582        while nanos_str.len() < 9 {
583            nanos_str.push('0');
584        }
585        let nanos: u32 = nanos_str.parse().ok()?;
586        if nanos == 0 {
587            DateTime::from_timestamp(-secs, 0)?
588        } else {
589            DateTime::from_timestamp(-(secs + 1), 1_000_000_000 - nanos)?
590        }
591    } else {
592        match abs_str.len() {
593            5..=10 => {
594                let secs: i64 = abs_str.parse().ok()?;
595                DateTime::from_timestamp(-secs, 0)?
596            }
597            13 => {
598                let ms: i64 = abs_str.parse().ok()?;
599                DateTime::from_timestamp_millis(-ms)?
600            }
601            16 => {
602                let us: i64 = abs_str.parse().ok()?;
603                DateTime::from_timestamp_micros(-us)?
604            }
605            _ => return None,
606        }
607    };
608
609    if !(1..=9999).contains(&dt.year()) {
610        return None;
611    }
612
613    Some(FastPathMatch {
614        naive: dt.naive_utc(),
615        tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
616        period: Period::Day,
617        has_time: true,
618        parts: vec!["year", "month", "day", "time"],
619        locale: None,
620    })
621}
622
623fn try_compact_iso_datetime(core: &str, tz: Option<TzSpec>) -> Option<FastPathMatch> {
624    let b = core.as_bytes();
625    if b.len() < 15 || (b[8] != b'T' && b[8] != b't') {
626        return None;
627    }
628    if !b[0..8].iter().all(|c| c.is_ascii_digit()) {
629        return None;
630    }
631    let y: i32 = core[0..4].parse().ok()?;
632    if !(1..=9999).contains(&y) {
633        return None;
634    }
635    let m: u32 = core[4..6].parse().ok()?;
636    let d: u32 = core[6..8].parse().ok()?;
637    let nd = NaiveDate::from_ymd_opt(y, m, d)?;
638
639    let time_raw = &core[9..];
640    let (hms, nano) = if let Some((main_t, frac)) = time_raw.split_once(['.', ',']) {
641        if main_t.len() != 6 || frac.is_empty() || !frac.bytes().all(|c| c.is_ascii_digit()) {
642            return None;
643        }
644        let mut padded = [b'0'; 9];
645        for (i, ch) in frac.bytes().take(9).enumerate() {
646            padded[i] = ch;
647        }
648        let nn: u32 = std::str::from_utf8(&padded).ok()?.parse().ok()?;
649        (main_t, nn)
650    } else {
651        if time_raw.len() != 6 {
652            return None;
653        }
654        (time_raw, 0u32)
655    };
656
657    if !hms.bytes().all(|c| c.is_ascii_digit()) {
658        return None;
659    }
660    let hh: u32 = hms[0..2].parse().ok()?;
661    let mm: u32 = hms[2..4].parse().ok()?;
662    let ss: u32 = hms[4..6].parse().ok()?;
663    let nt = NaiveTime::from_hms_nano_opt(hh, mm, ss, nano)?;
664
665    Some(FastPathMatch {
666        naive: nd.and_time(nt),
667        tz,
668        period: Period::Day,
669        has_time: true,
670        parts: vec!["year", "month", "day", "time"],
671        locale: None,
672    })
673}
674
675pub(crate) fn resolve_time_only_date(time: NaiveTime, settings: &Settings) -> NaiveDate {
676    let base = settings.effective_base();
677    let mut date = base.date();
678    match settings.prefer_dates_from {
679        PreferDatesFrom::Future if time < base.time() => {
680            if let Some(next) = date.succ_opt() {
681                date = next;
682            }
683        }
684        PreferDatesFrom::Past if time > base.time() => {
685            if let Some(prev) = date.pred_opt() {
686                date = prev;
687            }
688        }
689        _ => {}
690    }
691    date
692}
693
694fn try_iso_week_date(
695    core: &str,
696    tz: Option<TzSpec>,
697    settings: &Settings,
698) -> Option<FastPathMatch> {
699    let (date_part, time_part) = if let Some(idx) = core.find(['T', 't', ' ']) {
700        let (d, rest) = core.split_at(idx);
701        let t = rest[1..].trim();
702        (d, if t.is_empty() { None } else { Some(t) })
703    } else {
704        (core, None)
705    };
706
707    let bytes = date_part.as_bytes();
708    if bytes.len() < 7 || !bytes[0..4].iter().all(|b| b.is_ascii_digit()) {
709        return None;
710    }
711    let (year, week, weekday_opt) = if bytes.len() >= 8 && bytes[4] == b'-' && (bytes[5] == b'W' || bytes[5] == b'w') {
712        // YYYY-Www or YYYY-Www-D
713        let y: i32 = date_part[0..4].parse().ok()?;
714        if date_part.len() == 8 && bytes[6..8].iter().all(|b| b.is_ascii_digit()) {
715            let w: u32 = date_part[6..8].parse().ok()?;
716            (y, w, None)
717        } else if date_part.len() == 10
718            && bytes[8] == b'-'
719            && bytes[6..8].iter().all(|b| b.is_ascii_digit())
720            && bytes[9].is_ascii_digit()
721        {
722            let w: u32 = date_part[6..8].parse().ok()?;
723            let d: u32 = date_part[9..10].parse().ok()?;
724            (y, w, Some(d))
725        } else {
726            return None;
727        }
728    } else if (bytes[4] == b'W' || bytes[4] == b'w') && (date_part.len() == 7 || date_part.len() == 8) {
729        // YYYYWww or YYYYWwwD
730        let y: i32 = date_part[0..4].parse().ok()?;
731        if !bytes[5..].iter().all(|b| b.is_ascii_digit()) {
732            return None;
733        }
734        let w: u32 = date_part[5..7].parse().ok()?;
735        let d_opt = if date_part.len() == 8 {
736            Some(date_part[7..8].parse::<u32>().ok()?)
737        } else {
738            None
739        };
740        (y, w, d_opt)
741    } else {
742        return None;
743    };
744
745    if weekday_opt.is_none() && (settings.strict_parsing || settings.require_parts.contains(&DatePart::Day)) {
746        return None;
747    }
748
749    let wd = match weekday_opt.unwrap_or(1) {
750        1 => Weekday::Mon,
751        2 => Weekday::Tue,
752        3 => Weekday::Wed,
753        4 => Weekday::Thu,
754        5 => Weekday::Fri,
755        6 => Weekday::Sat,
756        7 => Weekday::Sun,
757        _ => return None,
758    };
759    let nd = NaiveDate::from_isoywd_opt(year, week, wd)?;
760    let has_time = time_part.is_some();
761    let time = match time_part {
762        Some(tp) => {
763            let clean_tp = tp
764                .strip_prefix("t ")
765                .or_else(|| tp.strip_prefix("T "))
766                .or_else(|| tp.strip_prefix("at "))
767                .or_else(|| tp.strip_prefix("AT "))
768                .or_else(|| tp.strip_prefix("@ "))
769                .map(|r| r.trim())
770                .unwrap_or(tp);
771            parse_time_str(clean_tp)?
772        }
773        None => NaiveTime::from_hms_opt(0, 0, 0)?,
774    };
775    let mut parts = vec!["year", "month", "day"];
776    if has_time {
777        parts.push("time");
778    }
779    Some(FastPathMatch {
780        naive: nd.and_time(time),
781        tz,
782        period: if weekday_opt.is_some() { Period::Day } else { Period::Week },
783        has_time,
784        parts,
785        locale: None,
786    })
787}
788
789fn try_timestamp_or_compact(
790    core: &str,
791    tz: Option<TzSpec>,
792    settings: &Settings,
793) -> Option<FastPathMatch> {
794    if !core.contains('.') {
795        match core.len() {
796            4 | 6 if settings.parsers.is_some()
797                && settings.allows_parser(ParserKind::NoSpacesTime)
798                && !settings.allows_parser(ParserKind::AbsoluteTime) =>
799            {
800                if settings.strict_parsing
801                    || settings.require_parts.contains(&DatePart::Year)
802                    || settings.require_parts.contains(&DatePart::Month)
803                    || settings.require_parts.contains(&DatePart::Day)
804                {
805                    return None;
806                }
807                let hh: u32 = core[0..2].parse().ok()?;
808                let mm: u32 = core[2..4].parse().ok()?;
809                let ss: u32 = if core.len() == 6 { core[4..6].parse().ok()? } else { 0 };
810                let time = NaiveTime::from_hms_opt(hh, mm, ss)?;
811                let date = resolve_time_only_date(time, settings);
812                return Some(FastPathMatch {
813                    naive: date.and_time(time),
814                    tz,
815                    period: Period::Day,
816                    has_time: true,
817                    parts: vec!["time"],
818                    locale: None,
819                });
820            }
821            8 => {
822                if !settings.allows_parser(ParserKind::BaseFormats)
823                    && !settings.allows_parser(ParserKind::NoSpacesTime)
824                    && !settings.allows_parser(ParserKind::AbsoluteTime)
825                {
826                    return None;
827                }
828                let nd = parse_compact_8digit_date(core, settings)?;
829                Some(FastPathMatch {
830                    naive: nd.and_hms_opt(0, 0, 0)?,
831                    tz,
832                    period: Period::Day,
833                    has_time: false,
834                    parts: vec!["year", "month", "day"],
835                    locale: None,
836                })
837            }
838            12 | 14 if settings.parsers.is_some()
839                && settings.allows_parser(ParserKind::NoSpacesTime) =>
840            {
841                let date_part = &core[0..8];
842                let time_part = &core[8..];
843                let nd = parse_compact_8digit_date(date_part, settings)?;
844                let hh: u32 = time_part[0..2].parse().ok()?;
845                let mm: u32 = time_part[2..4].parse().ok()?;
846                let ss: u32 = if time_part.len() == 6 {
847                    time_part[4..6].parse().ok()?
848                } else {
849                    0
850                };
851                let time = NaiveTime::from_hms_opt(hh, mm, ss)?;
852                Some(FastPathMatch {
853                    naive: nd.and_time(time),
854                    tz,
855                    period: Period::Day,
856                    has_time: true,
857                    parts: vec!["year", "month", "day", "time"],
858                    locale: None,
859                })
860            }
861            9..=10 => {
862                if settings.strict_parsing || !settings.allows_parser(ParserKind::Timestamp) {
863                    return None;
864                }
865                let secs: i64 = core.parse().ok()?;
866                let dt = DateTime::from_timestamp(secs, 0)?;
867                Some(FastPathMatch {
868                    naive: dt.naive_utc(),
869                    tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
870                    period: Period::Day,
871                    has_time: true,
872                    parts: vec!["year", "month", "day", "time"],
873                    locale: None,
874                })
875            }
876            13 => {
877                if settings.strict_parsing || !settings.allows_parser(ParserKind::Timestamp) {
878                    return None;
879                }
880                let ms: i64 = core.parse().ok()?;
881                let dt = DateTime::from_timestamp_millis(ms)?;
882                Some(FastPathMatch {
883                    naive: dt.naive_utc(),
884                    tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
885                    period: Period::Day,
886                    has_time: true,
887                    parts: vec!["year", "month", "day", "time"],
888                    locale: None,
889                })
890            }
891            16 => {
892                if settings.strict_parsing || !settings.allows_parser(ParserKind::Timestamp) {
893                    return None;
894                }
895                let us: i64 = core.parse().ok()?;
896                let dt = DateTime::from_timestamp_micros(us)?;
897                if !(1..=9999).contains(&dt.year()) {
898                    return None;
899                }
900                Some(FastPathMatch {
901                    naive: dt.naive_utc(),
902                    tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
903                    period: Period::Day,
904                    has_time: true,
905                    parts: vec!["year", "month", "day", "time"],
906                    locale: None,
907                })
908            }
909            _ => None,
910        }
911    } else {
912        if settings.strict_parsing || !settings.allows_parser(ParserKind::Timestamp) {
913            return None;
914        }
915        let (int_part, frac_part) = core.split_once('.')?;
916        if (9..=10).contains(&int_part.len())
917            && !frac_part.is_empty()
918            && frac_part.len() <= 9
919            && int_part.bytes().all(|b| b.is_ascii_digit())
920            && frac_part.bytes().all(|b| b.is_ascii_digit())
921        {
922            let secs: i64 = int_part.parse().ok()?;
923            let mut nanos_str = frac_part.to_string();
924            while nanos_str.len() < 9 {
925                nanos_str.push('0');
926            }
927            let nanos: u32 = nanos_str.parse().ok()?;
928            let dt = DateTime::from_timestamp(secs, nanos)?;
929            return Some(FastPathMatch {
930                naive: dt.naive_utc(),
931                tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
932                period: Period::Day,
933                has_time: true,
934                parts: vec!["year", "month", "day", "time"],
935                locale: None,
936            });
937        }
938        None
939    }
940}
941
942fn parse_compact_8digit_date(s: &str, settings: &Settings) -> Option<NaiveDate> {
943    if s.len() != 8 || !s.bytes().all(|b| b.is_ascii_digit()) {
944        return None;
945    }
946    let order = settings.effective_date_order(DateOrder::YMD);
947    let try_ymd = || -> Option<NaiveDate> {
948        let y: i32 = s[0..4].parse().ok()?;
949        let m: u32 = s[4..6].parse().ok()?;
950        let d: u32 = s[6..8].parse().ok()?;
951        if (1900..=2199).contains(&y) {
952            NaiveDate::from_ymd_opt(y, m, d)
953        } else {
954            None
955        }
956    };
957    let try_dmy = || -> Option<NaiveDate> {
958        let d: u32 = s[0..2].parse().ok()?;
959        let m: u32 = s[2..4].parse().ok()?;
960        let y: i32 = s[4..8].parse().ok()?;
961        if (1900..=2199).contains(&y) {
962            NaiveDate::from_ymd_opt(y, m, d)
963        } else {
964            None
965        }
966    };
967    let try_mdy = || -> Option<NaiveDate> {
968        let m: u32 = s[0..2].parse().ok()?;
969        let d: u32 = s[2..4].parse().ok()?;
970        let y: i32 = s[4..8].parse().ok()?;
971        if (1900..=2199).contains(&y) {
972            NaiveDate::from_ymd_opt(y, m, d)
973        } else {
974            None
975        }
976    };
977    match order {
978        DateOrder::DMY => try_dmy().or_else(|| {
979            if settings.strict_date_order == StrictDateOrder::All {
980                None
981            } else {
982                try_ymd().or_else(try_mdy)
983            }
984        }),
985        DateOrder::MDY => try_mdy().or_else(|| {
986            if settings.strict_date_order == StrictDateOrder::All {
987                None
988            } else {
989                try_ymd().or_else(try_dmy)
990            }
991        }),
992        _ => try_ymd().or_else(|| {
993            if settings.strict_date_order == StrictDateOrder::All {
994                None
995            } else if settings.allows_parser(ParserKind::NoSpacesTime) || settings.date_order.is_some()
996            {
997                try_dmy().or_else(try_mdy)
998            } else {
999                None
1000            }
1001        }),
1002    }
1003}
1004
1005fn try_numeric_datetime(
1006    core: &str,
1007    tz: Option<TzSpec>,
1008    settings: &Settings,
1009) -> Option<FastPathMatch> {
1010    if !core.contains(['-', '/']) {
1011        let lower = core.to_ascii_lowercase();
1012        let looks_like_time = core.contains(':')
1013            || core.contains('h')
1014            || core.contains('H')
1015            || lower.ends_with("am")
1016            || lower.ends_with("pm")
1017            || lower.ends_with("a.m.")
1018            || lower.ends_with("p.m.")
1019            || lower.ends_with("a.m")
1020            || lower.ends_with("p.m");
1021
1022        if looks_like_time {
1023            if let Some(time) = parse_time_str(core) {
1024                if settings.strict_parsing
1025                    || settings.require_parts.contains(&DatePart::Year)
1026                    || settings.require_parts.contains(&DatePart::Month)
1027                    || settings.require_parts.contains(&DatePart::Day)
1028                {
1029                    return None;
1030                }
1031                let date = resolve_time_only_date(time, settings);
1032                return Some(FastPathMatch {
1033                    naive: date.and_time(time),
1034                    tz,
1035                    period: Period::Day,
1036                    has_time: true,
1037                    parts: vec!["time"],
1038                    locale: None,
1039                });
1040            }
1041        }
1042    }
1043
1044    // Strip spaces around dots in numeric dates like "26. 10.21 14.12" or "30 . 09 . 22 12.12"
1045    let owned_compact_dots;
1046    let effective_core: &str = if core.contains(" .") || core.contains(". ") {
1047        owned_compact_dots = collapse_dot_spaces(core);
1048        &owned_compact_dots
1049    } else {
1050        core
1051    };
1052
1053    let (date_part, time_part) = if let Some(idx) = effective_core.find(['T', 't', ' ']) {
1054        let (d, rest) = effective_core.split_at(idx);
1055        let t = rest[1..].trim();
1056        (d, if t.is_empty() { None } else { Some(t) })
1057    } else {
1058        (effective_core, None)
1059    };
1060
1061    let sep = if date_part.contains('-') {
1062        '-'
1063    } else if date_part.contains('/') {
1064        '/'
1065    } else if date_part.contains('.') {
1066        '.'
1067    } else {
1068        return None;
1069    };
1070
1071    let mut parts = [0u32; 3];
1072    let mut lens = [0usize; 3];
1073    let mut count = 0usize;
1074    let date_clean = date_part.trim_end_matches('.');
1075    for seg in date_clean.split(sep) {
1076        let seg_t = seg.trim();
1077        if seg_t.is_empty()
1078            || seg_t.len() > 4
1079            || count >= 3
1080            || !seg_t.bytes().all(|b| b.is_ascii_digit())
1081        {
1082            return None;
1083        }
1084        parts[count] = seg_t.parse().ok()?;
1085        lens[count] = seg_t.len();
1086        count += 1;
1087    }
1088
1089    let has_time = time_part.is_some();
1090    let time = match time_part {
1091        Some(tp) => {
1092            let clean_tp = tp
1093                .strip_prefix("t ")
1094                .or_else(|| tp.strip_prefix("T "))
1095                .or_else(|| tp.strip_prefix("at "))
1096                .or_else(|| tp.strip_prefix("AT "))
1097                .or_else(|| tp.strip_prefix("@ "))
1098                .map(|r| r.trim())
1099                .unwrap_or(tp);
1100            parse_time_str(clean_tp)?
1101        }
1102        None => NaiveTime::from_hms_opt(0, 0, 0)?,
1103    };
1104
1105    if count == 2 {
1106        if settings.strict_parsing || settings.require_parts.contains(&DatePart::Day) {
1107            return None;
1108        }
1109        let (y, m) = if lens[0] == 4 && (1..=12).contains(&parts[1]) {
1110            (parts[0] as i32, parts[1])
1111        } else if lens[1] == 4 && (1..=12).contains(&parts[0]) {
1112            (parts[1] as i32, parts[0])
1113        } else {
1114            return None;
1115        };
1116        if !(1..=9999).contains(&y) {
1117            return None;
1118        }
1119        let base = settings.effective_base();
1120        let day = resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month);
1121        let nd = NaiveDate::from_ymd_opt(y, m, day)?;
1122        let mut p = vec!["year", "month"];
1123        if has_time {
1124            p.push("time");
1125        }
1126        return Some(FastPathMatch {
1127            naive: nd.and_time(time),
1128            tz,
1129            period: Period::Month,
1130            has_time,
1131            parts: p,
1132            locale: None,
1133        });
1134    }
1135
1136    if count != 3 {
1137        return None;
1138    }
1139
1140    let fallback_order = if lens[0] == 4 {
1141        DateOrder::YMD
1142    } else {
1143        DateOrder::MDY
1144    };
1145    let order = settings.effective_date_order(fallback_order);
1146
1147    let nd = resolve_ymd_triplet(parts, lens, order, settings.strict_date_order)?;
1148    let mut p = vec!["year", "month", "day"];
1149    if has_time {
1150        p.push("time");
1151    }
1152    Some(FastPathMatch {
1153        naive: nd.and_time(time),
1154        tz,
1155        period: Period::Day,
1156        has_time,
1157        parts: p,
1158        locale: None,
1159    })
1160}
1161
1162pub fn expand_two_digit_year(y: u32) -> i32 {
1163    if y >= 100 {
1164        y as i32
1165    } else if y >= 70 {
1166        1900 + y as i32
1167    } else {
1168        2000 + y as i32
1169    }
1170}
1171
1172fn resolve_ymd_triplet(
1173    parts: [u32; 3],
1174    lens: [usize; 3],
1175    order: DateOrder,
1176    strict: StrictDateOrder,
1177) -> Option<NaiveDate> {
1178    if lens[0] == 4 {
1179        let y = parts[0] as i32;
1180        if !(1..=9999).contains(&y) {
1181            return None;
1182        }
1183        if order == DateOrder::YDM {
1184            if let Some(d) = NaiveDate::from_ymd_opt(y, parts[2], parts[1]) {
1185                return Some(d);
1186            }
1187            if strict == StrictDateOrder::All {
1188                return None;
1189            }
1190            return NaiveDate::from_ymd_opt(y, parts[1], parts[2]);
1191        }
1192        if let Some(d) = NaiveDate::from_ymd_opt(y, parts[1], parts[2]) {
1193            return Some(d);
1194        }
1195        if strict == StrictDateOrder::None {
1196            return NaiveDate::from_ymd_opt(y, parts[2], parts[1]);
1197        }
1198        return None;
1199    }
1200
1201    if lens[2] == 4 {
1202        let y = parts[2] as i32;
1203        if !(1..=9999).contains(&y) {
1204            return None;
1205        }
1206        return match order {
1207            DateOrder::MDY => {
1208                if let Some(d) = NaiveDate::from_ymd_opt(y, parts[0], parts[1]) {
1209                    Some(d)
1210                } else if strict == StrictDateOrder::All {
1211                    None
1212                } else {
1213                    NaiveDate::from_ymd_opt(y, parts[1], parts[0])
1214                }
1215            }
1216            _ => {
1217                if let Some(d) = NaiveDate::from_ymd_opt(y, parts[1], parts[0]) {
1218                    Some(d)
1219                } else if strict == StrictDateOrder::All {
1220                    None
1221                } else {
1222                    NaiveDate::from_ymd_opt(y, parts[0], parts[1])
1223                }
1224            }
1225        };
1226    }
1227
1228    let (y, m, d) = match order {
1229        DateOrder::YMD => (expand_two_digit_year(parts[0]), parts[1], parts[2]),
1230        DateOrder::YDM => (expand_two_digit_year(parts[0]), parts[2], parts[1]),
1231        DateOrder::MDY => (expand_two_digit_year(parts[2]), parts[0], parts[1]),
1232        DateOrder::DMY => (expand_two_digit_year(parts[2]), parts[1], parts[0]),
1233        DateOrder::MYD => (expand_two_digit_year(parts[1]), parts[0], parts[2]),
1234        DateOrder::DYM => (expand_two_digit_year(parts[1]), parts[2], parts[0]),
1235    };
1236
1237    if let Some(nd) = NaiveDate::from_ymd_opt(y, m, d) {
1238        return Some(nd);
1239    }
1240    if strict != StrictDateOrder::None {
1241        return None;
1242    }
1243    NaiveDate::from_ymd_opt(y, d, m)
1244}
1245
1246fn collapse_dot_spaces(s: &str) -> String {
1247    let mut out = String::with_capacity(s.len());
1248    let chars: Vec<char> = s.chars().collect();
1249    for i in 0..chars.len() {
1250        let c = chars[i];
1251        if c == ' ' {
1252            let prev_dot = i > 0 && chars[i - 1] == '.';
1253            let next_dot = i + 1 < chars.len() && chars[i + 1] == '.';
1254            if prev_dot || next_dot {
1255                continue;
1256            }
1257        }
1258        out.push(c);
1259    }
1260    out
1261}
1262
1263/// Parse time strings like "15:30", "15:30:45,123", "5:30p.m.", "PM 2:26", "下午 02:26:26", "14.12".
1264pub fn parse_time_str(input: &str) -> Option<NaiveTime> {
1265    let mut s = input.trim().trim_end_matches('.');
1266    if s.is_empty() {
1267        return None;
1268    }
1269
1270    let mut is_pm = false;
1271    let mut is_am = false;
1272
1273    // Leading AM/PM/CJK/Korean markers ("PM 2:26", "下午 02:26:26", "午後2時30分", "오후 2시 30분")
1274    for prefix in ["下午", "午後", "오후", "p.m.", "p.m", "pm", "PM"] {
1275        if let Some(rest) = s.strip_prefix(prefix) {
1276            if rest.starts_with(char::is_whitespace) || rest.starts_with(|c: char| c.is_ascii_digit()) {
1277                s = rest.trim_start();
1278                is_pm = true;
1279                break;
1280            }
1281        }
1282    }
1283    if !is_pm {
1284        for prefix in ["上午", "午前", "오전", "a.m.", "a.m", "am", "AM"] {
1285            if let Some(rest) = s.strip_prefix(prefix) {
1286                if rest.starts_with(char::is_whitespace) || rest.starts_with(|c: char| c.is_ascii_digit()) {
1287                    s = rest.trim_start();
1288                    is_am = true;
1289                    break;
1290                }
1291            }
1292        }
1293    }
1294
1295    let lower = s.to_ascii_lowercase();
1296    if !is_am && !is_pm {
1297        for suffix in ["p.m.", "p.m", "pm", "ip.", "ip"] {
1298            if let Some(rest) = lower.strip_suffix(suffix) {
1299                if !rest.is_empty() {
1300                    s = s[..rest.len()].trim_end();
1301                    is_pm = true;
1302                    break;
1303                }
1304            }
1305        }
1306        if !is_pm {
1307            for suffix in ["a.m.", "a.m", "am", "ap.", "ap"] {
1308                if let Some(rest) = lower.strip_suffix(suffix) {
1309                    if !rest.is_empty() {
1310                        s = s[..rest.len()].trim_end();
1311                        is_am = true;
1312                        break;
1313                    }
1314                }
1315            }
1316        }
1317    }
1318
1319    // Trailing "Uhr" (German)
1320    if let Some(rest) = s.strip_suffix("Uhr").or_else(|| s.strip_suffix("uhr")) {
1321        s = rest.trim_end();
1322    }
1323
1324    // CJK / Korean clock times ("2시 30분", "2時30分", "2时30分15秒", "14点30分")
1325    if s.contains('시') || s.contains('時') || s.contains('时') || s.contains('点') {
1326        if let Some(t) = parse_cjk_korean_clock(s, is_am, is_pm) {
1327            return Some(t);
1328        }
1329    }
1330
1331    // French / European "14h30" or "09h15" or "14h"
1332    if (s.contains('h') || s.contains('H')) && !s.contains(':') {
1333        let idx = s.find(['h', 'H'])?;
1334        let h_str = &s[..idx];
1335        let rest = &s[idx + 1..];
1336        let mut h: u32 = h_str.parse().ok()?;
1337        let (m, sec) = if rest.is_empty() {
1338            (0u32, 0u32)
1339        } else if let Some(mi) = rest.find(['m', 'M']) {
1340            let mm: u32 = rest[..mi].parse().ok()?;
1341            let s_rest = rest[mi + 1..].trim_end_matches(['s', 'S']);
1342            let ss: u32 = if s_rest.is_empty() { 0 } else { s_rest.parse().ok()? };
1343            (mm, ss)
1344        } else {
1345            (rest.parse().ok()?, 0u32)
1346        };
1347        apply_ampm(&mut h, is_am, is_pm)?;
1348        return NaiveTime::from_hms_opt(h, m, sec);
1349    }
1350
1351    // Bare hour with AM/PM: "5pm", "12am"
1352    if (is_am || is_pm) && s.bytes().all(|b| b.is_ascii_digit()) && s.len() <= 2 {
1353        let mut h: u32 = s.parse().ok()?;
1354        apply_ampm(&mut h, is_am, is_pm)?;
1355        return NaiveTime::from_hms_opt(h, 0, 0);
1356    }
1357
1358    // Allow dot-separated HH.MM when no ':' is present (e.g. "13.12", "18.37", "5.45 ip.")
1359    let sep = if s.contains(':') {
1360        ':'
1361    } else if s.contains('.') && s.matches('.').count() == 1 {
1362        '.'
1363    } else {
1364        return None;
1365    };
1366
1367    let mut colon_parts = s.split(sep);
1368    let h_str = colon_parts.next()?;
1369    let m_str = colon_parts.next()?;
1370    let s_part = colon_parts.next();
1371    if colon_parts.next().is_some() {
1372        return None;
1373    }
1374
1375    if h_str.is_empty()
1376        || h_str.len() > 2
1377        || m_str.is_empty()
1378        || m_str.len() > 2
1379        || !h_str.bytes().all(|b| b.is_ascii_digit())
1380        || !m_str.bytes().all(|b| b.is_ascii_digit())
1381    {
1382        return None;
1383    }
1384
1385    let mut h: u32 = h_str.parse().ok()?;
1386    let m: u32 = m_str.parse().ok()?;
1387    let (sec, nano) = match s_part {
1388        None => (0u32, 0u32),
1389        Some(sp) => {
1390            if let Some((sec_s, frac_s)) = sp.split_once(['.', ',']) {
1391                if sec_s.is_empty()
1392                    || sec_s.len() > 2
1393                    || frac_s.is_empty()
1394                    || !sec_s.bytes().all(|b| b.is_ascii_digit())
1395                    || !frac_s.bytes().all(|b| b.is_ascii_digit())
1396                {
1397                    return None;
1398                }
1399                let ss: u32 = sec_s.parse().ok()?;
1400                let mut padded = [b'0'; 9];
1401                for (i, b) in frac_s.bytes().take(9).enumerate() {
1402                    padded[i] = b;
1403                }
1404                let nn: u32 = std::str::from_utf8(&padded).ok()?.parse().ok()?;
1405                (ss, nn)
1406            } else {
1407                if sp.is_empty() || sp.len() > 2 || !sp.bytes().all(|b| b.is_ascii_digit()) {
1408                    return None;
1409                }
1410                (sp.parse().ok()?, 0u32)
1411            }
1412        }
1413    };
1414
1415    apply_ampm(&mut h, is_am, is_pm)?;
1416    NaiveTime::from_hms_nano_opt(h, m, sec, nano)
1417}
1418
1419fn parse_cjk_korean_clock(s: &str, is_am: bool, is_pm: bool) -> Option<NaiveTime> {
1420    let mut rest = s.trim();
1421    let hour_idx = rest.find(['시', '時', '时', '点'])?;
1422    let h_str = rest[..hour_idx].trim();
1423    if h_str.is_empty() || h_str.len() > 2 || !h_str.bytes().all(|b| b.is_ascii_digit()) {
1424        return None;
1425    }
1426    let mut h: u32 = h_str.parse().ok()?;
1427    let sep_len = rest[hour_idx..].chars().next()?.len_utf8();
1428    rest = rest[hour_idx + sep_len..].trim();
1429
1430    let mut m: u32 = 0;
1431    let mut sec: u32 = 0;
1432    if !rest.is_empty() {
1433        if let Some(min_idx) = rest.find(['분', '分']) {
1434            let m_str = rest[..min_idx].trim();
1435            if m_str.is_empty() || m_str.len() > 2 || !m_str.bytes().all(|b| b.is_ascii_digit()) {
1436                return None;
1437            }
1438            m = m_str.parse().ok()?;
1439            let min_len = rest[min_idx..].chars().next()?.len_utf8();
1440            rest = rest[min_idx + min_len..].trim();
1441        }
1442        if !rest.is_empty() {
1443            if let Some(sec_idx) = rest.find(['초', '秒']) {
1444                let sec_str = rest[..sec_idx].trim();
1445                if sec_str.is_empty()
1446                    || sec_str.len() > 2
1447                    || !sec_str.bytes().all(|b| b.is_ascii_digit())
1448                {
1449                    return None;
1450                }
1451                sec = sec_str.parse().ok()?;
1452                let sec_len = rest[sec_idx..].chars().next()?.len_utf8();
1453                rest = rest[sec_idx + sec_len..].trim();
1454            }
1455        }
1456        if !rest.is_empty() {
1457            return None;
1458        }
1459    }
1460
1461    apply_ampm(&mut h, is_am, is_pm)?;
1462    NaiveTime::from_hms_opt(h, m, sec)
1463}
1464
1465fn apply_ampm(h: &mut u32, is_am: bool, is_pm: bool) -> Option<()> {
1466    if is_pm {
1467        if *h == 0 || *h > 12 {
1468            return None;
1469        }
1470        if *h < 12 {
1471            *h += 12;
1472        }
1473    } else if is_am {
1474        if *h == 0 || *h > 12 {
1475            return None;
1476        }
1477        if *h == 12 {
1478            *h = 0;
1479        }
1480    }
1481    Some(())
1482}
1483
1484pub fn days_in_month(year: i32, month: u32) -> u32 {
1485    match month {
1486        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1487        4 | 6 | 9 | 11 => 30,
1488        2 => {
1489            if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
1490                29
1491            } else {
1492                28
1493            }
1494        }
1495        _ => 30,
1496    }
1497}
1498
1499pub fn resolve_missing_day(
1500    year: i32,
1501    month: u32,
1502    base_day: u32,
1503    pref: crate::settings::PreferDayOfMonth,
1504) -> u32 {
1505    let max_d = days_in_month(year, month);
1506    match pref {
1507        crate::settings::PreferDayOfMonth::First => 1,
1508        crate::settings::PreferDayOfMonth::Last => max_d,
1509        crate::settings::PreferDayOfMonth::Current => base_day.min(max_d),
1510    }
1511}