1use crate::fast_path::{days_in_month, expand_two_digit_year, parse_time_str, resolve_missing_day};
2use crate::locale::{fold_diacritics, CompiledLocale, LocaleRegistry};
3use crate::settings::{
4 DateOrder, DatePart, PartOfDay, Period, PreferDatesFrom, PreferMonthOfYear, Settings,
5 StrictDateOrder,
6};
7use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
8
9#[derive(Debug, Clone)]
10pub struct AbsoluteMatch {
11 pub naive: NaiveDateTime,
12 pub period: Period,
13 pub locale: String,
14 pub has_time: bool,
15 pub parts: Vec<&'static str>,
16 pub part_of_day: Option<PartOfDay>,
17}
18
19pub fn try_parse_absolute(
21 normalized: &str,
22 candidate_ids: &[usize],
23 registry: &LocaleRegistry,
24 settings: &Settings,
25) -> Option<AbsoluteMatch> {
26 if normalized.contains('年')
27 || normalized.contains('月')
28 || normalized.contains('日')
29 || normalized.contains('년')
30 || normalized.contains('월')
31 || normalized.contains('일')
32 {
33 if let Some(m) = try_cjk_or_korean_date(normalized, settings) {
34 return Some(m);
35 }
36 }
37
38 if normalized.len() == 4 && normalized.bytes().all(|b| b.is_ascii_digit()) {
39 if !settings.strict_parsing
40 && !settings.require_parts.contains(&DatePart::Month)
41 && !settings.require_parts.contains(&DatePart::Day)
42 {
43 if let Ok(year) = normalized.parse::<i32>() {
44 if (1000..=2999).contains(&year) {
45 let base = settings.effective_base();
46 let month = match settings.prefer_month_of_year {
47 PreferMonthOfYear::First => 1,
48 PreferMonthOfYear::Last => 12,
49 PreferMonthOfYear::Current => base.month(),
50 };
51 let day = resolve_missing_day(year, month, base.day(), settings.prefer_day_of_month);
52 if let Some(nd) = NaiveDate::from_ymd_opt(year, month, day) {
53 return Some(AbsoluteMatch {
54 naive: nd.and_hms_opt(0, 0, 0)?,
55 period: Period::Year,
56 locale: "en".to_string(),
57 has_time: false,
58 parts: vec!["year"],
59 part_of_day: None,
60 });
61 }
62 }
63 }
64 }
65 return None;
66 }
67
68 for &lid in candidate_ids {
69 let loc = ®istry.locales[lid];
70 if let Some(m) = try_parse_in_locale(normalized, loc, settings) {
71 return Some(m);
72 }
73 }
74
75 None
76}
77
78fn try_cjk_or_korean_date(s: &str, settings: &Settings) -> Option<AbsoluteMatch> {
79 let mut year: Option<i32> = None;
80 let mut month: Option<u32> = None;
81 let mut day: Option<u32> = None;
82 let mut hour: u32 = 0;
83 let mut minute: u32 = 0;
84 let mut second: u32 = 0;
85 let mut has_time = false;
86 let is_korean = s.contains('년') || s.contains('월') || s.contains('일') || s.contains('시');
87 let is_pm = s.contains("오후") || s.contains("pm") || s.contains("下午");
88 let is_am = s.contains("오전") || s.contains("am") || s.contains("上午");
89
90 let mut loose_nums: Vec<(u32, usize)> = Vec::new();
91 let mut cur_num = String::new();
92 let chars: Vec<char> = s.chars().collect();
93 let mut idx = 0usize;
94
95 while idx < chars.len() {
96 let ch = chars[idx];
97 if ch.is_ascii_digit() {
98 cur_num.push(ch);
99 idx += 1;
100 continue;
101 }
102 if ch.is_whitespace() {
103 let mut la = idx + 1;
105 while la < chars.len() && chars[la].is_whitespace() {
106 la += 1;
107 }
108 if la < chars.len()
109 && matches!(
110 chars[la],
111 '年' | '년' | '月' | '월' | '日' | '号' | '일' | '時' | '时' | '시' | '分' | '분' | '秒' | '초'
112 )
113 {
114 idx += 1;
115 continue;
116 }
117 }
118 if !cur_num.is_empty() {
119 let val: u32 = cur_num.parse().ok()?;
120 let len = cur_num.len();
121 cur_num.clear();
122 match ch {
123 '年' | '년' => {
124 year = Some(if len <= 2 {
125 expand_two_digit_year(val)
126 } else {
127 val as i32
128 });
129 }
130 '月' | '월' => month = Some(val),
131 '日' | '号' | '일' => day = Some(val),
132 '時' | '时' | '시' => {
133 hour = val;
134 has_time = true;
135 }
136 '分' | '분' => {
137 minute = val;
138 has_time = true;
139 }
140 '秒' | '초' => {
141 second = val;
142 has_time = true;
143 }
144 ':' => {
145 if len == 4 && day.is_none() {
147 let d_cand = val / 100;
148 let h_cand = val % 100;
149 if (1..=31).contains(&d_cand) && h_cand <= 23 {
150 day = Some(d_cand);
151 let byte_idx = s
152 .char_indices()
153 .nth(idx)
154 .map(|(b, _)| b)
155 .unwrap_or(0);
156 if let Some(t) = parse_time_str(&format!("{}{}", h_cand, &s[byte_idx..])) {
157 hour = t.hour();
158 minute = t.minute();
159 second = t.second();
160 has_time = true;
161 break;
162 }
163 }
164 }
165 let byte_idx = s
166 .char_indices()
167 .nth(idx)
168 .map(|(b, _)| b)
169 .unwrap_or(0);
170 let start = s[..byte_idx]
171 .char_indices()
172 .rev()
173 .find(|&(_, c)| !c.is_ascii_digit())
174 .map(|(p, c)| p + c.len_utf8())
175 .unwrap_or(0);
176 if let Some(t) = parse_time_str(s[start..].trim()) {
177 hour = t.hour();
178 minute = t.minute();
179 second = t.second();
180 has_time = true;
181 break;
182 }
183 }
184 _ => loose_nums.push((val, len)),
185 }
186 }
187 idx += 1;
188 }
189
190 if !cur_num.is_empty() {
191 let len = cur_num.len();
192 if let Ok(val) = cur_num.parse::<u32>() {
193 loose_nums.push((val, len));
194 }
195 }
196
197 for (val, len) in loose_nums {
198 if year.is_none() && len == 4 && (1000..=2999).contains(&val) {
199 year = Some(val as i32);
200 } else if day.is_none() && (1..=31).contains(&val) && len <= 2 {
201 day = Some(val);
202 }
203 }
204
205 if year.is_none() && month.is_none() {
206 return None;
207 }
208
209 let mut part_of_day: Option<PartOfDay> = None;
210 let mut tod_time: Option<NaiveTime> = None;
211 if has_time {
212 if is_pm && hour >= 1 && hour < 12 {
213 hour += 12;
214 } else if is_am && hour == 12 {
215 hour = 0;
216 }
217 } else {
218 let tod_hour: Option<u8> = [
219 ("真夜中", 0u8),
220 ("午夜", 0),
221 ("자정", 0),
222 ("早上", 9),
223 ("上午", 9),
224 ("아침", 9),
225 ("오전", 9),
226 ("朝", 9),
227 ("正午", 12),
228 ("中午", 12),
229 ("정오", 12),
230 ("午後", 15),
231 ("下午", 15),
232 ("오후", 15),
233 ("夕方", 18),
234 ("傍晚", 18),
235 ("저녁", 18),
236 ("晚上", 20),
237 ("夜", 20),
238 ("밤", 20),
239 ]
240 .into_iter()
241 .find(|(tok, _)| s.contains(tok))
242 .map(|(_, h)| h);
243
244 if let Some(h) = tod_hour {
245 has_time = true;
246 part_of_day = PartOfDay::from_hour(h);
247 if h == 0 || h == 12 {
248 tod_time = NaiveTime::from_hms_opt(h as u32, 0, 0);
249 } else if let Some(p) = part_of_day {
250 tod_time = Some(settings.parts_of_day.time_for(p));
251 }
252 }
253 }
254
255 let base = settings.effective_base();
256 let (y, m, d, period, parts) = complete_partial_date(year, month, day, has_time, base, settings)?;
257 let nd = NaiveDate::from_ymd_opt(y, m, d)?;
258 let nt = tod_time.or_else(|| NaiveTime::from_hms_opt(hour, minute, second))?;
259 let lang = if is_korean {
260 "ko"
261 } else if s.contains('時') || s.contains('朝') || s.contains('夜') || s.contains("夕方") || s.contains("正午") || s.contains("真夜中") {
262 "ja"
263 } else {
264 "zh"
265 };
266
267 Some(AbsoluteMatch {
268 naive: nd.and_time(nt),
269 period,
270 locale: lang.to_string(),
271 has_time,
272 parts,
273 part_of_day,
274 })
275}
276
277fn lookup_month(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
278 if let Some(&m) = loc.months.get(s) {
279 return Some(m);
280 }
281 if normalize {
282 let f = fold_diacritics(s);
283 if let Some(&m) = loc.folded_months.get(&f) {
284 return Some(m);
285 }
286 }
287 None
288}
289
290fn lookup_weekday(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
291 if let Some(&w) = loc.weekdays.get(s) {
292 return Some(w);
293 }
294 if normalize {
295 let f = fold_diacritics(s);
296 if let Some(&w) = loc.folded_weekdays.get(&f) {
297 return Some(w);
298 }
299 }
300 None
301}
302
303fn lookup_tod_hour(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
304 if let Some(&h) = loc.time_of_day.get(s) {
305 return Some(h);
306 }
307 if normalize {
308 let f = fold_diacritics(s);
309 if let Some(&h) = loc.folded_time_of_day.get(&f).or_else(|| loc.time_of_day.get(&f)) {
310 return Some(h);
311 }
312 }
313 None
314}
315
316fn tod_hour_to_time_and_pod(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
317 match hour {
318 3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
319 9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
320 15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
321 18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
322 20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
323 12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
324 0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
325 h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
326 }
327}
328
329fn try_parse_in_locale(
330 normalized: &str,
331 loc: &CompiledLocale,
332 settings: &Settings,
333) -> Option<AbsoluteMatch> {
334 let raw_tokens = split_date_tokens(normalized, loc, settings.normalize);
335 if raw_tokens.is_empty() || raw_tokens.len() > 18 {
336 return None;
337 }
338
339 let mut year: Option<i32> = None;
340 let mut month: Option<u32> = None;
341 let mut day: Option<u32> = None;
342 let mut weekday_seen: Option<u8> = None;
343 let mut time: Option<NaiveTime> = None;
344 let mut part_of_day: Option<PartOfDay> = None;
345 let mut ampm: Option<bool> = None;
346 let mut free_nums: Vec<(u32, usize)> = Vec::new();
347 let mut matched_locale_signal = false;
348
349 let mut i = 0;
350 while i < raw_tokens.len() {
351 let tok = raw_tokens[i];
352 let clean = tok.trim_matches(|c: char| matches!(c, ',' | '.' | '(' | ')' | '[' | ']'));
353 if clean.is_empty() {
354 i += 1;
355 continue;
356 }
357
358 if settings
359 .skip_tokens
360 .iter()
361 .any(|st| st.eq_ignore_ascii_case(clean))
362 {
363 i += 1;
364 continue;
365 }
366
367 if year.is_none() && time.is_none() && clean.len() >= 12 {
369 if let Some((y_part, t_part)) = clean.split_once(':') {
370 if y_part.len() == 4 && y_part.bytes().all(|b| b.is_ascii_digit()) {
371 if let (Ok(y_val), Some(t_val)) = (y_part.parse::<i32>(), parse_time_str(t_part)) {
372 if (1000..=2999).contains(&y_val) {
373 year = Some(y_val);
374 time = Some(t_val);
375 i += 1;
376 continue;
377 }
378 }
379 }
380 }
381 }
382
383 if time.is_none()
385 && (clean.contains(':')
386 || (clean.len() >= 4
387 && clean.contains('.')
388 && clean.as_bytes()[0].is_ascii_digit()
389 && clean.matches('.').count() == 1)
390 || (clean.len() >= 3
391 && clean.as_bytes()[0].is_ascii_digit()
392 && (clean.contains('h')
393 || clean.ends_with("am")
394 || clean.ends_with("pm")
395 || clean.ends_with("a.m")
396 || clean.ends_with("p.m")
397 || tok.ends_with("a.m.")
398 || tok.ends_with("p.m."))))
399 {
400 let time_cand = if tok.ends_with("a.m.") || tok.ends_with("p.m.") {
401 tok.trim_matches(',')
402 } else {
403 clean
404 };
405 if i + 1 < raw_tokens.len() {
406 let next_clean = raw_tokens[i + 1].trim_matches(|c: char| c == '.' || c == ',');
407 if next_clean == "am"
408 || next_clean == "pm"
409 || next_clean == "a.m"
410 || next_clean == "p.m"
411 || next_clean == "ip"
412 || next_clean == "ap"
413 || next_clean == "uhr"
414 || loc.am.contains(next_clean)
415 || loc.pm.contains(next_clean)
416 {
417 let combined = format!("{} {}", time_cand, raw_tokens[i + 1].trim_matches(','));
418 if let Some(t) = parse_time_str(&combined) {
419 time = Some(t);
420 i += 2;
421 continue;
422 }
423 }
424 }
425 if let Some(t) = parse_time_str(time_cand) {
426 time = Some(t);
427 i += 1;
428 continue;
429 }
430 }
431
432 if month.is_none() {
434 let mut matched_span = 0usize;
435 for span in (1..=5).rev() {
436 if i + span <= raw_tokens.len() {
437 let cand = if span == 1 {
438 clean.to_string()
439 } else {
440 let mut s = String::from(clean);
441 for k in 1..span {
442 s.push(' ');
443 s.push_str(raw_tokens[i + k].trim_matches(','));
444 }
445 s
446 };
447 if let Some(m) = lookup_month(&cand, loc, settings.normalize) {
448 month = Some(m as u32);
449 matched_locale_signal = true;
450 matched_span = span;
451 break;
452 }
453 }
454 }
455 if matched_span > 0 {
456 i += matched_span;
457 continue;
458 }
459 }
460
461 if clean == "pm" || clean == "p.m" || loc.pm.contains(clean) {
463 ampm = Some(true);
464 i += 1;
465 continue;
466 }
467 if clean == "am" || clean == "a.m" || loc.am.contains(clean) {
468 ampm = Some(false);
469 i += 1;
470 continue;
471 }
472
473 if weekday_seen.is_none() {
475 let mut matched_span = 0usize;
476 for span in (1..=4).rev() {
477 if i + span <= raw_tokens.len() {
478 let cand = if span == 1 {
479 clean.to_string()
480 } else {
481 let mut s = String::from(clean);
482 for k in 1..span {
483 s.push(' ');
484 s.push_str(raw_tokens[i + k].trim_matches(','));
485 }
486 s
487 };
488 if let Some(wd) = lookup_weekday(&cand, loc, settings.normalize) {
489 weekday_seen = Some(wd);
490 matched_locale_signal = true;
491 matched_span = span;
492 break;
493 }
494 }
495 }
496 if matched_span > 0 {
497 i += matched_span;
498 continue;
499 }
500 }
501
502 if time.is_none() {
504 if i + 1 < raw_tokens.len() {
505 let bigram = format!("{} {}", clean, raw_tokens[i + 1].trim_matches(','));
506 if let Some(h) = lookup_tod_hour(&bigram, loc, settings.normalize) {
507 let (t, pod) = tod_hour_to_time_and_pod(h, settings);
508 time = Some(t);
509 part_of_day = pod;
510 i += 2;
511 continue;
512 }
513 }
514 if let Some(h) = lookup_tod_hour(clean, loc, settings.normalize) {
515 let (t, pod) = tod_hour_to_time_and_pod(h, settings);
516 time = Some(t);
517 part_of_day = pod;
518 i += 1;
519 continue;
520 }
521 }
522
523 if let Some((num, digit_len)) = parse_date_number_or_ordinal(clean) {
525 if digit_len == 4 && (1000..=2999).contains(&num) && year.is_none() {
526 year = Some(num as i32);
527 } else {
528 free_nums.push((num, digit_len));
529 }
530 i += 1;
531 continue;
532 }
533
534 if loc.skip.contains(clean)
536 || loc.units.contains_key(clean)
537 || matches!(
538 clean,
539 "at" | "on" | "of" | "the" | "in" | "de" | "del" | "el" | "la" | "le" | "à"
540 | "am" | "um" | "den" | "saat" | "tarih" | "tarihinde" | "в" | "г" | "года"
541 | "год" | "günü" | "gunu" | "yılında" | "yilinda" | "yılı" | "year" | "klo"
542 | "u" | "у" | "سنة" | "år"
543 )
544 {
545 i += 1;
546 continue;
547 }
548
549 return None;
550 }
551
552 if !matched_locale_signal && year.is_none() {
553 return None;
554 }
555
556 let has_time = time.is_some();
557 if let (Some(t), Some(is_pm)) = (time, ampm) {
558 let mut h = t.hour();
559 if is_pm && h >= 1 && h < 12 {
560 h += 12;
561 } else if !is_pm && h == 12 {
562 h = 0;
563 }
564 time = NaiveTime::from_hms_nano_opt(h, t.minute(), t.second(), t.nanosecond());
565 }
566
567 let year_first = year.is_some()
568 && raw_tokens
569 .first()
570 .and_then(|t| parse_date_number_or_ordinal(t))
571 .map(|(n, l)| l == 4 && n as i32 == year.unwrap())
572 .unwrap_or(false);
573
574 let order = if settings.date_order.is_some() || settings.region.is_some() {
575 settings.effective_date_order(loc.date_order)
576 } else if year_first {
577 DateOrder::YMD
578 } else if settings.prefer_locale_date_order {
579 loc.date_order
580 } else {
581 DateOrder::MDY
582 };
583
584 match free_nums.as_slice() {
585 [] => {}
586 [(n, len)] => {
587 if month.is_some() && day.is_none() && (1..=31).contains(n) && *len <= 2 {
588 day = Some(*n);
589 } else if year.is_none() && *len == 2 {
590 year = Some(expand_two_digit_year(*n));
591 } else {
592 return None;
593 }
594 }
595 [(n1, l1), (n2, l2)] => {
596 if month.is_some() && day.is_none() && year.is_none() {
597 if (1..=31).contains(n1) && *l1 <= 2 && *l2 == 2 {
598 day = Some(*n1);
599 year = Some(expand_two_digit_year(*n2));
600 } else if (1..=31).contains(n2) && *l2 <= 2 && *l1 == 2 {
601 year = Some(expand_two_digit_year(*n1));
602 day = Some(*n2);
603 } else if (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
604 day = Some(*n1);
606 } else {
607 return None;
608 }
609 } else if month.is_some() && year.is_some() && day.is_none() && (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
610 day = Some(*n1);
612 } else if month.is_none() && day.is_none() {
613 match order {
614 DateOrder::YMD | DateOrder::MDY if (1..=12).contains(n1) && (1..=31).contains(n2) => {
615 month = Some(*n1);
616 day = Some(*n2);
617 }
618 DateOrder::YMD | DateOrder::MDY if settings.strict_date_order == StrictDateOrder::All => {
619 return None;
620 }
621 _ if (1..=31).contains(n1) && (1..=12).contains(n2) => {
622 day = Some(*n1);
623 month = Some(*n2);
624 }
625 _ if settings.strict_date_order == StrictDateOrder::All => {
626 return None;
627 }
628 _ if (1..=12).contains(n1) && (1..=31).contains(n2) => {
629 month = Some(*n1);
630 day = Some(*n2);
631 }
632 _ => return None,
633 }
634 } else {
635 return None;
636 }
637 }
638 _ => return None,
639 }
640
641 if year.is_none() && month.is_none() && day.is_none() {
642 let wd = weekday_seen?;
643 if settings.strict_parsing
644 || settings.require_parts.contains(&DatePart::Year)
645 || settings.require_parts.contains(&DatePart::Month)
646 || settings.require_parts.contains(&DatePart::Day)
647 {
648 return None;
649 }
650 let base = settings.effective_base();
651 let cur_wd = base.weekday().num_days_from_monday() as i64;
652 let tgt_wd = wd as i64;
653 let diff = match settings.prefer_dates_from {
654 PreferDatesFrom::Past | PreferDatesFrom::CurrentPeriod => {
655 let mut d = tgt_wd - cur_wd;
656 if d > 0 {
657 d -= 7;
658 }
659 d
660 }
661 PreferDatesFrom::Future => {
662 let mut d = tgt_wd - cur_wd;
663 if d < 0 {
664 d += 7;
665 }
666 d
667 }
668 };
669 let target_date = base.date() + chrono::Duration::days(diff);
670 let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
671 let mut p = vec!["year", "month", "day"];
672 if has_time {
673 p.push("time");
674 }
675 return Some(AbsoluteMatch {
676 naive: target_date.and_time(nt),
677 period: Period::Day,
678 locale: loc.code.clone(),
679 has_time,
680 parts: p,
681 part_of_day,
682 });
683 }
684
685 let base = settings.effective_base();
686 let (y, m, d, period, parts) =
687 complete_partial_date(year, month, day, has_time, base, settings)?;
688 let nd = NaiveDate::from_ymd_opt(y, m, d)?;
689 let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
690
691 Some(AbsoluteMatch {
692 naive: nd.and_time(nt),
693 period,
694 locale: loc.code.clone(),
695 has_time,
696 parts,
697 part_of_day,
698 })
699}
700
701fn complete_partial_date(
702 year: Option<i32>,
703 month: Option<u32>,
704 day: Option<u32>,
705 has_time: bool,
706 base: NaiveDateTime,
707 settings: &Settings,
708) -> Option<(i32, u32, u32, Period, Vec<&'static str>)> {
709 if settings.strict_parsing && (year.is_none() || month.is_none() || day.is_none()) {
710 return None;
711 }
712 if settings.require_parts.contains(&DatePart::Year) && year.is_none() {
713 return None;
714 }
715 if settings.require_parts.contains(&DatePart::Month) && month.is_none() {
716 return None;
717 }
718 if settings.require_parts.contains(&DatePart::Day) && day.is_none() {
719 return None;
720 }
721
722 let period = if day.is_some() {
723 Period::Day
724 } else if month.is_some() {
725 Period::Month
726 } else {
727 Period::Year
728 };
729
730 let mut parts = Vec::with_capacity(4);
731 if year.is_some() {
732 parts.push("year");
733 }
734 if month.is_some() {
735 parts.push("month");
736 }
737 if day.is_some() {
738 parts.push("day");
739 }
740 if has_time {
741 parts.push("time");
742 }
743
744 let m = month.unwrap_or_else(|| match settings.prefer_month_of_year {
745 PreferMonthOfYear::First => 1,
746 PreferMonthOfYear::Last => 12,
747 PreferMonthOfYear::Current => base.month(),
748 });
749 if !(1..=12).contains(&m) {
750 return None;
751 }
752
753 let mut y = year.unwrap_or_else(|| base.year());
754 let d = day.unwrap_or_else(|| resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month));
755 if d < 1 || d > days_in_month(y, m) {
756 return None;
757 }
758
759 if year.is_none() {
760 if let Some(cand) = NaiveDate::from_ymd_opt(y, m, d) {
761 match settings.prefer_dates_from {
762 PreferDatesFrom::Past if cand > base.date() => y -= 1,
763 PreferDatesFrom::Future if cand < base.date() => y += 1,
764 _ => {}
765 }
766 }
767 }
768
769 let final_d = d.min(days_in_month(y, m));
770 Some((y, m, final_d, period, parts))
771}
772
773fn split_date_tokens<'a>(s: &'a str, loc: &CompiledLocale, normalize: bool) -> Vec<&'a str> {
774 let mut out = Vec::with_capacity(8);
775 for chunk in s.split(|c: char| {
776 c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
777 }) {
778 if chunk.is_empty() {
779 continue;
780 }
781 if chunk.contains('.')
783 && !chunk.contains(':')
784 && !chunk.ends_with("a.m.")
785 && !chunk.ends_with("p.m.")
786 && !(chunk.matches('.').count() == 1
787 && chunk.chars().all(|c| c.is_ascii_digit() || c == '.'))
788 {
789 let clean = chunk.trim_matches('.');
790 if lookup_month(clean, loc, normalize).is_some()
791 || lookup_weekday(clean, loc, normalize).is_some()
792 {
793 out.push(clean);
794 continue;
795 }
796 for sub in chunk.split('.') {
797 if !sub.is_empty() {
798 push_splitting_attached_digits(sub, loc, normalize, &mut out);
799 }
800 }
801 continue;
802 }
803 if chunk.contains('-') {
804 let clean = chunk.trim_matches('.');
805 if lookup_month(clean, loc, normalize).is_some()
806 || lookup_weekday(clean, loc, normalize).is_some()
807 || loc.months.keys().any(|k| k.split_whitespace().any(|w| w == clean))
808 {
809 out.push(chunk);
810 continue;
811 }
812 for sub in chunk.split('-') {
813 if !sub.is_empty() {
814 push_splitting_attached_digits(sub, loc, normalize, &mut out);
815 }
816 }
817 } else {
818 push_splitting_attached_digits(chunk, loc, normalize, &mut out);
819 }
820 }
821 out
822}
823
824fn push_splitting_attached_digits<'a>(
825 tok: &'a str,
826 loc: &CompiledLocale,
827 normalize: bool,
828 out: &mut Vec<&'a str>,
829) {
830 if tok.contains(':')
832 || tok.ends_with("am")
833 || tok.ends_with("pm")
834 || tok.ends_with("a.m.")
835 || tok.ends_with("p.m.")
836 || tok.bytes().all(|b| b.is_ascii_digit())
837 || parse_date_number_or_ordinal(tok).is_some()
838 || lookup_month(tok, loc, normalize).is_some()
839 || lookup_weekday(tok, loc, normalize).is_some()
840 {
841 out.push(tok);
842 return;
843 }
844 let has_digit = tok.chars().any(|c| c.is_ascii_digit());
846 let has_alpha = tok.chars().any(|c| c.is_alphabetic());
847 if !has_digit || !has_alpha {
848 out.push(tok);
849 return;
850 }
851 if tok.contains('h') && tok.chars().all(|c| c.is_ascii_digit() || c == 'h' || c == 'm' || c == 's') {
853 out.push(tok);
854 return;
855 }
856 let mut start = 0usize;
857 let mut prev_digit = tok.chars().next().unwrap().is_ascii_digit();
858 for (idx, ch) in tok.char_indices().skip(1) {
859 let cur_digit = ch.is_ascii_digit();
860 if cur_digit != prev_digit {
861 out.push(&tok[start..idx]);
862 start = idx;
863 prev_digit = cur_digit;
864 }
865 }
866 if start < tok.len() {
867 out.push(&tok[start..]);
868 }
869}
870
871fn parse_date_number_or_ordinal(s: &str) -> Option<(u32, usize)> {
872 if s.is_empty() || s.len() > 6 {
873 return None;
874 }
875 let stripped = s
876 .strip_suffix("st")
877 .or_else(|| s.strip_suffix("nd"))
878 .or_else(|| s.strip_suffix("rd"))
879 .or_else(|| s.strip_suffix("th"))
880 .or_else(|| s.strip_suffix("er"))
881 .or_else(|| s.strip_suffix('º'))
882 .or_else(|| s.strip_suffix('ª'))
883 .unwrap_or(s);
884
885 if stripped.is_empty() || stripped.len() > 4 || !stripped.bytes().all(|b| b.is_ascii_digit()) {
886 return None;
887 }
888 let val: u32 = stripped.parse().ok()?;
889 Some((val, stripped.len()))
890}