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