Skip to main content

sql_values/datetime/
input.rs

1//! PostgreSQL 18's `date_in`, `time_in`, `timetz_in`, `timestamp_in` and `timestamptz_in`, and
2//! the readers of the text PostgreSQL, MySQL and SQLite print.
3
4use super::{
5    DateTimeError, POSTGRES_EPOCH_JDATE, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
6    USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, abbreviation_offset, date2j,
7    days_in_month, is_valid_julian, local_offset, tm2timestamp,
8};
9use super::{
10    decode::{
11        DateOrder, DateType, DecodedTime, Dterr, Tm, ZoneSource, current_time, decode_date_time,
12        decode_time_only,
13    },
14    tokens::{Tokens, parse_date_time, parse_fractional_second, strtoint},
15};
16use crate::{PgTimeZone, PgType, TimeZoneAbbreviations, zone::DEFAULT_ABBREVIATIONS};
17
18/// 1970-01-01 00:00:00, `epoch`, in microseconds from 2000-01-01.
19const EPOCH_MICROS: i64 = -946_684_800_000_000;
20/// 1970-01-01, `epoch`, in days from 2000-01-01.
21const EPOCH_DAYS: i32 = -10_957;
22
23/// The session state PostgreSQL's input functions read, which the caller supplies.
24///
25/// ```
26/// use sql_values::{DateTimeError, InputContext, PgTimeZone, PgTimestampTz, TimeZoneAbbreviations};
27///
28/// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
29/// let local = "2026-07-01 12:00:00";
30/// assert_eq!(
31///     PgTimestampTz::parse(local, InputContext::new()),
32///     Err(DateTimeError::NeedsTimeZone),
33/// );
34/// let at = PgTimestampTz::parse(local, InputContext::new().with_time_zone(&rome)).unwrap();
35/// assert_eq!(at.to_string(), "2026-07-01 10:00:00+00");
36///
37/// // `EST` is New York's time in `Default` and Brisbane's in `Australia`.
38/// let australia = TimeZoneAbbreviations::bundled("Australia").unwrap();
39/// let context = InputContext::new().with_time_zone_abbreviations(australia);
40/// let est = PgTimestampTz::parse("2026-07-01 12:00 EST", context).unwrap();
41/// assert_eq!(est.to_string(), "2026-07-01 02:00:00+00");
42/// ```
43#[derive(Debug, Clone, Copy)]
44pub struct InputContext<'a> {
45    pub(super) time_zone: Option<&'a PgTimeZone>,
46    pub(super) abbreviations: &'a TimeZoneAbbreviations,
47    pub(super) date_order: Option<DateOrder>,
48    pub(super) now: Option<PgTimestampTz>,
49}
50
51impl<'a> InputContext<'a> {
52    /// A context with no time zone, no `DateStyle` order and no current time, and the `Default`
53    /// abbreviations, as a stock installation's `timezone_abbreviations` names them.
54    #[must_use]
55    pub const fn new() -> Self {
56        Self {
57            time_zone: None,
58            abbreviations: &DEFAULT_ABBREVIATIONS,
59            date_order: None,
60            now: None,
61        }
62    }
63
64    /// The context with `zone` as the session's `TimeZone`, which reads a `timestamptz` or
65    /// `timetz` written without an offset, and whose own abbreviations a literal may write
66    /// before those of the set.
67    #[must_use]
68    pub const fn with_time_zone(self, zone: &'a PgTimeZone) -> Self {
69        Self {
70            time_zone: Some(zone),
71            ..self
72        }
73    }
74
75    /// The context with `abbreviations` as the session's `timezone_abbreviations`.
76    #[must_use]
77    pub const fn with_time_zone_abbreviations(
78        self,
79        abbreviations: &'a TimeZoneAbbreviations,
80    ) -> Self {
81        Self {
82            abbreviations,
83            ..self
84        }
85    }
86
87    /// The context with `order` as the field order of the session's `DateStyle`, which reads a
88    /// date written in numbers alone such as `01/02/2026`.
89    #[must_use]
90    pub const fn with_date_order(self, order: DateOrder) -> Self {
91        Self {
92            date_order: Some(order),
93            ..self
94        }
95    }
96
97    /// The context with `now` as the transaction's start, which `now`, `today`, `tomorrow` and
98    /// `yesterday` read, in the context's time zone, and whose date a `timetz` without a date
99    /// takes its zone's offset on. An infinite `now` reads as
100    /// [`DateTimeError::TimestampOutOfRange`], as no transaction starts at one.
101    #[must_use]
102    pub const fn with_now(self, now: PgTimestampTz) -> Self {
103        Self {
104            now: Some(now),
105            ..self
106        }
107    }
108}
109
110impl Default for InputContext<'_> {
111    fn default() -> Self {
112        Self::new()
113    }
114}
115
116/// `MAXDATELEN`, whose `workbuf` of one byte more bounds a literal's tokens.
117const MAX_DATE_LEN: usize = 128;
118
119/// `ParseDateTime` and `decoder`, `DecodeDateTime` or `DecodeTimeOnly`, over a literal of
120/// `pg_type`, which a NUL ends as it ends a C string.
121fn decode<'a, T>(
122    text: &str,
123    context: InputContext<'a>,
124    pg_type: PgType,
125    decoder: fn(&Tokens, InputContext<'a>) -> Result<T, Dterr>,
126) -> Result<T, DateTimeError> {
127    let text = text.split('\0').next().unwrap_or_default();
128    let tokens = parse_date_time(text.as_bytes(), MAX_DATE_LEN + 1)
129        .map_err(|_| DateTimeError::InvalidInputSyntax(pg_type))?;
130    decoder(&tokens, context).map_err(|error| error.for_type(pg_type))
131}
132
133/// `read` under the context's `DateStyle` order. Without one, a literal the order touches reads
134/// only if every order reads it alike, as `January 8, 1999` does.
135fn by_date_order<'a, T: PartialEq>(
136    context: InputContext<'a>,
137    read: impl Fn(InputContext<'a>) -> Result<T, DateTimeError>,
138) -> Result<T, DateTimeError> {
139    match read(context) {
140        Err(DateTimeError::NeedsDateOrder) => {
141            let [mdy, dmy, ymd] = [DateOrder::Mdy, DateOrder::Dmy, DateOrder::Ymd]
142                .map(|order| read(context.with_date_order(order)));
143            if mdy == dmy && dmy == ymd {
144                mdy
145            } else {
146                Err(DateTimeError::NeedsDateOrder)
147            }
148        }
149        other => other,
150    }
151}
152
153/// The local clock of `tm` to the second, as `DetermineTimeZoneOffset` reads it, in microseconds
154/// from 2000-01-01, or `None` where that overflows.
155fn local_seconds(tm: &Tm) -> Option<i64> {
156    let days = i64::from(date2j(tm.year, tm.mon, tm.mday)) - i64::from(POSTGRES_EPOCH_JDATE);
157    let clock = (i64::from(tm.hour) * 60 + i64::from(tm.min)) * 60 + i64::from(tm.sec);
158    days.checked_mul(USECS_PER_DAY)?
159        .checked_add(clock * USECS_PER_SEC)
160}
161
162/// `DetermineTimeZoneOffset` and `DetermineTimeZoneAbbrevOffset` for a `timetz`, whose date
163/// may lie anywhere `ValidateDate` accepts. Outside `IS_VALID_JULIAN` PostgreSQL takes UTC and
164/// reads the abbreviation at the Unix epoch, and a date it can place that jiff cannot is
165/// [`DateTimeError::OutsideJiffRange`].
166fn time_zone_offset(
167    zone: &PgTimeZone,
168    abbreviation: Option<&str>,
169    tm: &Tm,
170) -> Result<i32, DateTimeError> {
171    if !is_valid_julian(tm.year, tm.mon) {
172        return match abbreviation {
173            Some(abbreviation) => Ok(zone
174                .interpret_abbreviation(abbreviation, 0)?
175                .map_or(0, |meaning| meaning.offset)),
176            None => Ok(0),
177        };
178    }
179    let local = local_seconds(tm).ok_or(DateTimeError::OutsideJiffRange)?;
180    match abbreviation {
181        Some(abbreviation) => abbreviation_offset(zone, abbreviation, local),
182        None => local_offset(zone, local),
183    }
184    .map_err(|_| DateTimeError::OutsideJiffRange)
185}
186
187impl PgDate {
188    /// PostgreSQL's `date_in`, reading every spelling `DecodeDateTime` reads, with a clock and
189    /// zone read, checked and ignored.
190    ///
191    /// # Errors
192    ///
193    /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
194    /// context lacks, [`DateTimeError::NeedsDateOrder`], [`DateTimeError::NeedsCurrentTime`] or
195    /// [`DateTimeError::NeedsTimeZone`].
196    ///
197    /// ```
198    /// use sql_values::{DateOrder, DateTimeError, InputContext, PgDate, PgType};
199    ///
200    /// let read = |text, context| PgDate::parse(text, context).map(|d| d.to_string());
201    /// let context = InputContext::new();
202    /// assert_eq!(read("5874897-12-31", context).unwrap(), "5874897-12-31");
203    /// assert_eq!(read("January 8, 1999 BC", context).unwrap(), "1999-01-08 BC");
204    /// assert_eq!(read("J2451545", context).unwrap(), "2000-01-01");
205    /// // Under `YMD` a short number after a month name is the year, which `99` can be.
206    /// assert_eq!(read("January 8, 99", context), Err(DateTimeError::NeedsDateOrder));
207    /// assert_eq!(read("2024-02-30", context), Err(DateTimeError::FieldValueOutOfRange));
208    /// assert_eq!(read("nope", context), Err(DateTimeError::InvalidInputSyntax(PgType::Date)));
209    /// assert_eq!(read("01/02/2026", context), Err(DateTimeError::NeedsDateOrder));
210    /// let dmy = context.with_date_order(DateOrder::Dmy);
211    /// assert_eq!(read("01/02/2026", dmy).unwrap(), "2026-02-01");
212    /// ```
213    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
214        by_date_order(context, |context| Self::read(text, context))
215    }
216
217    /// [`Self::parse`] under the context's order alone.
218    fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
219        let decoded = decode(text, context, PgType::Date, decode_date_time)?;
220        let tm = match decoded.dtype {
221            DateType::Date => decoded.tm,
222            DateType::Epoch => return Ok(Self(EPOCH_DAYS)),
223            DateType::Late => return Ok(Self::INFINITY),
224            DateType::Early => return Ok(Self::NEG_INFINITY),
225        };
226        if !is_valid_julian(tm.year, tm.mon) {
227            return Err(DateTimeError::DateOutOfRange);
228        }
229        Self::from_pg_days(date2j(tm.year, tm.mon, tm.mday) - POSTGRES_EPOCH_JDATE)
230            .filter(|date| date.is_finite())
231            .ok_or(DateTimeError::DateOutOfRange)
232    }
233}
234
235impl PgTimestamp {
236    /// PostgreSQL's `timestamp_in`, reading every spelling `DecodeDateTime` reads, with a zone
237    /// read, checked and ignored.
238    ///
239    /// # Errors
240    ///
241    /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
242    /// context lacks.
243    ///
244    /// ```
245    /// use sql_values::{DateTimeError, InputContext, PgTimestamp};
246    ///
247    /// let read = |text| PgTimestamp::parse(text, InputContext::new()).map(|t| t.to_string());
248    /// assert_eq!(read("2024-12-31 24:00:00").unwrap(), "2025-01-01 00:00:00");
249    /// assert_eq!(read("Jan 1999 08 04:05:06 PM").unwrap(), "1999-01-08 16:05:06");
250    /// assert_eq!(read("19990108T040506.5").unwrap(), "1999-01-08 04:05:06.5");
251    /// assert_eq!(read("294277-01-01"), Err(DateTimeError::TimestampOutOfRange));
252    /// ```
253    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
254        by_date_order(context, |context| Self::read(text, context))
255    }
256
257    /// [`Self::parse`] under the context's order alone.
258    fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
259        let decoded = decode(text, context, PgType::Timestamp, decode_date_time)?;
260        match decoded.dtype {
261            DateType::Date => {
262                let tm = decoded.tm;
263                tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), 0)
264                    .map(Self)
265                    .ok_or(DateTimeError::TimestampOutOfRange)
266            }
267            DateType::Epoch => Ok(Self(EPOCH_MICROS)),
268            DateType::Late => Ok(Self::INFINITY),
269            DateType::Early => Ok(Self::NEG_INFINITY),
270        }
271    }
272}
273
274impl PgTimestampTz {
275    /// PostgreSQL's `timestamptz_in`, reading every spelling `DecodeDateTime` reads. A zone the
276    /// literal names, or else the context's time zone, decides the offset of a literal without
277    /// a numeric one, its local clock resolved as [`PgTimestamp::to_timestamptz`] resolves it,
278    /// and an abbreviation whose meaning changed takes the one it had at that clock.
279    ///
280    /// # Errors
281    ///
282    /// The [`DateTimeError`] PostgreSQL raises, the session state the literal needs and the
283    /// context lacks, or [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about
284    /// a clock outside jiff's years.
285    ///
286    /// ```
287    /// use sql_values::{DateTimeError, InputContext, PgTimeZone, PgTimestampTz};
288    ///
289    /// let read = |text, context| PgTimestampTz::parse(text, context).map(|t| t.to_string());
290    /// let context = InputContext::new();
291    /// assert_eq!(read("2024-01-01 12:00+15:59:59", context).unwrap(), "2023-12-31 20:00:01+00");
292    /// assert_eq!(
293    ///     read("2024-01-01 12:00+16", context),
294    ///     Err(DateTimeError::TimeZoneDisplacementOutOfRange),
295    /// );
296    /// // `MSK` follows Europe/Moscow, which kept +04 from 2011 to 2014.
297    /// assert_eq!(read("2012-01-01 12:00 MSK", context).unwrap(), "2012-01-01 08:00:00+00");
298    /// assert_eq!(read("2015-01-01 12:00 MSK", context).unwrap(), "2015-01-01 09:00:00+00");
299    /// assert_eq!(read("2026-07-01 12:00 Europe/Rome", context).unwrap(), "2026-07-01 10:00:00+00");
300    /// assert_eq!(read("now", context), Err(DateTimeError::NeedsCurrentTime));
301    /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
302    /// let start = PgTimestampTz::parse("2026-07-01 23:30+00", context).unwrap();
303    /// let session = context.with_time_zone(&rome).with_now(start);
304    /// assert_eq!(read("today", session).unwrap(), "2026-07-01 22:00:00+00");
305    /// ```
306    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
307        by_date_order(context, |context| Self::read(text, context))
308    }
309
310    /// [`Self::parse`] under the context's order alone.
311    fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
312        let decoded = decode(text, context, PgType::TimestampTz, decode_date_time)?;
313        let tm = match decoded.dtype {
314            DateType::Date => decoded.tm,
315            DateType::Epoch => return Ok(Self(EPOCH_MICROS)),
316            DateType::Late => return Ok(Self::INFINITY),
317            DateType::Early => return Ok(Self::NEG_INFINITY),
318        };
319        let out_of_range = DateTimeError::TimestampOutOfRange;
320        // The local clock as microseconds from 2000-01-01, for a zone to resolve.
321        let local = || {
322            if !is_valid_julian(tm.year, tm.mon) {
323                return Err(out_of_range);
324            }
325            let days =
326                i64::from(date2j(tm.year, tm.mon, tm.mday)) - i64::from(POSTGRES_EPOCH_JDATE);
327            days.checked_mul(USECS_PER_DAY)
328                .and_then(|micros| micros.checked_add(tm.clock()))
329                .ok_or(out_of_range)
330        };
331        let offset = match &decoded.zone {
332            ZoneSource::West(west) => -*west,
333            ZoneSource::Abbreviation { zone, upper } => abbreviation_offset(zone, upper, local()?)?,
334            ZoneSource::Named(zone) => local_offset(zone, local()?)?,
335            ZoneSource::Session => {
336                let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
337                local_offset(zone, local()?)?
338            }
339        };
340        tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), offset)
341            .map(Self)
342            .ok_or(out_of_range)
343    }
344}
345
346impl PgTime {
347    /// PostgreSQL's `time_in`, reading every spelling `DecodeTimeOnly` reads, with a date and
348    /// zone read, checked and ignored, and the fraction rounded to the microsecond.
349    ///
350    /// # Errors
351    ///
352    /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
353    /// context lacks.
354    ///
355    /// ```
356    /// use sql_values::{DateTimeError, InputContext, PgTime, PgType};
357    ///
358    /// let read = |text| PgTime::parse(text, InputContext::new()).map(|t| t.to_string());
359    /// assert_eq!(read("23:59:60").unwrap(), "24:00:00");
360    /// assert_eq!(read("12:00:00.1234565").unwrap(), "12:00:00.123456");
361    /// assert_eq!(read("040506.5 PM").unwrap(), "16:05:06.5");
362    /// assert_eq!(read("T12:00 Europe/Rome"), Err(DateTimeError::InvalidInputSyntax(PgType::Time)));
363    /// assert_eq!(read("2026-07-01 12:00 Europe/Rome").unwrap(), "12:00:00");
364    /// assert_eq!(read("24:00:00.000001"), Err(DateTimeError::FieldValueOutOfRange));
365    /// ```
366    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
367        by_date_order(context, |context| Self::read(text, context))
368    }
369
370    /// [`Self::parse`] under the context's order alone.
371    fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
372        let decoded = decode(text, context, PgType::Time, decode_time_only)?;
373        Ok(Self(decoded.tm.clock()))
374    }
375}
376
377impl PgTimeTz {
378    /// PostgreSQL's `timetz_in`, reading every spelling `DecodeTimeOnly` reads. A time without
379    /// an offset, or with a zone whose offset changes, takes the zone's offset on the date the
380    /// literal writes, or else on the current date in the context's time zone.
381    ///
382    /// # Errors
383    ///
384    /// The [`DateTimeError`] PostgreSQL raises, the session state the literal needs and the
385    /// context lacks, or [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about
386    /// a date outside jiff's years.
387    ///
388    /// ```
389    /// use sql_values::{DateTimeError, InputContext, PgTimeTz, PgTimeZone, PgTimestampTz};
390    ///
391    /// let read = |text, context| PgTimeTz::parse(text, context).map(|t| t.to_string());
392    /// let context = InputContext::new();
393    /// assert_eq!(read("12:00:00-05:30", context).unwrap(), "12:00:00-05:30");
394    /// assert_eq!(read("allballs", context).unwrap(), "00:00:00+00");
395    /// assert_eq!(read("2026-07-01 12:00 Europe/Rome", context).unwrap(), "12:00:00+02");
396    /// assert_eq!(read("12:00", context), Err(DateTimeError::NeedsCurrentTime));
397    /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
398    /// let start = PgTimestampTz::parse("2026-01-15 12:00+00", context).unwrap();
399    /// let session = context.with_time_zone(&rome).with_now(start);
400    /// assert_eq!(read("12:00", session).unwrap(), "12:00:00+01");
401    /// ```
402    pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
403        by_date_order(context, |context| Self::read(text, context))
404    }
405
406    /// [`Self::parse`] under the context's order alone.
407    fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
408        let pg_type = PgType::TimeTz;
409        let DecodedTime { tm, dated, zone } = decode(text, context, pg_type, decode_time_only)?;
410        // The literal's date, or the current one, at the literal's clock.
411        let at = || {
412            let mut at = if dated {
413                tm
414            } else {
415                current_time(context)
416                    .map_err(|error| error.for_type(pg_type))?
417                    .0
418            };
419            (at.hour, at.min, at.sec) = (tm.hour, tm.min, tm.sec);
420            Ok::<_, DateTimeError>(at)
421        };
422        let offset = match &zone {
423            ZoneSource::West(west) => -*west,
424            ZoneSource::Named(zone) => time_zone_offset(zone, None, &tm)?,
425            ZoneSource::Abbreviation { zone, upper } => {
426                time_zone_offset(zone, Some(upper), &at()?)?
427            }
428            ZoneSource::Session => {
429                let at = at()?;
430                let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
431                time_zone_offset(zone, None, &at)?
432            }
433        };
434        Ok(Self {
435            time: tm.clock(),
436            offset,
437        })
438    }
439}
440
441/// Parse `YYYY-MM-DD HH:MM:SS[.f]` with a space or `T` separator, a year of four or more digits,
442/// PostgreSQL's trailing ` BC`, and `infinity` and `-infinity`, the fraction rounded to the
443/// microsecond. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
444///
445/// ```
446/// let at = sql_values::parse_timestamp("2024-01-02 03:04:05.125").unwrap();
447/// assert_eq!(at.to_string(), "2024-01-02 03:04:05.125");
448/// ```
449#[must_use]
450pub fn parse_timestamp(text: &str) -> Option<PgTimestamp> {
451    match text {
452        "infinity" => return Some(PgTimestamp::INFINITY),
453        "-infinity" => return Some(PgTimestamp::NEG_INFINITY),
454        _ => {}
455    }
456    let (body, bc) = split_era(text.as_bytes());
457    match parse_datetime_prefix(body, bc)? {
458        (date, clock, []) => date.at(clock, 0).map(PgTimestamp),
459        _ => None,
460    }
461}
462
463/// Parse a [`parse_timestamp`] layout followed by a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS`
464/// offset, then PostgreSQL's optional ` BC`, or `infinity` and `-infinity`.
465///
466/// ```
467/// let at = sql_values::parse_timestamp_tz("2024-01-02T03:04:05+02:00").unwrap();
468/// assert_eq!(at.to_string(), "2024-01-02 01:04:05+00");
469/// ```
470#[must_use]
471pub fn parse_timestamp_tz(text: &str) -> Option<PgTimestampTz> {
472    match text {
473        "infinity" => return Some(PgTimestampTz::INFINITY),
474        "-infinity" => return Some(PgTimestampTz::NEG_INFINITY),
475        _ => {}
476    }
477    let (body, bc) = split_era(text.as_bytes());
478    let (date, clock, offset) = parse_datetime_prefix(body, bc)?;
479    date.at(clock, parse_offset(offset)?).map(PgTimestampTz)
480}
481
482/// Parse a `YYYY-MM-DD` date with a year of four or more digits and PostgreSQL's trailing ` BC`,
483/// or `infinity` and `-infinity`. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
484///
485/// ```
486/// let d = sql_values::parse_date("2024-01-02").unwrap();
487/// assert_eq!(d.to_string(), "2024-01-02");
488/// ```
489#[must_use]
490pub fn parse_date(text: &str) -> Option<PgDate> {
491    match text {
492        "infinity" => return Some(PgDate::INFINITY),
493        "-infinity" => return Some(PgDate::NEG_INFINITY),
494        _ => {}
495    }
496    let (body, bc) = split_era(text.as_bytes());
497    match parse_date_prefix(body, bc)? {
498        (date, []) => PgDate::from_ymd(date.year, date.month, date.day),
499        _ => None,
500    }
501}
502
503/// Parse `HH:MM:SS[.f]` with one to nine fraction digits, rounded to the microsecond, up to
504/// 24:00:00.
505///
506/// ```
507/// let t = sql_values::parse_time("03:04:05.125").unwrap();
508/// assert_eq!(t.to_string(), "03:04:05.125");
509/// ```
510#[must_use]
511pub fn parse_time(text: &str) -> Option<PgTime> {
512    match parse_time_prefix(text.as_bytes())? {
513        (micros, []) => Some(PgTime(micros)),
514        _ => None,
515    }
516}
517
518/// Split off PostgreSQL's ` BC`, which trails the whole value.
519fn split_era(bytes: &[u8]) -> (&[u8], bool) {
520    match bytes.strip_suffix(b" BC") {
521        Some(body) => (body, true),
522        None => (bytes, false),
523    }
524}
525
526/// A year, month and day as written, where year `Y` BC is year `1 - Y`.
527#[derive(Clone, Copy)]
528struct Ymd {
529    year: i32,
530    month: u8,
531    day: u8,
532}
533
534impl Ymd {
535    /// The timestamp of `clock` on this date with `offset` seconds east subtracted, or `None`
536    /// outside the calendar or PostgreSQL's range.
537    fn at(self, clock: i64, offset: i32) -> Option<i64> {
538        let (month, day) = (i32::from(self.month), i32::from(self.day));
539        if !(1..=12).contains(&month) || !(1..=days_in_month(self.year, month)).contains(&day) {
540            return None;
541        }
542        tm2timestamp(self.year, month, day, clock, offset)
543    }
544}
545
546/// Parse a leading `Y{4,}-MM-DD`, where year `Y` BC is year `1 - Y` and year `0000` is year 0.
547fn parse_date_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, &[u8])> {
548    let year_len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
549    if year_len < 4 || (year_len > 4 && bytes[0] == b'0') {
550        return None;
551    }
552    let (year, _, erange) = strtoint(bytes, 0);
553    if erange {
554        return None;
555    }
556    let rest = &bytes[year_len..];
557    let year = match (year, bc) {
558        (0, true) => return None,
559        (_, true) => 1 - year,
560        (_, false) => year,
561    };
562    let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
563        return None;
564    };
565    let month = parse_two_digits([m1, m2])?;
566    let day = parse_two_digits([d1, d2])?;
567    Some((Ymd { year, month, day }, rest))
568}
569
570/// Parse a leading `HH:MM:SS[.f]` with one to nine fraction digits, as microseconds up to
571/// 24:00:00.
572fn parse_time_prefix(bytes: &[u8]) -> Option<(i64, &[u8])> {
573    let Some((&[h1, h2, b':', m1, m2, b':', s1, s2], rest)) = bytes.split_first_chunk() else {
574        return None;
575    };
576    let (fsec, rest) = match rest.split_first() {
577        Some((b'.', fraction)) => {
578            let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
579            if !(1..=9).contains(&len) {
580                return None;
581            }
582            let fsec = parse_fractional_second(&rest[..=len]).ok()?;
583            (i64::from(fsec), &fraction[len..])
584        }
585        _ => (0, rest),
586    };
587    let (hour, minute, second) = (
588        parse_two_digits([h1, h2])?,
589        parse_two_digits([m1, m2])?,
590        parse_two_digits([s1, s2])?,
591    );
592    if minute > 59 || second > 59 {
593        return None;
594    }
595    let micros = i64::from(hour) * USECS_PER_HOUR
596        + i64::from(minute) * USECS_PER_MINUTE
597        + i64::from(second) * USECS_PER_SEC
598        + fsec;
599    (micros <= USECS_PER_DAY).then_some((micros, rest))
600}
601
602/// Parse a leading date and time joined by a space or `T`, the clock in microseconds.
603fn parse_datetime_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, i64, &[u8])> {
604    let (date, rest) = parse_date_prefix(bytes, bc)?;
605    let (&(b' ' | b'T'), rest) = rest.split_first()? else {
606        return None;
607    };
608    let (clock, rest) = parse_time_prefix(rest)?;
609    Some((date, clock, rest))
610}
611
612/// Two ASCII digits as a number.
613fn parse_two_digits(digits: [u8; 2]) -> Option<u8> {
614    if digits.iter().all(u8::is_ascii_digit) {
615        Some((digits[0] - b'0') * 10 + (digits[1] - b'0'))
616    } else {
617        None
618    }
619}
620
621/// Parse a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS` offset as seconds east of UTC, with an
622/// hour up to 23.
623fn parse_offset(bytes: &[u8]) -> Option<i32> {
624    if bytes == b"Z" {
625        return Some(0);
626    }
627    let (&sign, digits) = bytes.split_first()?;
628    let negative = match sign {
629        b'+' => false,
630        b'-' => true,
631        _ => return None,
632    };
633    let pair = |at: usize| parse_two_digits(digits.get(at..at + 2)?.try_into().ok()?);
634    let hour = pair(0)?;
635    let (minute, second) = match digits.len() {
636        2 => (0, 0),
637        4 => (pair(2)?, 0),
638        5 if digits[2] == b':' => (pair(3)?, 0),
639        8 if digits[2] == b':' && digits[5] == b':' => (pair(3)?, pair(6)?),
640        _ => return None,
641    };
642    if hour > 23 || minute > 59 || second > 59 {
643        return None;
644    }
645    let seconds = (i32::from(hour) * 60 + i32::from(minute)) * 60 + i32::from(second);
646    Some(if negative { -seconds } else { seconds })
647}