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
use crate::{
ClassifiedDate, DateClassification, DateOrder, DateOrderFirst, DateParseMode, Dt, DtErr,
DtErrKind, MAX_DATE_STRING_LEN, ParseCfg, Scale, an_err, classify_date,
default_date_parse_options, generate_ambiguous_day_first_candidates,
generate_ambiguous_month_first_candidates, generate_ambiguous_year_first_candidates,
generate_unambiguous_candidates, is_week_date_missing_weekday,
parse_pure_numeric_unix_timestamp, parse_syslog_no_year, parse_week_date_no_weekday,
parse_yyyy_mm, smart_detect_date_order, try_pure_numeric,
};
use alloc::borrow::Cow;
use alloc::string::String;
impl Dt {
pub fn from_str_parse(s: &str, opts: &Option<ParseCfg>) -> Result<Dt, DtErr> {
let opts: &ParseCfg = opts
.as_ref()
.unwrap_or_else(|| default_date_parse_options());
if s.is_empty() {
return Err(an_err!(DtErrKind::Incomplete, "empty"));
} else if s.len() > MAX_DATE_STRING_LEN {
return Err(an_err!(DtErrKind::InvalidInput, "too long: {}", s));
}
let lang = opts.lang;
let ref_time = &opts.ref_time;
let lowered: Cow<str> = if opts.to_lower {
Cow::Owned(s.to_lowercase())
} else {
Cow::Borrowed(s)
};
let classification = match classify_date(&lowered, lang, ref_time) {
Ok(ClassifiedDate::Parsed(time_point)) => return Ok(time_point),
Ok(ClassifiedDate::Cls(c)) => c,
Err(e) => {
// std::eprintln!("{}", e);
return Err(an_err!(
DtErrKind::InvalidInput,
"{}",
s => e
));
}
};
// let xx = &classification.date;
// if xx != trimmed {
// eprintln!("NOT EQUAL: {:?}, {:?}", trimmed, xx);
// }
// eprintln!("BEFORE & AFTER: {:?}, {:?}", lowered, &classification.date);
let normalized = &classification.date;
let (mode, date_order) = if let Some(formats) = &opts.parse {
if !formats.is_empty() {
for fmt in formats {
if let Ok(value) = Self::from_str(normalized, fmt, true, true, false) {
return Ok(value);
}
}
// None of the provided formats worked and mode is Explicit
if opts.mode == DateParseMode::Explicit {
return Err(an_err!(DtErrKind::InvalidInput, "{}", s));
}
}
(opts.mode, opts.order)
} else {
(opts.mode, opts.order)
};
// if s == "2460000" {
// std::eprintln!("INPUT CLS: {:?}", classification);
// }
if classification.is_pure_numeric {
match mode {
DateParseMode::UnixTimestamp => {
if let Some(dt) = parse_pure_numeric_unix_timestamp(
normalized,
classification.num_non_decimal_digits as usize,
) {
return Ok(dt);
}
}
_ => {
if let Some(dt) = try_pure_numeric(
normalized,
classification.num_digits,
classification.num_non_decimal_digits,
classification.is_decimal,
mode,
) {
// std::eprintln!("NUMERIC INPUT SUCCESS: {:?}", s);
return Ok(dt);
}
}
}
}
if !classification.has_year
&& let Some(dt) = parse_syslog_no_year(normalized, lang, ref_time)
{
return Ok(dt);
}
if is_week_date_missing_weekday(&classification) {
// std::eprintln!("IS WEEK DATE MISSING WEEKDAY: {:?}", s);
if let Some(dt) = parse_week_date_no_weekday(&classification.date, lang, ref_time) {
return Ok(dt);
}
}
if let Some(dt) = try_unambiguous(normalized, &classification) {
return Ok(dt);
}
// std::eprintln!("done trying unambiguous");
if let Some(dt) = match date_order {
DateOrder::Smart => {
let order = smart_detect_date_order(normalized, &classification);
let mut result: Option<Dt>;
match order {
DateOrderFirst::Day => {
result = try_compatible_formats(
normalized,
generate_ambiguous_day_first_candidates(&classification),
);
// std::eprintln!("done trying day first: {:?}", result);
if result.is_none() {
result = try_compatible_formats(
normalized,
generate_ambiguous_month_first_candidates(&classification),
);
// std::eprintln!("done trying month first: {:?}", result);
}
if result.is_none() {
result = try_compatible_formats(
normalized,
generate_ambiguous_year_first_candidates(&classification),
);
// std::eprintln!("done trying year first: {:?}", result);
}
}
DateOrderFirst::Month => {
result = try_compatible_formats(
normalized,
generate_ambiguous_month_first_candidates(&classification),
);
// std::eprintln!("done trying month first: {:?}", result);
if result.is_none() {
result = try_compatible_formats(
normalized,
generate_ambiguous_day_first_candidates(&classification),
);
// std::eprintln!("done trying day first: {:?}", result);
}
if result.is_none() {
result = try_compatible_formats(
normalized,
generate_ambiguous_year_first_candidates(&classification),
);
// std::eprintln!("done trying year first: {:?}", result);
}
}
DateOrderFirst::Year => {
result = try_compatible_formats(
normalized,
generate_ambiguous_year_first_candidates(&classification),
);
// std::eprintln!("done trying year first: {:?}", result);
if result.is_none() {
result = try_compatible_formats(
normalized,
generate_ambiguous_day_first_candidates(&classification),
);
// std::eprintln!("done trying day first: {:?}", result);
}
if result.is_none() {
result = try_compatible_formats(
normalized,
generate_ambiguous_month_first_candidates(&classification),
);
// std::eprintln!("done trying month first: {:?}", result);
}
}
}
result
}
DateOrder::Year => try_compatible_formats(
normalized,
generate_ambiguous_year_first_candidates(&classification),
),
DateOrder::Day => try_compatible_formats(
normalized,
generate_ambiguous_day_first_candidates(&classification),
),
DateOrder::Month => try_compatible_formats(
normalized,
generate_ambiguous_month_first_candidates(&classification),
),
} {
return Ok(dt);
}
// std::eprintln!("NOW trying numeric timestamp");
if classification.is_pure_numeric
&& mode != DateParseMode::UnixTimestamp
&& let Some(dt) = parse_pure_numeric_unix_timestamp(
normalized,
classification.num_non_decimal_digits as usize,
)
{
return Ok(dt);
}
Err(an_err!(DtErrKind::InvalidInput, "{}", s))
}
/// Same parsing logic as `Dt::from_str`, but returns attoseconds since
/// the library epoch: 2000-01-01 12:00:00 UTC (on the UTC scale).
///
/// Returns `Some(attos)` on success (negative for pre-2000 dates) or `None`
/// on any parse error.
#[inline]
pub fn str_to_attos(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
Dt::from_str_parse(s, opts).ok().map(|tp| tp.to_attos())
}
/// Same parsing logic as `Dt::from_str`, but returns milliseconds since
/// the library epoch: 2000-01-01 12:00:00 UTC (on the UTC scale).
///
/// Returns `Some(millis)` on success (negative for pre-2000 dates) or `None`
/// on any parse error.
#[inline]
pub fn str_to_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
Dt::from_str_parse(s, opts).ok().map(|tp| tp.to_ms())
}
/// Same parsing logic as `Dt::from_str`, but returns milliseconds since
/// the UNIX epoch: (1970-01-01 00:00:00 UTC).
///
/// Returns `Some(millis)` on success (negative for pre-2000 dates) or `None`
/// on any parse error.
#[inline]
pub fn str_to_unix_ms(s: &str, opts: &Option<ParseCfg>) -> Option<i128> {
Dt::from_str_parse(s, opts).ok().map(|tp| {
tp.to_scale_and_then_diff(Scale::UTC, Dt::UNIX_EPOCH)
.to_ms()
})
}
}
/// Core zero-allocation helper (updated to match the new `&str` signature).
///
/// The `fmt` we get from the iterator is still `'static`, but it coerces automatically
/// to `&str`, so everything continues to work.
#[inline]
pub(crate) fn try_compatible_formats<I>(s: &str, formats: I) -> Option<Dt>
where
I: IntoIterator<Item = String>,
{
formats
.into_iter()
.find_map(|fmt| Dt::from_str(s, &fmt, true, true, false).ok())
}
#[inline]
pub(crate) fn try_unambiguous(s: &str, classification: &DateClassification) -> Option<Dt> {
if matches!(classification.bytes_len, 6..=8)
&& let Some(dt) = parse_yyyy_mm(s.as_bytes())
{
return Some(dt);
}
try_compatible_formats(s, generate_unambiguous_candidates(classification))
}