dateoxide-core 0.1.0

High-performance, low-memory multilingual natural-language date parser core in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
pub mod absolute;
pub mod calendars;
pub mod fast_path;
pub mod locale;
pub mod relative;
pub mod search;
pub mod settings;
pub mod time_spans;
pub mod timezone;
pub mod umm_al_qura;

use locale::{normalize_digits_and_lower, LocaleRegistry};
use rayon::prelude::*;
use search::SearchMatch;
use settings::{DateData, ParsedDateTime, ParserKind, Period, Settings};
use timezone::{extract_trailing_timezone_with_abbrevs, finalize_datetime};

/// Parse a date string using default settings.
#[inline]
pub fn parse(input: &str) -> Option<ParsedDateTime> {
    parse_with_settings(input, &Settings::default())
}

/// Parse a date string using explicit `Settings`.
#[inline]
pub fn parse_with_settings(input: &str, settings: &Settings) -> Option<ParsedDateTime> {
    get_date_data(input, settings).date_obj
}

fn strip_user_skip_tokens(input: &str, skip_tokens: &[String]) -> String {
    let mut out = Vec::new();
    for tok in input.split_whitespace() {
        let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
        if skip_tokens
            .iter()
            .any(|sk| sk.eq_ignore_ascii_case(tok) || sk.eq_ignore_ascii_case(clean))
        {
            continue;
        }
        out.push(tok);
    }
    out.join(" ")
}

#[inline]
fn apply_time_period(period: Period, has_time: bool, settings: &Settings) -> Period {
    if settings.return_time_as_period && has_time {
        Period::Time
    } else {
        period
    }
}

/// Relative-only parser backing `dateparser.freshness_date_parser.FreshnessDateDataParser`.
pub fn parse_freshness(input: &str, settings: &Settings) -> DateData {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return DateData::empty();
    }
    let (without_tz, tz) =
        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
    let normalized = normalize_digits_and_lower(without_tz);
    if normalized.is_empty() {
        return DateData::empty();
    }
    let registry = LocaleRegistry::global();
    let tokens: Vec<&str> = normalized
        .split(|c: char| c.is_whitespace() || c == ',' || c == '/')
        .map(|t| t.trim_matches(|c: char| c == '.' || c == '(' || c == ')'))
        .filter(|t| !t.is_empty())
        .collect();
    let candidates = registry.detect_candidates(
        &normalized,
        &tokens,
        settings.languages.as_deref(),
        &settings.default_languages,
        settings.normalize,
    );
    if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
        return DateData {
            date_obj: Some(finalize_datetime(m.naive, tz, settings)),
            period: apply_time_period(m.period, m.has_time, settings),
            locale: Some(m.locale),
            parts: m.parts,
            part_of_day: m.part_of_day,
        };
    }
    DateData::empty()
}

/// Full `dateparser.date.DateDataParser.get_date_data` equivalent returning
/// `DateData { date_obj, period, locale, parts, part_of_day }`.
pub fn get_date_data(input: &str, settings: &Settings) -> DateData {
    let trimmed_raw = input.trim();
    if trimmed_raw.is_empty() {
        return DateData::empty();
    }

    let owned_cleaned;
    let trimmed: &str = if settings.skip_tokens.is_empty() {
        trimmed_raw
    } else {
        owned_cleaned = strip_user_skip_tokens(trimmed_raw, &settings.skip_tokens);
        if owned_cleaned.trim().is_empty() {
            return DateData::empty();
        }
        owned_cleaned.trim()
    };

    // 0. Custom user strptime formats (`date_formats`)
    if let Some(m) = fast_path::try_custom_formats(trimmed, settings) {
        return DateData {
            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
            period: apply_time_period(m.period, m.has_time, settings),
            locale: Some("en".to_string()),
            parts: m.parts,
            part_of_day: None,
        };
    }

    // 1. Zero-regex, zero-allocation fast path
    if let Some(m) = fast_path::try_fast_path(trimmed, settings) {
        return DateData {
            date_obj: Some(finalize_datetime(m.naive, m.tz, settings)),
            period: apply_time_period(m.period, m.has_time, settings),
            locale: Some("en".to_string()),
            parts: m.parts,
            part_of_day: None,
        };
    }

    // 2. Peel off optional trailing timezone before natural-language normalization
    let (without_tz, tz) =
        extract_trailing_timezone_with_abbrevs(trimmed, &settings.timezone_abbreviations);
    let normalized = normalize_digits_and_lower(without_tz);
    if normalized.is_empty() {
        return DateData::empty();
    }

    // Re-check fast path if Unicode digits (e.g. Arabic-Indic / Persian) were normalized to ASCII
    if normalized.as_bytes()[0].is_ascii_digit() && normalized != without_tz {
        if let Some(m) = fast_path::try_fast_path(&normalized, settings) {
            return DateData {
                date_obj: Some(finalize_datetime(m.naive, m.tz.or(tz), settings)),
                period: apply_time_period(m.period, m.has_time, settings),
                locale: Some("en".to_string()),
                parts: m.parts,
                part_of_day: None,
            };
        }
    }

    // 3. Lazy-load the compact 205-language registry and detect top candidates in O(tokens)
    let registry = LocaleRegistry::global();
    let mut tokens: Vec<&str> = Vec::with_capacity(8);
    for chunk in normalized.split(|c: char| {
        c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
    }) {
        let clean = chunk.trim_matches(|c: char| matches!(c, '.' | '(' | ')' | '[' | ']'));
        if clean.is_empty() {
            continue;
        }
        if registry.token_to_langs.contains_key(clean) {
            tokens.push(clean);
            continue;
        }
        for sub in clean.split(['-', '.']) {
            if sub.is_empty() {
                continue;
            }
            if sub.chars().any(|c| c.is_ascii_digit()) && sub.chars().any(|c| c.is_alphabetic()) {
                let mut start = 0usize;
                let mut prev_d = sub.chars().next().unwrap().is_ascii_digit();
                for (idx, ch) in sub.char_indices().skip(1) {
                    let cur_d = ch.is_ascii_digit();
                    if cur_d != prev_d {
                        tokens.push(&sub[start..idx]);
                        start = idx;
                        prev_d = cur_d;
                    }
                }
                if start < sub.len() {
                    tokens.push(&sub[start..]);
                }
            } else {
                tokens.push(sub);
            }
        }
    }

    let candidates = registry.detect_candidates(
        &normalized,
        &tokens,
        settings.languages.as_deref(),
        &settings.default_languages,
        settings.normalize,
    );

    if candidates.is_empty() {
        if settings.allows_parser(ParserKind::AbsoluteTime)
            && (normalized.contains('年')
                || normalized.contains('月')
                || normalized.contains('日')
                || normalized.contains('년')
                || normalized.contains('월')
                || normalized.contains('일'))
        {
            if let Some(m) = absolute::try_parse_absolute(&normalized, &[], registry, settings) {
                return DateData {
                    date_obj: Some(finalize_datetime(m.naive, tz, settings)),
                    period: apply_time_period(m.period, m.has_time, settings),
                    locale: Some(m.locale),
                    parts: m.parts,
                    part_of_day: m.part_of_day,
                };
            }
        }
        return ignore_surrounding_fallback(trimmed, settings);
    }

    // 4. Multilingual Relative Date Engine
    if settings.allows_parser(ParserKind::RelativeTime) {
        if let Some(m) = relative::try_parse_relative(&normalized, &candidates, registry, settings) {
            return DateData {
                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
                period: apply_time_period(m.period, m.has_time, settings),
                locale: Some(m.locale),
                parts: m.parts,
                part_of_day: m.part_of_day,
            };
        }
    }

    // 5. Multilingual Absolute & Partial Date Engine
    if settings.allows_parser(ParserKind::AbsoluteTime) {
        if let Some(m) = absolute::try_parse_absolute(&normalized, &candidates, registry, settings) {
            return DateData {
                date_obj: Some(finalize_datetime(m.naive, tz, settings)),
                period: apply_time_period(m.period, m.has_time, settings),
                locale: Some(m.locale),
                parts: m.parts,
                part_of_day: m.part_of_day,
            };
        }
    }

    ignore_surrounding_fallback(trimmed, settings)
}

fn ignore_surrounding_fallback(trimmed: &str, settings: &Settings) -> DateData {
    if !settings.ignore_surrounding_text {
        return DateData::empty();
    }
    let mut inner = settings.clone();
    inner.ignore_surrounding_text = false;
    let found = search_dates_full(trimmed, &inner);
    if let Some(first) = found.into_iter().next() {
        return DateData {
            date_obj: Some(first.date_obj),
            period: first.period,
            locale: first.locale,
            parts: vec!["year", "month", "day"],
            part_of_day: None,
        };
    }
    DateData::empty()
}

/// Parallel batch parsing powered by Rayon across all available CPU cores.
pub fn parse_batch<S: AsRef<str> + Sync>(
    inputs: &[S],
    settings: &Settings,
) -> Vec<Option<ParsedDateTime>> {
    if inputs.len() < 256 {
        return inputs
            .iter()
            .map(|s| parse_with_settings(s.as_ref(), settings))
            .collect();
    }
    inputs
        .par_iter()
        .map(|s| parse_with_settings(s.as_ref(), settings))
        .collect()
}

/// Find and parse all date expressions embedded in free-form text.
pub fn search_dates(text: &str, settings: &Settings) -> Vec<(String, ParsedDateTime)> {
    search::search_dates(text, settings)
}

/// Find and parse all date expressions embedded in free-form text, including detected locale code.
pub fn search_dates_with_locale(
    text: &str,
    settings: &Settings,
) -> Vec<(String, ParsedDateTime, Option<String>)> {
    search::search_dates_with_locale(text, settings)
}

/// Find and parse all date expressions returning full match metadata.
pub fn search_dates_full(text: &str, settings: &Settings) -> Vec<SearchMatch> {
    search::search_dates_full(text, settings)
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike};
    use settings::{DateOrder, PartOfDay, PreferDatesFrom, PreferDayOfMonth, StrictDateOrder};

    fn fixed_settings() -> Settings {
        Settings {
            relative_base: Some(
                NaiveDate::from_ymd_opt(2026, 11, 26)
                    .unwrap()
                    .and_hms_opt(15, 0, 0)
                    .unwrap(),
            ),
            ..Default::default()
        }
    }

    #[test]
    fn test_fast_path_and_strict_date_order() {
        let mut s = fixed_settings();
        s.date_order = Some(DateOrder::MDY);
        s.strict_date_order = StrictDateOrder::None;
        assert_eq!(
            parse_with_settings("26/11/2026", &s).unwrap().naive_local().date(),
            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
        );

        s.strict_date_order = StrictDateOrder::All;
        assert!(parse_with_settings("26/11/2026", &s).is_none());
        assert_eq!(
            parse_with_settings("2026/11/26", &s).unwrap().naive_local().date(),
            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
        );
    }

    #[test]
    fn test_calendars_conversions() {
        let s = fixed_settings();
        assert_eq!(
            calendars::jalali_to_gregorian(1395, 1, 1),
            Some(NaiveDate::from_ymd_opt(2016, 3, 20).unwrap())
        );
        assert_eq!(
            calendars::jalali_to_gregorian(1400, 1, 1),
            Some(NaiveDate::from_ymd_opt(2021, 3, 21).unwrap())
        );
        assert_eq!(
            calendars::jalali_to_gregorian(1404, 9, 5),
            Some(NaiveDate::from_ymd_opt(2025, 11, 26).unwrap())
        );
        assert_eq!(
            calendars::parse_jalali("۵ آذر ۱۴۰۴", &s).date_obj.unwrap().naive_local().date(),
            NaiveDate::from_ymd_opt(2025, 11, 26).unwrap()
        );

        assert_eq!(
            calendars::hijri_to_gregorian(1445, 1, 1),
            Some(NaiveDate::from_ymd_opt(2023, 7, 19).unwrap())
        );
        assert_eq!(
            calendars::hijri_to_gregorian(1446, 9, 1),
            Some(NaiveDate::from_ymd_opt(2025, 3, 1).unwrap())
        );

        assert_eq!(
            calendars::parse_minguo("115年11月26日", &s).date_obj.unwrap().naive_local().date(),
            NaiveDate::from_ymd_opt(2026, 11, 26).unwrap()
        );

        assert_eq!(
            calendars::french_republican_to_gregorian(1, 1, 1),
            Some(NaiveDate::from_ymd_opt(1792, 9, 22).unwrap())
        );
        assert_eq!(
            calendars::parse_french_republican("14 Germinal an III", &s)
                .date_obj
                .unwrap()
                .naive_local()
                .date(),
            NaiveDate::from_ymd_opt(1795, 4, 3).unwrap()
        );
    }

    #[test]
    fn test_parts_of_day_bare_durations_and_surrounding_text() {
        let mut s = fixed_settings();
        s.parts_of_day.morning = NaiveTime::from_hms_opt(8, 30, 0).unwrap();
        let dd = get_date_data("yesterday morning", &s);
        assert_eq!(
            dd.date_obj.unwrap().naive_local(),
            NaiveDate::from_ymd_opt(2026, 11, 25)
                .unwrap()
                .and_hms_opt(8, 30, 0)
                .unwrap()
        );
        assert_eq!(dd.part_of_day, Some(PartOfDay::Morning));
        assert_eq!(dd.parts, vec!["year", "month", "day", "time"]);

        // Bare duration
        let d_bare = parse_with_settings("2 days", &fixed_settings()).unwrap();
        assert_eq!(d_bare.naive_local().date(), NaiveDate::from_ymd_opt(2026, 11, 24).unwrap());

        // Week period
        let dd_week = get_date_data("last week", &fixed_settings());
        assert_eq!(dd_week.period, Period::Week);

        // Ignore surrounding text
        let mut s_ign = fixed_settings();
        s_ign.ignore_surrounding_text = true;
        assert_eq!(
            parse_with_settings("Published: 12 December 2025", &s_ign)
                .unwrap()
                .naive_local()
                .date(),
            NaiveDate::from_ymd_opt(2025, 12, 12).unwrap()
        );
    }

    #[test]
    fn test_time_spans_and_custom_tz_abbrevs() {
        let mut s = fixed_settings();
        s.return_time_span = true;
        let span_matches = search_dates_full("Show logs from last week please", &s);
        assert_eq!(span_matches.len(), 2);

        let mut s_tz = fixed_settings();
        s_tz.timezone_abbreviations
            .insert("FOO".to_string(), "+04:30".to_string());
        s_tz.return_as_timezone_aware = Some(true);
        let dt = parse_with_settings("2026-11-26 10:00 FOO", &s_tz).unwrap();
        assert!(dt.is_aware());
        assert_eq!(dt.naive_local().hour(), 10);
    }

    #[test]
    fn test_timezone_conversion_and_preferences() {
        let mut s = fixed_settings();
        s.to_timezone = Some("Europe/Istanbul".to_string());
        s.return_as_timezone_aware = Some(true);
        let dt = parse_with_settings("2026-11-26T12:00:00Z", &s).unwrap();
        assert_eq!(
            dt.naive_local(),
            NaiveDateTime::parse_from_str("2026-11-26 15:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
        );

        s.prefer_day_of_month = PreferDayOfMonth::First;
        assert_eq!(
            parse_with_settings("December 2025", &s).unwrap().naive_local().date(),
            NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
        );
        s.prefer_dates_from = PreferDatesFrom::Past;
        assert_eq!(
            parse_with_settings("December 15", &s).unwrap().naive_local().date(),
            NaiveDate::from_ymd_opt(2025, 12, 15).unwrap()
        );
    }
}