mod arithmetic;
mod decode;
mod float;
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, interval_in,
};
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
}
}
#[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,
}
}
const fn ends_in_second(self) -> bool {
matches!(
self,
Self::Second | Self::DayToSecond | Self::HourToSecond | Self::MinuteToSecond
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct IntervalTypmod {
fields: Option<IntervalFields>,
precision: Option<u8>,
}
const MAX_INTERVAL_PRECISION: u8 = 6;
impl IntervalTypmod {
#[must_use]
pub const fn new(fields: Option<IntervalFields>, precision: Option<u8>) -> Option<Self> {
let precision = match (fields, precision) {
(Some(fields), Some(_)) if !fields.ends_in_second() => return None,
(_, Some(precision)) if precision > MAX_INTERVAL_PRECISION => {
Some(MAX_INTERVAL_PRECISION)
}
(_, precision) => precision,
};
Some(Self { fields, precision })
}
const fn range(self) -> u16 {
match self.fields {
Some(fields) => fields.range(),
None => INTERVAL_FULL_RANGE,
}
}
}
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)
}