mod arithmetic;
mod decode;
use core::{
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
};
pub use arithmetic::{IntervalSum, ShiftError};
use decode::{
INTERVAL_FULL_RANGE, RANGE_DAY, RANGE_HOUR, RANGE_MINUTE, RANGE_MONTH, RANGE_SECOND,
RANGE_YEAR, adjust_interval_for_typmod, interval_in,
};
pub(crate) use decode::{decode_extract_unit, decode_units, strtod};
const USECS_PER_DAY: i128 = 86_400_000_000;
const USECS_PER_SEC: u64 = 1_000_000;
const DAYS_PER_MONTH: i64 = 30;
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PgInterval {
pub months: i32,
pub days: i32,
pub microseconds: i64,
}
impl PgInterval {
pub const INFINITY: Self = Self {
months: i32::MAX,
days: i32::MAX,
microseconds: i64::MAX,
};
pub const NEG_INFINITY: Self = Self {
months: i32::MIN,
days: i32::MIN,
microseconds: i64::MIN,
};
#[must_use]
pub const fn is_finite(&self) -> bool {
!self.fields_equal(&Self::INFINITY) && !self.fields_equal(&Self::NEG_INFINITY)
}
const fn fields_equal(&self, other: &Self) -> bool {
self.months == other.months
&& self.days == other.days
&& self.microseconds == other.microseconds
}
#[must_use]
pub fn span_microseconds(&self) -> i128 {
let days = i64::from(self.months) * DAYS_PER_MONTH + i64::from(self.days);
i128::from(self.microseconds) + i128::from(days) * USECS_PER_DAY
}
pub fn adjust_for_typmod(mut self, typmod: IntervalTypmod) -> Result<Self, IntervalError> {
adjust_interval_for_typmod(
&mut self,
typmod.range(),
typmod.precision.map(super::TimePrecision::get),
)?;
Ok(self)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum IntervalError {
#[error("invalid input syntax for type interval")]
InvalidSyntax,
#[error("interval field value out of range")]
FieldValueOutOfRange,
#[error("interval out of range")]
OutOfRange,
#[error("division by zero")]
DivisionByZero,
}
impl PartialEq for PgInterval {
fn eq(&self, other: &Self) -> bool {
self.span_microseconds() == other.span_microseconds()
}
}
impl Eq for PgInterval {}
impl PartialOrd for PgInterval {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PgInterval {
fn cmp(&self, other: &Self) -> Ordering {
self.span_microseconds().cmp(&other.span_microseconds())
}
}
impl Hash for PgInterval {
fn hash<H: Hasher>(&self, state: &mut H) {
self.span_microseconds().hash(state);
}
}
impl fmt::Display for PgInterval {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.fields_equal(&Self::INFINITY) {
return f.write_str("infinity");
}
if self.fields_equal(&Self::NEG_INFINITY) {
return f.write_str("-infinity");
}
let mut is_zero = true;
let mut is_before = false;
for (count, unit) in [
(self.months / 12, "year"),
(self.months % 12, "mon"),
(self.days, "day"),
] {
if count == 0 {
continue;
}
let separator = if is_zero { "" } else { " " };
let plus = if is_before && count > 0 { "+" } else { "" };
let plural = if count == 1 { "" } else { "s" };
write!(f, "{separator}{plus}{count} {unit}{plural}")?;
is_before = count < 0;
is_zero = false;
}
if is_zero || self.microseconds != 0 {
let separator = if is_zero { "" } else { " " };
let sign = if self.microseconds < 0 {
"-"
} else if is_before {
"+"
} else {
""
};
let magnitude = self.microseconds.unsigned_abs();
let seconds = magnitude / USECS_PER_SEC;
write!(
f,
"{separator}{sign}{:02}:{:02}:{:02}",
seconds / 3_600,
seconds % 3_600 / 60,
seconds % 60
)?;
let mut fraction = magnitude % USECS_PER_SEC;
if fraction != 0 {
let mut digits = 6;
while fraction.is_multiple_of(10) {
fraction /= 10;
digits -= 1;
}
write!(f, ".{fraction:0digits$}")?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntervalFields {
Year,
Month,
Day,
Hour,
Minute,
Second,
YearToMonth,
DayToHour,
DayToMinute,
DayToSecond,
HourToMinute,
HourToSecond,
MinuteToSecond,
}
impl IntervalFields {
const fn range(self) -> u16 {
match self {
Self::Year => RANGE_YEAR,
Self::Month => RANGE_MONTH,
Self::Day => RANGE_DAY,
Self::Hour => RANGE_HOUR,
Self::Minute => RANGE_MINUTE,
Self::Second => RANGE_SECOND,
Self::YearToMonth => RANGE_YEAR | RANGE_MONTH,
Self::DayToHour => RANGE_DAY | RANGE_HOUR,
Self::DayToMinute => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE,
Self::DayToSecond => RANGE_DAY | RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
Self::HourToMinute => RANGE_HOUR | RANGE_MINUTE,
Self::HourToSecond => RANGE_HOUR | RANGE_MINUTE | RANGE_SECOND,
Self::MinuteToSecond => RANGE_MINUTE | RANGE_SECOND,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct IntervalTypmod {
fields: Option<IntervalFields>,
precision: Option<super::TimePrecision>,
}
impl IntervalTypmod {
pub const UNMODIFIED: Self = Self {
fields: None,
precision: None,
};
pub(crate) fn catalog_typmod(self) -> i32 {
if self.fields.is_none() && self.precision.is_none() {
-1
} else {
(i32::from(self.range()) << 16)
| self
.precision
.map_or(0xffff, |precision| i32::from(precision.get()))
}
}
pub(crate) fn from_catalog_typmod(typmod: i32) -> Option<Self> {
let range = u16::try_from(typmod >> 16).ok()?;
let fields = match range {
INTERVAL_FULL_RANGE => None,
range => Some(
[
IntervalFields::Year,
IntervalFields::Month,
IntervalFields::Day,
IntervalFields::Hour,
IntervalFields::Minute,
IntervalFields::Second,
IntervalFields::YearToMonth,
IntervalFields::DayToHour,
IntervalFields::DayToMinute,
IntervalFields::DayToSecond,
IntervalFields::HourToMinute,
IntervalFields::HourToSecond,
IntervalFields::MinuteToSecond,
]
.into_iter()
.find(|fields| fields.range() == range)?,
),
};
let precision = match typmod & 0xffff {
0xffff => None,
precision => Some(u8::try_from(precision).ok()?),
};
let modifier = Self::new(fields, precision)?;
(modifier.catalog_typmod() == typmod).then_some(modifier)
}
#[must_use]
pub const fn new(fields: Option<IntervalFields>, precision: Option<u8>) -> Option<Self> {
let precision = match precision {
Some(precision) => Some(super::TimePrecision::new(precision)),
None => None,
};
Some(Self { fields, precision })
}
const fn range(self) -> u16 {
match self.fields {
Some(fields) => fields.range(),
None => INTERVAL_FULL_RANGE,
}
}
}
impl fmt::Display for IntervalTypmod {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(fields) = self.fields {
formatter.write_str(match fields {
IntervalFields::Year => " year",
IntervalFields::Month => " month",
IntervalFields::Day => " day",
IntervalFields::Hour => " hour",
IntervalFields::Minute => " minute",
IntervalFields::Second => " second",
IntervalFields::YearToMonth => " year to month",
IntervalFields::DayToHour => " day to hour",
IntervalFields::DayToMinute => " day to minute",
IntervalFields::DayToSecond => " day to second",
IntervalFields::HourToMinute => " hour to minute",
IntervalFields::HourToSecond => " hour to second",
IntervalFields::MinuteToSecond => " minute to second",
})?;
}
if let Some(precision) = self.precision {
write!(formatter, "({precision})")?;
}
Ok(())
}
}
pub fn parse_interval(text: &str) -> Result<PgInterval, IntervalError> {
interval_in(text, INTERVAL_FULL_RANGE, None)
}
pub fn parse_interval_typmod(
text: &str,
typmod: IntervalTypmod,
) -> Result<PgInterval, IntervalError> {
interval_in(
text,
typmod.range(),
typmod.precision.map(super::TimePrecision::get),
)
}