Skip to main content

dateoxide_core/
fast_path.rs

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