dateoxide-core 0.6.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
use chrono::{DateTime, FixedOffset, NaiveDateTime, NaiveTime};
use chrono_tz::Tz;
use rustc_hash::FxHashMap;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateOrder {
    DMY,
    MDY,
    YMD,
    YDM,
    MYD,
    DYM,
}

impl DateOrder {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_uppercase().as_str() {
            "DMY" => Some(Self::DMY),
            "MDY" => Some(Self::MDY),
            "YMD" => Some(Self::YMD),
            "YDM" => Some(Self::YDM),
            "MYD" => Some(Self::MYD),
            "DYM" => Some(Self::DYM),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StrictDateOrder {
    #[default]
    None,
    Year,
    All,
}

impl StrictDateOrder {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "none" => Some(Self::None),
            "year" => Some(Self::Year),
            "all" => Some(Self::All),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PreferDatesFrom {
    #[default]
    CurrentPeriod,
    Past,
    Future,
}

impl PreferDatesFrom {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "current_period" => Some(Self::CurrentPeriod),
            "past" => Some(Self::Past),
            "future" => Some(Self::Future),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PreferDayOfMonth {
    #[default]
    Current,
    First,
    Last,
}

impl PreferDayOfMonth {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "current" => Some(Self::Current),
            "first" => Some(Self::First),
            "last" => Some(Self::Last),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PreferMonthOfYear {
    #[default]
    Current,
    First,
    Last,
}

impl PreferMonthOfYear {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "current" => Some(Self::Current),
            "first" => Some(Self::First),
            "last" => Some(Self::Last),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DatePart {
    Year,
    Month,
    Day,
}

impl DatePart {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "year" => Some(Self::Year),
            "month" => Some(Self::Month),
            "day" => Some(Self::Day),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Period {
    #[default]
    Day,
    Week,
    Month,
    Year,
    Time,
}

impl Period {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Day => "day",
            Self::Week => "week",
            Self::Month => "month",
            Self::Year => "year",
            Self::Time => "time",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartOfDay {
    EarlyMorning,
    Morning,
    Afternoon,
    Evening,
    Night,
}

impl PartOfDay {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::EarlyMorning => "early_morning",
            Self::Morning => "morning",
            Self::Afternoon => "afternoon",
            Self::Evening => "evening",
            Self::Night => "night",
        }
    }

    pub fn from_hour(hour: u8) -> Option<Self> {
        match hour {
            0..=6 => Some(Self::EarlyMorning),
            7..=11 => Some(Self::Morning),
            12..=16 => Some(Self::Afternoon),
            17..=19 => Some(Self::Evening),
            20..=23 => Some(Self::Night),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PartsOfDay {
    pub early_morning: NaiveTime,
    pub morning: NaiveTime,
    pub afternoon: NaiveTime,
    pub evening: NaiveTime,
    pub night: NaiveTime,
}

impl Default for PartsOfDay {
    fn default() -> Self {
        Self {
            early_morning: NaiveTime::from_hms_opt(3, 0, 0).unwrap(),
            morning: NaiveTime::from_hms_opt(9, 0, 0).unwrap(),
            afternoon: NaiveTime::from_hms_opt(15, 0, 0).unwrap(),
            evening: NaiveTime::from_hms_opt(18, 0, 0).unwrap(),
            night: NaiveTime::from_hms_opt(20, 0, 0).unwrap(),
        }
    }
}

impl PartsOfDay {
    #[inline]
    pub fn time_for(&self, p: PartOfDay) -> NaiveTime {
        match p {
            PartOfDay::EarlyMorning => self.early_morning,
            PartOfDay::Morning => self.morning,
            PartOfDay::Afternoon => self.afternoon,
            PartOfDay::Evening => self.evening,
            PartOfDay::Night => self.night,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StartOfWeek {
    #[default]
    Monday,
    Sunday,
}

impl StartOfWeek {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "monday" => Some(Self::Monday),
            "sunday" => Some(Self::Sunday),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParserKind {
    Timestamp,
    NegativeTimestamp,
    RelativeTime,
    CustomFormats,
    AbsoluteTime,
    BaseFormats,
    NoSpacesTime,
}

impl ParserKind {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "timestamp" => Some(Self::Timestamp),
            "negative-timestamp" => Some(Self::NegativeTimestamp),
            "relative-time" => Some(Self::RelativeTime),
            "custom-formats" => Some(Self::CustomFormats),
            "absolute-time" => Some(Self::AbsoluteTime),
            "base-formats" => Some(Self::BaseFormats),
            "no-spaces-time" => Some(Self::NoSpacesTime),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsedDateTime {
    Naive(NaiveDateTime),
    FixedOffset(DateTime<FixedOffset>),
    Tz(DateTime<Tz>),
}

impl ParsedDateTime {
    pub fn naive_local(&self) -> NaiveDateTime {
        match self {
            Self::Naive(ndt) => *ndt,
            Self::FixedOffset(dt) => dt.naive_local(),
            Self::Tz(dt) => dt.naive_local(),
        }
    }

    pub fn is_aware(&self) -> bool {
        !matches!(self, Self::Naive(_))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DateData {
    pub date_obj: Option<ParsedDateTime>,
    pub period: Period,
    pub locale: Option<String>,
    pub parts: Vec<&'static str>,
    pub part_of_day: Option<PartOfDay>,
}

impl DateData {
    pub fn empty() -> Self {
        Self {
            date_obj: None,
            period: Period::Day,
            locale: None,
            parts: Vec::new(),
            part_of_day: None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Settings {
    pub date_order: Option<DateOrder>,
    pub strict_date_order: StrictDateOrder,
    pub prefer_locale_date_order: bool,
    pub prefer_dates_from: PreferDatesFrom,
    pub prefer_day_of_month: PreferDayOfMonth,
    pub prefer_month_of_year: PreferMonthOfYear,
    pub strict_parsing: bool,
    pub relative_base: Option<NaiveDateTime>,
    pub timezone: Option<String>,
    pub to_timezone: Option<String>,
    pub return_as_timezone_aware: Option<bool>,
    pub timezone_abbreviations: FxHashMap<String, String>,
    pub languages: Option<Vec<String>>,
    pub default_languages: Vec<String>,
    pub use_given_language_order: bool,
    pub language_detection_confidence_threshold: f64,
    pub date_formats: Option<Vec<String>>,
    pub require_parts: Vec<DatePart>,
    pub normalize: bool,
    pub return_time_as_period: bool,
    pub return_time_span: bool,
    pub default_start_of_week: StartOfWeek,
    pub default_days_in_month: u32,
    pub ignore_surrounding_text: bool,
    pub skip_tokens: Vec<String>,
    pub parsers: Option<Vec<ParserKind>>,
    pub region: Option<String>,
    pub parts_of_day: PartsOfDay,
    pub cache_size_limit: usize,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            date_order: None,
            strict_date_order: StrictDateOrder::None,
            prefer_locale_date_order: true,
            prefer_dates_from: PreferDatesFrom::default(),
            prefer_day_of_month: PreferDayOfMonth::default(),
            prefer_month_of_year: PreferMonthOfYear::default(),
            strict_parsing: false,
            relative_base: None,
            timezone: None,
            to_timezone: None,
            return_as_timezone_aware: None,
            timezone_abbreviations: FxHashMap::default(),
            languages: None,
            default_languages: Vec::new(),
            use_given_language_order: false,
            language_detection_confidence_threshold: 0.5,
            date_formats: None,
            require_parts: Vec::new(),
            normalize: true,
            return_time_as_period: false,
            return_time_span: false,
            default_start_of_week: StartOfWeek::Monday,
            default_days_in_month: 30,
            ignore_surrounding_text: false,
            skip_tokens: Vec::new(),
            parsers: None,
            region: None,
            parts_of_day: PartsOfDay::default(),
            cache_size_limit: 1000,
        }
    }
}

/// Extract an ISO 3166-1 alpha-2 region subtag from a BCP-47 locale tag (e.g. `"en-GB"` -> `"GB"`,
/// `"en_CA"` -> `"CA"`, `"zh-Hans-TW"` -> `"TW"`), ignoring 4-letter script subtags like `"uz-Cyrl"`.
pub fn extract_region_from_locale(code: &str) -> Option<&str> {
    let mut parts = code.trim().split(['-', '_']);
    let _lang = parts.next()?;
    for sub in parts {
        if sub.len() == 2 && sub.bytes().all(|b| b.is_ascii_alphabetic()) {
            return Some(sub);
        }
    }
    None
}

/// Map a 2-letter region/country code to its conventional numeric date order.
pub fn region_to_date_order(reg: &str) -> Option<DateOrder> {
    let code = reg.trim().to_ascii_uppercase();
    match code.as_str() {
        "US" | "PH" | "FM" | "AS" | "UM" => Some(DateOrder::MDY),
        "CN" | "JP" | "KR" | "TW" | "HU" | "LT" | "SE" | "ZA" | "CA" => Some(DateOrder::YMD),
        r if r.len() == 2 && r.bytes().all(|b| b.is_ascii_alphabetic()) => Some(DateOrder::DMY),
        _ => None,
    }
}

impl Settings {
    pub fn effective_base(&self) -> NaiveDateTime {
        self.relative_base
            .unwrap_or_else(|| chrono::Local::now().naive_local())
    }

    #[inline]
    pub fn allows_parser(&self, kind: ParserKind) -> bool {
        match &self.parsers {
            None => !matches!(kind, ParserKind::NegativeTimestamp),
            Some(list) => list.contains(&kind),
        }
    }

    pub fn effective_date_order(&self, fallback: DateOrder) -> DateOrder {
        if let Some(order) = self.date_order {
            return order;
        }
        if let Some(ref reg) = self.region {
            return region_to_date_order(reg).unwrap_or(fallback);
        }
        if self.prefer_locale_date_order {
            if let Some(first) = self.languages.as_deref().and_then(|ls| ls.first()) {
                if let Some(reg) = extract_region_from_locale(first) {
                    if let Some(order) = region_to_date_order(reg) {
                        return order;
                    }
                }
                let reg = crate::locale::LocaleRegistry::global();
                if let Some(id) = reg.resolve_lang_id(first) {
                    return reg.locales[id].date_order;
                }
            }
        }
        fallback
    }
}