use alloc::{string::String, vec::Vec};
use super::{
DateTimeError, POSTGRES_EPOCH_JDATE, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
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 crate::{
PgTimeZone, TimeZoneAbbreviations,
cast::{is_pg_space, trim_pg_space},
float::{round_ties_even, truncate_to_i64},
interval::date_word_era,
zone::{DEFAULT_ABBREVIATIONS, Meaning},
};
const MAX_TZDISP_HOUR: i32 = 15;
const MAX_LITERAL_LEN: usize = 64;
const EPOCH_MICROS: i64 = -946_684_800_000_000;
const EPOCH_DAYS: i32 = -10_957;
#[derive(Debug, Clone, Copy)]
pub struct InputContext<'a> {
time_zone: Option<&'a PgTimeZone>,
abbreviations: &'a TimeZoneAbbreviations,
}
impl<'a> InputContext<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
time_zone: None,
abbreviations: &DEFAULT_ABBREVIATIONS,
}
}
#[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
}
}
}
impl Default for InputContext<'_> {
fn default() -> Self {
Self::new()
}
}
enum Special {
Late,
Early,
Epoch,
}
struct Fields {
year: i32,
month: i32,
day: i32,
clock: i64,
offset: Option<i32>,
zone: Option<LiteralZone>,
}
enum Literal {
Special(Special),
Fields(Fields),
}
struct RawOffset<'a> {
negative: bool,
digits: &'a [u8],
}
enum Word {
Era(bool),
Zone(LiteralZone),
}
#[derive(Clone)]
enum LiteralZone {
Fixed(i32),
Dynamic {
zone: PgTimeZone,
abbreviation: String,
},
Named(PgTimeZone),
}
struct RawClock<'a> {
hour: [u8; 2],
minute: [u8; 2],
second: Option<[u8; 2]>,
fraction: Option<&'a [u8]>,
offset: Option<RawOffset<'a>>,
}
struct Scanner<'a> {
bytes: &'a [u8],
at: usize,
}
impl<'a> Scanner<'a> {
const fn new(bytes: &'a [u8]) -> Self {
Self { bytes, at: 0 }
}
fn peek(&self) -> Option<u8> {
self.bytes.get(self.at).copied()
}
fn peek_at(&self, ahead: usize) -> Option<u8> {
self.bytes.get(self.at + ahead).copied()
}
fn eat(&mut self, byte: u8) -> bool {
let found = self.peek() == Some(byte);
self.at += usize::from(found);
found
}
fn digits(&mut self) -> &'a [u8] {
let start = self.at;
while self.peek().is_some_and(|b| b.is_ascii_digit()) {
self.at += 1;
}
&self.bytes[start..self.at]
}
fn two_digits(&mut self) -> Option<[u8; 2]> {
match (self.peek(), self.peek_at(1)) {
(Some(a), Some(b)) if a.is_ascii_digit() && b.is_ascii_digit() => {
self.at += 2;
Some([a, b])
}
_ => None,
}
}
fn spaces(&mut self) -> usize {
let start = self.at;
while self.peek().is_some_and(is_pg_space) {
self.at += 1;
}
self.at - start
}
fn is_done(&self) -> bool {
self.at == self.bytes.len()
}
fn clock(&mut self) -> Option<RawClock<'a>> {
let hour = self.two_digits()?;
if !self.eat(b':') {
return None;
}
let minute = self.two_digits()?;
let mut second = None;
let mut fraction = None;
if self.eat(b':') {
second = Some(self.two_digits()?);
if self.peek() == Some(b'.') {
let start = self.at;
self.at += 1;
self.digits();
fraction = Some(&self.bytes[start..self.at]);
}
}
if self.peek().is_some_and(|b| b.is_ascii_digit() || b == b'.') {
return None;
}
let before_offset = self.at;
self.spaces();
let offset = match self.peek() {
Some(sign @ (b'+' | b'-')) if self.peek_at(1).is_some_and(|b| b.is_ascii_digit()) => {
self.at += 1;
let start = self.at;
while self.peek().is_some_and(|b| b.is_ascii_digit() || b == b':') {
self.at += 1;
}
if matches!(self.peek(), Some(b'.' | b'-')) {
return None;
}
Some(RawOffset {
negative: sign == b'-',
digits: &self.bytes[start..self.at],
})
}
_ => {
self.at = before_offset;
None
}
};
Some(RawClock {
hour,
minute,
second,
fraction,
offset,
})
}
fn words(&mut self) -> Option<Vec<Vec<u8>>> {
let mut words = Vec::new();
loop {
self.spaces();
if self.is_done() {
return Some(words);
}
let start = self.at;
while self.peek().is_some_and(|b| b.is_ascii_alphabetic()) {
self.at += 1;
}
if self.at == start || !(self.is_done() || self.peek().is_some_and(is_pg_space)) {
return None;
}
words.push(self.bytes[start..self.at].to_ascii_lowercase());
}
}
}
fn strtoint(digits: &[u8]) -> Option<i32> {
digits.iter().try_fold(0i32, |value, &digit| {
value.checked_mul(10)?.checked_add(i32::from(digit - b'0'))
})
}
fn two(digits: [u8; 2]) -> i32 {
i32::from(digits[0] - b'0') * 10 + i32::from(digits[1] - b'0')
}
fn fractional_second(fraction: &[u8]) -> i64 {
if fraction.len() == 1 {
return 0;
}
let value: f64 = core::str::from_utf8(fraction)
.ok()
.and_then(|text| text.parse().ok())
.expect("a point and digits read as a double");
truncate_to_i64(round_ties_even(value * 1_000_000.0))
}
impl RawClock<'_> {
fn decode(&self) -> Result<i64, DateTimeError> {
let (hour, minute) = (two(self.hour), two(self.minute));
let second = self.second.map_or(0, two);
let fsec = self.fraction.map_or(0, fractional_second);
if minute > 59 || second > 60 {
return Err(DateTimeError::FieldValueOutOfRange);
}
Ok(i64::from(hour) * USECS_PER_HOUR
+ i64::from(minute) * USECS_PER_MINUTE
+ i64::from(second) * USECS_PER_SEC
+ fsec)
}
}
fn check_time_overflow(clock: i64) -> Result<i64, DateTimeError> {
if clock > USECS_PER_DAY {
Err(DateTimeError::FieldValueOutOfRange)
} else {
Ok(clock)
}
}
fn decode_timezone(offset: &RawOffset<'_>) -> Result<i32, DateTimeError> {
let RawOffset { negative, digits } = *offset;
let mut parts = digits.split(|&b| b == b':');
let mut field = || match parts.next() {
None => Ok(0),
Some([]) => Err(DateTimeError::Unsupported),
Some(part) => strtoint(part).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange),
};
let mut hour = field()?;
let mut minute = field()?;
let second = field()?;
if parts.next().is_some() {
return Err(DateTimeError::Unsupported);
}
let colon = digits.contains(&b':');
if !colon && digits.len() > 2 {
minute = hour % 100;
hour /= 100;
}
if hour > MAX_TZDISP_HOUR || minute >= 60 || second >= 60 {
return Err(DateTimeError::TimeZoneDisplacementOutOfRange);
}
let seconds = (hour * 60 + minute) * 60 + second;
Ok(if negative { -seconds } else { seconds })
}
fn classify(word: &[u8], context: InputContext<'_>) -> Result<Word, DateTimeError> {
let upper = String::from_utf8_lossy(word).to_ascii_uppercase();
if let Some(zone) = context.time_zone
&& let Some((meaning, fixed)) = zone.abbreviation_is_known(&upper)
{
return Ok(Word::Zone(if fixed {
LiteralZone::Fixed(meaning.offset)
} else {
LiteralZone::Dynamic {
zone: zone.clone(),
abbreviation: upper,
}
}));
}
match context.abbreviations.lookup(word) {
Some(Meaning::Fixed { offset, .. }) => return Ok(Word::Zone(LiteralZone::Fixed(*offset))),
Some(Meaning::Zone(name)) => {
let zone = PgTimeZone::load(name).ok_or(DateTimeError::TimeZoneNotRecognized)?;
return Ok(Word::Zone(LiteralZone::Dynamic {
zone,
abbreviation: upper,
}));
}
None => {}
}
match date_word_era(word) {
Some(Some(bc)) => Ok(Word::Era(bc)),
Some(None) => Err(DateTimeError::Unsupported),
None => PgTimeZone::load(&upper)
.map(|zone| Word::Zone(LiteralZone::Named(zone)))
.ok_or(DateTimeError::Unsupported),
}
}
fn classify_words(
words: &[Vec<u8>],
numeric_offset: bool,
context: InputContext<'_>,
) -> Result<(Option<bool>, Option<LiteralZone>), DateTimeError> {
let (mut era, mut zone) = (None, None);
for word in words {
match classify(word, context)? {
Word::Era(_) if era.is_some() => return Err(DateTimeError::Unsupported),
Word::Era(bc) => era = Some(bc),
Word::Zone(_) if zone.is_some() || numeric_offset => {
return Err(DateTimeError::Unsupported);
}
Word::Zone(written) => zone = Some(written),
}
}
Ok((era, zone))
}
fn read_date_time(text: &str, context: InputContext<'_>) -> Result<Literal, DateTimeError> {
let bytes = trim_pg_space(text.as_bytes());
if bytes.len() > MAX_LITERAL_LEN {
return Err(DateTimeError::Unsupported);
}
let special =
if bytes.eq_ignore_ascii_case(b"infinity") || bytes.eq_ignore_ascii_case(b"+infinity") {
Some(Special::Late)
} else if bytes.eq_ignore_ascii_case(b"-infinity") {
Some(Special::Early)
} else if bytes.eq_ignore_ascii_case(b"epoch") {
Some(Special::Epoch)
} else {
None
};
if let Some(special) = special {
return Ok(Literal::Special(special));
}
let unsupported = DateTimeError::Unsupported;
let mut scanner = Scanner::new(bytes);
let year = scanner.digits();
if year.len() < 4 || (year.len() > 4 && year[0] == b'0') || !scanner.eat(b'-') {
return Err(unsupported);
}
let month = scanner.two_digits().ok_or(unsupported)?;
if !scanner.eat(b'-') {
return Err(unsupported);
}
let day = scanner.two_digits().ok_or(unsupported)?;
if scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
return Err(unsupported);
}
let after_date = scanner.at;
let separated = match scanner.peek() {
Some(b'T' | b't') => {
scanner.at += 1;
true
}
_ => scanner.spaces() > 0,
};
let clock = if separated && scanner.peek().is_some_and(|b| b.is_ascii_digit()) {
Some(scanner.clock().ok_or(unsupported)?)
} else {
scanner.at = after_date;
None
};
let words = scanner.words().ok_or(unsupported)?;
let year = strtoint(year).ok_or(DateTimeError::FieldValueOutOfRange)?;
let (clock, offset) = match clock {
None => (0, None),
Some(raw) => {
let clock = check_time_overflow(raw.decode()?)?;
let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
(clock, offset)
}
};
let (era, zone) = classify_words(&words, offset.is_some(), context)?;
let bc = era.unwrap_or(false);
if year <= 0 {
return Err(DateTimeError::FieldValueOutOfRange);
}
let year = if bc { 1 - year } else { year };
let (month, day) = (two(month), two(day));
if !(1..=12).contains(&month) || !(1..=days_in_month(year, month)).contains(&day) {
return Err(DateTimeError::FieldValueOutOfRange);
}
Ok(Literal::Fields(Fields {
year,
month,
day,
clock,
offset,
zone,
}))
}
enum TimeOffset {
Unwritten,
Known(i32),
NeedsDate,
}
fn read_time(
text: &str,
context: InputContext<'_>,
) -> Result<Option<(i64, TimeOffset)>, DateTimeError> {
let bytes = trim_pg_space(text.as_bytes());
if bytes.len() > MAX_LITERAL_LEN {
return Err(DateTimeError::Unsupported);
}
if bytes.eq_ignore_ascii_case(b"allballs") {
return Ok(None);
}
let mut scanner = Scanner::new(bytes);
let raw = scanner.clock().ok_or(DateTimeError::Unsupported)?;
let words = scanner.words().ok_or(DateTimeError::Unsupported)?;
let clock = raw.decode()?;
let offset = raw.offset.as_ref().map(decode_timezone).transpose()?;
let (era, zone) = classify_words(&words, offset.is_some(), context)?;
if era.is_some() {
return Err(DateTimeError::Unsupported);
}
let offset = match (offset, zone) {
(Some(offset), _) | (None, Some(LiteralZone::Fixed(offset))) => TimeOffset::Known(offset),
(None, Some(LiteralZone::Named(zone))) => zone
.fixed_offset()
.map_or(TimeOffset::NeedsDate, TimeOffset::Known),
(None, Some(LiteralZone::Dynamic { .. })) => TimeOffset::NeedsDate,
(None, None) => TimeOffset::Unwritten,
};
Ok(Some((check_time_overflow(clock)?, offset)))
}
impl PgDate {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
let fields = match read_date_time(text, context)? {
Literal::Special(Special::Late) => return Ok(Self::INFINITY),
Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_DAYS)),
Literal::Fields(fields) => fields,
};
if !is_valid_julian(fields.year, fields.month) {
return Err(DateTimeError::DateOutOfRange);
}
Self::from_pg_days(date2j(fields.year, fields.month, fields.day) - POSTGRES_EPOCH_JDATE)
.filter(|date| date.is_finite())
.ok_or(DateTimeError::DateOutOfRange)
}
}
impl PgTimestamp {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
match read_date_time(text, context)? {
Literal::Special(Special::Late) => Ok(Self::INFINITY),
Literal::Special(Special::Early) => Ok(Self::NEG_INFINITY),
Literal::Special(Special::Epoch) => Ok(Self(EPOCH_MICROS)),
Literal::Fields(fields) => {
tm2timestamp(fields.year, fields.month, fields.day, fields.clock, 0)
.map(Self)
.ok_or(DateTimeError::TimestampOutOfRange)
}
}
}
}
impl PgTimestampTz {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
let fields = match read_date_time(text, context)? {
Literal::Special(Special::Late) => return Ok(Self::INFINITY),
Literal::Special(Special::Early) => return Ok(Self::NEG_INFINITY),
Literal::Special(Special::Epoch) => return Ok(Self(EPOCH_MICROS)),
Literal::Fields(fields) => fields,
};
let out_of_range = DateTimeError::TimestampOutOfRange;
let local = || {
if !is_valid_julian(fields.year, fields.month) {
return Err(out_of_range);
}
let days = i64::from(date2j(fields.year, fields.month, fields.day))
- i64::from(POSTGRES_EPOCH_JDATE);
days.checked_mul(USECS_PER_DAY)
.and_then(|micros| micros.checked_add(fields.clock))
.ok_or(out_of_range)
};
let offset = match (fields.offset, &fields.zone, context.time_zone) {
(Some(offset), _, _) => offset,
(None, Some(LiteralZone::Fixed(offset)), _) => *offset,
(None, Some(LiteralZone::Dynamic { zone, abbreviation }), _) => {
abbreviation_offset(zone, abbreviation, local()?)?
}
(None, Some(LiteralZone::Named(zone)), _) | (None, None, Some(zone)) => {
local_offset(zone, local()?)?
}
(None, None, None) => return Err(DateTimeError::NeedsTimeZone),
};
tm2timestamp(fields.year, fields.month, fields.day, fields.clock, offset)
.map(Self)
.ok_or(out_of_range)
}
}
impl PgTime {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
Ok(Self(
read_time(text, context)?.map_or(0, |(clock, _)| clock),
))
}
}
impl PgTimeTz {
pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
match read_time(text, context)? {
None => Ok(Self { time: 0, offset: 0 }),
Some((clock, TimeOffset::Known(offset))) => Ok(Self {
time: clock,
offset,
}),
Some((_, TimeOffset::Unwritten | TimeOffset::NeedsDate)) => {
Err(DateTimeError::Unsupported)
}
}
}
}
#[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_digits, rest) = bytes.split_at(year_len);
let year = strtoint(year_digits)?;
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;
}
(fractional_second(&rest[..=len]), &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 })
}