1use core::cmp::Ordering;
5
6use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
7
8use super::{
9 IntervalError, PgInterval,
10 float::{
11 fits_in_i32, fits_in_i64, int_to_f64, round_ties_even, truncate_to_i32, truncate_to_i64,
12 ts_round,
13 },
14};
15
16const DAYS_PER_MONTH: f64 = 30.0;
17const SECS_PER_DAY: f64 = 86_400.0;
18const MONTHS_PER_YEAR: i32 = 12;
19const USECS_PER_DAY: i64 = 86_400_000_000;
20const USECS_PER_SEC: i64 = 1_000_000;
21
22const POSTGRES_EPOCH_JDATE: i64 = 2_451_545;
24const JULIAN_BEFORE_CE: i64 = 1_721_425;
26const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
28const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
33pub enum ShiftError {
34 #[error("timestamp out of range")]
36 TimestampOutOfRange,
37 #[error("interval out of range")]
39 IntervalOutOfRange,
40 #[error("cannot add infinite interval to time")]
42 InfiniteIntervalAddedToTime,
43 #[error("cannot subtract infinite interval from time")]
45 InfiniteIntervalSubtractedFromTime,
46 #[error("timestamp beyond chrono")]
49 Unrepresentable,
50}
51
52impl PgInterval {
53 const fn infinity(&self) -> Option<Ordering> {
55 if self.fields_equal(&Self::INFINITY) {
56 Some(Ordering::Greater)
57 } else if self.fields_equal(&Self::NEG_INFINITY) {
58 Some(Ordering::Less)
59 } else {
60 None
61 }
62 }
63
64 const fn finite(self) -> Result<Self, IntervalError> {
66 if self.is_finite() {
67 Ok(self)
68 } else {
69 Err(IntervalError::OutOfRange)
70 }
71 }
72
73 const fn infinite(sign: Ordering) -> Self {
75 match sign {
76 Ordering::Less => Self::NEG_INFINITY,
77 _ => Self::INFINITY,
78 }
79 }
80
81 pub fn checked_add(self, other: Self) -> Result<Self, IntervalError> {
100 match (self.infinity(), other.infinity()) {
101 (Some(left), Some(right)) if left != right => Err(IntervalError::OutOfRange),
102 (Some(_), _) => Ok(self),
103 (None, Some(_)) => Ok(other),
104 (None, None) => Self::finite_fields(FieldResults {
105 months: self.months.checked_add(other.months),
106 days: self.days.checked_add(other.days),
107 microseconds: self.microseconds.checked_add(other.microseconds),
108 }),
109 }
110 }
111
112 pub fn checked_sub(self, other: Self) -> Result<Self, IntervalError> {
119 match (self.infinity(), other.infinity()) {
120 (Some(left), Some(right)) if left == right => Err(IntervalError::OutOfRange),
121 (Some(_), _) => Ok(self),
122 (None, Some(right)) => Ok(Self::infinite(right.reverse())),
123 (None, None) => Self::finite_fields(FieldResults {
124 months: self.months.checked_sub(other.months),
125 days: self.days.checked_sub(other.days),
126 microseconds: self.microseconds.checked_sub(other.microseconds),
127 }),
128 }
129 }
130
131 pub fn checked_neg(self) -> Result<Self, IntervalError> {
147 match self.infinity() {
148 Some(sign) => Ok(Self::infinite(sign.reverse())),
149 None => Self::finite_fields(FieldResults {
150 months: self.months.checked_neg(),
151 days: self.days.checked_neg(),
152 microseconds: self.microseconds.checked_neg(),
153 }),
154 }
155 }
156
157 pub fn checked_mul(self, factor: f64) -> Result<Self, IntervalError> {
177 if factor.is_nan() {
178 return Err(IntervalError::OutOfRange);
179 }
180 if let Some(sign) = self.infinity() {
181 return match factor.partial_cmp(&0.0) {
182 Some(Ordering::Less) => Ok(Self::infinite(sign.reverse())),
183 Some(Ordering::Greater) => Ok(self),
184 _ => Err(IntervalError::OutOfRange),
185 };
186 }
187 if factor.is_infinite() {
188 return match self.span_microseconds().cmp(&0) {
189 Ordering::Equal => Err(IntervalError::OutOfRange),
190 sign if factor < 0.0 => Ok(Self::infinite(sign.reverse())),
191 sign => Ok(Self::infinite(sign)),
192 };
193 }
194 self.cascade(|field| field * factor)
195 }
196
197 pub fn checked_div(self, factor: f64) -> Result<Self, IntervalError> {
214 if factor == 0.0 {
215 return Err(IntervalError::DivisionByZero);
216 }
217 if factor.is_nan() {
218 return Err(IntervalError::OutOfRange);
219 }
220 if let Some(sign) = self.infinity() {
221 return if factor.is_infinite() {
222 Err(IntervalError::OutOfRange)
223 } else if factor < 0.0 {
224 Ok(Self::infinite(sign.reverse()))
225 } else {
226 Ok(self)
227 };
228 }
229 self.cascade(|field| field / factor)
230 }
231
232 fn finite_fields(fields: FieldResults) -> Result<Self, IntervalError> {
234 Self {
235 months: fields.months.ok_or(IntervalError::OutOfRange)?,
236 days: fields.days.ok_or(IntervalError::OutOfRange)?,
237 microseconds: fields.microseconds.ok_or(IntervalError::OutOfRange)?,
238 }
239 .finite()
240 }
241
242 fn cascade(self, scale: impl Fn(f64) -> f64) -> Result<Self, IntervalError> {
245 let month_product = scale(f64::from(self.months));
246 if !fits_in_i32(month_product) {
247 return Err(IntervalError::OutOfRange);
248 }
249 let months = truncate_to_i32(month_product);
250 let day_product = scale(f64::from(self.days));
251 if !fits_in_i32(day_product) {
252 return Err(IntervalError::OutOfRange);
253 }
254 let mut days = truncate_to_i32(day_product);
255 let month_remainder_days = ts_round((month_product - f64::from(months)) * DAYS_PER_MONTH);
257 let whole_remainder_days = truncate_to_i32(month_remainder_days);
258 let mut sec_remainder = ts_round(
259 (day_product - f64::from(days) + month_remainder_days
260 - f64::from(whole_remainder_days))
261 * SECS_PER_DAY,
262 );
263 if sec_remainder.abs() >= SECS_PER_DAY {
264 let carried = truncate_to_i32(sec_remainder / SECS_PER_DAY);
266 days = days.checked_add(carried).ok_or(IntervalError::OutOfRange)?;
267 sec_remainder -= f64::from(carried) * SECS_PER_DAY;
268 }
269 days = days
270 .checked_add(whole_remainder_days)
271 .ok_or(IntervalError::OutOfRange)?;
272 let microseconds = round_ties_even(
273 scale(int_to_f64(self.microseconds)) + sec_remainder * int_to_f64(USECS_PER_SEC),
274 );
275 if !fits_in_i64(microseconds) {
276 return Err(IntervalError::OutOfRange);
277 }
278 Self {
279 months,
280 days,
281 microseconds: truncate_to_i64(microseconds),
282 }
283 .finite()
284 }
285
286 pub fn add_to_timestamp(self, at: NaiveDateTime) -> Result<NaiveDateTime, ShiftError> {
305 let timestamp = pg_timestamp(at)?;
306 if !self.is_finite() {
307 return Err(ShiftError::Unrepresentable);
308 }
309 let mut timestamp = timestamp;
310 if self.months != 0 {
311 let (mut year, month, mut day, clock) = timestamp2tm(timestamp);
312 let mut month = month
313 .checked_add(self.months)
314 .ok_or(ShiftError::TimestampOutOfRange)?;
315 if month > MONTHS_PER_YEAR {
317 year += (month - 1) / MONTHS_PER_YEAR;
318 month = (month - 1) % MONTHS_PER_YEAR + 1;
319 } else if month < 1 {
320 year += month / MONTHS_PER_YEAR - 1;
321 month = month % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
322 }
323 day = day.min(days_in_month(year, month));
324 timestamp = tm2timestamp(year, month, day, clock)?;
325 }
326 if self.days != 0 {
327 let (year, month, day, clock) = timestamp2tm(timestamp);
328 let julian = date2j(year, month, day)
329 .checked_add(self.days)
330 .filter(|julian| *julian >= 0)
331 .ok_or(ShiftError::TimestampOutOfRange)?;
332 let (year, month, day) = j2date(julian);
333 timestamp = tm2timestamp(year, month, day, clock)?;
334 }
335 let timestamp = timestamp
336 .checked_add(self.microseconds)
337 .filter(|timestamp| (MIN_TIMESTAMP..END_TIMESTAMP).contains(timestamp))
338 .ok_or(ShiftError::TimestampOutOfRange)?;
339 chrono_timestamp(timestamp)
340 }
341
342 pub fn subtract_from_timestamp(self, at: NaiveDateTime) -> Result<NaiveDateTime, ShiftError> {
349 self.checked_neg()
350 .map_err(|_| ShiftError::IntervalOutOfRange)?
351 .add_to_timestamp(at)
352 }
353
354 pub fn timestamp_difference(
370 later: NaiveDateTime,
371 earlier: NaiveDateTime,
372 ) -> Result<Self, ShiftError> {
373 let time = pg_timestamp(later)? - pg_timestamp(earlier)?;
375 let days =
379 i32::try_from(time / USECS_PER_DAY).expect("timestamps lie under 2^27 days apart");
380 Ok(Self {
381 months: 0,
382 days,
383 microseconds: time % USECS_PER_DAY,
384 })
385 }
386
387 pub fn add_to_time(self, at: NaiveTime) -> Result<NaiveTime, ShiftError> {
403 if !self.is_finite() {
404 return Err(ShiftError::InfiniteIntervalAddedToTime);
405 }
406 Ok(wrap_time(pg_time(at).wrapping_add(self.microseconds)))
407 }
408
409 pub fn subtract_from_time(self, at: NaiveTime) -> Result<NaiveTime, ShiftError> {
416 if !self.is_finite() {
417 return Err(ShiftError::InfiniteIntervalSubtractedFromTime);
418 }
419 Ok(wrap_time(pg_time(at).wrapping_sub(self.microseconds)))
420 }
421}
422
423struct FieldResults {
425 months: Option<i32>,
426 days: Option<i32>,
427 microseconds: Option<i64>,
428}
429
430fn pg_time(at: NaiveTime) -> i64 {
432 i64::from(at.num_seconds_from_midnight()) * USECS_PER_SEC + i64::from(at.nanosecond() / 1_000)
433}
434
435fn wrap_time(moved: i64) -> NaiveTime {
437 let micros = moved.rem_euclid(USECS_PER_DAY);
438 let seconds = u32::try_from(micros / USECS_PER_SEC).expect("a second of the day fits u32");
440 let nanos = u32::try_from(micros % USECS_PER_SEC * 1_000).expect("a nanosecond fits u32");
441 NaiveTime::from_num_seconds_from_midnight_opt(seconds, nanos)
442 .expect("a clock within the day is a time")
443}
444
445fn pg_timestamp(at: NaiveDateTime) -> Result<i64, ShiftError> {
447 let days = i64::from(at.date().num_days_from_ce()) + JULIAN_BEFORE_CE - POSTGRES_EPOCH_JDATE;
448 let timestamp = days * USECS_PER_DAY + pg_time(at.time());
450 if (MIN_TIMESTAMP..END_TIMESTAMP).contains(×tamp) {
451 Ok(timestamp)
452 } else {
453 Err(ShiftError::TimestampOutOfRange)
454 }
455}
456
457fn chrono_timestamp(timestamp: i64) -> Result<NaiveDateTime, ShiftError> {
459 let days = timestamp.div_euclid(USECS_PER_DAY) + POSTGRES_EPOCH_JDATE - JULIAN_BEFORE_CE;
460 let date = i32::try_from(days)
461 .ok()
462 .and_then(NaiveDate::from_num_days_from_ce_opt)
463 .ok_or(ShiftError::Unrepresentable)?;
464 Ok(date.and_time(wrap_time(timestamp)))
465}
466
467fn timestamp2tm(timestamp: i64) -> (i32, i32, i32, i64) {
469 let julian = timestamp.div_euclid(USECS_PER_DAY) + POSTGRES_EPOCH_JDATE;
470 let julian = i32::try_from(julian).expect("a valid timestamp's Julian day fits int");
472 let (year, month, day) = j2date(julian);
473 (year, month, day, timestamp.rem_euclid(USECS_PER_DAY))
474}
475
476fn tm2timestamp(year: i32, month: i32, day: i32, clock: i64) -> Result<i64, ShiftError> {
478 let valid_julian = (year > -4713 || (year == -4713 && month >= 11))
480 && (year < 5_874_898 || (year == 5_874_898 && month < 6));
481 if !valid_julian {
482 return Err(ShiftError::TimestampOutOfRange);
483 }
484 let days = i64::from(date2j(year, month, day)) - POSTGRES_EPOCH_JDATE;
485 days.checked_mul(USECS_PER_DAY)
486 .and_then(|micros| micros.checked_add(clock))
487 .filter(|timestamp| (MIN_TIMESTAMP..END_TIMESTAMP).contains(timestamp))
488 .ok_or(ShiftError::TimestampOutOfRange)
489}
490
491const fn date2j(year: i32, month: i32, day: i32) -> i32 {
493 let (year, month) = if month > 2 {
494 (year + 4800, month + 1)
495 } else {
496 (year + 4799, month + 13)
497 };
498 let century = year / 100;
499 let mut julian = year * 365 - 32_167;
500 julian += year / 4 - century + century / 4;
501 julian + 7_834 * month / 256 + day
502}
503
504const fn j2date(julian_day: i32) -> (i32, i32, i32) {
506 let mut julian = julian_day.cast_unsigned() + 32_044;
508 let mut quad = julian / 146_097;
509 let extra = (julian - quad * 146_097) * 4 + 3;
510 julian += 60 + quad * 3 + extra / 146_097;
511 quad = julian / 1_461;
512 julian -= quad * 1_461;
513 let mut year = julian * 4 / 1_461;
514 julian = if year == 0 {
515 (julian + 306) % 366
516 } else {
517 (julian + 305) % 365
518 } + 123;
519 year += quad * 4;
520 let quad = julian * 2_141 / 65_536;
521 let day = julian - 7_834 * quad / 256;
522 let month = (quad + 10) % 12 + 1;
523 (
525 year.cast_signed() - 4_800,
526 month.cast_signed(),
527 day.cast_signed(),
528 )
529}
530
531const fn days_in_month(year: i32, month: i32) -> i32 {
533 let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
534 match month {
535 2 if leap => 29,
536 2 => 28,
537 4 | 6 | 9 | 11 => 30,
538 _ => 31,
539 }
540}
541
542#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
567#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
568pub struct IntervalSum {
569 finite: i64,
570 positive_infinities: i64,
571 negative_infinities: i64,
572 months: i128,
573 days: i128,
574 microseconds: i128,
575}
576
577impl IntervalSum {
578 #[must_use]
581 pub fn of(value: PgInterval, weight: i64) -> Self {
582 match value.infinity() {
583 Some(Ordering::Greater) => Self {
584 positive_infinities: weight,
585 ..Self::default()
586 },
587 Some(_) => Self {
588 negative_infinities: weight,
589 ..Self::default()
590 },
591 None => {
592 let wide = i128::from(weight);
593 Self {
594 finite: weight,
595 positive_infinities: 0,
596 negative_infinities: 0,
597 months: i128::from(value.months) * wide,
598 days: i128::from(value.days) * wide,
599 microseconds: i128::from(value.microseconds) * wide,
600 }
601 }
602 }
603 }
604
605 #[must_use]
608 pub fn seeded(
609 finite_sum: Option<PgInterval>,
610 finite: i64,
611 positive_infinities: i64,
612 negative_infinities: i64,
613 ) -> Self {
614 let (months, days, microseconds) =
615 finite_sum.map_or((0, 0, 0), |sum| (sum.months, sum.days, sum.microseconds));
616 Self {
617 finite,
618 positive_infinities,
619 negative_infinities,
620 months: i128::from(months),
621 days: i128::from(days),
622 microseconds: i128::from(microseconds),
623 }
624 }
625
626 pub const fn merge(&mut self, other: Self) {
628 self.finite += other.finite;
629 self.positive_infinities += other.positive_infinities;
630 self.negative_infinities += other.negative_infinities;
631 self.months += other.months;
632 self.days += other.days;
633 self.microseconds += other.microseconds;
634 }
635
636 #[must_use]
638 pub fn is_zero(&self) -> bool {
639 *self == Self::default()
640 }
641
642 #[must_use]
644 pub const fn count(&self) -> i64 {
645 self.finite + self.positive_infinities + self.negative_infinities
646 }
647
648 pub fn sum(&self) -> Result<Option<PgInterval>, IntervalError> {
655 if self.count() <= 0 {
656 return Ok(None);
657 }
658 match (self.positive_infinities > 0, self.negative_infinities > 0) {
659 (true, true) => Err(IntervalError::OutOfRange),
660 (true, false) => Ok(Some(PgInterval::INFINITY)),
661 (false, true) => Ok(Some(PgInterval::NEG_INFINITY)),
662 (false, false) => PgInterval::finite_fields(FieldResults {
663 months: i32::try_from(self.months).ok(),
664 days: i32::try_from(self.days).ok(),
665 microseconds: i64::try_from(self.microseconds).ok(),
666 })
667 .map(Some),
668 }
669 }
670
671 pub fn avg(&self) -> Result<Option<PgInterval>, IntervalError> {
679 match self.sum()? {
680 Some(sum) if sum.is_finite() => {
681 let count = self.finite as f64;
683 sum.checked_div(count).map(Some)
684 }
685 other => Ok(other),
686 }
687 }
688}