use core::cmp::Ordering;
use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
use super::{
IntervalError, PgInterval,
float::{
fits_in_i32, fits_in_i64, int_to_f64, round_ties_even, truncate_to_i32, truncate_to_i64,
ts_round,
},
};
const DAYS_PER_MONTH: f64 = 30.0;
const SECS_PER_DAY: f64 = 86_400.0;
const MONTHS_PER_YEAR: i32 = 12;
const USECS_PER_DAY: i64 = 86_400_000_000;
const USECS_PER_SEC: i64 = 1_000_000;
const POSTGRES_EPOCH_JDATE: i64 = 2_451_545;
const JULIAN_BEFORE_CE: i64 = 1_721_425;
const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum ShiftError {
#[error("timestamp out of range")]
TimestampOutOfRange,
#[error("interval out of range")]
IntervalOutOfRange,
#[error("cannot add infinite interval to time")]
InfiniteIntervalAddedToTime,
#[error("cannot subtract infinite interval from time")]
InfiniteIntervalSubtractedFromTime,
#[error("timestamp beyond chrono")]
Unrepresentable,
}
impl PgInterval {
const fn infinity(&self) -> Option<Ordering> {
if self.fields_equal(&Self::INFINITY) {
Some(Ordering::Greater)
} else if self.fields_equal(&Self::NEG_INFINITY) {
Some(Ordering::Less)
} else {
None
}
}
const fn finite(self) -> Result<Self, IntervalError> {
if self.is_finite() {
Ok(self)
} else {
Err(IntervalError::OutOfRange)
}
}
const fn infinite(sign: Ordering) -> Self {
match sign {
Ordering::Less => Self::NEG_INFINITY,
_ => Self::INFINITY,
}
}
pub fn checked_add(self, other: Self) -> Result<Self, IntervalError> {
match (self.infinity(), other.infinity()) {
(Some(left), Some(right)) if left != right => Err(IntervalError::OutOfRange),
(Some(_), _) => Ok(self),
(None, Some(_)) => Ok(other),
(None, None) => Self::finite_fields(FieldResults {
months: self.months.checked_add(other.months),
days: self.days.checked_add(other.days),
microseconds: self.microseconds.checked_add(other.microseconds),
}),
}
}
pub fn checked_sub(self, other: Self) -> Result<Self, IntervalError> {
match (self.infinity(), other.infinity()) {
(Some(left), Some(right)) if left == right => Err(IntervalError::OutOfRange),
(Some(_), _) => Ok(self),
(None, Some(right)) => Ok(Self::infinite(right.reverse())),
(None, None) => Self::finite_fields(FieldResults {
months: self.months.checked_sub(other.months),
days: self.days.checked_sub(other.days),
microseconds: self.microseconds.checked_sub(other.microseconds),
}),
}
}
pub fn checked_neg(self) -> Result<Self, IntervalError> {
match self.infinity() {
Some(sign) => Ok(Self::infinite(sign.reverse())),
None => Self::finite_fields(FieldResults {
months: self.months.checked_neg(),
days: self.days.checked_neg(),
microseconds: self.microseconds.checked_neg(),
}),
}
}
pub fn checked_mul(self, factor: f64) -> Result<Self, IntervalError> {
if factor.is_nan() {
return Err(IntervalError::OutOfRange);
}
if let Some(sign) = self.infinity() {
return match factor.partial_cmp(&0.0) {
Some(Ordering::Less) => Ok(Self::infinite(sign.reverse())),
Some(Ordering::Greater) => Ok(self),
_ => Err(IntervalError::OutOfRange),
};
}
if factor.is_infinite() {
return match self.span_microseconds().cmp(&0) {
Ordering::Equal => Err(IntervalError::OutOfRange),
sign if factor < 0.0 => Ok(Self::infinite(sign.reverse())),
sign => Ok(Self::infinite(sign)),
};
}
self.cascade(|field| field * factor)
}
pub fn checked_div(self, factor: f64) -> Result<Self, IntervalError> {
if factor == 0.0 {
return Err(IntervalError::DivisionByZero);
}
if factor.is_nan() {
return Err(IntervalError::OutOfRange);
}
if let Some(sign) = self.infinity() {
return if factor.is_infinite() {
Err(IntervalError::OutOfRange)
} else if factor < 0.0 {
Ok(Self::infinite(sign.reverse()))
} else {
Ok(self)
};
}
self.cascade(|field| field / factor)
}
fn finite_fields(fields: FieldResults) -> Result<Self, IntervalError> {
Self {
months: fields.months.ok_or(IntervalError::OutOfRange)?,
days: fields.days.ok_or(IntervalError::OutOfRange)?,
microseconds: fields.microseconds.ok_or(IntervalError::OutOfRange)?,
}
.finite()
}
fn cascade(self, scale: impl Fn(f64) -> f64) -> Result<Self, IntervalError> {
let month_product = scale(f64::from(self.months));
if !fits_in_i32(month_product) {
return Err(IntervalError::OutOfRange);
}
let months = truncate_to_i32(month_product);
let day_product = scale(f64::from(self.days));
if !fits_in_i32(day_product) {
return Err(IntervalError::OutOfRange);
}
let mut days = truncate_to_i32(day_product);
let month_remainder_days = ts_round((month_product - f64::from(months)) * DAYS_PER_MONTH);
let whole_remainder_days = truncate_to_i32(month_remainder_days);
let mut sec_remainder = ts_round(
(day_product - f64::from(days) + month_remainder_days
- f64::from(whole_remainder_days))
* SECS_PER_DAY,
);
if sec_remainder.abs() >= SECS_PER_DAY {
let carried = truncate_to_i32(sec_remainder / SECS_PER_DAY);
days = days.checked_add(carried).ok_or(IntervalError::OutOfRange)?;
sec_remainder -= f64::from(carried) * SECS_PER_DAY;
}
days = days
.checked_add(whole_remainder_days)
.ok_or(IntervalError::OutOfRange)?;
let microseconds = round_ties_even(
scale(int_to_f64(self.microseconds)) + sec_remainder * int_to_f64(USECS_PER_SEC),
);
if !fits_in_i64(microseconds) {
return Err(IntervalError::OutOfRange);
}
Self {
months,
days,
microseconds: truncate_to_i64(microseconds),
}
.finite()
}
pub fn add_to_timestamp(self, at: NaiveDateTime) -> Result<NaiveDateTime, ShiftError> {
let timestamp = pg_timestamp(at)?;
if !self.is_finite() {
return Err(ShiftError::Unrepresentable);
}
let mut timestamp = timestamp;
if self.months != 0 {
let (mut year, month, mut day, clock) = timestamp2tm(timestamp);
let mut month = month
.checked_add(self.months)
.ok_or(ShiftError::TimestampOutOfRange)?;
if month > MONTHS_PER_YEAR {
year += (month - 1) / MONTHS_PER_YEAR;
month = (month - 1) % MONTHS_PER_YEAR + 1;
} else if month < 1 {
year += month / MONTHS_PER_YEAR - 1;
month = month % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
}
day = day.min(days_in_month(year, month));
timestamp = tm2timestamp(year, month, day, clock)?;
}
if self.days != 0 {
let (year, month, day, clock) = timestamp2tm(timestamp);
let julian = date2j(year, month, day)
.checked_add(self.days)
.filter(|julian| *julian >= 0)
.ok_or(ShiftError::TimestampOutOfRange)?;
let (year, month, day) = j2date(julian);
timestamp = tm2timestamp(year, month, day, clock)?;
}
let timestamp = timestamp
.checked_add(self.microseconds)
.filter(|timestamp| (MIN_TIMESTAMP..END_TIMESTAMP).contains(timestamp))
.ok_or(ShiftError::TimestampOutOfRange)?;
chrono_timestamp(timestamp)
}
pub fn subtract_from_timestamp(self, at: NaiveDateTime) -> Result<NaiveDateTime, ShiftError> {
self.checked_neg()
.map_err(|_| ShiftError::IntervalOutOfRange)?
.add_to_timestamp(at)
}
pub fn timestamp_difference(
later: NaiveDateTime,
earlier: NaiveDateTime,
) -> Result<Self, ShiftError> {
let time = pg_timestamp(later)? - pg_timestamp(earlier)?;
let days =
i32::try_from(time / USECS_PER_DAY).expect("timestamps lie under 2^27 days apart");
Ok(Self {
months: 0,
days,
microseconds: time % USECS_PER_DAY,
})
}
pub fn add_to_time(self, at: NaiveTime) -> Result<NaiveTime, ShiftError> {
if !self.is_finite() {
return Err(ShiftError::InfiniteIntervalAddedToTime);
}
Ok(wrap_time(pg_time(at).wrapping_add(self.microseconds)))
}
pub fn subtract_from_time(self, at: NaiveTime) -> Result<NaiveTime, ShiftError> {
if !self.is_finite() {
return Err(ShiftError::InfiniteIntervalSubtractedFromTime);
}
Ok(wrap_time(pg_time(at).wrapping_sub(self.microseconds)))
}
}
struct FieldResults {
months: Option<i32>,
days: Option<i32>,
microseconds: Option<i64>,
}
fn pg_time(at: NaiveTime) -> i64 {
i64::from(at.num_seconds_from_midnight()) * USECS_PER_SEC + i64::from(at.nanosecond() / 1_000)
}
fn wrap_time(moved: i64) -> NaiveTime {
let micros = moved.rem_euclid(USECS_PER_DAY);
let seconds = u32::try_from(micros / USECS_PER_SEC).expect("a second of the day fits u32");
let nanos = u32::try_from(micros % USECS_PER_SEC * 1_000).expect("a nanosecond fits u32");
NaiveTime::from_num_seconds_from_midnight_opt(seconds, nanos)
.expect("a clock within the day is a time")
}
fn pg_timestamp(at: NaiveDateTime) -> Result<i64, ShiftError> {
let days = i64::from(at.date().num_days_from_ce()) + JULIAN_BEFORE_CE - POSTGRES_EPOCH_JDATE;
let timestamp = days * USECS_PER_DAY + pg_time(at.time());
if (MIN_TIMESTAMP..END_TIMESTAMP).contains(×tamp) {
Ok(timestamp)
} else {
Err(ShiftError::TimestampOutOfRange)
}
}
fn chrono_timestamp(timestamp: i64) -> Result<NaiveDateTime, ShiftError> {
let days = timestamp.div_euclid(USECS_PER_DAY) + POSTGRES_EPOCH_JDATE - JULIAN_BEFORE_CE;
let date = i32::try_from(days)
.ok()
.and_then(NaiveDate::from_num_days_from_ce_opt)
.ok_or(ShiftError::Unrepresentable)?;
Ok(date.and_time(wrap_time(timestamp)))
}
fn timestamp2tm(timestamp: i64) -> (i32, i32, i32, i64) {
let julian = timestamp.div_euclid(USECS_PER_DAY) + POSTGRES_EPOCH_JDATE;
let julian = i32::try_from(julian).expect("a valid timestamp's Julian day fits int");
let (year, month, day) = j2date(julian);
(year, month, day, timestamp.rem_euclid(USECS_PER_DAY))
}
fn tm2timestamp(year: i32, month: i32, day: i32, clock: i64) -> Result<i64, ShiftError> {
let valid_julian = (year > -4713 || (year == -4713 && month >= 11))
&& (year < 5_874_898 || (year == 5_874_898 && month < 6));
if !valid_julian {
return Err(ShiftError::TimestampOutOfRange);
}
let days = i64::from(date2j(year, month, day)) - POSTGRES_EPOCH_JDATE;
days.checked_mul(USECS_PER_DAY)
.and_then(|micros| micros.checked_add(clock))
.filter(|timestamp| (MIN_TIMESTAMP..END_TIMESTAMP).contains(timestamp))
.ok_or(ShiftError::TimestampOutOfRange)
}
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
}
const fn j2date(julian_day: i32) -> (i32, i32, i32) {
let mut julian = julian_day.cast_unsigned() + 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(),
)
}
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,
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IntervalSum {
finite: i64,
positive_infinities: i64,
negative_infinities: i64,
months: i128,
days: i128,
microseconds: i128,
}
impl IntervalSum {
#[must_use]
pub fn of(value: PgInterval, weight: i64) -> Self {
match value.infinity() {
Some(Ordering::Greater) => Self {
positive_infinities: weight,
..Self::default()
},
Some(_) => Self {
negative_infinities: weight,
..Self::default()
},
None => {
let wide = i128::from(weight);
Self {
finite: weight,
positive_infinities: 0,
negative_infinities: 0,
months: i128::from(value.months) * wide,
days: i128::from(value.days) * wide,
microseconds: i128::from(value.microseconds) * wide,
}
}
}
}
#[must_use]
pub fn seeded(
finite_sum: Option<PgInterval>,
finite: i64,
positive_infinities: i64,
negative_infinities: i64,
) -> Self {
let (months, days, microseconds) =
finite_sum.map_or((0, 0, 0), |sum| (sum.months, sum.days, sum.microseconds));
Self {
finite,
positive_infinities,
negative_infinities,
months: i128::from(months),
days: i128::from(days),
microseconds: i128::from(microseconds),
}
}
pub const fn merge(&mut self, other: Self) {
self.finite += other.finite;
self.positive_infinities += other.positive_infinities;
self.negative_infinities += other.negative_infinities;
self.months += other.months;
self.days += other.days;
self.microseconds += other.microseconds;
}
#[must_use]
pub fn is_zero(&self) -> bool {
*self == Self::default()
}
#[must_use]
pub const fn count(&self) -> i64 {
self.finite + self.positive_infinities + self.negative_infinities
}
pub fn sum(&self) -> Result<Option<PgInterval>, IntervalError> {
if self.count() <= 0 {
return Ok(None);
}
match (self.positive_infinities > 0, self.negative_infinities > 0) {
(true, true) => Err(IntervalError::OutOfRange),
(true, false) => Ok(Some(PgInterval::INFINITY)),
(false, true) => Ok(Some(PgInterval::NEG_INFINITY)),
(false, false) => PgInterval::finite_fields(FieldResults {
months: i32::try_from(self.months).ok(),
days: i32::try_from(self.days).ok(),
microseconds: i64::try_from(self.microseconds).ok(),
})
.map(Some),
}
}
pub fn avg(&self) -> Result<Option<PgInterval>, IntervalError> {
match self.sum()? {
Some(sum) if sum.is_finite() => {
let count = self.finite as f64;
sum.checked_div(count).map(Some)
}
other => Ok(other),
}
}
}