Skip to main content

dateoxide_core/
fast_path.rs

1use crate::settings::{
2    DateOrder, DatePart, ParserKind, Period, PreferDatesFrom, Settings, StrictDateOrder,
3};
4use crate::timezone::{extract_trailing_timezone_with_abbrevs, TzSpec};
5use chrono::{DateTime, Datelike, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Weekday};
6
7#[derive(Debug, Clone)]
8pub struct FastPathMatch {
9    pub naive: NaiveDateTime,
10    pub tz: Option<TzSpec>,
11    pub period: Period,
12    pub has_time: bool,
13    pub parts: Vec<&'static str>,
14}
15
16/// Try explicit user-provided strptime formats (`date_formats`).
17pub fn try_custom_formats(input: &str, settings: &Settings) -> Option<FastPathMatch> {
18    if !settings.allows_parser(ParserKind::CustomFormats) {
19        return None;
20    }
21    let formats = settings.date_formats.as_deref()?;
22    if formats.is_empty() {
23        return None;
24    }
25    let s = input.trim();
26    for fmt in formats {
27        if let Ok(dt) = DateTime::parse_from_str(s, fmt) {
28            return Some(FastPathMatch {
29                naive: dt.naive_local(),
30                tz: Some(TzSpec::Fixed(*dt.offset())),
31                period: Period::Day,
32                has_time: true,
33                parts: vec!["year", "month", "day", "time"],
34            });
35        }
36        if let Ok(ndt) = NaiveDateTime::parse_from_str(s, fmt) {
37            return Some(FastPathMatch {
38                naive: ndt,
39                tz: None,
40                period: Period::Day,
41                has_time: true,
42                parts: vec!["year", "month", "day", "time"],
43            });
44        }
45        if let Ok(nd) = NaiveDate::parse_from_str(s, fmt) {
46            return Some(FastPathMatch {
47                naive: nd.and_hms_opt(0, 0, 0)?,
48                tz: None,
49                period: Period::Day,
50                has_time: false,
51                parts: vec!["year", "month", "day"],
52            });
53        }
54    }
55    None
56}
57
58/// Zero-regex, zero-allocation fast path for ISO-8601 (extended & compact), RFC-2822/3339,
59/// delimited numeric dates, standalone times, Unix timestamps, and compact YYYYMMDD dates.
60pub fn try_fast_path(input: &str, settings: &Settings) -> Option<FastPathMatch> {
61    let s = input.trim();
62    if s.is_empty() || s.len() > 80 {
63        return None;
64    }
65
66    let allow_base = settings.allows_parser(ParserKind::BaseFormats)
67        || settings.allows_parser(ParserKind::AbsoluteTime);
68
69    // 1. RFC 2822 (e.g., "Thu, 26 Nov 2026 15:30:00 +0300")
70    if allow_base && s.len() >= 16 && s.contains(',') {
71        if let Ok(dt) = DateTime::parse_from_rfc2822(s) {
72            return Some(FastPathMatch {
73                naive: dt.naive_local(),
74                tz: Some(TzSpec::Fixed(*dt.offset())),
75                period: Period::Day,
76                has_time: true,
77                parts: vec!["year", "month", "day", "time"],
78            });
79        }
80    }
81
82    // 2. RFC 3339 (e.g., "2026-11-26T15:30:00Z" or "2026-11-26T15:30:00.123+03:00")
83    if allow_base
84        && s.len() >= 19
85        && s.as_bytes().get(4) == Some(&b'-')
86        && s.as_bytes().get(7) == Some(&b'-')
87    {
88        if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
89            return Some(FastPathMatch {
90                naive: dt.naive_local(),
91                tz: Some(TzSpec::Fixed(*dt.offset())),
92                period: Period::Day,
93                has_time: true,
94                parts: vec!["year", "month", "day", "time"],
95            });
96        }
97    }
98
99    // Peel off optional trailing timezone (including custom abbreviations) before numeric checks
100    let (core, tz) = extract_trailing_timezone_with_abbrevs(s, &settings.timezone_abbreviations);
101    if core.is_empty() {
102        return None;
103    }
104
105    // 3. Compact ISO-8601 basic format: YYYYMMDDTHHMMSS[.frac] (e.g., "20261126T153000Z")
106    if allow_base {
107        if let Some(m) = try_compact_iso_datetime(core, tz) {
108            return Some(m);
109        }
110        if let Some(m) = try_iso_week_date(core, tz, settings) {
111            return Some(m);
112        }
113    }
114
115    // 4. Pure ASCII digits (Unix timestamp or compact YYYYMMDD)
116    if core.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
117        if let Some(m) = try_timestamp_or_compact(core, tz, settings) {
118            return Some(m);
119        }
120    }
121
122    // 5. ISO-like & delimited numeric dates / standalone times
123    if allow_base && core.as_bytes()[0].is_ascii_digit() {
124        if let Some(m) = try_numeric_datetime(core, tz, settings) {
125            return Some(m);
126        }
127    }
128
129    None
130}
131
132fn try_compact_iso_datetime(core: &str, tz: Option<TzSpec>) -> Option<FastPathMatch> {
133    let b = core.as_bytes();
134    if b.len() < 15 || (b[8] != b'T' && b[8] != b't') {
135        return None;
136    }
137    if !b[0..8].iter().all(|c| c.is_ascii_digit()) {
138        return None;
139    }
140    let y: i32 = core[0..4].parse().ok()?;
141    if !(1..=9999).contains(&y) {
142        return None;
143    }
144    let m: u32 = core[4..6].parse().ok()?;
145    let d: u32 = core[6..8].parse().ok()?;
146    let nd = NaiveDate::from_ymd_opt(y, m, d)?;
147
148    let time_raw = &core[9..];
149    let (hms, nano) = if let Some((main_t, frac)) = time_raw.split_once(['.', ',']) {
150        if main_t.len() != 6 || frac.is_empty() || !frac.bytes().all(|c| c.is_ascii_digit()) {
151            return None;
152        }
153        let mut padded = [b'0'; 9];
154        for (i, ch) in frac.bytes().take(9).enumerate() {
155            padded[i] = ch;
156        }
157        let nn: u32 = std::str::from_utf8(&padded).ok()?.parse().ok()?;
158        (main_t, nn)
159    } else {
160        if time_raw.len() != 6 {
161            return None;
162        }
163        (time_raw, 0u32)
164    };
165
166    if !hms.bytes().all(|c| c.is_ascii_digit()) {
167        return None;
168    }
169    let hh: u32 = hms[0..2].parse().ok()?;
170    let mm: u32 = hms[2..4].parse().ok()?;
171    let ss: u32 = hms[4..6].parse().ok()?;
172    let nt = NaiveTime::from_hms_nano_opt(hh, mm, ss, nano)?;
173
174    Some(FastPathMatch {
175        naive: nd.and_time(nt),
176        tz,
177        period: Period::Day,
178        has_time: true,
179        parts: vec!["year", "month", "day", "time"],
180    })
181}
182
183pub(crate) fn resolve_time_only_date(time: NaiveTime, settings: &Settings) -> NaiveDate {
184    let base = settings.effective_base();
185    let mut date = base.date();
186    match settings.prefer_dates_from {
187        PreferDatesFrom::Future if time < base.time() => {
188            if let Some(next) = date.succ_opt() {
189                date = next;
190            }
191        }
192        PreferDatesFrom::Past if time > base.time() => {
193            if let Some(prev) = date.pred_opt() {
194                date = prev;
195            }
196        }
197        _ => {}
198    }
199    date
200}
201
202fn try_iso_week_date(
203    core: &str,
204    tz: Option<TzSpec>,
205    settings: &Settings,
206) -> Option<FastPathMatch> {
207    let (date_part, time_part) = if let Some(idx) = core.find(['T', 't', ' ']) {
208        let (d, rest) = core.split_at(idx);
209        let t = rest[1..].trim();
210        (d, if t.is_empty() { None } else { Some(t) })
211    } else {
212        (core, None)
213    };
214
215    let bytes = date_part.as_bytes();
216    if bytes.len() < 7 || !bytes[0..4].iter().all(|b| b.is_ascii_digit()) {
217        return None;
218    }
219    let (year, week, weekday_opt) = if bytes.len() >= 8 && bytes[4] == b'-' && (bytes[5] == b'W' || bytes[5] == b'w') {
220        // YYYY-Www or YYYY-Www-D
221        let y: i32 = date_part[0..4].parse().ok()?;
222        if date_part.len() == 8 && bytes[6..8].iter().all(|b| b.is_ascii_digit()) {
223            let w: u32 = date_part[6..8].parse().ok()?;
224            (y, w, None)
225        } else if date_part.len() == 10
226            && bytes[8] == b'-'
227            && bytes[6..8].iter().all(|b| b.is_ascii_digit())
228            && bytes[9].is_ascii_digit()
229        {
230            let w: u32 = date_part[6..8].parse().ok()?;
231            let d: u32 = date_part[9..10].parse().ok()?;
232            (y, w, Some(d))
233        } else {
234            return None;
235        }
236    } else if (bytes[4] == b'W' || bytes[4] == b'w') && (date_part.len() == 7 || date_part.len() == 8) {
237        // YYYYWww or YYYYWwwD
238        let y: i32 = date_part[0..4].parse().ok()?;
239        if !bytes[5..].iter().all(|b| b.is_ascii_digit()) {
240            return None;
241        }
242        let w: u32 = date_part[5..7].parse().ok()?;
243        let d_opt = if date_part.len() == 8 {
244            Some(date_part[7..8].parse::<u32>().ok()?)
245        } else {
246            None
247        };
248        (y, w, d_opt)
249    } else {
250        return None;
251    };
252
253    if weekday_opt.is_none() && (settings.strict_parsing || settings.require_parts.contains(&DatePart::Day)) {
254        return None;
255    }
256
257    let wd = match weekday_opt.unwrap_or(1) {
258        1 => Weekday::Mon,
259        2 => Weekday::Tue,
260        3 => Weekday::Wed,
261        4 => Weekday::Thu,
262        5 => Weekday::Fri,
263        6 => Weekday::Sat,
264        7 => Weekday::Sun,
265        _ => return None,
266    };
267    let nd = NaiveDate::from_isoywd_opt(year, week, wd)?;
268    let has_time = time_part.is_some();
269    let time = match time_part {
270        Some(tp) => parse_time_str(tp)?,
271        None => NaiveTime::from_hms_opt(0, 0, 0)?,
272    };
273    let mut parts = vec!["year", "month", "day"];
274    if has_time {
275        parts.push("time");
276    }
277    Some(FastPathMatch {
278        naive: nd.and_time(time),
279        tz,
280        period: if weekday_opt.is_some() { Period::Day } else { Period::Week },
281        has_time,
282        parts,
283    })
284}
285
286fn try_timestamp_or_compact(
287    core: &str,
288    tz: Option<TzSpec>,
289    settings: &Settings,
290) -> Option<FastPathMatch> {
291    if !core.contains('.') {
292        match core.len() {
293            4 | 6 if settings.parsers.is_some()
294                && settings.allows_parser(ParserKind::NoSpacesTime)
295                && !settings.allows_parser(ParserKind::AbsoluteTime) =>
296            {
297                if settings.strict_parsing
298                    || settings.require_parts.contains(&DatePart::Year)
299                    || settings.require_parts.contains(&DatePart::Month)
300                    || settings.require_parts.contains(&DatePart::Day)
301                {
302                    return None;
303                }
304                let hh: u32 = core[0..2].parse().ok()?;
305                let mm: u32 = core[2..4].parse().ok()?;
306                let ss: u32 = if core.len() == 6 { core[4..6].parse().ok()? } else { 0 };
307                let time = NaiveTime::from_hms_opt(hh, mm, ss)?;
308                let date = resolve_time_only_date(time, settings);
309                return Some(FastPathMatch {
310                    naive: date.and_time(time),
311                    tz,
312                    period: Period::Day,
313                    has_time: true,
314                    parts: vec!["time"],
315                });
316            }
317            8 => {
318                if !settings.allows_parser(ParserKind::BaseFormats)
319                    && !settings.allows_parser(ParserKind::NoSpacesTime)
320                    && !settings.allows_parser(ParserKind::AbsoluteTime)
321                {
322                    return None;
323                }
324                let order = settings.effective_date_order(DateOrder::YMD);
325                let try_ymd = || -> Option<NaiveDate> {
326                    let y: i32 = core[0..4].parse().ok()?;
327    if !(1..=9999).contains(&y) {
328        return None;
329    }
330                    let m: u32 = core[4..6].parse().ok()?;
331                    let d: u32 = core[6..8].parse().ok()?;
332                    if (1900..=2199).contains(&y) {
333                        NaiveDate::from_ymd_opt(y, m, d)
334                    } else {
335                        None
336                    }
337                };
338                let try_dmy = || -> Option<NaiveDate> {
339                    let d: u32 = core[0..2].parse().ok()?;
340                    let m: u32 = core[2..4].parse().ok()?;
341                    let y: i32 = core[4..8].parse().ok()?;
342                    if (1900..=2199).contains(&y) {
343                        NaiveDate::from_ymd_opt(y, m, d)
344                    } else {
345                        None
346                    }
347                };
348                let try_mdy = || -> Option<NaiveDate> {
349                    let m: u32 = core[0..2].parse().ok()?;
350                    let d: u32 = core[2..4].parse().ok()?;
351                    let y: i32 = core[4..8].parse().ok()?;
352                    if (1900..=2199).contains(&y) {
353                        NaiveDate::from_ymd_opt(y, m, d)
354                    } else {
355                        None
356                    }
357                };
358                let nd = match order {
359                    DateOrder::DMY => try_dmy().or_else(|| {
360                        if settings.strict_date_order == StrictDateOrder::All { None } else { try_ymd().or_else(try_mdy) }
361                    }),
362                    DateOrder::MDY => try_mdy().or_else(|| {
363                        if settings.strict_date_order == StrictDateOrder::All { None } else { try_ymd().or_else(try_dmy) }
364                    }),
365                    _ => try_ymd().or_else(|| {
366                        if settings.strict_date_order == StrictDateOrder::All {
367                            None
368                        } else if settings.allows_parser(ParserKind::NoSpacesTime) || settings.date_order.is_some() {
369                            try_dmy().or_else(try_mdy)
370                        } else {
371                            None
372                        }
373                    }),
374                };
375                if let Some(nd) = nd {
376                    return Some(FastPathMatch {
377                        naive: nd.and_hms_opt(0, 0, 0)?,
378                        tz,
379                        period: Period::Day,
380                        has_time: false,
381                        parts: vec!["year", "month", "day"],
382                    });
383                }
384                None
385            }
386            9..=10 => {
387                if settings.strict_parsing || !settings.allows_parser(ParserKind::Timestamp) {
388                    return None;
389                }
390                let secs: i64 = core.parse().ok()?;
391                let dt = DateTime::from_timestamp(secs, 0)?;
392                Some(FastPathMatch {
393                    naive: dt.naive_utc(),
394                    tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
395                    period: Period::Day,
396                    has_time: true,
397                    parts: vec!["year", "month", "day", "time"],
398                })
399            }
400            13 => {
401                if settings.strict_parsing || !settings.allows_parser(ParserKind::Timestamp) {
402                    return None;
403                }
404                let ms: i64 = core.parse().ok()?;
405                let dt = DateTime::from_timestamp_millis(ms)?;
406                Some(FastPathMatch {
407                    naive: dt.naive_utc(),
408                    tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
409                    period: Period::Day,
410                    has_time: true,
411                    parts: vec!["year", "month", "day", "time"],
412                })
413            }
414            _ => None,
415        }
416    } else {
417        if settings.strict_parsing || !settings.allows_parser(ParserKind::Timestamp) {
418            return None;
419        }
420        let (int_part, frac_part) = core.split_once('.')?;
421        if (9..=10).contains(&int_part.len())
422            && !frac_part.is_empty()
423            && frac_part.len() <= 9
424            && int_part.bytes().all(|b| b.is_ascii_digit())
425            && frac_part.bytes().all(|b| b.is_ascii_digit())
426        {
427            let secs: i64 = int_part.parse().ok()?;
428            let mut nanos_str = frac_part.to_string();
429            while nanos_str.len() < 9 {
430                nanos_str.push('0');
431            }
432            let nanos: u32 = nanos_str.parse().ok()?;
433            let dt = DateTime::from_timestamp(secs, nanos)?;
434            return Some(FastPathMatch {
435                naive: dt.naive_utc(),
436                tz: tz.or_else(|| FixedOffset::east_opt(0).map(TzSpec::Fixed)),
437                period: Period::Day,
438                has_time: true,
439                parts: vec!["year", "month", "day", "time"],
440            });
441        }
442        None
443    }
444}
445
446fn try_numeric_datetime(
447    core: &str,
448    tz: Option<TzSpec>,
449    settings: &Settings,
450) -> Option<FastPathMatch> {
451    if !core.contains(['-', '/']) {
452        let lower = core.to_ascii_lowercase();
453        let looks_like_time = core.contains(':')
454            || core.contains('h')
455            || core.contains('H')
456            || lower.ends_with("am")
457            || lower.ends_with("pm")
458            || lower.ends_with("a.m.")
459            || lower.ends_with("p.m.")
460            || lower.ends_with("a.m")
461            || lower.ends_with("p.m");
462
463        if looks_like_time {
464            if let Some(time) = parse_time_str(core) {
465                if settings.strict_parsing
466                    || settings.require_parts.contains(&DatePart::Year)
467                    || settings.require_parts.contains(&DatePart::Month)
468                    || settings.require_parts.contains(&DatePart::Day)
469                {
470                    return None;
471                }
472                let date = resolve_time_only_date(time, settings);
473                return Some(FastPathMatch {
474                    naive: date.and_time(time),
475                    tz,
476                    period: Period::Day,
477                    has_time: true,
478                    parts: vec!["time"],
479                });
480            }
481        }
482    }
483
484    // Strip spaces around dots in numeric dates like "26. 10.21 14.12" or "30 . 09 . 22 12.12"
485    let owned_compact_dots;
486    let effective_core: &str = if core.contains(" .") || core.contains(". ") {
487        owned_compact_dots = collapse_dot_spaces(core);
488        &owned_compact_dots
489    } else {
490        core
491    };
492
493    let (date_part, time_part) = if let Some(idx) = effective_core.find(['T', 't', ' ']) {
494        let (d, rest) = effective_core.split_at(idx);
495        let t = rest[1..].trim();
496        (d, if t.is_empty() { None } else { Some(t) })
497    } else {
498        (effective_core, None)
499    };
500
501    let sep = if date_part.contains('-') {
502        '-'
503    } else if date_part.contains('/') {
504        '/'
505    } else if date_part.contains('.') {
506        '.'
507    } else {
508        return None;
509    };
510
511    let mut parts = [0u32; 3];
512    let mut lens = [0usize; 3];
513    let mut count = 0usize;
514    let date_clean = date_part.trim_end_matches('.');
515    for seg in date_clean.split(sep) {
516        let seg_t = seg.trim();
517        if seg_t.is_empty()
518            || seg_t.len() > 4
519            || count >= 3
520            || !seg_t.bytes().all(|b| b.is_ascii_digit())
521        {
522            return None;
523        }
524        parts[count] = seg_t.parse().ok()?;
525        lens[count] = seg_t.len();
526        count += 1;
527    }
528
529    let has_time = time_part.is_some();
530    let time = match time_part {
531        Some(tp) => parse_time_str(tp)?,
532        None => NaiveTime::from_hms_opt(0, 0, 0)?,
533    };
534
535    if count == 2 {
536        if settings.strict_parsing || settings.require_parts.contains(&DatePart::Day) {
537            return None;
538        }
539        let (y, m) = if lens[0] == 4 && (1..=12).contains(&parts[1]) {
540            (parts[0] as i32, parts[1])
541        } else if lens[1] == 4 && (1..=12).contains(&parts[0]) {
542            (parts[1] as i32, parts[0])
543        } else {
544            return None;
545        };
546        if !(1..=9999).contains(&y) {
547            return None;
548        }
549        let base = settings.effective_base();
550        let day = resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month);
551        let nd = NaiveDate::from_ymd_opt(y, m, day)?;
552        let mut p = vec!["year", "month"];
553        if has_time {
554            p.push("time");
555        }
556        return Some(FastPathMatch {
557            naive: nd.and_time(time),
558            tz,
559            period: Period::Month,
560            has_time,
561            parts: p,
562        });
563    }
564
565    if count != 3 {
566        return None;
567    }
568
569    let fallback_order = if lens[0] == 4 {
570        DateOrder::YMD
571    } else {
572        DateOrder::MDY
573    };
574    let order = settings.effective_date_order(fallback_order);
575
576    let nd = resolve_ymd_triplet(parts, lens, order, settings.strict_date_order)?;
577    let mut p = vec!["year", "month", "day"];
578    if has_time {
579        p.push("time");
580    }
581    Some(FastPathMatch {
582        naive: nd.and_time(time),
583        tz,
584        period: Period::Day,
585        has_time,
586        parts: p,
587    })
588}
589
590pub fn expand_two_digit_year(y: u32) -> i32 {
591    if y >= 100 {
592        y as i32
593    } else if y >= 70 {
594        1900 + y as i32
595    } else {
596        2000 + y as i32
597    }
598}
599
600fn resolve_ymd_triplet(
601    parts: [u32; 3],
602    lens: [usize; 3],
603    order: DateOrder,
604    strict: StrictDateOrder,
605) -> Option<NaiveDate> {
606    if lens[0] == 4 {
607        let y = parts[0] as i32;
608        if !(1..=9999).contains(&y) {
609            return None;
610        }
611        if order == DateOrder::YDM {
612            if let Some(d) = NaiveDate::from_ymd_opt(y, parts[2], parts[1]) {
613                return Some(d);
614            }
615            if strict == StrictDateOrder::All {
616                return None;
617            }
618        }
619        if let Some(d) = NaiveDate::from_ymd_opt(y, parts[1], parts[2]) {
620            return Some(d);
621        }
622        if strict == StrictDateOrder::All {
623            return None;
624        }
625        return NaiveDate::from_ymd_opt(y, parts[2], parts[1]);
626    }
627
628    if lens[2] == 4 {
629        let y = parts[2] as i32;
630        if !(1..=9999).contains(&y) {
631            return None;
632        }
633        return match order {
634            DateOrder::MDY => {
635                if let Some(d) = NaiveDate::from_ymd_opt(y, parts[0], parts[1]) {
636                    Some(d)
637                } else if strict == StrictDateOrder::All {
638                    None
639                } else {
640                    NaiveDate::from_ymd_opt(y, parts[1], parts[0])
641                }
642            }
643            _ => {
644                if let Some(d) = NaiveDate::from_ymd_opt(y, parts[1], parts[0]) {
645                    Some(d)
646                } else if strict == StrictDateOrder::All {
647                    None
648                } else {
649                    NaiveDate::from_ymd_opt(y, parts[0], parts[1])
650                }
651            }
652        };
653    }
654
655    let (y, m, d) = match order {
656        DateOrder::YMD => (expand_two_digit_year(parts[0]), parts[1], parts[2]),
657        DateOrder::YDM => (expand_two_digit_year(parts[0]), parts[2], parts[1]),
658        DateOrder::MDY => (expand_two_digit_year(parts[2]), parts[0], parts[1]),
659        DateOrder::DMY => (expand_two_digit_year(parts[2]), parts[1], parts[0]),
660        DateOrder::MYD => (expand_two_digit_year(parts[1]), parts[0], parts[2]),
661        DateOrder::DYM => (expand_two_digit_year(parts[1]), parts[2], parts[0]),
662    };
663
664    if let Some(nd) = NaiveDate::from_ymd_opt(y, m, d) {
665        return Some(nd);
666    }
667    if strict != StrictDateOrder::None {
668        return None;
669    }
670    NaiveDate::from_ymd_opt(y, d, m)
671}
672
673fn collapse_dot_spaces(s: &str) -> String {
674    let mut out = String::with_capacity(s.len());
675    let chars: Vec<char> = s.chars().collect();
676    for i in 0..chars.len() {
677        let c = chars[i];
678        if c == ' ' {
679            let prev_dot = i > 0 && chars[i - 1] == '.';
680            let next_dot = i + 1 < chars.len() && chars[i + 1] == '.';
681            if prev_dot || next_dot {
682                continue;
683            }
684        }
685        out.push(c);
686    }
687    out
688}
689
690/// Parse time strings like "15:30", "15:30:45,123", "5:30p.m.", "PM 2:26", "下午 02:26:26", "14.12".
691pub fn parse_time_str(input: &str) -> Option<NaiveTime> {
692    let mut s = input.trim().trim_end_matches('.');
693    if s.is_empty() {
694        return None;
695    }
696
697    let mut is_pm = false;
698    let mut is_am = false;
699
700    // Leading AM/PM/CJK/Korean markers ("PM 2:26", "下午 02:26:26", "오후 2:26")
701    for prefix in ["下午", "오후", "p.m.", "p.m", "pm", "PM"] {
702        if let Some(rest) = s.strip_prefix(prefix) {
703            if rest.starts_with(char::is_whitespace) || rest.starts_with(|c: char| c.is_ascii_digit()) {
704                s = rest.trim_start();
705                is_pm = true;
706                break;
707            }
708        }
709    }
710    if !is_pm {
711        for prefix in ["上午", "오전", "a.m.", "a.m", "am", "AM"] {
712            if let Some(rest) = s.strip_prefix(prefix) {
713                if rest.starts_with(char::is_whitespace) || rest.starts_with(|c: char| c.is_ascii_digit()) {
714                    s = rest.trim_start();
715                    is_am = true;
716                    break;
717                }
718            }
719        }
720    }
721
722    let lower = s.to_ascii_lowercase();
723    if !is_am && !is_pm {
724        for suffix in ["p.m.", "p.m", "pm", "ip.", "ip"] {
725            if let Some(rest) = lower.strip_suffix(suffix) {
726                if !rest.is_empty() {
727                    s = s[..rest.len()].trim_end();
728                    is_pm = true;
729                    break;
730                }
731            }
732        }
733        if !is_pm {
734            for suffix in ["a.m.", "a.m", "am", "ap.", "ap"] {
735                if let Some(rest) = lower.strip_suffix(suffix) {
736                    if !rest.is_empty() {
737                        s = s[..rest.len()].trim_end();
738                        is_am = true;
739                        break;
740                    }
741                }
742            }
743        }
744    }
745
746    // Trailing "Uhr" (German)
747    if let Some(rest) = s.strip_suffix("Uhr").or_else(|| s.strip_suffix("uhr")) {
748        s = rest.trim_end();
749    }
750
751    // French / European "14h30" or "09h15" or "14h"
752    if (s.contains('h') || s.contains('H')) && !s.contains(':') {
753        let idx = s.find(['h', 'H'])?;
754        let h_str = &s[..idx];
755        let rest = &s[idx + 1..];
756        let mut h: u32 = h_str.parse().ok()?;
757        let (m, sec) = if rest.is_empty() {
758            (0u32, 0u32)
759        } else if let Some(mi) = rest.find(['m', 'M']) {
760            let mm: u32 = rest[..mi].parse().ok()?;
761            let s_rest = rest[mi + 1..].trim_end_matches(['s', 'S']);
762            let ss: u32 = if s_rest.is_empty() { 0 } else { s_rest.parse().ok()? };
763            (mm, ss)
764        } else {
765            (rest.parse().ok()?, 0u32)
766        };
767        apply_ampm(&mut h, is_am, is_pm)?;
768        return NaiveTime::from_hms_opt(h, m, sec);
769    }
770
771    // Bare hour with AM/PM: "5pm", "12am"
772    if (is_am || is_pm) && s.bytes().all(|b| b.is_ascii_digit()) && s.len() <= 2 {
773        let mut h: u32 = s.parse().ok()?;
774        apply_ampm(&mut h, is_am, is_pm)?;
775        return NaiveTime::from_hms_opt(h, 0, 0);
776    }
777
778    // Allow dot-separated HH.MM when no ':' is present (e.g. "13.12", "18.37", "5.45 ip.")
779    let sep = if s.contains(':') {
780        ':'
781    } else if s.contains('.') && s.matches('.').count() == 1 {
782        '.'
783    } else {
784        return None;
785    };
786
787    let mut colon_parts = s.split(sep);
788    let h_str = colon_parts.next()?;
789    let m_str = colon_parts.next()?;
790    let s_part = colon_parts.next();
791    if colon_parts.next().is_some() {
792        return None;
793    }
794
795    if h_str.is_empty()
796        || h_str.len() > 2
797        || m_str.is_empty()
798        || m_str.len() > 2
799        || !h_str.bytes().all(|b| b.is_ascii_digit())
800        || !m_str.bytes().all(|b| b.is_ascii_digit())
801    {
802        return None;
803    }
804
805    let mut h: u32 = h_str.parse().ok()?;
806    let m: u32 = m_str.parse().ok()?;
807    let (sec, nano) = match s_part {
808        None => (0u32, 0u32),
809        Some(sp) => {
810            if let Some((sec_s, frac_s)) = sp.split_once(['.', ',']) {
811                if sec_s.is_empty()
812                    || sec_s.len() > 2
813                    || frac_s.is_empty()
814                    || !sec_s.bytes().all(|b| b.is_ascii_digit())
815                    || !frac_s.bytes().all(|b| b.is_ascii_digit())
816                {
817                    return None;
818                }
819                let ss: u32 = sec_s.parse().ok()?;
820                let mut padded = [b'0'; 9];
821                for (i, b) in frac_s.bytes().take(9).enumerate() {
822                    padded[i] = b;
823                }
824                let nn: u32 = std::str::from_utf8(&padded).ok()?.parse().ok()?;
825                (ss, nn)
826            } else {
827                if sp.is_empty() || sp.len() > 2 || !sp.bytes().all(|b| b.is_ascii_digit()) {
828                    return None;
829                }
830                (sp.parse().ok()?, 0u32)
831            }
832        }
833    };
834
835    apply_ampm(&mut h, is_am, is_pm)?;
836    NaiveTime::from_hms_nano_opt(h, m, sec, nano)
837}
838
839fn apply_ampm(h: &mut u32, is_am: bool, is_pm: bool) -> Option<()> {
840    if is_pm {
841        if *h == 0 || *h > 12 {
842            return None;
843        }
844        if *h < 12 {
845            *h += 12;
846        }
847    } else if is_am {
848        if *h == 0 || *h > 12 {
849            return None;
850        }
851        if *h == 12 {
852            *h = 0;
853        }
854    }
855    Some(())
856}
857
858pub fn days_in_month(year: i32, month: u32) -> u32 {
859    match month {
860        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
861        4 | 6 | 9 | 11 => 30,
862        2 => {
863            if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
864                29
865            } else {
866                28
867            }
868        }
869        _ => 30,
870    }
871}
872
873pub fn resolve_missing_day(
874    year: i32,
875    month: u32,
876    base_day: u32,
877    pref: crate::settings::PreferDayOfMonth,
878) -> u32 {
879    let max_d = days_in_month(year, month);
880    match pref {
881        crate::settings::PreferDayOfMonth::First => 1,
882        crate::settings::PreferDayOfMonth::Last => max_d,
883        crate::settings::PreferDayOfMonth::Current => base_day.min(max_d),
884    }
885}