Skip to main content

php_std/datetime/
parse.rs

1//! `timelib_strtotime` (`parse_date.re`): PHP's free-form date/time parser,
2//! used by `strtotime()`, `date_parse()`, `new DateTime()`,
3//! `DateTime::modify()` and `DateInterval::createFromDateString()`.
4
5use super::scanner::{Lazy, P, alt, ci, digit, lit, opt, plus, range, ranges, rep, seq, set, star};
6use super::timelib::*;
7use super::tz::{TzInfo, abbr_search, strcasecmp};
8
9/// One error or warning: where (byte offset in the trimmed input), the byte
10/// there, and the message.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Message {
13    /// The byte offset in the trimmed input.
14    pub position: i64,
15    /// The byte at that offset (NUL past the end).
16    pub character: u8,
17    /// The message, as timelib words it.
18    pub message: &'static str,
19}
20
21/// `timelib_error_container`.
22#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct Messages {
24    /// The warnings, in the order they were found.
25    pub warnings: Vec<Message>,
26    /// The errors, in the order they were found.
27    pub errors: Vec<Message>,
28}
29
30/// `TIMELIB_MAX_ERRORS` (PHP 8.5.12): the most errors, and the most
31/// warnings, a parse keeps; later ones are dropped.
32pub(super) const MAX_ERRORS: usize = 1000;
33
34impl Messages {
35    /// `add_error`/`add_pbf_error`: kept unless there are
36    /// [`MAX_ERRORS`] already.
37    pub(super) fn error(&mut self, message: Message) {
38        if self.errors.len() < MAX_ERRORS {
39            self.errors.push(message);
40        }
41    }
42
43    /// `add_warning`/`add_pbf_warning`: kept unless there are
44    /// [`MAX_ERRORS`] already.
45    pub(super) fn warning(&mut self, message: Message) {
46        if self.warnings.len() < MAX_ERRORS {
47            self.warnings.push(message);
48        }
49    }
50}
51
52// Rule ids, in the order of parse_date.re (earlier wins a tie).
53const YESTERDAY: u16 = 0;
54const NOW: u16 = 1;
55const NOON: u16 = 2;
56const MIDNIGHT_TODAY: u16 = 3;
57const TOMORROW: u16 = 4;
58const TIMESTAMP: u16 = 5;
59const TIMESTAMP_MS: u16 = 6;
60const FIRST_LAST_DAY_OF: u16 = 7;
61const BACK_FRONT_OF: u16 = 8;
62const WEEKDAY_OF: u16 = 9;
63const TIME12: u16 = 10;
64const MSSQL_TIME: u16 = 11;
65const TIME24: u16 = 12;
66const GNU_NO_COLON: u16 = 13;
67const ISO8601_NO_COLON: u16 = 14;
68const AMERICAN: u16 = 15;
69const ISO_DATE4: u16 = 16;
70const ISO_DATE2: u16 = 17;
71const ISO_DATE_X: u16 = 18;
72const GNU_DATE_SHORTER: u16 = 19;
73const GNU_DATE_SHORT: u16 = 20;
74const DATE_FULL: u16 = 21;
75const POINTED_DATE4: u16 = 22;
76const POINTED_DATE2: u16 = 23;
77const DATE_NO_DAY: u16 = 24;
78const DATE_NO_DAY_REV: u16 = 25;
79const DATE_TEXTUAL: u16 = 26;
80const DATE_NO_YEAR_REV: u16 = 27;
81const DATE_NO_COLON: u16 = 28;
82const XMLRPC: u16 = 29;
83const PG_YDOTD: u16 = 30;
84const ISO_WEEK_DAY: u16 = 31;
85const ISO_WEEK: u16 = 32;
86const PG_TEXT_SHORT: u16 = 33;
87const PG_TEXT_REVERSE: u16 = 34;
88const CLF: u16 = 35;
89const YEAR4: u16 = 36;
90const AGO: u16 = 37;
91const DAY_TEXT: u16 = 38;
92const RELATIVE_TEXT_WEEK: u16 = 39;
93const RELATIVE_TEXT: u16 = 40;
94const MONTH_TEXT: u16 = 41;
95const TZ: u16 = 42;
96const DATE_SHORT_WITH_TIME12: u16 = 43;
97const DATE_SHORT_WITH_TIME: u16 = 44;
98const RELATIVE: u16 = 45;
99const COMMA: u16 = 46;
100const SPACE: u16 = 47;
101const NUL: u16 = 48;
102const ANY: u16 = 49;
103
104fn cis(words: &[&str]) -> P {
105    alt(words.iter().map(|w| ci(w)).collect())
106}
107
108fn lits(words: &[&str]) -> P {
109    alt(words.iter().map(|w| lit(w)).collect())
110}
111
112/// The definitions and rules of `parse_date.re`.
113fn rules() -> Vec<P> {
114    let space = alt(vec![plus(set(" \t")), plus(lit("\u{a0}")), plus(lit("\u{202f}"))]);
115    let frac = seq(vec![lit("."), plus(digit())]);
116    let hour24 = alt(vec![seq(vec![opt(set("01")), digit()]), seq(vec![lit("2"), range(b'0', b'4')])]);
117    let hour24lz = alt(vec![seq(vec![set("01"), digit()]), seq(vec![lit("2"), range(b'0', b'4')])]);
118    let hour12 = alt(vec![seq(vec![opt(lit("0")), range(b'1', b'9')]), seq(vec![lit("1"), range(b'0', b'2')])]);
119    let minute = seq(vec![opt(range(b'0', b'5')), digit()]);
120    let minutelz = seq(vec![range(b'0', b'5'), digit()]);
121    let second = alt(vec![minute.clone(), lit("60")]);
122    let secondlz = alt(vec![minutelz.clone(), lit("60")]);
123    let meridian = seq(vec![set("AaPp"), opt(lit(".")), set("Mm"), opt(lit(".")), set("\0\t ")]);
124    let alpha = ranges(&[(b'A', b'Z'), (b'a', b'z')]);
125    let tz = alt(vec![
126        seq(vec![opt(lit("(")), rep(alpha.clone(), 1, 6), opt(lit(")"))]),
127        seq(vec![range(b'A', b'Z'), plus(range(b'a', b'z')), plus(seq(vec![set("_/-"), plus(alpha.clone())]))]),
128    ]);
129    let tzcorrection = seq(vec![
130        opt(lit("GMT")),
131        set("+-"),
132        alt(vec![
133            seq(vec![hour24.clone(), opt(seq(vec![opt(lit(":")), minute.clone()]))]),
134            seq(vec![hour24lz.clone(), minutelz.clone(), secondlz.clone()]),
135            seq(vec![hour24lz.clone(), lit(":"), minutelz.clone(), lit(":"), secondlz.clone()]),
136        ]),
137    ]);
138    let daysuf = lits(&["st", "nd", "rd", "th"]);
139    let month = alt(vec![seq(vec![opt(lit("0")), digit()]), seq(vec![lit("1"), range(b'0', b'2')])]);
140    let day =
141        seq(vec![alt(vec![seq(vec![opt(range(b'0', b'2')), digit()]), seq(vec![lit("3"), set("01")])]), opt(daysuf)]);
142    let year = rep(digit(), 1, 4);
143    let year2 = rep(digit(), 2, 2);
144    let year4 = rep(digit(), 4, 4);
145    let year4withsign = seq(vec![opt(set("+-")), rep(digit(), 4, 4)]);
146    let yearx = seq(vec![set("+-"), rep(digit(), 5, 19)]);
147    let dayofyear = alt(vec![
148        seq(vec![lit("00"), range(b'1', b'9')]),
149        seq(vec![lit("0"), range(b'1', b'9'), digit()]),
150        seq(vec![range(b'1', b'2'), digit(), digit()]),
151        seq(vec![lit("3"), range(b'0', b'5'), digit()]),
152        seq(vec![lit("36"), range(b'0', b'6')]),
153    ]);
154    let weekofyear = alt(vec![
155        seq(vec![lit("0"), range(b'1', b'9')]),
156        seq(vec![range(b'1', b'4'), digit()]),
157        seq(vec![lit("5"), range(b'0', b'3')]),
158    ]);
159    let monthlz = alt(vec![seq(vec![lit("0"), digit()]), seq(vec![lit("1"), range(b'0', b'2')])]);
160    let daylz =
161        alt(vec![seq(vec![lit("0"), digit()]), seq(vec![range(b'1', b'2'), digit()]), seq(vec![lit("3"), set("01")])]);
162    let dayfulls = cis(&["sundays", "mondays", "tuesdays", "wednesdays", "thursdays", "fridays", "saturdays"]);
163    let dayfull = cis(&["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]);
164    let dayabbr = cis(&["sun", "mon", "tue", "wed", "thu", "fri", "sat", "sun"]);
165    let dayspecial = cis(&["weekday", "weekdays"]);
166    let daytext = alt(vec![dayfulls.clone(), dayfull.clone(), dayabbr.clone(), dayspecial]);
167    let monthfull = cis(&[
168        "january",
169        "february",
170        "march",
171        "april",
172        "may",
173        "june",
174        "july",
175        "august",
176        "september",
177        "october",
178        "november",
179        "december",
180    ]);
181    let monthabbr = cis(&["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "sept", "oct", "nov", "dec"]);
182    let monthroman = lits(&["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"]);
183    let monthtext = alt(vec![monthfull.clone(), monthabbr.clone(), monthroman]);
184
185    let timetiny12 = seq(vec![hour12.clone(), opt(space.clone()), meridian.clone()]);
186    let timeshort12 = seq(vec![hour12.clone(), set(":."), minutelz.clone(), opt(space.clone()), meridian.clone()]);
187    let timelong12 = seq(vec![
188        hour12.clone(),
189        set(":."),
190        minute.clone(),
191        set(":."),
192        secondlz.clone(),
193        opt(space.clone()),
194        meridian.clone(),
195    ]);
196    let t = || ci("t");
197    let timetiny24 = seq(vec![t(), hour24.clone()]);
198    let timeshort24 = seq(vec![opt(t()), hour24.clone(), set(":."), minute.clone()]);
199    let timelong24 = seq(vec![opt(t()), hour24.clone(), set(":."), minute.clone(), set(":."), second.clone()]);
200    let iso8601long =
201        seq(vec![opt(t()), hour24.clone(), set(":."), minute.clone(), set(":."), second.clone(), frac.clone()]);
202    let iso8601normtz = seq(vec![
203        opt(t()),
204        hour24.clone(),
205        set(":."),
206        minute.clone(),
207        set(":."),
208        secondlz.clone(),
209        opt(space.clone()),
210        alt(vec![tzcorrection.clone(), tz.clone()]),
211    ]);
212    let gnunocolon = seq(vec![opt(t()), hour24lz.clone(), minutelz.clone()]);
213    let iso8601nocolon = seq(vec![opt(t()), hour24lz.clone(), minutelz.clone(), secondlz.clone()]);
214
215    let americanshort = seq(vec![month.clone(), lit("/"), day.clone()]);
216    let american = seq(vec![month.clone(), lit("/"), day.clone(), lit("/"), year.clone()]);
217    let iso8601dateslash = seq(vec![year4.clone(), lit("/"), monthlz.clone(), lit("/"), daylz.clone(), opt(lit("/"))]);
218    let dateslash = seq(vec![year4.clone(), lit("/"), month.clone(), lit("/"), day.clone()]);
219    let iso8601date4 = seq(vec![year4withsign, lit("-"), monthlz.clone(), lit("-"), daylz.clone()]);
220    let iso8601date2 = seq(vec![year2.clone(), lit("-"), monthlz.clone(), lit("-"), daylz.clone()]);
221    let iso8601datex = seq(vec![yearx, lit("-"), monthlz.clone(), lit("-"), daylz.clone()]);
222    let gnudateshorter = seq(vec![year4.clone(), lit("-"), month.clone()]);
223    let gnudateshort = seq(vec![year.clone(), lit("-"), month.clone(), lit("-"), day.clone()]);
224    let pointeddate4 = seq(vec![day.clone(), set(".\t-"), month.clone(), set(".-"), year4.clone()]);
225    let pointeddate2 = seq(vec![day.clone(), set(".\t"), month.clone(), lit("."), year2]);
226    let sep = || star(set(" \t.-"));
227    let datefull = seq(vec![day.clone(), sep(), monthtext.clone(), sep(), year.clone()]);
228    let datenoday = seq(vec![monthtext.clone(), sep(), year4.clone()]);
229    let datenodayrev = seq(vec![year4.clone(), sep(), monthtext.clone()]);
230    let datetextual = seq(vec![monthtext.clone(), sep(), day.clone(), plus(set(",.stndrh\t ")), year.clone()]);
231    let datenoyear = seq(vec![monthtext.clone(), sep(), day.clone(), alt(vec![plus(set(",.stndrh\t ")), set("\0")])]);
232    let datenoyearrev = seq(vec![day.clone(), sep(), monthtext.clone()]);
233    let datenocolon = seq(vec![year4.clone(), monthlz.clone(), daylz.clone()]);
234
235    let soap = seq(vec![
236        year4.clone(),
237        lit("-"),
238        monthlz.clone(),
239        lit("-"),
240        daylz.clone(),
241        lit("T"),
242        hour24lz.clone(),
243        lit(":"),
244        minutelz.clone(),
245        lit(":"),
246        secondlz.clone(),
247        frac.clone(),
248        opt(tzcorrection.clone()),
249    ]);
250    let xmlrpc = seq(vec![
251        year4.clone(),
252        monthlz.clone(),
253        daylz.clone(),
254        lit("T"),
255        hour24.clone(),
256        lit(":"),
257        minutelz.clone(),
258        lit(":"),
259        secondlz.clone(),
260    ]);
261    let xmlrpcnocolon = seq(vec![
262        year4.clone(),
263        monthlz.clone(),
264        daylz.clone(),
265        t(),
266        hour24.clone(),
267        minutelz.clone(),
268        secondlz.clone(),
269    ]);
270    let wddx = seq(vec![
271        year4.clone(),
272        lit("-"),
273        month.clone(),
274        lit("-"),
275        day.clone(),
276        lit("T"),
277        hour24.clone(),
278        lit(":"),
279        minute.clone(),
280        lit(":"),
281        second.clone(),
282    ]);
283    let pgydotd = seq(vec![year4.clone(), opt(set(".-")), dayofyear]);
284    let pgtextshort = seq(vec![monthabbr.clone(), lit("-"), daylz.clone(), lit("-"), year.clone()]);
285    let pgtextreverse = seq(vec![year.clone(), lit("-"), monthabbr.clone(), lit("-"), daylz.clone()]);
286    let mssqltime = seq(vec![
287        hour12.clone(),
288        lit(":"),
289        minutelz.clone(),
290        lit(":"),
291        secondlz.clone(),
292        set(":."),
293        plus(digit()),
294        meridian.clone(),
295    ]);
296    let isoweekday =
297        seq(vec![year4.clone(), opt(lit("-")), lit("W"), weekofyear.clone(), opt(lit("-")), range(b'0', b'7')]);
298    let isoweek = seq(vec![year4.clone(), opt(lit("-")), lit("W"), weekofyear]);
299    let exif = seq(vec![
300        year4.clone(),
301        lit(":"),
302        monthlz.clone(),
303        lit(":"),
304        daylz.clone(),
305        lit(" "),
306        hour24lz.clone(),
307        lit(":"),
308        minutelz.clone(),
309        lit(":"),
310        secondlz.clone(),
311    ]);
312    let firstdayof = ci("first day of");
313    let lastdayof = ci("last day of");
314    let backof = seq(vec![ci("back of "), hour24.clone(), opt(seq(vec![opt(space.clone()), meridian.clone()]))]);
315    let frontof = seq(vec![ci("front of "), hour24.clone(), opt(seq(vec![opt(space.clone()), meridian.clone()]))]);
316    let clf = seq(vec![
317        day.clone(),
318        lit("/"),
319        monthabbr.clone(),
320        lit("/"),
321        year4.clone(),
322        lit(":"),
323        hour24lz.clone(),
324        lit(":"),
325        minutelz.clone(),
326        lit(":"),
327        secondlz.clone(),
328        space.clone(),
329        tzcorrection.clone(),
330    ]);
331    let timestamp = seq(vec![lit("@"), opt(lit("-")), plus(digit())]);
332    let timestampms = seq(vec![lit("@"), opt(lit("-")), plus(digit()), lit("."), rep(digit(), 0, 6)]);
333    let dateshortwithtimeshort12 = seq(vec![datenoyear.clone(), timeshort12.clone()]);
334    let dateshortwithtimelong12 = seq(vec![datenoyear.clone(), timelong12.clone()]);
335    let dateshortwithtimeshort = seq(vec![datenoyear.clone(), timeshort24.clone()]);
336    let dateshortwithtimelong = seq(vec![datenoyear.clone(), timelong24.clone()]);
337    let dateshortwithtimelongtz = seq(vec![datenoyear.clone(), iso8601normtz]);
338    let reltextnumber = cis(&[
339        "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eight", "eighth", "ninth", "tenth",
340        "eleventh", "twelfth",
341    ]);
342    let reltexttext = cis(&["next", "last", "previous", "this"]);
343    let reltextunit = alt(vec![
344        ci("ms"),
345        ci("\u{b5}s"),
346        seq(vec![
347            cis(&[
348                "msec",
349                "millisecond",
350                "\u{b5}sec",
351                "microsecond",
352                "usec",
353                "sec",
354                "second",
355                "min",
356                "minute",
357                "hour",
358                "day",
359                "fortnight",
360                "forthnight",
361                "month",
362                "year",
363            ]),
364            opt(ci("s")),
365        ]),
366        ci("weeks"),
367        daytext.clone(),
368    ]);
369    let relnumber = seq(vec![star(set("+-")), star(set(" \t")), rep(digit(), 1, 13)]);
370    let relative = seq(vec![relnumber, opt(space.clone()), alt(vec![reltextunit.clone(), ci("week")])]);
371    let relativetext = seq(vec![alt(vec![reltextnumber.clone(), reltexttext.clone()]), space.clone(), reltextunit]);
372    let relativetextweek = seq(vec![reltexttext.clone(), space.clone(), ci("week")]);
373    let weekdayof = seq(vec![
374        alt(vec![reltextnumber, reltexttext]),
375        space.clone(),
376        alt(vec![dayfulls, dayfull, dayabbr]),
377        space.clone(),
378        ci("of"),
379    ]);
380
381    vec![
382        ci("yesterday"),
383        ci("now"),
384        ci("noon"),
385        cis(&["midnight", "today"]),
386        ci("tomorrow"),
387        timestamp,
388        timestampms,
389        alt(vec![firstdayof, lastdayof]),
390        alt(vec![backof, frontof]),
391        weekdayof,
392        alt(vec![timetiny12, timeshort12, timelong12]),
393        mssqltime,
394        alt(vec![timetiny24, timeshort24, timelong24, iso8601long]),
395        gnunocolon,
396        iso8601nocolon,
397        alt(vec![americanshort, american]),
398        alt(vec![iso8601date4, iso8601dateslash, dateslash]),
399        iso8601date2,
400        iso8601datex,
401        gnudateshorter,
402        gnudateshort,
403        datefull,
404        pointeddate4,
405        pointeddate2,
406        datenoday,
407        datenodayrev,
408        alt(vec![datetextual, datenoyear]),
409        datenoyearrev,
410        datenocolon,
411        alt(vec![xmlrpc, xmlrpcnocolon, soap, wddx, exif]),
412        pgydotd,
413        isoweekday,
414        isoweek,
415        pgtextshort,
416        pgtextreverse,
417        clf,
418        year4,
419        ci("ago"),
420        daytext,
421        relativetextweek,
422        relativetext,
423        alt(vec![monthfull, monthabbr]),
424        alt(vec![tzcorrection, tz]),
425        alt(vec![dateshortwithtimeshort12, dateshortwithtimelong12]),
426        alt(vec![dateshortwithtimeshort, dateshortwithtimelong, dateshortwithtimelongtz]),
427        relative,
428        set(".,"),
429        space,
430        set("\0\n"),
431        range(0, 255),
432    ]
433}
434
435static NFA: Lazy = Lazy::new(rules);
436
437/// A C-string view of a token: bytes past the end (and an embedded NUL,
438/// which C code stops at) read as 0.
439pub(super) struct Cursor<'a> {
440    pub s: &'a [u8],
441    pub p: usize,
442}
443
444impl Cursor<'_> {
445    /// The byte at `i`, or 0 past the end.
446    pub fn at(&self, i: usize) -> u8 {
447        self.s.get(i).copied().unwrap_or(0)
448    }
449
450    /// The byte at the cursor, or 0 past the end.
451    pub fn cur(&self) -> u8 {
452        self.at(self.p)
453    }
454
455    /// The C string from the cursor (up to the first NUL).
456    pub fn rest(&self) -> &[u8] {
457        let r = self.s.get(self.p..).unwrap_or(&[]);
458        &r[..r.iter().position(|&c| c == 0).unwrap_or(r.len())]
459    }
460
461    /// `timelib_get_nr_ex`: up to `max` digits after skipping non-digits;
462    /// `UNSET` when the string ends first. Also returns the digit count.
463    pub fn get_nr_ex(&mut self, max: usize) -> (i64, usize) {
464        while !self.cur().is_ascii_digit() {
465            if self.cur() == 0 {
466                return (UNSET, 0);
467            }
468            self.p += 1;
469        }
470        let begin = self.p;
471        while self.cur().is_ascii_digit() && self.p - begin < max {
472            self.p += 1;
473        }
474        let digits = &self.s[begin..self.p];
475        (strtoll(digits), self.p - begin)
476    }
477
478    /// `timelib_get_nr`: the number of up to `max` digits after skipping non-digits (`UNSET` when the string ends first).
479    pub fn get_nr(&mut self, max: usize) -> i64 {
480        self.get_nr_ex(max).0
481    }
482
483    /// `timelib_skip_day_suffix`.
484    pub fn skip_day_suffix(&mut self) {
485        if is_c_space(self.cur()) {
486            return;
487        }
488        let r = self.rest();
489        if r.len() >= 2 && [&b"nd"[..], b"rd", b"st", b"th"].iter().any(|s| r[..2].eq_ignore_ascii_case(s)) {
490            self.p += 2;
491        }
492    }
493
494    /// `timelib_get_frac_nr`: microseconds from `.123`.
495    pub fn get_frac_nr(&mut self) -> i64 {
496        while self.cur() != b'.' && self.cur() != b':' && !self.cur().is_ascii_digit() {
497            if self.cur() == 0 {
498                return UNSET;
499            }
500            self.p += 1;
501        }
502        let begin = self.p;
503        while self.cur() == b'.' || self.cur() == b':' || self.cur().is_ascii_digit() {
504            self.p += 1;
505        }
506        let end = self.p;
507        let value = c_strtod(&self.s[begin + 1..end]);
508        (value * 10f64.powi(7 - (end - begin) as i32)) as i64
509    }
510
511    /// `timelib_eat_spaces`: spaces, tabs, NBSP and NNBSP.
512    pub fn eat_spaces(&mut self) {
513        loop {
514            if self.cur() == b' ' || self.cur() == b'\t' {
515                self.p += 1;
516            } else if self.cur() == 0xe2 && self.at(self.p + 1) == 0x80 && self.at(self.p + 2) == 0xaf {
517                self.p += 3;
518            } else if self.cur() == 0xc2 && self.at(self.p + 1) == 0xa0 {
519                self.p += 2;
520            } else {
521                return;
522            }
523        }
524    }
525
526    /// The `[A-Za-z]+` word at the cursor.
527    fn word(&mut self) -> &[u8] {
528        let begin = self.p;
529        while self.cur().is_ascii_alphabetic() {
530            self.p += 1;
531        }
532        &self.s[begin..self.p]
533    }
534
535    /// `timelib_lookup_month`: 0 when the word is not a month.
536    pub fn lookup_month(&mut self) -> i64 {
537        let word = self.word();
538        let mut value = 0;
539        for (name, v) in MONTHS {
540            if strcasecmp(word, name.as_bytes()) == 0 {
541                value = *v;
542            }
543        }
544        value
545    }
546
547    /// `timelib_get_month`.
548    pub fn get_month(&mut self) -> i64 {
549        while matches!(self.cur(), b' ' | b'\t' | b'-' | b'.' | b'/') {
550            self.p += 1;
551        }
552        self.lookup_month()
553    }
554
555    /// `timelib_lookup_relunit`.
556    pub fn lookup_relunit(&mut self) -> Option<&'static RelUnit> {
557        let begin = self.p;
558        while !matches!(self.cur(), 0 | b' ' | b',' | b'\t' | b';' | b':' | b'/' | b'.' | b'-' | b'(' | b')') {
559            self.p += 1;
560        }
561        let word = &self.s[begin..self.p];
562        RELUNITS.iter().find(|u| strcasecmp(word, u.name.as_bytes()) == 0)
563    }
564
565    /// `timelib_eat_until_separator`.
566    pub fn eat_until_separator(&mut self) {
567        self.p += 1;
568        while !b" \t.,:;/-0123456789\0".contains(&self.cur()) {
569            self.p += 1;
570        }
571    }
572
573    /// `timelib_meridian`: the hour adjustment of `am`/`pm`.
574    pub fn meridian(&mut self, h: i64) -> i64 {
575        while !b"AaPp\0".contains(&self.cur()) {
576            self.p += 1;
577        }
578        let mut retval = 0;
579        if self.cur() == b'a' || self.cur() == b'A' {
580            if h == 12 {
581                retval = -12;
582            }
583        } else if h != 12 {
584            retval = 12;
585        }
586        self.p += 1;
587        if self.cur() == b'.' {
588            self.p += 1;
589        }
590        if self.cur() == b'M' || self.cur() == b'm' {
591            self.p += 1;
592        }
593        if self.cur() == b'.' {
594            self.p += 1;
595        }
596        retval
597    }
598
599    /// `timelib_meridian_with_check`.
600    pub fn meridian_with_check(&mut self, h: i64) -> i64 {
601        while self.cur() != 0 && !b"AaPp".contains(&self.cur()) {
602            self.p += 1;
603        }
604        if self.cur() == 0 {
605            return UNSET;
606        }
607        let mut retval = 0;
608        if self.cur() == b'a' || self.cur() == b'A' {
609            if h == 12 {
610                retval = -12;
611            }
612        } else if h != 12 {
613            retval = 12;
614        }
615        self.p += 1;
616        if self.cur() == b'.' {
617            self.p += 1;
618            if self.cur() != b'm' && self.cur() != b'M' {
619                return UNSET;
620            }
621            self.p += 1;
622            if self.cur() != b'.' {
623                return UNSET;
624            }
625            self.p += 1;
626        } else if self.cur() == b'm' || self.cur() == b'M' {
627            self.p += 1;
628        } else {
629            return UNSET;
630        }
631        retval
632    }
633}
634
635/// C `isspace` in the C locale.
636pub fn is_c_space(c: u8) -> bool {
637    matches!(c, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
638}
639
640/// `strtoll` of a run of ASCII digits (at most a few here).
641fn strtoll(digits: &[u8]) -> i64 {
642    let mut v: i64 = 0;
643    for &d in digits {
644        v = v.saturating_mul(10).saturating_add(i64::from(d - b'0'));
645    }
646    v
647}
648
649/// C `strtod` of `[.:0-9]*`: the longest decimal prefix (`0` when none).
650fn c_strtod(s: &[u8]) -> f64 {
651    let mut end = 0;
652    while end < s.len() && s[end].is_ascii_digit() {
653        end += 1;
654    }
655    if end < s.len() && s[end] == b'.' {
656        let mut e = end + 1;
657        while e < s.len() && s[e].is_ascii_digit() {
658            e += 1;
659        }
660        if e > end + 1 || end > 0 {
661            end = e;
662        }
663    }
664    std::str::from_utf8(&s[..end])
665        .ok()
666        .and_then(|t| if t.is_empty() || t == "." { None } else { t.parse().ok() })
667        .unwrap_or(0.0)
668}
669
670const MONTHS: &[(&str, i64)] = &[
671    ("jan", 1),
672    ("feb", 2),
673    ("mar", 3),
674    ("apr", 4),
675    ("may", 5),
676    ("jun", 6),
677    ("jul", 7),
678    ("aug", 8),
679    ("sep", 9),
680    ("sept", 9),
681    ("oct", 10),
682    ("nov", 11),
683    ("dec", 12),
684    ("i", 1),
685    ("ii", 2),
686    ("iii", 3),
687    ("iv", 4),
688    ("v", 5),
689    ("vi", 6),
690    ("vii", 7),
691    ("viii", 8),
692    ("ix", 9),
693    ("x", 10),
694    ("xi", 11),
695    ("xii", 12),
696    ("january", 1),
697    ("february", 2),
698    ("march", 3),
699    ("april", 4),
700    ("may", 5),
701    ("june", 6),
702    ("july", 7),
703    ("august", 8),
704    ("september", 9),
705    ("october", 10),
706    ("november", 11),
707    ("december", 12),
708];
709
710/// The relative text table: (name, behavior, value).
711const RELTEXT: &[(&str, i32, i64)] = &[
712    ("first", 0, 1),
713    ("next", 0, 1),
714    ("second", 0, 2),
715    ("third", 0, 3),
716    ("fourth", 0, 4),
717    ("fifth", 0, 5),
718    ("sixth", 0, 6),
719    ("seventh", 0, 7),
720    ("eight", 0, 8),
721    ("eighth", 0, 8),
722    ("ninth", 0, 9),
723    ("tenth", 0, 10),
724    ("eleventh", 0, 11),
725    ("twelfth", 0, 12),
726    ("last", 0, -1),
727    ("previous", 0, -1),
728    ("this", 1, 0),
729];
730
731/// The unit of a relative time word (`timelib_relunit`).
732#[derive(Debug, Clone, Copy, PartialEq, Eq)]
733pub enum Unit {
734    Microsec,
735    Second,
736    Minute,
737    Hour,
738    Day,
739    Month,
740    Year,
741    Weekday,
742    Special,
743}
744
745/// A relative time word: its name, unit and multiplier (`timelib_relunit`).
746pub struct RelUnit {
747    pub name: &'static str,
748    pub unit: Unit,
749    pub multiplier: i64,
750}
751
752const fn ru(name: &'static str, unit: Unit, multiplier: i64) -> RelUnit {
753    RelUnit { name, unit, multiplier }
754}
755
756pub static RELUNITS: &[RelUnit] = &[
757    ru("ms", Unit::Microsec, 1000),
758    ru("msec", Unit::Microsec, 1000),
759    ru("msecs", Unit::Microsec, 1000),
760    ru("millisecond", Unit::Microsec, 1000),
761    ru("milliseconds", Unit::Microsec, 1000),
762    ru("\u{b5}s", Unit::Microsec, 1),
763    ru("usec", Unit::Microsec, 1),
764    ru("usecs", Unit::Microsec, 1),
765    ru("\u{b5}sec", Unit::Microsec, 1),
766    ru("\u{b5}secs", Unit::Microsec, 1),
767    ru("microsecond", Unit::Microsec, 1),
768    ru("microseconds", Unit::Microsec, 1),
769    ru("sec", Unit::Second, 1),
770    ru("secs", Unit::Second, 1),
771    ru("second", Unit::Second, 1),
772    ru("seconds", Unit::Second, 1),
773    ru("min", Unit::Minute, 1),
774    ru("mins", Unit::Minute, 1),
775    ru("minute", Unit::Minute, 1),
776    ru("minutes", Unit::Minute, 1),
777    ru("hour", Unit::Hour, 1),
778    ru("hours", Unit::Hour, 1),
779    ru("day", Unit::Day, 1),
780    ru("days", Unit::Day, 1),
781    ru("week", Unit::Day, 7),
782    ru("weeks", Unit::Day, 7),
783    ru("fortnight", Unit::Day, 14),
784    ru("fortnights", Unit::Day, 14),
785    ru("forthnight", Unit::Day, 14),
786    ru("forthnights", Unit::Day, 14),
787    ru("month", Unit::Month, 1),
788    ru("months", Unit::Month, 1),
789    ru("year", Unit::Year, 1),
790    ru("years", Unit::Year, 1),
791    ru("mondays", Unit::Weekday, 1),
792    ru("monday", Unit::Weekday, 1),
793    ru("mon", Unit::Weekday, 1),
794    ru("tuesdays", Unit::Weekday, 2),
795    ru("tuesday", Unit::Weekday, 2),
796    ru("tue", Unit::Weekday, 2),
797    ru("wednesdays", Unit::Weekday, 3),
798    ru("wednesday", Unit::Weekday, 3),
799    ru("wed", Unit::Weekday, 3),
800    ru("thursdays", Unit::Weekday, 4),
801    ru("thursday", Unit::Weekday, 4),
802    ru("thu", Unit::Weekday, 4),
803    ru("fridays", Unit::Weekday, 5),
804    ru("friday", Unit::Weekday, 5),
805    ru("fri", Unit::Weekday, 5),
806    ru("saturdays", Unit::Weekday, 6),
807    ru("saturday", Unit::Weekday, 6),
808    ru("sat", Unit::Weekday, 6),
809    ru("sundays", Unit::Weekday, 0),
810    ru("sunday", Unit::Weekday, 0),
811    ru("sun", Unit::Weekday, 0),
812    ru("weekday", Unit::Special, SPECIAL_WEEKDAY as i64),
813    ru("weekdays", Unit::Special, SPECIAL_WEEKDAY as i64),
814];
815
816/// What a timezone string resolved to (`timelib_parse_zone`).
817pub(super) struct Zone {
818    pub offset: i64,
819    pub not_found: bool,
820}
821
822/// `timelib_parse_tz_cor`: `HH`, `HHMM`, `HH:MM`, `HHMMSS`, `HH:MM:SS`.
823fn parse_tz_cor(c: &mut Cursor) -> (i64, bool) {
824    let begin = c.p;
825    while c.cur().is_ascii_digit() || c.cur() == b':' {
826        c.p += 1;
827    }
828    let len = c.p - begin;
829    // C's strtol(): it reads past the run of digits and colons when that run
830    // ends early (`+14:+5` is 14:05), skipping whitespace and taking a sign.
831    let strtol = |i: usize| -> i64 {
832        let mut j = begin + i;
833        while matches!(c.at(j), b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r') {
834            j += 1;
835        }
836        let negative = c.at(j) == b'-';
837        if matches!(c.at(j), b'+' | b'-') {
838            j += 1;
839        }
840        let mut v: i64 = 0;
841        while c.at(j).is_ascii_digit() {
842            let d = i64::from(c.at(j) - b'0');
843            v = if negative { v.saturating_mul(10).saturating_sub(d) } else { v.saturating_mul(10).saturating_add(d) };
844            j += 1;
845        }
846        v
847    };
848    let hour = |a: i64| (a.wrapping_mul(3600)) as i32 as i64;
849    let min = |a: i64| (a.wrapping_mul(60)) as i32 as i64;
850    match len {
851        1 | 2 => (hour(strtol(0)), false),
852        3 | 4 => {
853            if c.at(begin + 1) == b':' {
854                (hour(strtol(0)) + min(strtol(2)), false)
855            } else if c.at(begin + 2) == b':' {
856                (hour(strtol(0)) + min(strtol(3)), false)
857            } else {
858                let t = strtol(0);
859                (hour(t / 100) + min(t % 100), false)
860            }
861        }
862        5 if c.at(begin + 2) == b':' => (hour(strtol(0)) + min(strtol(3)), false),
863        6 => {
864            let t = strtol(0);
865            (hour(t / 10000) + min((t / 100) % 100) + t % 100, false)
866        }
867        8 if c.at(begin + 2) == b':' && c.at(begin + 5) == b':' => {
868            (hour(strtol(0)) + min(strtol(3)) + strtol(6), false)
869        }
870        _ => (0, true),
871    }
872}
873
874/// `timelib_parse_zone`: a UTC offset, an abbreviation or an identifier,
875/// recorded in `t`.
876pub(super) fn parse_zone(c: &mut Cursor, t: &mut Time) -> Zone {
877    let mut paren_count = 0usize;
878    while matches!(c.cur(), b' ' | b'\t' | b'(') {
879        if c.cur() == b'(' {
880            paren_count += 1;
881        }
882        c.p += 1;
883    }
884    if c.cur() == b'G' && c.at(c.p + 1) == b'M' && c.at(c.p + 2) == b'T' && matches!(c.at(c.p + 3), b'+' | b'-') {
885        c.p += 3;
886    }
887    let zone = if c.cur() == b'+' || c.cur() == b'-' {
888        let negative = c.cur() == b'-';
889        c.p += 1;
890        t.is_localtime = true;
891        t.zone_type = ZONETYPE_OFFSET;
892        t.dst = 0;
893        let (offset, not_found) = parse_tz_cor(c);
894        Zone { offset: if negative { -offset } else { offset }, not_found }
895    } else {
896        t.is_localtime = true;
897        // timelib_lookup_abbr
898        let begin = c.p;
899        while c.cur().is_ascii_alphanumeric() || matches!(c.cur(), b'/' | b'_' | b'-' | b'+') {
900            c.p += 1;
901        }
902        let word = &c.s[begin..c.p];
903        let mut found = 0;
904        let mut offset = 0i64;
905        if word.len() < 6
906            && let Some(a) = abbr_search(word, -1, 0)
907        {
908            offset = i64::from(a.gmtoffset) - i64::from(a.dst) * 3600;
909            t.dst = i32::from(a.dst);
910            found = 1;
911            t.zone_type = ZONETYPE_ABBR;
912            t.tz_abbr = Some(String::from_utf8_lossy(word).to_ascii_uppercase());
913        }
914        // timelib: `if (!found || strcmp("UTC", tz_abbr) == 0)` looks the word
915        // up as an identifier; the `UTC` abbreviation case is the branch below.
916        if found == 0
917            && let Some(tz) = std::str::from_utf8(word).ok().and_then(TzInfo::get)
918        {
919            t.tz_info = Some(tz);
920            t.zone_type = ZONETYPE_ID;
921            found += 1;
922        } else if found != 0
923            && word == b"UTC"
924            && let Some(tz) = TzInfo::get("UTC")
925        {
926            t.tz_info = Some(tz);
927            t.zone_type = ZONETYPE_ID;
928            found += 1;
929        }
930        Zone { offset, not_found: found == 0 }
931    };
932    while paren_count > 0 && c.cur() == b')' {
933        c.p += 1;
934        paren_count -= 1;
935    }
936    zone
937}
938
939/// The scanner state.
940struct Scanner<'a> {
941    s: &'a [u8],
942    tok: usize,
943    time: Time,
944    errors: Messages,
945}
946
947impl Scanner<'_> {
948    fn message(&self, message: &'static str) -> Message {
949        Message { position: self.tok as i64, character: self.s.get(self.tok).copied().unwrap_or(0), message }
950    }
951
952    fn error(&mut self, message: &'static str) {
953        let m = self.message(message);
954        self.errors.error(m);
955    }
956
957    fn warning(&mut self, message: &'static str) {
958        let m = self.message(message);
959        self.errors.warning(m);
960    }
961
962    /// `TIMELIB_HAVE_TIME`: `false` (after an error) on a second time.
963    fn have_time(&mut self) -> bool {
964        if self.time.have_time != 0 {
965            self.error("Double time specification");
966            return false;
967        }
968        self.time.have_time = 1;
969        self.time.h = 0;
970        self.time.i = 0;
971        self.time.s = 0;
972        self.time.us = 0;
973        true
974    }
975
976    fn unhave_time(&mut self) {
977        self.time.have_time = 0;
978        self.time.h = 0;
979        self.time.i = 0;
980        self.time.s = 0;
981        self.time.us = 0;
982    }
983
984    fn have_date(&mut self) -> bool {
985        if self.time.have_date != 0 {
986            self.error("Double date specification");
987            return false;
988        }
989        self.time.have_date = 1;
990        true
991    }
992
993    fn unhave_date(&mut self) {
994        self.time.have_date = 0;
995        self.time.d = 0;
996        self.time.m = 0;
997        self.time.y = 0;
998    }
999
1000    /// `TIMELIB_HAVE_TZ`.
1001    fn have_tz(&mut self) -> bool {
1002        if self.time.have_zone != 0 {
1003            if self.time.have_zone > 1 {
1004                self.error("Double timezone specification");
1005            } else {
1006                self.warning("Double timezone specification");
1007            }
1008            self.time.have_zone += 1;
1009            return false;
1010        }
1011        self.time.have_zone += 1;
1012        true
1013    }
1014
1015    /// `timelib_get_signed_nr`.
1016    fn get_signed_nr(&mut self, c: &mut Cursor, max: usize) -> i64 {
1017        while !c.cur().is_ascii_digit() && c.cur() != b'+' && c.cur() != b'-' {
1018            if c.cur() == 0 {
1019                self.error("Found unexpected data");
1020                return 0;
1021            }
1022            c.p += 1;
1023        }
1024        let mut negative = false;
1025        while c.cur() == b'+' || c.cur() == b'-' {
1026            if c.cur() == b'-' {
1027                negative = !negative;
1028            }
1029            c.p += 1;
1030        }
1031        while !c.cur().is_ascii_digit() {
1032            if c.cur() == 0 {
1033                self.error("Found unexpected data");
1034                return 0;
1035            }
1036            c.p += 1;
1037        }
1038        let begin = c.p;
1039        while c.cur().is_ascii_digit() && c.p - begin < max {
1040            c.p += 1;
1041        }
1042        let digits = &c.s[begin..c.p];
1043        let mut v: i128 = 0;
1044        for &d in digits {
1045            v = v * 10 + i128::from(d - b'0');
1046        }
1047        if negative {
1048            v = -v;
1049        }
1050        match i64::try_from(v) {
1051            Ok(v) => v,
1052            Err(_) => {
1053                self.error("Number out of range");
1054                0
1055            }
1056        }
1057    }
1058
1059    /// `add_with_overflow`.
1060    fn add_with_overflow(&mut self, field: Field, amount: i64, multiplier: i64) {
1061        let r = &mut self.time.relative;
1062        let e = match field {
1063            Field::Us => &mut r.us,
1064            Field::S => &mut r.s,
1065            Field::I => &mut r.i,
1066            Field::H => &mut r.h,
1067            Field::D => &mut r.d,
1068            Field::M => &mut r.m,
1069            Field::Y => &mut r.y,
1070        };
1071        let (v, overflow) = e.overflowing_add(amount.wrapping_mul(multiplier));
1072        *e = v;
1073        if overflow {
1074            self.error("Number out of range");
1075        }
1076    }
1077
1078    /// `timelib_set_relative`.
1079    fn set_relative(&mut self, c: &mut Cursor, amount: i64, behavior: i32, keep_time: bool) {
1080        let Some(unit) = c.lookup_relunit() else { return };
1081        match unit.unit {
1082            Unit::Microsec => self.add_with_overflow(Field::Us, amount, unit.multiplier),
1083            Unit::Second => self.add_with_overflow(Field::S, amount, unit.multiplier),
1084            Unit::Minute => self.add_with_overflow(Field::I, amount, unit.multiplier),
1085            Unit::Hour => self.add_with_overflow(Field::H, amount, unit.multiplier),
1086            Unit::Day => self.add_with_overflow(Field::D, amount, unit.multiplier),
1087            Unit::Month => self.add_with_overflow(Field::M, amount, unit.multiplier),
1088            Unit::Year => self.add_with_overflow(Field::Y, amount, unit.multiplier),
1089            Unit::Weekday => {
1090                self.time.have_relative = true;
1091                self.time.relative.have_weekday_relative = true;
1092                if !keep_time {
1093                    self.unhave_time();
1094                }
1095                let n = if amount > 0 { amount - 1 } else { amount };
1096                self.time.relative.d = self.time.relative.d.wrapping_add(n.wrapping_mul(7));
1097                self.time.relative.weekday = unit.multiplier as i32;
1098                self.time.relative.weekday_behavior = behavior;
1099            }
1100            Unit::Special => {
1101                self.time.have_relative = true;
1102                self.time.relative.have_special_relative = true;
1103                if !keep_time {
1104                    self.unhave_time();
1105                }
1106                self.time.relative.special_type = unit.multiplier as u32;
1107                self.time.relative.special_amount = amount;
1108            }
1109        }
1110    }
1111
1112    /// `timelib_get_relative_text`: the value and behavior of `first`, `next`, `last`, `this`...
1113    fn get_relative_text(c: &mut Cursor, behavior: &mut i32) -> i64 {
1114        while matches!(c.cur(), b' ' | b'\t' | b'-' | b'/') {
1115            c.p += 1;
1116        }
1117        let word = c.word();
1118        let mut value = 0;
1119        for (name, b, v) in RELTEXT {
1120            if strcasecmp(word, name.as_bytes()) == 0 {
1121                value = *v;
1122                *behavior = *b;
1123            }
1124        }
1125        value
1126    }
1127
1128    fn zone(&mut self, c: &mut Cursor) {
1129        let z = parse_zone(c, &mut self.time);
1130        self.time.z = z.offset as i32;
1131        if z.not_found {
1132            self.error("The timezone could not be found in the database");
1133        }
1134    }
1135
1136    /// The action of one rule on the token `self.s[self.tok..end]`.
1137    fn action(&mut self, rule: u16, end: usize) {
1138        let token = &self.s[self.tok..end.min(self.s.len())];
1139        let mut c = Cursor { s: token, p: 0 };
1140        let t = &mut self.time;
1141        match rule {
1142            YESTERDAY => {
1143                t.have_relative = true;
1144                self.unhave_time();
1145                self.time.relative.d = -1;
1146            }
1147            NOW => {}
1148            NOON => {
1149                self.unhave_time();
1150                self.have_time();
1151                self.time.h = 12;
1152            }
1153            MIDNIGHT_TODAY => self.unhave_time(),
1154            TOMORROW => {
1155                t.have_relative = true;
1156                self.unhave_time();
1157                self.time.relative.d = 1;
1158            }
1159            TIMESTAMP | TIMESTAMP_MS => {
1160                t.have_relative = true;
1161                self.unhave_date();
1162                self.unhave_time();
1163                if !self.have_tz() {
1164                    return;
1165                }
1166                let negative = c.at(1) == b'-';
1167                let i = self.get_signed_nr(&mut c, 24);
1168                let mut us = 0i64;
1169                if rule == TIMESTAMP_MS {
1170                    let before = c.p;
1171                    let v = self.get_signed_nr(&mut c, 6) as u64;
1172                    let v = (v as f64 * 10f64.powi(7 - (c.p - before) as i32)) as u64;
1173                    us = if negative { v.wrapping_neg() as i64 } else { v as i64 };
1174                }
1175                let t = &mut self.time;
1176                t.y = 1970;
1177                t.m = 1;
1178                t.d = 1;
1179                t.h = 0;
1180                t.i = 0;
1181                t.s = 0;
1182                t.us = 0;
1183                t.relative.s = t.relative.s.wrapping_add(i);
1184                if rule == TIMESTAMP_MS {
1185                    t.relative.us = us;
1186                }
1187                t.is_localtime = true;
1188                t.zone_type = ZONETYPE_OFFSET;
1189                t.z = 0;
1190                t.dst = 0;
1191            }
1192            FIRST_LAST_DAY_OF => {
1193                t.have_relative = true;
1194                t.relative.first_last_day_of =
1195                    if matches!(c.cur(), b'l' | b'L') { LAST_DAY_OF_MONTH } else { FIRST_DAY_OF_MONTH };
1196            }
1197            BACK_FRONT_OF => {
1198                self.unhave_time();
1199                self.have_time();
1200                let back = c.cur() == b'b';
1201                let h = c.get_nr(2);
1202                let t = &mut self.time;
1203                if back {
1204                    t.h = h;
1205                    t.i = 15;
1206                } else {
1207                    t.h = h.wrapping_sub(1);
1208                    t.i = 45;
1209                }
1210                if c.cur() != 0 {
1211                    c.eat_spaces();
1212                    let h = t.h;
1213                    t.h = h.wrapping_add(c.meridian(h));
1214                }
1215            }
1216            WEEKDAY_OF => {
1217                t.have_relative = true;
1218                t.relative.have_special_relative = true;
1219                let mut behavior = 0;
1220                let i = Self::get_relative_text(&mut c, &mut behavior);
1221                c.eat_spaces();
1222                if i > 0 {
1223                    self.time.relative.special_type = SPECIAL_DAY_OF_WEEK_IN_MONTH;
1224                    self.set_relative(&mut c, i, 1, false);
1225                } else {
1226                    self.time.relative.special_type = SPECIAL_LAST_DAY_OF_WEEK_IN_MONTH;
1227                    self.set_relative(&mut c, i, behavior, false);
1228                }
1229            }
1230            TIME12 => {
1231                if !self.have_time() {
1232                    return;
1233                }
1234                let t = &mut self.time;
1235                t.h = c.get_nr(2);
1236                if matches!(c.cur(), b':' | b'.') {
1237                    t.i = c.get_nr(2);
1238                    if matches!(c.cur(), b':' | b'.') {
1239                        t.s = c.get_nr(2);
1240                    }
1241                }
1242                c.eat_spaces();
1243                let h = t.h;
1244                t.h = h.wrapping_add(c.meridian(h));
1245            }
1246            MSSQL_TIME => {
1247                if !self.have_time() {
1248                    return;
1249                }
1250                let t = &mut self.time;
1251                t.h = c.get_nr(2);
1252                t.i = c.get_nr(2);
1253                if matches!(c.cur(), b':' | b'.') {
1254                    t.s = c.get_nr(2);
1255                    if matches!(c.cur(), b':' | b'.') {
1256                        t.us = c.get_frac_nr();
1257                    }
1258                }
1259                c.eat_spaces();
1260                let h = t.h;
1261                t.h = h.wrapping_add(c.meridian(h));
1262            }
1263            TIME24 => {
1264                if !self.have_time() {
1265                    return;
1266                }
1267                let t = &mut self.time;
1268                t.h = c.get_nr(2);
1269                if matches!(c.cur(), b':' | b'.') {
1270                    t.i = c.get_nr(2);
1271                    if matches!(c.cur(), b':' | b'.') {
1272                        t.s = c.get_nr(2);
1273                        if c.cur() == b'.' {
1274                            t.us = c.get_frac_nr();
1275                        }
1276                    }
1277                }
1278                if c.cur() != 0 {
1279                    self.zone(&mut c);
1280                }
1281            }
1282            GNU_NO_COLON => match t.have_time {
1283                0 => {
1284                    t.h = c.get_nr(2);
1285                    t.i = c.get_nr(2);
1286                    t.s = 0;
1287                    t.have_time += 1;
1288                }
1289                1 => {
1290                    t.y = c.get_nr(4);
1291                    t.have_time += 1;
1292                }
1293                _ => self.error("Double time specification"),
1294            },
1295            ISO8601_NO_COLON => {
1296                if !self.have_time() {
1297                    return;
1298                }
1299                let t = &mut self.time;
1300                t.h = c.get_nr(2);
1301                t.i = c.get_nr(2);
1302                t.s = c.get_nr(2);
1303                if c.cur() != 0 {
1304                    self.zone(&mut c);
1305                }
1306            }
1307            AMERICAN => {
1308                if !self.have_date() {
1309                    return;
1310                }
1311                let t = &mut self.time;
1312                t.m = c.get_nr(2);
1313                t.d = c.get_nr(2);
1314                if c.cur() == b'/' {
1315                    let (y, len) = c.get_nr_ex(4);
1316                    t.y = process_year(y, len);
1317                }
1318            }
1319            ISO_DATE4 => {
1320                if !self.have_date() {
1321                    return;
1322                }
1323                let y = self.get_signed_nr(&mut c, 4);
1324                let t = &mut self.time;
1325                t.y = y;
1326                t.m = c.get_nr(2);
1327                t.d = c.get_nr(2);
1328            }
1329            ISO_DATE2 => {
1330                if !self.have_date() {
1331                    return;
1332                }
1333                let t = &mut self.time;
1334                let (y, len) = c.get_nr_ex(4);
1335                t.m = c.get_nr(2);
1336                t.d = c.get_nr(2);
1337                t.y = process_year(y, len);
1338            }
1339            ISO_DATE_X => {
1340                if !self.have_date() {
1341                    return;
1342                }
1343                let y = self.get_signed_nr(&mut c, 19);
1344                let t = &mut self.time;
1345                t.y = y;
1346                t.m = c.get_nr(2);
1347                t.d = c.get_nr(2);
1348            }
1349            GNU_DATE_SHORTER => {
1350                if !self.have_date() {
1351                    return;
1352                }
1353                let t = &mut self.time;
1354                let (y, len) = c.get_nr_ex(4);
1355                t.m = c.get_nr(2);
1356                t.d = 1;
1357                t.y = process_year(y, len);
1358            }
1359            GNU_DATE_SHORT => {
1360                if !self.have_date() {
1361                    return;
1362                }
1363                let t = &mut self.time;
1364                let (y, len) = c.get_nr_ex(4);
1365                t.m = c.get_nr(2);
1366                t.d = c.get_nr(2);
1367                t.y = process_year(y, len);
1368            }
1369            DATE_FULL => {
1370                if !self.have_date() {
1371                    return;
1372                }
1373                let t = &mut self.time;
1374                t.d = c.get_nr(2);
1375                c.skip_day_suffix();
1376                t.m = c.get_month();
1377                let (y, len) = c.get_nr_ex(4);
1378                t.y = process_year(y, len);
1379            }
1380            POINTED_DATE4 => {
1381                if !self.have_date() {
1382                    return;
1383                }
1384                let t = &mut self.time;
1385                t.d = c.get_nr(2);
1386                t.m = c.get_nr(2);
1387                t.y = c.get_nr(4);
1388            }
1389            POINTED_DATE2 => {
1390                if !self.have_date() {
1391                    return;
1392                }
1393                let t = &mut self.time;
1394                t.d = c.get_nr(2);
1395                t.m = c.get_nr(2);
1396                let (y, len) = c.get_nr_ex(2);
1397                t.y = process_year(y, len);
1398            }
1399            DATE_NO_DAY => {
1400                if !self.have_date() {
1401                    return;
1402                }
1403                let t = &mut self.time;
1404                t.m = c.get_month();
1405                let (y, len) = c.get_nr_ex(4);
1406                t.d = 1;
1407                t.y = process_year(y, len);
1408            }
1409            DATE_NO_DAY_REV => {
1410                if !self.have_date() {
1411                    return;
1412                }
1413                let t = &mut self.time;
1414                let (y, len) = c.get_nr_ex(4);
1415                t.m = c.get_month();
1416                t.d = 1;
1417                t.y = process_year(y, len);
1418            }
1419            DATE_TEXTUAL | PG_TEXT_SHORT => {
1420                if !self.have_date() {
1421                    return;
1422                }
1423                let t = &mut self.time;
1424                t.m = c.get_month();
1425                t.d = c.get_nr(2);
1426                let (y, len) = c.get_nr_ex(4);
1427                t.y = process_year(y, len);
1428            }
1429            DATE_NO_YEAR_REV => {
1430                if !self.have_date() {
1431                    return;
1432                }
1433                let t = &mut self.time;
1434                t.d = c.get_nr(2);
1435                c.skip_day_suffix();
1436                t.m = c.get_month();
1437            }
1438            DATE_NO_COLON => {
1439                if !self.have_date() {
1440                    return;
1441                }
1442                let t = &mut self.time;
1443                t.y = c.get_nr(4);
1444                t.m = c.get_nr(2);
1445                t.d = c.get_nr(2);
1446            }
1447            XMLRPC => {
1448                if !self.have_time() || !self.have_date() {
1449                    return;
1450                }
1451                let t = &mut self.time;
1452                t.y = c.get_nr(4);
1453                t.m = c.get_nr(2);
1454                t.d = c.get_nr(2);
1455                t.h = c.get_nr(2);
1456                t.i = c.get_nr(2);
1457                t.s = c.get_nr(2);
1458                if c.cur() == b'.' {
1459                    t.us = c.get_frac_nr();
1460                    if c.cur() != 0 {
1461                        self.zone(&mut c);
1462                    }
1463                }
1464            }
1465            PG_YDOTD => {
1466                if !self.have_date() {
1467                    return;
1468                }
1469                let t = &mut self.time;
1470                let (y, len) = c.get_nr_ex(4);
1471                t.d = c.get_nr(3);
1472                t.m = 1;
1473                t.y = process_year(y, len);
1474            }
1475            ISO_WEEK_DAY | ISO_WEEK => {
1476                if !self.have_date() {
1477                    return;
1478                }
1479                let t = &mut self.time;
1480                t.have_relative = true;
1481                t.y = c.get_nr(4);
1482                let w = c.get_nr(2);
1483                let d = if rule == ISO_WEEK_DAY { c.get_nr(1) } else { 1 };
1484                t.m = 1;
1485                t.d = 1;
1486                t.relative.d = daynr_from_weeknr(t.y, w, d);
1487            }
1488            PG_TEXT_REVERSE => {
1489                if !self.have_date() {
1490                    return;
1491                }
1492                let t = &mut self.time;
1493                let (y, len) = c.get_nr_ex(4);
1494                t.m = c.get_month();
1495                t.d = c.get_nr(2);
1496                t.y = process_year(y, len);
1497            }
1498            CLF => {
1499                if !self.have_time() || !self.have_date() {
1500                    return;
1501                }
1502                let t = &mut self.time;
1503                t.d = c.get_nr(2);
1504                t.m = c.get_month();
1505                t.y = c.get_nr(4);
1506                t.h = c.get_nr(2);
1507                t.i = c.get_nr(2);
1508                t.s = c.get_nr(2);
1509                c.eat_spaces();
1510                self.zone(&mut c);
1511            }
1512            YEAR4 => t.y = c.get_nr(4),
1513            AGO => {
1514                let r = &mut t.relative;
1515                r.y = 0i64.wrapping_sub(r.y);
1516                r.m = 0i64.wrapping_sub(r.m);
1517                r.d = 0i64.wrapping_sub(r.d);
1518                r.h = 0i64.wrapping_sub(r.h);
1519                r.i = 0i64.wrapping_sub(r.i);
1520                r.s = 0i64.wrapping_sub(r.s);
1521                r.weekday = 0i32.wrapping_sub(r.weekday);
1522                if r.weekday == 0 {
1523                    r.weekday = -7;
1524                }
1525                if r.have_special_relative && r.special_type == SPECIAL_WEEKDAY {
1526                    r.special_amount = 0i64.wrapping_sub(r.special_amount);
1527                }
1528            }
1529            DAY_TEXT => {
1530                t.have_relative = true;
1531                t.relative.have_weekday_relative = true;
1532                self.unhave_time();
1533                let unit = c.lookup_relunit();
1534                let t = &mut self.time;
1535                t.relative.weekday = unit.map(|u| u.multiplier as i32).unwrap_or(0);
1536                if t.relative.weekday_behavior != 2 {
1537                    t.relative.weekday_behavior = 1;
1538                }
1539            }
1540            RELATIVE_TEXT_WEEK | RELATIVE_TEXT => {
1541                t.have_relative = true;
1542                while c.cur() != 0 {
1543                    let mut behavior = 0;
1544                    let i = Self::get_relative_text(&mut c, &mut behavior);
1545                    c.eat_spaces();
1546                    self.set_relative(&mut c, i, behavior, false);
1547                    if rule == RELATIVE_TEXT_WEEK {
1548                        let r = &mut self.time.relative;
1549                        r.weekday_behavior = 2;
1550                        if !r.have_weekday_relative {
1551                            self.time.have_relative = true;
1552                            self.time.relative.have_weekday_relative = true;
1553                            self.time.relative.weekday = 1;
1554                        }
1555                    }
1556                }
1557            }
1558            MONTH_TEXT => {
1559                if !self.have_date() {
1560                    return;
1561                }
1562                self.time.m = c.lookup_month();
1563            }
1564            TZ => {
1565                if !self.have_tz() {
1566                    return;
1567                }
1568                c.eat_spaces();
1569                self.zone(&mut c);
1570            }
1571            DATE_SHORT_WITH_TIME12 => {
1572                if !self.have_date() {
1573                    return;
1574                }
1575                self.time.m = c.get_month();
1576                self.time.d = c.get_nr(2);
1577                if !self.have_time() {
1578                    return;
1579                }
1580                let t = &mut self.time;
1581                t.h = c.get_nr(2);
1582                t.i = c.get_nr(2);
1583                if matches!(c.cur(), b':' | b'.') {
1584                    t.s = c.get_nr(2);
1585                    if c.cur() == b'.' {
1586                        t.us = c.get_frac_nr();
1587                    }
1588                }
1589                let h = t.h;
1590                t.h = h.wrapping_add(c.meridian(h));
1591            }
1592            DATE_SHORT_WITH_TIME => {
1593                if !self.have_date() {
1594                    return;
1595                }
1596                self.time.m = c.get_month();
1597                self.time.d = c.get_nr(2);
1598                if !self.have_time() {
1599                    return;
1600                }
1601                let t = &mut self.time;
1602                t.h = c.get_nr(2);
1603                t.i = c.get_nr(2);
1604                if c.cur() == b':' {
1605                    t.s = c.get_nr(2);
1606                    if c.cur() == b'.' {
1607                        t.us = c.get_frac_nr();
1608                    }
1609                }
1610                if c.cur() != 0 {
1611                    self.zone(&mut c);
1612                }
1613            }
1614            RELATIVE => {
1615                t.have_relative = true;
1616                while c.cur() != 0 {
1617                    let i = self.get_signed_nr(&mut c, 24);
1618                    c.eat_spaces();
1619                    self.set_relative(&mut c, i, 1, true);
1620                }
1621            }
1622            COMMA | SPACE | NUL => {}
1623            _ => self.error("Unexpected character"),
1624        }
1625    }
1626}
1627
1628#[derive(Clone, Copy)]
1629enum Field {
1630    Us,
1631    S,
1632    I,
1633    H,
1634    D,
1635    M,
1636    Y,
1637}
1638
1639/// `TIMELIB_PROCESS_YEAR`: two-digit years are 1970-2069.
1640pub(super) fn process_year(y: i64, len: usize) -> i64 {
1641    if y == UNSET || len >= 4 {
1642        y
1643    } else if y < 100 {
1644        if y < 70 { y + 2000 } else { y + 1900 }
1645    } else {
1646        y
1647    }
1648}
1649
1650/// `timelib_strtotime`: the parsed (unnormalized) time and the errors and
1651/// warnings, positions relative to the input with surrounding whitespace
1652/// removed.
1653pub fn strtotime(input: &[u8]) -> (Time, Messages) {
1654    let mut s = 0usize;
1655    let mut e = input.len() as isize - 1;
1656    if !input.is_empty() {
1657        // `s <= e` (parse_date.c regenerated in PHP 8.5.12): a
1658        // whitespace-only string is stripped to nothing, the "Empty string"
1659        // error.
1660        while (s as isize) <= e && is_c_space(input[s]) {
1661            s += 1;
1662        }
1663        while e > s as isize && is_c_space(input[e as usize]) {
1664            e -= 1;
1665        }
1666    }
1667    if e - (s as isize) < 0 {
1668        let mut t = Time::unset();
1669        t.is_localtime = false;
1670        t.zone_type = 0;
1671        let errors = Messages {
1672            warnings: Vec::new(),
1673            errors: vec![Message { position: 0, character: 0, message: "Empty string" }],
1674        };
1675        return (t, errors);
1676    }
1677    let text = &input[s..=e as usize];
1678    let mut t = Time::unset();
1679    t.relative.days = UNSET;
1680    let mut sc = Scanner { s: text, tok: 0, time: t, errors: Messages::default() };
1681    let nfa = NFA.get();
1682    let mut cursor = 0usize;
1683    while cursor < text.len() {
1684        sc.tok = cursor;
1685        let (end, rule) = nfa.longest(text, cursor).unwrap_or((cursor + 1, ANY));
1686        sc.action(rule, end);
1687        cursor = end;
1688    }
1689    // End of input: one past the NUL after the text.
1690    sc.tok = text.len() + 1;
1691    if sc.time.have_time != 0 && !valid_time(sc.time.h, sc.time.i, sc.time.s) {
1692        sc.errors.warning(Message { position: sc.tok as i64, character: 0, message: "The parsed time was invalid" });
1693    }
1694    if sc.time.have_date != 0 && !valid_date(sc.time.y, sc.time.m, sc.time.d) {
1695        sc.errors.warning(Message { position: sc.tok as i64, character: 0, message: "The parsed date was invalid" });
1696    }
1697    (sc.time, sc.errors)
1698}
1699
1700#[cfg(test)]
1701mod tests {
1702    use super::*;
1703
1704    fn parse(s: &str) -> (Time, Messages) {
1705        strtotime(s.as_bytes())
1706    }
1707
1708    #[test]
1709    fn parses_dates_and_times() {
1710        let (t, e) = parse("2024-07-01 12:00:00.5 +05:30");
1711        assert!(e.errors.is_empty(), "{e:?}");
1712        assert_eq!((t.y, t.m, t.d, t.h, t.i, t.s, t.us, t.z), (2024, 7, 1, 12, 0, 0, 500000, 19800));
1713        let (t, _) = parse("Jan 5");
1714        assert_eq!((t.y, t.m, t.d, t.h), (UNSET, 1, 5, UNSET));
1715        let (_, e) = parse("10:00 chadt");
1716        assert_eq!(e.errors[0].position, 6);
1717        let (_, e) = parse("2024-07-01 12:00:00.5 +05:30 foo bar");
1718        assert_eq!(e.warnings[0].position, 29);
1719        assert_eq!(e.errors[0].position, 33);
1720    }
1721
1722    #[test]
1723    fn whitespace_only_is_the_empty_string() {
1724        for s in [" ", "\t", "  ", "\n", " \t", "\x0b"] {
1725            let (_, e) = parse(s);
1726            assert_eq!(e.errors.len(), 1, "{s:?}");
1727            assert_eq!((e.errors[0].position, e.errors[0].message), (0, "Empty string"));
1728        }
1729        let (_, e) = parse(" 2020-01-01 ");
1730        assert!(e.errors.is_empty());
1731    }
1732
1733    #[test]
1734    fn keeps_at_most_max_errors() {
1735        let (_, e) = parse(&"!".repeat(MAX_ERRORS + 500));
1736        assert_eq!(e.errors.len(), MAX_ERRORS);
1737        assert_eq!(e.errors[MAX_ERRORS - 1].position, (MAX_ERRORS - 1) as i64);
1738    }
1739}