mod input;
#[cfg(feature = "jiff")]
mod jiff_conversions;
use core::{cmp::Ordering, fmt};
pub use input::{InputContext, parse_date, parse_time, parse_timestamp, parse_timestamp_tz};
use crate::PgTimeZone;
pub(crate) const USECS_PER_SEC: i64 = 1_000_000;
pub(crate) const USECS_PER_MINUTE: i64 = 60_000_000;
pub(crate) const USECS_PER_HOUR: i64 = 3_600_000_000;
pub(crate) const USECS_PER_DAY: i64 = 86_400_000_000;
pub(crate) const MONTHS_PER_YEAR: i32 = 12;
pub(crate) const POSTGRES_EPOCH_JDATE: i32 = 2_451_545;
const UNIX_TO_POSTGRES_SECS: i64 = 946_684_800;
const DATE_END_JULIAN: i32 = 2_147_483_494;
pub(crate) const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
pub(crate) const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
const TZDISP_LIMIT: i32 = 16 * 3_600;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum DateTimeError {
#[error("date/time field value out of range")]
FieldValueOutOfRange,
#[error("time zone displacement out of range")]
TimeZoneDisplacementOutOfRange,
#[error("date out of range")]
DateOutOfRange,
#[error("timestamp out of range")]
TimestampOutOfRange,
#[error("value outside jiff's years -9999 to 9999")]
OutsideJiffRange,
#[error("the literal needs a time zone to read as timestamp with time zone")]
NeedsTimeZone,
#[error("time zone not recognized")]
TimeZoneNotRecognized,
#[error("date/time spelling not modelled")]
Unsupported,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(try_from = "i32", into = "i32")
)]
pub struct PgDate(i32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(try_from = "i64", into = "i64")
)]
pub struct PgTime(i64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "(i64, i32)", into = "(i64, i32)"))]
pub struct PgTimeTz {
time: i64,
offset: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(try_from = "i64", into = "i64")
)]
pub struct PgTimestamp(i64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(try_from = "i64", into = "i64")
)]
pub struct PgTimestampTz(i64);
impl PgDate {
pub const INFINITY: Self = Self(i32::MAX);
pub const NEG_INFINITY: Self = Self(i32::MIN);
#[must_use]
pub fn from_ymd(year: i32, month: u8, day: u8) -> Option<Self> {
let (month, day) = (i32::from(month), i32::from(day));
if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
return None;
}
if !is_valid_julian(year, month) {
return None;
}
Self::from_pg_days(date2j(year, month, day) - POSTGRES_EPOCH_JDATE)
}
#[must_use]
pub const fn from_pg_days(days: i32) -> Option<Self> {
let valid = -POSTGRES_EPOCH_JDATE <= days && days < DATE_END_JULIAN - POSTGRES_EPOCH_JDATE;
if valid || days == i32::MAX || days == i32::MIN {
Some(Self(days))
} else {
None
}
}
#[must_use]
pub const fn pg_days(self) -> i32 {
self.0
}
#[must_use]
pub const fn is_finite(self) -> bool {
self.0 != i32::MAX && self.0 != i32::MIN
}
#[must_use]
pub fn ymd(self) -> Option<(i32, u8, u8)> {
self.is_finite().then(|| {
let (year, month, day) = j2date(self.0 + POSTGRES_EPOCH_JDATE);
(year, narrow_u8(month.into()), narrow_u8(day.into()))
})
}
}
impl PgTime {
pub const MIDNIGHT: Self = Self(0);
#[must_use]
pub const fn from_micros(micros: i64) -> Option<Self> {
if 0 <= micros && micros <= USECS_PER_DAY {
Some(Self(micros))
} else {
None
}
}
#[must_use]
pub fn from_hms_micro(hour: u8, minute: u8, second: u8, microsecond: u32) -> Option<Self> {
if hour > 24 || minute > 59 || second > 59 || microsecond > 999_999 {
return None;
}
Self::from_micros(
i64::from(hour) * USECS_PER_HOUR
+ i64::from(minute) * USECS_PER_MINUTE
+ i64::from(second) * USECS_PER_SEC
+ i64::from(microsecond),
)
}
#[must_use]
pub const fn micros(self) -> i64 {
self.0
}
#[must_use]
pub fn hms_micro(self) -> (u8, u8, u8, u32) {
let (hour, minute, second, micro) = split_clock(self.0);
(
narrow_u8(hour),
narrow_u8(minute),
narrow_u8(second),
u32::try_from(micro).expect("a microsecond of a second fits u32"),
)
}
}
impl PgTimeTz {
#[must_use]
pub const fn new(time: PgTime, offset: i32) -> Option<Self> {
if -TZDISP_LIMIT <= offset && offset <= TZDISP_LIMIT {
Some(Self {
time: time.0,
offset,
})
} else {
None
}
}
#[must_use]
pub const fn time(self) -> PgTime {
PgTime(self.time)
}
#[must_use]
pub const fn offset(self) -> i32 {
self.offset
}
fn sort_key(self) -> (i64, i32) {
(
self.time - i64::from(self.offset) * USECS_PER_SEC,
-self.offset,
)
}
}
impl PartialOrd for PgTimeTz {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PgTimeTz {
fn cmp(&self, other: &Self) -> Ordering {
self.sort_key().cmp(&other.sort_key())
}
}
impl PgTimestamp {
pub const INFINITY: Self = Self(i64::MAX);
pub const NEG_INFINITY: Self = Self(i64::MIN);
#[must_use]
pub const fn from_pg_micros(micros: i64) -> Option<Self> {
if is_valid_timestamp(micros) || micros == i64::MAX || micros == i64::MIN {
Some(Self(micros))
} else {
None
}
}
#[must_use]
pub fn new(date: PgDate, time: PgTime) -> Option<Self> {
if !date.is_finite() {
return None;
}
i64::from(date.0)
.checked_mul(USECS_PER_DAY)
.and_then(|micros| micros.checked_add(time.0))
.and_then(Self::from_pg_micros)
.filter(|at| at.is_finite())
}
pub(crate) const fn from_stored(micros: i64) -> Self {
Self(micros)
}
#[must_use]
pub const fn pg_micros(self) -> i64 {
self.0
}
#[must_use]
pub const fn is_finite(self) -> bool {
self.0 != i64::MAX && self.0 != i64::MIN
}
#[must_use]
pub fn date(self) -> PgDate {
match self.0 {
i64::MAX => PgDate::INFINITY,
i64::MIN => PgDate::NEG_INFINITY,
micros => PgDate(narrow_days(micros.div_euclid(USECS_PER_DAY))),
}
}
#[must_use]
pub const fn time(self) -> Option<PgTime> {
if self.is_finite() {
Some(PgTime(self.0.rem_euclid(USECS_PER_DAY)))
} else {
None
}
}
pub fn to_timestamptz(self, zone: &PgTimeZone) -> Result<PgTimestampTz, DateTimeError> {
if !self.is_finite() {
return Ok(PgTimestampTz(self.0));
}
let offset = local_offset(zone, self.0)?;
let instant = self.0 - i64::from(offset) * USECS_PER_SEC;
if is_valid_timestamp(instant) {
Ok(PgTimestampTz(instant))
} else {
Err(DateTimeError::TimestampOutOfRange)
}
}
}
impl PgTimestampTz {
pub const INFINITY: Self = Self(i64::MAX);
pub const NEG_INFINITY: Self = Self(i64::MIN);
#[must_use]
pub const fn from_pg_micros(micros: i64) -> Option<Self> {
match PgTimestamp::from_pg_micros(micros) {
Some(at) => Some(Self(at.0)),
None => None,
}
}
pub(crate) const fn from_stored(micros: i64) -> Self {
Self(micros)
}
#[must_use]
pub const fn pg_micros(self) -> i64 {
self.0
}
#[must_use]
pub const fn is_finite(self) -> bool {
self.0 != i64::MAX && self.0 != i64::MIN
}
pub fn to_timestamp(self, zone: &PgTimeZone) -> Result<PgTimestamp, DateTimeError> {
if !self.is_finite() {
return Ok(PgTimestamp(self.0));
}
let local = self.0 + i64::from(utc_offset(zone, self.0)?) * USECS_PER_SEC;
if is_valid_timestamp(local) {
Ok(PgTimestamp(local))
} else {
Err(DateTimeError::TimestampOutOfRange)
}
}
pub fn to_date(self, zone: &PgTimeZone) -> Result<PgDate, DateTimeError> {
match self.0 {
i64::MAX => Ok(PgDate::INFINITY),
i64::MIN => Ok(PgDate::NEG_INFINITY),
utc => {
let local = utc + i64::from(utc_offset(zone, utc)?) * USECS_PER_SEC;
Ok(PgDate(narrow_days(local.div_euclid(USECS_PER_DAY))))
}
}
}
}
pub(crate) fn utc_offset(zone: &PgTimeZone, utc: i64) -> Result<i32, DateTimeError> {
let unix = utc.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
zone.utc_offset(unix).ok_or(DateTimeError::OutsideJiffRange)
}
pub(crate) fn local_offset(zone: &PgTimeZone, local: i64) -> Result<i32, DateTimeError> {
const JIFF_OFFSET_LIMIT: i64 = 26 * USECS_PER_HOUR;
let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS;
zone.local_offset(unix).ok_or(
if (MIN_TIMESTAMP - JIFF_OFFSET_LIMIT..END_TIMESTAMP + JIFF_OFFSET_LIMIT).contains(&local) {
DateTimeError::OutsideJiffRange
} else {
DateTimeError::TimestampOutOfRange
},
)
}
pub(crate) fn abbreviation_offset(
zone: &PgTimeZone,
abbreviation: &str,
local: i64,
) -> Result<i32, DateTimeError> {
let zone_offset = local_offset(zone, local)?;
let unix = local.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS - i64::from(zone_offset);
Ok(zone
.interpret_abbreviation(abbreviation, unix)?
.map_or(zone_offset, |meaning| meaning.offset))
}
pub(crate) const fn is_valid_timestamp(micros: i64) -> bool {
MIN_TIMESTAMP <= micros && micros < END_TIMESTAMP
}
pub(crate) const fn is_valid_julian(year: i32, month: i32) -> bool {
(year > -4713 || (year == -4713 && month >= 11))
&& (year < 5_874_898 || (year == 5_874_898 && month < 6))
}
pub(crate) fn tm2timestamp(
year: i32,
month: i32,
day: i32,
clock: i64,
offset: i32,
) -> Option<i64> {
if !is_valid_julian(year, month) {
return None;
}
let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
days.checked_mul(USECS_PER_DAY)?
.checked_add(clock)?
.checked_sub(i64::from(offset) * USECS_PER_SEC)
.filter(|µs| is_valid_timestamp(micros))
}
pub(crate) fn timestamp2tm(micros: i64) -> (i32, i32, i32, i64) {
let (year, month, day) =
j2date(narrow_days(micros.div_euclid(USECS_PER_DAY)) + POSTGRES_EPOCH_JDATE);
(year, month, day, micros.rem_euclid(USECS_PER_DAY))
}
pub(crate) const fn date2j(year: i32, month: i32, day: i32) -> i32 {
let (year, month) = if month > 2 {
(year + 4800, month + 1)
} else {
(year + 4799, month + 13)
};
let century = year / 100;
let mut julian = year * 365 - 32_167;
julian += year / 4 - century + century / 4;
julian + 7_834 * month / 256 + day
}
pub(crate) const fn j2date(julian_day: i32) -> (i32, i32, i32) {
let mut julian = julian_day.cast_unsigned().wrapping_add(32_044);
let mut quad = julian / 146_097;
let extra = (julian - quad * 146_097) * 4 + 3;
julian += 60 + quad * 3 + extra / 146_097;
quad = julian / 1_461;
julian -= quad * 1_461;
let mut year = julian * 4 / 1_461;
julian = if year == 0 {
(julian + 306) % 366
} else {
(julian + 305) % 365
} + 123;
year += quad * 4;
let quad = julian * 2_141 / 65_536;
let day = julian - 7_834 * quad / 256;
let month = (quad + 10) % 12 + 1;
(
year.cast_signed() - 4_800,
month.cast_signed(),
day.cast_signed(),
)
}
pub(crate) const fn days_in_month(year: i32, month: i32) -> i32 {
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
match month {
2 if leap => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn narrow_days(days: i64) -> i32 {
i32::try_from(days).expect("a timestamp lies under 2^31 days from 2000-01-01")
}
fn narrow_u8(field: i64) -> u8 {
u8::try_from(field).expect("a calendar or clock field fits u8")
}
const fn split_clock(micros: i64) -> (i64, i64, i64, i64) {
(
micros / USECS_PER_HOUR,
micros % USECS_PER_HOUR / USECS_PER_MINUTE,
micros % USECS_PER_MINUTE / USECS_PER_SEC,
micros % USECS_PER_SEC,
)
}
fn write_ymd(f: &mut fmt::Formatter<'_>, year: i32, month: i32, day: i32) -> fmt::Result {
let shown = if year > 0 { year } else { 1 - year };
write!(f, "{shown:04}-{month:02}-{day:02}")
}
fn write_clock(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
let (hour, minute, second, mut fraction) = split_clock(micros);
write!(f, "{hour:02}:{minute:02}:{second:02}")?;
if fraction > 0 {
let mut width = 6;
while fraction % 10 == 0 {
fraction /= 10;
width -= 1;
}
write!(f, ".{fraction:0width$}")?;
}
Ok(())
}
fn write_offset(f: &mut fmt::Formatter<'_>, offset: i32) -> fmt::Result {
let sign = if offset >= 0 { '+' } else { '-' };
let magnitude = offset.unsigned_abs();
let (hour, minute, second) = (magnitude / 3_600, magnitude / 60 % 60, magnitude % 60);
write!(f, "{sign}{hour:02}")?;
if second != 0 {
write!(f, ":{minute:02}:{second:02}")
} else if minute != 0 {
write!(f, ":{minute:02}")
} else {
Ok(())
}
}
fn write_timestamp(f: &mut fmt::Formatter<'_>, micros: i64, zone: bool) -> fmt::Result {
match micros {
i64::MAX => return f.write_str("infinity"),
i64::MIN => return f.write_str("-infinity"),
_ => {}
}
let (year, month, day, clock) = timestamp2tm(micros);
write_ymd(f, year, month, day)?;
f.write_str(" ")?;
write_clock(f, clock)?;
if zone {
f.write_str("+00")?;
}
if year <= 0 {
f.write_str(" BC")?;
}
Ok(())
}
impl fmt::Display for PgDate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
i32::MAX => f.write_str("infinity"),
i32::MIN => f.write_str("-infinity"),
days => {
let (year, month, day) = j2date(days + POSTGRES_EPOCH_JDATE);
write_ymd(f, year, month, day)?;
if year <= 0 {
f.write_str(" BC")?;
}
Ok(())
}
}
}
}
impl fmt::Display for PgTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_clock(f, self.0)
}
}
impl fmt::Display for PgTimeTz {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_clock(f, self.time)?;
write_offset(f, self.offset)
}
}
impl fmt::Display for PgTimestamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_timestamp(f, self.0, false)
}
}
impl fmt::Display for PgTimestampTz {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_timestamp(f, self.0, true)
}
}
impl TryFrom<i32> for PgDate {
type Error = DateTimeError;
fn try_from(days: i32) -> Result<Self, Self::Error> {
Self::from_pg_days(days).ok_or(DateTimeError::DateOutOfRange)
}
}
impl From<PgDate> for i32 {
fn from(date: PgDate) -> Self {
date.0
}
}
impl TryFrom<i64> for PgTime {
type Error = DateTimeError;
fn try_from(micros: i64) -> Result<Self, Self::Error> {
Self::from_micros(micros).ok_or(DateTimeError::FieldValueOutOfRange)
}
}
impl From<PgTime> for i64 {
fn from(time: PgTime) -> Self {
time.0
}
}
impl TryFrom<(i64, i32)> for PgTimeTz {
type Error = DateTimeError;
fn try_from((micros, offset): (i64, i32)) -> Result<Self, Self::Error> {
let time = PgTime::try_from(micros)?;
Self::new(time, offset).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange)
}
}
impl From<PgTimeTz> for (i64, i32) {
fn from(time: PgTimeTz) -> Self {
(time.time, time.offset)
}
}
impl TryFrom<i64> for PgTimestamp {
type Error = DateTimeError;
fn try_from(micros: i64) -> Result<Self, Self::Error> {
Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
}
}
impl From<PgTimestamp> for i64 {
fn from(at: PgTimestamp) -> Self {
at.0
}
}
impl TryFrom<i64> for PgTimestampTz {
type Error = DateTimeError;
fn try_from(micros: i64) -> Result<Self, Self::Error> {
Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
}
}
impl From<PgTimestampTz> for i64 {
fn from(at: PgTimestampTz) -> Self {
at.0
}
}