1use crate::fast_path::{days_in_month, parse_time_str};
2use crate::locale::TimeUnit;
3use crate::relative::apply_relative_offset;
4use crate::settings::{ParsedDateTime, Period, Settings};
5use crate::timezone::{finalize_datetime_checked, is_valid_year_range, resolve_iana_local};
6use crate::{get_date_data, parse_with_settings};
7use chrono::{Datelike, Duration, NaiveDate};
8
9const RANGE_INTRODUCERS: &[&str] = &[
10 "between ", "from ", "von ", "zwischen ", "du ", "entre ", "desde ", "del ", "de ",
11];
12
13const RANGE_CONNECTORS: &[&str] = &[
14 " jusqu'au ",
15 " jusqu'à ",
16 " through ",
17 " until ",
18 " thru ",
19 " entre ",
20 " hasta ",
21 " and ",
22 " bis ",
23 " ile ",
24 " по ",
25 " to ",
26 " au ",
27 " al ",
28 " ve ",
29 " - ",
30 " – ",
31 " — ",
32 " 〜 ",
33 " ~ ",
34 " ~ ",
35 "..",
36 "〜",
37 "~",
38 "到",
39];
40
41pub fn parse_date_range(
45 input: &str,
46 settings: &Settings,
47) -> Option<(ParsedDateTime, ParsedDateTime)> {
48 let cleaned_surface = crate::locale::clean_unicode_surface(input);
49 let mut s = cleaned_surface.trim();
50 if s.is_empty() || s.len() > 200 {
51 return None;
52 }
53
54 if let Some(pair) = try_iso_interval(s, settings) {
56 return Some(pair);
57 }
58
59 if is_single_iso_like(s) {
61 return None;
62 }
63
64 if let Some(pair) = try_tight_time_range(s, settings) {
66 return Some(pair);
67 }
68
69 let mut stripped_intro = false;
70 for prefix in ["с ", "С ", "от ", "От "] {
71 if let Some(rest) = s.strip_prefix(prefix) {
72 s = rest.trim_start();
73 stripped_intro = true;
74 break;
75 }
76 }
77 if !stripped_intro {
78 let ascii_lower = s.to_ascii_lowercase();
79 for prefix in RANGE_INTRODUCERS {
80 if ascii_lower.starts_with(prefix) && s.len() > prefix.len() {
81 s = s[prefix.len()..].trim_start();
82 break;
83 }
84 }
85 }
86
87 if let Some(pair) = try_split_connector_range(s, settings) {
89 return Some(pair);
90 }
91
92 if let Some(pair) = try_compact_same_month_range(s, settings) {
94 return Some(pair);
95 }
96
97 None
98}
99
100fn is_single_iso_like(s: &str) -> bool {
101 let b = s.as_bytes();
102 b.len() >= 10
103 && b[0..4].iter().all(|c| c.is_ascii_digit())
104 && b[4] == b'-'
105 && !s.contains([' ', '–', '—', '~', '/'])
106 && !s.contains("..")
107}
108
109fn shift_parsed_days(dt: &ParsedDateTime, delta_days: i64) -> Option<ParsedDateTime> {
110 if delta_days == 0 {
111 return Some(dt.clone());
112 }
113 let delta = Duration::try_days(delta_days)?;
114 Some(match dt {
115 ParsedDateTime::Naive(ndt) => ParsedDateTime::Naive(ndt.checked_add_signed(delta)?),
116 ParsedDateTime::FixedOffset(fdt) => {
117 ParsedDateTime::FixedOffset(fdt.checked_add_signed(delta)?)
118 }
119 ParsedDateTime::Tz(tdt) => ParsedDateTime::Tz(tdt.checked_add_signed(delta)?),
120 })
121}
122
123fn snap_range_endpoint(
124 dt: ParsedDateTime,
125 period: Period,
126 parts: &[&'static str],
127 is_end: bool,
128) -> ParsedDateTime {
129 let naive = dt.naive_local();
130 if period == Period::Month && !parts.contains(&"day") {
131 let target_day = if is_end {
132 days_in_month(naive.year(), naive.month())
133 } else {
134 1
135 };
136 let delta = target_day as i64 - naive.day() as i64;
137 return shift_parsed_days(&dt, delta).unwrap_or(dt);
138 }
139 if period == Period::Year && !parts.contains(&"month") {
140 let target = if is_end {
141 NaiveDate::from_ymd_opt(naive.year(), 12, 31)
142 } else {
143 NaiveDate::from_ymd_opt(naive.year(), 1, 1)
144 };
145 if let Some(td) = target {
146 let delta = (td - naive.date()).num_days();
147 return shift_parsed_days(&dt, delta).unwrap_or(dt);
148 }
149 }
150 dt
151}
152
153fn try_iso_interval(s: &str, settings: &Settings) -> Option<(ParsedDateTime, ParsedDateTime)> {
154 let (left, right) = s.split_once('/')?;
155 let lb = left.as_bytes();
156 if right.contains('/') || lb.len() < 10 || !lb[0..4].iter().all(|b| b.is_ascii_digit()) || lb[4] != b'-' {
157 return None;
158 }
159 let start_dt = parse_with_settings(left.trim(), settings)?;
160 let r = right.trim();
161 if r.starts_with('P') || r.starts_with('p') {
162 let (date_shifted, time_delta) = apply_iso_duration_split(start_dt.naive_local(), r)?;
163 let end_dt = match start_dt {
164 ParsedDateTime::Naive(_) => ParsedDateTime::Naive(date_shifted.checked_add_signed(time_delta)?),
165 ParsedDateTime::FixedOffset(f) => {
166 let d_delta = date_shifted - start_dt.naive_local();
167 let total_delta = d_delta.checked_add(&time_delta)?;
168 ParsedDateTime::FixedOffset(f.checked_add_signed(total_delta)?)
169 }
170 ParsedDateTime::Tz(t) => {
171 let localized = resolve_iana_local(t.timezone(), date_shifted);
172 ParsedDateTime::Tz(localized.checked_add_signed(time_delta)?)
173 }
174 };
175 if !is_valid_year_range(&end_dt) {
176 return None;
177 }
178 return Some((start_dt, end_dt));
179 }
180 if r.len() >= 10 && r.as_bytes()[0..4].iter().all(|b| b.is_ascii_digit()) && r.as_bytes()[4] == b'-' {
181 let end_dt = parse_with_settings(r, settings)?;
182 return Some((start_dt, end_dt));
183 }
184 None
185}
186
187fn apply_iso_duration_split(
188 mut cur: chrono::NaiveDateTime,
189 dur: &str,
190) -> Option<(chrono::NaiveDateTime, Duration)> {
191 let body = dur.strip_prefix('P').or_else(|| dur.strip_prefix('p'))?;
192 if body.is_empty() {
193 return None;
194 }
195 let mut in_time = false;
196 let mut num_buf = String::new();
197 let mut time_delta = Duration::zero();
198 let mut applied = false;
199 for ch in body.chars() {
200 if ch == 'T' || ch == 't' {
201 if !num_buf.is_empty() {
202 return None;
203 }
204 in_time = true;
205 continue;
206 }
207 if ch.is_ascii_digit() {
208 num_buf.push(ch);
209 continue;
210 }
211 let val_i: i64 = num_buf.parse().ok()?;
212 let val: f64 = num_buf.parse().ok()?;
213 num_buf.clear();
214 if in_time {
215 let add = match ch.to_ascii_uppercase() {
216 'H' => Duration::try_hours(val_i)?,
217 'M' => Duration::try_minutes(val_i)?,
218 'S' => Duration::try_seconds(val_i)?,
219 _ => return None,
220 };
221 time_delta = time_delta.checked_add(&add)?;
222 } else {
223 let unit = match ch.to_ascii_uppercase() {
224 'Y' => TimeUnit::Year,
225 'M' => TimeUnit::Month,
226 'W' => TimeUnit::Week,
227 'D' => TimeUnit::Day,
228 _ => return None,
229 };
230 cur = apply_relative_offset(cur, 1, val, unit)?;
231 }
232 applied = true;
233 }
234 if !num_buf.is_empty() || !applied {
235 return None;
236 }
237 Some((cur, time_delta))
238}
239
240fn try_tight_time_range(s: &str, settings: &Settings) -> Option<(ParsedDateTime, ParsedDateTime)> {
241 for sep in ['-', '–', '—'] {
242 if let Some((l, r)) = s.split_once(sep) {
243 if let (Some(t1), Some(t2)) = (parse_time_str(l.trim()), parse_time_str(r.trim())) {
244 let base = settings.effective_base();
245 let d1 = base.date().and_time(t1);
246 let d2_date = if t2 < t1 {
247 base.date()
248 .succ_opt()
249 .filter(|d| (1..=9999).contains(&d.year()))?
250 } else {
251 base.date()
252 };
253 return Some((
254 finalize_datetime_checked(d1, None, settings)?,
255 finalize_datetime_checked(d2_date.and_time(t2), None, settings)?,
256 ));
257 }
258 }
259 }
260 None
261}
262
263fn try_split_connector_range(
264 s: &str,
265 settings: &Settings,
266) -> Option<(ParsedDateTime, ParsedDateTime)> {
267 let ascii_lower = s.to_ascii_lowercase();
268 for &conn in RANGE_CONNECTORS {
269 let split_pos = if conn.is_ascii() {
271 ascii_lower.find(conn).map(|pos| (pos, pos + conn.len()))
272 } else {
273 s.find(conn).map(|pos| (pos, pos + conn.len()))
274 };
275
276 let Some((start, end)) = split_pos else {
277 continue;
278 };
279 let left = s[..start].trim();
280 let right = s[end..].trim();
281 if left.is_empty() || right.is_empty() {
282 continue;
283 }
284
285 if let (Some(t1), Some(t2)) = (parse_time_str(left), parse_time_str(right)) {
287 let base = settings.effective_base();
288 let d1 = base.date().and_time(t1);
289 let d2_date = if t2 < t1 {
290 base.date()
291 .succ_opt()
292 .filter(|d| (1..=9999).contains(&d.year()))?
293 } else {
294 base.date()
295 };
296 let d2 = d2_date.and_time(t2);
297 return Some((
298 finalize_datetime_checked(d1, None, settings)?,
299 finalize_datetime_checked(d2, None, settings)?,
300 ));
301 }
302
303 if let Some(t2) = parse_time_str(right) {
305 if let Some(start_dt) = parse_with_settings(left, settings) {
306 let sn = start_dt.naive_local();
307 let d2_date = if t2 < sn.time() {
308 sn.date()
309 .succ_opt()
310 .filter(|d| (1..=9999).contains(&d.year()))?
311 } else {
312 sn.date()
313 };
314 let end_naive = d2_date.and_time(t2);
315 let end_dt = finalize_datetime_checked(end_naive, None, settings)?;
316 return Some((start_dt, end_dt));
317 }
318 }
319
320 let end_dd = get_date_data(right, settings);
322 if end_dd.date_obj.is_none()
323 && (right.ends_with('日') || right.ends_with('号') || right.ends_with('일'))
324 {
325 if let Some(start_dt) = parse_with_settings(left, settings) {
326 let sn = start_dt.naive_local();
327 let inherited = if right.ends_with('일') {
328 format!("{}년 {}월 {}", sn.year(), sn.month(), right)
329 } else {
330 format!("{}年{}月{}", sn.year(), sn.month(), right)
331 };
332 if let Some(end_dt) = parse_with_settings(&inherited, settings) {
333 return Some((start_dt, end_dt));
334 }
335 }
336 }
337
338 let Some(raw_end_dt) = end_dd.date_obj else {
339 continue;
340 };
341 let end_dt = snap_range_endpoint(raw_end_dt, end_dd.period, &end_dd.parts, true);
342
343 if is_day_num(left) {
345 if let Ok(d) = left.parse::<u32>() {
346 let en = end_dt.naive_local();
347 if let Some(sd) = NaiveDate::from_ymd_opt(en.year(), en.month(), d) {
348 if let Some(start_dt) = finalize_datetime_checked(sd.and_time(en.time()), None, settings) {
349 return Some((start_dt, end_dt));
350 }
351 }
352 }
353 }
354
355 let left_has_year = has_four_digit_year(left);
357 if !left_has_year {
358 let end_year = end_dt.naive_local().year();
359 if !left.chars().any(|c| c.is_ascii_digit()) {
360 let direct_dd = get_date_data(left, settings);
361 if let Some(raw_direct) = direct_dd.date_obj {
362 if raw_direct.naive_local().year() == end_year {
363 let start_dt =
364 snap_range_endpoint(raw_direct, direct_dd.period, &direct_dd.parts, false);
365 let mut final_end = end_dt;
366 if start_dt.naive_local() > final_end.naive_local()
367 && !right.chars().any(|c| c.is_ascii_digit())
368 {
369 if let Some(shifted) = shift_parsed_days(&final_end, 7) {
370 if is_valid_year_range(&shifted) {
371 final_end = shifted;
372 }
373 }
374 }
375 return Some((start_dt, final_end));
376 }
377 }
378 }
379 let left_with_year = format!("{} {}", left.trim_end_matches(','), end_year);
380 let left_dd = get_date_data(&left_with_year, settings);
381 if let Some(raw_start) = left_dd.date_obj {
382 let mut start_dt =
383 snap_range_endpoint(raw_start, left_dd.period, &left_dd.parts, false);
384 if start_dt.naive_local() > end_dt.naive_local() {
385 let prev_year = format!("{} {}", left.trim_end_matches(','), end_year - 1);
386 let prev_dd = get_date_data(&prev_year, settings);
387 if let Some(raw_prev) = prev_dd.date_obj {
388 start_dt =
389 snap_range_endpoint(raw_prev, prev_dd.period, &prev_dd.parts, false);
390 }
391 }
392 return Some((start_dt, end_dt));
393 }
394 }
395
396 let start_dd = get_date_data(left, settings);
397 if let Some(raw_start) = start_dd.date_obj {
398 let start_dt =
399 snap_range_endpoint(raw_start, start_dd.period, &start_dd.parts, false);
400 return Some((start_dt, end_dt));
401 }
402 }
403 None
404}
405
406fn has_four_digit_year(s: &str) -> bool {
407 let mut run = 0usize;
408 for b in s.bytes() {
409 if b.is_ascii_digit() {
410 run += 1;
411 if run == 4 {
412 return true;
413 }
414 } else {
415 run = 0;
416 }
417 }
418 false
419}
420
421fn try_compact_same_month_range(
422 s: &str,
423 settings: &Settings,
424) -> Option<(ParsedDateTime, ParsedDateTime)> {
425 let normalized_dashes: String = s
427 .chars()
428 .map(|c| if matches!(c, '–' | '—' | '~' | '~') { '-' } else { c })
429 .collect();
430 let work = normalized_dashes.as_str();
431
432 if work.as_bytes().first().is_some_and(|b| b.is_ascii_digit()) {
434 if let Some(space_idx) = work.find(char::is_whitespace) {
435 let first_tok = &work[..space_idx];
436 let rest = work[space_idx..].trim();
437 if !rest.is_empty() && first_tok.contains('-') {
438 if let Some((d1, d2)) = first_tok.split_once('-') {
439 if is_day_num(d1) && is_day_num(d2) {
440 let left_str = format!("{} {}", d1, rest);
441 let right_str = format!("{} {}", d2, rest);
442 if let (Some(a), Some(b)) = (
443 parse_with_settings(&left_str, settings),
444 parse_with_settings(&right_str, settings),
445 ) {
446 return Some((a, b));
447 }
448 }
449 }
450 }
451 }
452 }
453
454 if let Some(dash_idx) = work.find('-') {
456 let before_dash = &work[..dash_idx];
457 let after_dash = &work[dash_idx + 1..];
458 let d1_start = before_dash
459 .char_indices()
460 .rev()
461 .find(|&(_, c)| !c.is_ascii_digit())
462 .map(|(i, c)| i + c.len_utf8())
463 .unwrap_or(0);
464 let d1 = &before_dash[d1_start..];
465 let prefix = before_dash[..d1_start].trim_end();
466
467 let d2_end = after_dash
468 .find(|c: char| !c.is_ascii_digit())
469 .unwrap_or(after_dash.len());
470 let d2 = &after_dash[..d2_end];
471 let suffix = after_dash[d2_end..].trim();
472
473 if !prefix.is_empty()
474 && prefix.chars().any(|c| c.is_alphabetic())
475 && is_day_num(d1)
476 && is_day_num(d2)
477 {
478 let left_str = if suffix.is_empty() {
479 format!("{} {}", prefix, d1)
480 } else {
481 format!("{} {}{}", prefix, d1, if suffix.starts_with(',') { suffix.to_string() } else { format!(" {}", suffix) })
482 };
483 let right_str = if suffix.is_empty() {
484 format!("{} {}", prefix, d2)
485 } else {
486 format!("{} {}{}", prefix, d2, if suffix.starts_with(',') { suffix.to_string() } else { format!(" {}", suffix) })
487 };
488 if let (Some(a), Some(b)) = (
489 parse_with_settings(&left_str, settings),
490 parse_with_settings(&right_str, settings),
491 ) {
492 return Some((a, b));
493 }
494 }
495 }
496
497 None
498}
499
500#[inline]
501fn is_day_num(s: &str) -> bool {
502 if !(1..=2).contains(&s.len()) || !s.bytes().all(|b| b.is_ascii_digit()) {
503 return false;
504 }
505 matches!(s.parse::<u32>(), Ok(1..=31))
506}