use super::{
DateTimeError, POSTGRES_EPOCH_JDATE, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
UNIX_TO_POSTGRES_SECS, USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC,
abbreviation_offset, date2j, days_in_month, is_valid_julian, local_offset, tm2timestamp,
};
use super::{
decode::{
DateOrder, DateType, DecodedTime, Dterr, Tm, ZoneSource, current_time, decode_date_time,
decode_time_only,
},
tokens::{Tokens, parse_date_time, parse_fractional_second, strtoint},
};
use crate::postgres::{PgTimeZone, PgType, TimeZoneAbbreviations, zone::DEFAULT_ABBREVIATIONS};
const EPOCH_MICROS: i64 = -946_684_800_000_000;
const EPOCH_DAYS: i32 = -10_957;
#[derive(Debug, Clone, Copy)]
pub struct InputContext<'a> {
pub(super) time_zone: Option<&'a PgTimeZone>,
pub(super) abbreviations: &'a TimeZoneAbbreviations,
pub(super) date_order: Option<DateOrder>,
pub(super) now: Option<PgTimestampTz>,
}
impl<'a> InputContext<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
time_zone: None,
abbreviations: &DEFAULT_ABBREVIATIONS,
date_order: None,
now: None,
}
}
#[must_use]
pub const fn with_time_zone(self, zone: &'a PgTimeZone) -> Self {
Self {
time_zone: Some(zone),
..self
}
}
#[must_use]
pub const fn with_time_zone_abbreviations(
self,
abbreviations: &'a TimeZoneAbbreviations,
) -> Self {
Self {
abbreviations,
..self
}
}
#[must_use]
pub const fn with_date_order(self, order: DateOrder) -> Self {
Self {
date_order: Some(order),
..self
}
}
#[must_use]
pub const fn with_now(self, now: PgTimestampTz) -> Self {
Self {
now: Some(now),
..self
}
}
}
impl Default for InputContext<'_> {
fn default() -> Self {
Self::new()
}
}
const MAX_DATE_LEN: usize = 128;
fn decode<'a, T>(
text: &str,
context: InputContext<'a>,
pg_type: PgType,
decoder: fn(&Tokens, InputContext<'a>) -> Result<T, Dterr>,
) -> Result<T, DateTimeError> {
let text = text.split('\0').next().unwrap_or_default();
let tokens = parse_date_time(text.as_bytes(), MAX_DATE_LEN + 1)
.map_err(|_| DateTimeError::InvalidInputSyntax(pg_type))?;
decoder(&tokens, context).map_err(|error| error.for_type(pg_type))
}
fn by_date_order<'a, T: PartialEq>(
context: InputContext<'a>,
read: impl Fn(InputContext<'a>) -> Result<T, DateTimeError>,
) -> Result<T, DateTimeError> {
match read(context) {
Err(DateTimeError::NeedsDateOrder) => {
let [mdy, dmy, ymd] = [DateOrder::Mdy, DateOrder::Dmy, DateOrder::Ymd]
.map(|order| read(context.with_date_order(order)));
if mdy == dmy && dmy == ymd {
mdy
} else {
Err(DateTimeError::NeedsDateOrder)
}
}
other => other,
}
}
fn local_seconds(tm: &Tm) -> i64 {
let days = i64::from(date2j(tm.year, tm.mon, tm.mday)) - i64::from(POSTGRES_EPOCH_JDATE);
let clock = (i64::from(tm.hour) * 60 + i64::from(tm.min)) * 60 + i64::from(tm.sec);
days * (USECS_PER_DAY / USECS_PER_SEC) + clock + UNIX_TO_POSTGRES_SECS
}
fn time_zone_offset(zone: &PgTimeZone, abbreviation: Option<&str>, tm: &Tm) -> i32 {
if !is_valid_julian(tm.year, tm.mon) {
return abbreviation
.and_then(|abbreviation| zone.interpret_abbreviation(abbreviation, 0))
.map_or(0, |meaning| meaning.offset);
}
let local = local_seconds(tm);
match abbreviation {
Some(abbreviation) => zone.abbreviation_offset(abbreviation, local),
None => zone.local_offset(local),
}
}
impl PgDate {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
by_date_order(context, |context| Self::read(text, context))
}
fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
let decoded = decode(text, context, PgType::Date, decode_date_time)?;
let tm = match decoded.dtype {
DateType::Date => decoded.tm,
DateType::Epoch => return Ok(Self(EPOCH_DAYS)),
DateType::Late => return Ok(Self::INFINITY),
DateType::Early => return Ok(Self::NEG_INFINITY),
};
if !is_valid_julian(tm.year, tm.mon) {
return Err(DateTimeError::DateOutOfRange);
}
Self::from_pg_days(date2j(tm.year, tm.mon, tm.mday) - POSTGRES_EPOCH_JDATE)
.filter(|date| date.is_finite())
.ok_or(DateTimeError::DateOutOfRange)
}
}
impl PgTimestamp {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
by_date_order(context, |context| Self::read(text, context))
}
fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
let decoded = decode(text, context, PgType::Timestamp, decode_date_time)?;
match decoded.dtype {
DateType::Date => {
let tm = decoded.tm;
tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), 0)
.map(Self)
.ok_or(DateTimeError::TimestampOutOfRange)
}
DateType::Epoch => Ok(Self(EPOCH_MICROS)),
DateType::Late => Ok(Self::INFINITY),
DateType::Early => Ok(Self::NEG_INFINITY),
}
}
}
impl PgTimestampTz {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
by_date_order(context, |context| Self::read(text, context))
}
fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
let decoded = decode(text, context, PgType::TimestampTz, decode_date_time)?;
let tm = match decoded.dtype {
DateType::Date => decoded.tm,
DateType::Epoch => return Ok(Self(EPOCH_MICROS)),
DateType::Late => return Ok(Self::INFINITY),
DateType::Early => return Ok(Self::NEG_INFINITY),
};
let out_of_range = DateTimeError::TimestampOutOfRange;
let local = || {
if !is_valid_julian(tm.year, tm.mon) {
return Err(out_of_range);
}
let days =
i64::from(date2j(tm.year, tm.mon, tm.mday)) - i64::from(POSTGRES_EPOCH_JDATE);
days.checked_mul(USECS_PER_DAY)
.and_then(|micros| micros.checked_add(tm.clock()))
.ok_or(out_of_range)
};
let offset = match &decoded.zone {
ZoneSource::West(west) => -*west,
ZoneSource::Abbreviation { zone, upper } => abbreviation_offset(zone, upper, local()?),
ZoneSource::Named(zone) => local_offset(zone, local()?),
ZoneSource::Session => {
let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
local_offset(zone, local()?)
}
};
tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), offset)
.map(Self)
.ok_or(out_of_range)
}
}
impl PgTime {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
by_date_order(context, |context| Self::read(text, context))
}
fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
let decoded = decode(text, context, PgType::Time, decode_time_only)?;
Ok(Self(decoded.tm.clock()))
}
}
impl PgTimeTz {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
by_date_order(context, |context| Self::read(text, context))
}
fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
let pg_type = PgType::TimeTz;
let DecodedTime { tm, dated, zone } = decode(text, context, pg_type, decode_time_only)?;
let at = || {
let mut at = if dated {
tm
} else {
current_time(context)
.map_err(|error| error.for_type(pg_type))?
.0
};
(at.hour, at.min, at.sec) = (tm.hour, tm.min, tm.sec);
Ok::<_, DateTimeError>(at)
};
let offset = match &zone {
ZoneSource::West(west) => -*west,
ZoneSource::Named(zone) => time_zone_offset(zone, None, &tm),
ZoneSource::Abbreviation { zone, upper } => time_zone_offset(zone, Some(upper), &at()?),
ZoneSource::Session => match context.time_zone.and_then(PgTimeZone::fixed_offset) {
Some(offset) if !dated => offset,
_ => {
let at = at()?;
let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
time_zone_offset(zone, None, &at)
}
},
};
Ok(Self {
time: tm.clock(),
offset,
})
}
}
#[must_use]
pub fn parse_timestamp(text: &str) -> Option<PgTimestamp> {
match text {
"infinity" => return Some(PgTimestamp::INFINITY),
"-infinity" => return Some(PgTimestamp::NEG_INFINITY),
_ => {}
}
let (body, bc) = split_era(text.as_bytes());
match parse_datetime_prefix(body, bc)? {
(date, clock, []) => date.at(clock, 0).map(PgTimestamp),
_ => None,
}
}
#[must_use]
pub fn parse_timestamp_tz(text: &str) -> Option<PgTimestampTz> {
match text {
"infinity" => return Some(PgTimestampTz::INFINITY),
"-infinity" => return Some(PgTimestampTz::NEG_INFINITY),
_ => {}
}
let (body, bc) = split_era(text.as_bytes());
let (date, clock, offset) = parse_datetime_prefix(body, bc)?;
date.at(clock, parse_offset(offset)?).map(PgTimestampTz)
}
#[must_use]
pub fn parse_date(text: &str) -> Option<PgDate> {
match text {
"infinity" => return Some(PgDate::INFINITY),
"-infinity" => return Some(PgDate::NEG_INFINITY),
_ => {}
}
let (body, bc) = split_era(text.as_bytes());
match parse_date_prefix(body, bc)? {
(date, []) => PgDate::from_ymd(date.year, date.month, date.day),
_ => None,
}
}
#[must_use]
pub fn parse_time(text: &str) -> Option<PgTime> {
match parse_time_prefix(text.as_bytes())? {
(micros, []) => Some(PgTime(micros)),
_ => None,
}
}
fn split_era(bytes: &[u8]) -> (&[u8], bool) {
match bytes.strip_suffix(b" BC") {
Some(body) => (body, true),
None => (bytes, false),
}
}
#[derive(Clone, Copy)]
struct Ymd {
year: i32,
month: u8,
day: u8,
}
impl Ymd {
fn at(self, clock: i64, offset: i32) -> Option<i64> {
let (month, day) = (i32::from(self.month), i32::from(self.day));
if !(1..=12).contains(&month) || !(1..=days_in_month(self.year, month)).contains(&day) {
return None;
}
tm2timestamp(self.year, month, day, clock, offset)
}
}
fn parse_date_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, &[u8])> {
let year_len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
if year_len < 4 || (year_len > 4 && bytes[0] == b'0') {
return None;
}
let (year, _, erange) = strtoint(bytes, 0);
if erange {
return None;
}
let rest = &bytes[year_len..];
let year = match (year, bc) {
(0, true) => return None,
(_, true) => 1 - year,
(_, false) => year,
};
let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
return None;
};
let month = parse_two_digits([m1, m2])?;
let day = parse_two_digits([d1, d2])?;
Some((Ymd { year, month, day }, rest))
}
fn parse_time_prefix(bytes: &[u8]) -> Option<(i64, &[u8])> {
let Some((&[h1, h2, b':', m1, m2, b':', s1, s2], rest)) = bytes.split_first_chunk() else {
return None;
};
let (fsec, rest) = match rest.split_first() {
Some((b'.', fraction)) => {
let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
if !(1..=9).contains(&len) {
return None;
}
let fsec = parse_fractional_second(&rest[..=len]).ok()?;
(i64::from(fsec), &fraction[len..])
}
_ => (0, rest),
};
let (hour, minute, second) = (
parse_two_digits([h1, h2])?,
parse_two_digits([m1, m2])?,
parse_two_digits([s1, s2])?,
);
if minute > 59 || second > 59 {
return None;
}
let micros = i64::from(hour) * USECS_PER_HOUR
+ i64::from(minute) * USECS_PER_MINUTE
+ i64::from(second) * USECS_PER_SEC
+ fsec;
(micros <= USECS_PER_DAY).then_some((micros, rest))
}
fn parse_datetime_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, i64, &[u8])> {
let (date, rest) = parse_date_prefix(bytes, bc)?;
let (&(b' ' | b'T'), rest) = rest.split_first()? else {
return None;
};
let (clock, rest) = parse_time_prefix(rest)?;
Some((date, clock, rest))
}
fn parse_two_digits(digits: [u8; 2]) -> Option<u8> {
if digits.iter().all(u8::is_ascii_digit) {
Some((digits[0] - b'0') * 10 + (digits[1] - b'0'))
} else {
None
}
}
fn parse_offset(bytes: &[u8]) -> Option<i32> {
if bytes == b"Z" {
return Some(0);
}
let (&sign, digits) = bytes.split_first()?;
let negative = match sign {
b'+' => false,
b'-' => true,
_ => return None,
};
let pair = |at: usize| parse_two_digits(digits.get(at..at + 2)?.try_into().ok()?);
let hour = pair(0)?;
let (minute, second) = match digits.len() {
2 => (0, 0),
4 => (pair(2)?, 0),
5 if digits[2] == b':' => (pair(3)?, 0),
8 if digits[2] == b':' && digits[5] == b':' => (pair(3)?, pair(6)?),
_ => return None,
};
if hour > 23 || minute > 59 || second > 59 {
return None;
}
let seconds = (i32::from(hour) * 60 + i32::from(minute)) * 60 + i32::from(second);
Some(if negative { -seconds } else { seconds })
}