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