Skip to main content

dateoxide_core/
settings.rs

1use chrono::{DateTime, FixedOffset, NaiveDateTime, NaiveTime};
2use chrono_tz::Tz;
3use rustc_hash::FxHashMap;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum DateOrder {
7    DMY,
8    MDY,
9    YMD,
10    YDM,
11    MYD,
12    DYM,
13}
14
15impl DateOrder {
16    pub fn from_str(s: &str) -> Option<Self> {
17        match s.trim().to_ascii_uppercase().as_str() {
18            "DMY" => Some(Self::DMY),
19            "MDY" => Some(Self::MDY),
20            "YMD" => Some(Self::YMD),
21            "YDM" => Some(Self::YDM),
22            "MYD" => Some(Self::MYD),
23            "DYM" => Some(Self::DYM),
24            _ => None,
25        }
26    }
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub enum StrictDateOrder {
31    #[default]
32    None,
33    Year,
34    All,
35}
36
37impl StrictDateOrder {
38    pub fn from_str(s: &str) -> Option<Self> {
39        match s.trim().to_ascii_lowercase().as_str() {
40            "none" => Some(Self::None),
41            "year" => Some(Self::Year),
42            "all" => Some(Self::All),
43            _ => None,
44        }
45    }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
49pub enum PreferDatesFrom {
50    #[default]
51    CurrentPeriod,
52    Past,
53    Future,
54}
55
56impl PreferDatesFrom {
57    pub fn from_str(s: &str) -> Option<Self> {
58        match s.trim().to_ascii_lowercase().as_str() {
59            "current_period" => Some(Self::CurrentPeriod),
60            "past" => Some(Self::Past),
61            "future" => Some(Self::Future),
62            _ => None,
63        }
64    }
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
68pub enum PreferDayOfMonth {
69    #[default]
70    Current,
71    First,
72    Last,
73}
74
75impl PreferDayOfMonth {
76    pub fn from_str(s: &str) -> Option<Self> {
77        match s.trim().to_ascii_lowercase().as_str() {
78            "current" => Some(Self::Current),
79            "first" => Some(Self::First),
80            "last" => Some(Self::Last),
81            _ => None,
82        }
83    }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
87pub enum PreferMonthOfYear {
88    #[default]
89    Current,
90    First,
91    Last,
92}
93
94impl PreferMonthOfYear {
95    pub fn from_str(s: &str) -> Option<Self> {
96        match s.trim().to_ascii_lowercase().as_str() {
97            "current" => Some(Self::Current),
98            "first" => Some(Self::First),
99            "last" => Some(Self::Last),
100            _ => None,
101        }
102    }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum DatePart {
107    Year,
108    Month,
109    Day,
110}
111
112impl DatePart {
113    pub fn from_str(s: &str) -> Option<Self> {
114        match s.trim().to_ascii_lowercase().as_str() {
115            "year" => Some(Self::Year),
116            "month" => Some(Self::Month),
117            "day" => Some(Self::Day),
118            _ => None,
119        }
120    }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
124pub enum Period {
125    #[default]
126    Day,
127    Week,
128    Month,
129    Year,
130    Time,
131}
132
133impl Period {
134    pub fn as_str(&self) -> &'static str {
135        match self {
136            Self::Day => "day",
137            Self::Week => "week",
138            Self::Month => "month",
139            Self::Year => "year",
140            Self::Time => "time",
141        }
142    }
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum PartOfDay {
147    EarlyMorning,
148    Morning,
149    Afternoon,
150    Evening,
151    Night,
152}
153
154impl PartOfDay {
155    pub fn as_str(&self) -> &'static str {
156        match self {
157            Self::EarlyMorning => "early_morning",
158            Self::Morning => "morning",
159            Self::Afternoon => "afternoon",
160            Self::Evening => "evening",
161            Self::Night => "night",
162        }
163    }
164
165    pub fn from_hour(hour: u8) -> Option<Self> {
166        match hour {
167            0..=6 => Some(Self::EarlyMorning),
168            7..=11 => Some(Self::Morning),
169            12..=16 => Some(Self::Afternoon),
170            17..=19 => Some(Self::Evening),
171            20..=23 => Some(Self::Night),
172            _ => None,
173        }
174    }
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub struct PartsOfDay {
179    pub early_morning: NaiveTime,
180    pub morning: NaiveTime,
181    pub afternoon: NaiveTime,
182    pub evening: NaiveTime,
183    pub night: NaiveTime,
184}
185
186impl Default for PartsOfDay {
187    fn default() -> Self {
188        Self {
189            early_morning: NaiveTime::from_hms_opt(3, 0, 0).unwrap(),
190            morning: NaiveTime::from_hms_opt(9, 0, 0).unwrap(),
191            afternoon: NaiveTime::from_hms_opt(15, 0, 0).unwrap(),
192            evening: NaiveTime::from_hms_opt(18, 0, 0).unwrap(),
193            night: NaiveTime::from_hms_opt(20, 0, 0).unwrap(),
194        }
195    }
196}
197
198impl PartsOfDay {
199    #[inline]
200    pub fn time_for(&self, p: PartOfDay) -> NaiveTime {
201        match p {
202            PartOfDay::EarlyMorning => self.early_morning,
203            PartOfDay::Morning => self.morning,
204            PartOfDay::Afternoon => self.afternoon,
205            PartOfDay::Evening => self.evening,
206            PartOfDay::Night => self.night,
207        }
208    }
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
212pub enum StartOfWeek {
213    #[default]
214    Monday,
215    Sunday,
216}
217
218impl StartOfWeek {
219    pub fn from_str(s: &str) -> Option<Self> {
220        match s.trim().to_ascii_lowercase().as_str() {
221            "monday" => Some(Self::Monday),
222            "sunday" => Some(Self::Sunday),
223            _ => None,
224        }
225    }
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum ParserKind {
230    Timestamp,
231    NegativeTimestamp,
232    RelativeTime,
233    CustomFormats,
234    AbsoluteTime,
235    BaseFormats,
236    NoSpacesTime,
237}
238
239impl ParserKind {
240    pub fn from_str(s: &str) -> Option<Self> {
241        match s.trim().to_ascii_lowercase().as_str() {
242            "timestamp" => Some(Self::Timestamp),
243            "negative-timestamp" => Some(Self::NegativeTimestamp),
244            "relative-time" => Some(Self::RelativeTime),
245            "custom-formats" => Some(Self::CustomFormats),
246            "absolute-time" => Some(Self::AbsoluteTime),
247            "base-formats" => Some(Self::BaseFormats),
248            "no-spaces-time" => Some(Self::NoSpacesTime),
249            _ => None,
250        }
251    }
252}
253
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum ParsedDateTime {
256    Naive(NaiveDateTime),
257    FixedOffset(DateTime<FixedOffset>),
258    Tz(DateTime<Tz>),
259}
260
261impl ParsedDateTime {
262    pub fn naive_local(&self) -> NaiveDateTime {
263        match self {
264            Self::Naive(ndt) => *ndt,
265            Self::FixedOffset(dt) => dt.naive_local(),
266            Self::Tz(dt) => dt.naive_local(),
267        }
268    }
269
270    pub fn is_aware(&self) -> bool {
271        !matches!(self, Self::Naive(_))
272    }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct DateData {
277    pub date_obj: Option<ParsedDateTime>,
278    pub period: Period,
279    pub locale: Option<String>,
280    pub parts: Vec<&'static str>,
281    pub part_of_day: Option<PartOfDay>,
282}
283
284impl DateData {
285    pub fn empty() -> Self {
286        Self {
287            date_obj: None,
288            period: Period::Day,
289            locale: None,
290            parts: Vec::new(),
291            part_of_day: None,
292        }
293    }
294}
295
296#[derive(Debug, Clone)]
297pub struct Settings {
298    pub date_order: Option<DateOrder>,
299    pub strict_date_order: StrictDateOrder,
300    pub prefer_locale_date_order: bool,
301    pub prefer_dates_from: PreferDatesFrom,
302    pub prefer_day_of_month: PreferDayOfMonth,
303    pub prefer_month_of_year: PreferMonthOfYear,
304    pub strict_parsing: bool,
305    pub relative_base: Option<NaiveDateTime>,
306    pub timezone: Option<String>,
307    pub to_timezone: Option<String>,
308    pub return_as_timezone_aware: Option<bool>,
309    pub timezone_abbreviations: FxHashMap<String, String>,
310    pub languages: Option<Vec<String>>,
311    pub default_languages: Vec<String>,
312    pub use_given_language_order: bool,
313    pub language_detection_confidence_threshold: f64,
314    pub date_formats: Option<Vec<String>>,
315    pub require_parts: Vec<DatePart>,
316    pub normalize: bool,
317    pub return_time_as_period: bool,
318    pub return_time_span: bool,
319    pub default_start_of_week: StartOfWeek,
320    pub default_days_in_month: u32,
321    pub ignore_surrounding_text: bool,
322    pub skip_tokens: Vec<String>,
323    pub parsers: Option<Vec<ParserKind>>,
324    pub region: Option<String>,
325    pub parts_of_day: PartsOfDay,
326    pub cache_size_limit: usize,
327}
328
329impl Default for Settings {
330    fn default() -> Self {
331        Self {
332            date_order: None,
333            strict_date_order: StrictDateOrder::None,
334            prefer_locale_date_order: true,
335            prefer_dates_from: PreferDatesFrom::default(),
336            prefer_day_of_month: PreferDayOfMonth::default(),
337            prefer_month_of_year: PreferMonthOfYear::default(),
338            strict_parsing: false,
339            relative_base: None,
340            timezone: None,
341            to_timezone: None,
342            return_as_timezone_aware: None,
343            timezone_abbreviations: FxHashMap::default(),
344            languages: None,
345            default_languages: Vec::new(),
346            use_given_language_order: false,
347            language_detection_confidence_threshold: 0.5,
348            date_formats: None,
349            require_parts: Vec::new(),
350            normalize: true,
351            return_time_as_period: false,
352            return_time_span: false,
353            default_start_of_week: StartOfWeek::Monday,
354            default_days_in_month: 30,
355            ignore_surrounding_text: false,
356            skip_tokens: Vec::new(),
357            parsers: None,
358            region: None,
359            parts_of_day: PartsOfDay::default(),
360            cache_size_limit: 1000,
361        }
362    }
363}
364
365/// Extract an ISO 3166-1 alpha-2 region subtag from a BCP-47 locale tag (e.g. `"en-GB"` -> `"GB"`,
366/// `"en_CA"` -> `"CA"`, `"zh-Hans-TW"` -> `"TW"`), ignoring 4-letter script subtags like `"uz-Cyrl"`.
367pub fn extract_region_from_locale(code: &str) -> Option<&str> {
368    let mut parts = code.trim().split(['-', '_']);
369    let _lang = parts.next()?;
370    for sub in parts {
371        if sub.len() == 2 && sub.bytes().all(|b| b.is_ascii_alphabetic()) {
372            return Some(sub);
373        }
374    }
375    None
376}
377
378/// Map a 2-letter region/country code to its conventional numeric date order.
379pub fn region_to_date_order(reg: &str) -> Option<DateOrder> {
380    let code = reg.trim().to_ascii_uppercase();
381    match code.as_str() {
382        "US" | "PH" | "FM" | "AS" | "UM" => Some(DateOrder::MDY),
383        "CN" | "JP" | "KR" | "TW" | "HU" | "LT" | "SE" | "ZA" | "CA" => Some(DateOrder::YMD),
384        r if r.len() == 2 && r.bytes().all(|b| b.is_ascii_alphabetic()) => Some(DateOrder::DMY),
385        _ => None,
386    }
387}
388
389impl Settings {
390    pub fn effective_base(&self) -> NaiveDateTime {
391        self.relative_base
392            .unwrap_or_else(|| chrono::Local::now().naive_local())
393    }
394
395    #[inline]
396    pub fn allows_parser(&self, kind: ParserKind) -> bool {
397        match &self.parsers {
398            None => !matches!(kind, ParserKind::NegativeTimestamp),
399            Some(list) => list.contains(&kind),
400        }
401    }
402
403    pub fn effective_date_order(&self, fallback: DateOrder) -> DateOrder {
404        if let Some(order) = self.date_order {
405            return order;
406        }
407        if let Some(ref reg) = self.region {
408            return region_to_date_order(reg).unwrap_or(fallback);
409        }
410        if self.prefer_locale_date_order {
411            if let Some(first) = self.languages.as_deref().and_then(|ls| ls.first()) {
412                if let Some(reg) = extract_region_from_locale(first) {
413                    if let Some(order) = region_to_date_order(reg) {
414                        return order;
415                    }
416                }
417                let reg = crate::locale::LocaleRegistry::global();
418                if let Some(id) = reg.resolve_lang_id(first) {
419                    return reg.locales[id].date_order;
420                }
421            }
422        }
423        fallback
424    }
425}