sql_values/interval/arithmetic.rs
1//! PostgreSQL 18's arithmetic on intervals, ported from `timestamp.c` and `date.c` with
2//! PostgreSQL's order of checks.
3
4use core::cmp::Ordering;
5
6use super::{IntervalError, PgInterval};
7use crate::{
8 DateTimeError, PgTime, PgTimeZone, PgTimestamp, PgTimestampTz,
9 datetime::{
10 MONTHS_PER_YEAR, POSTGRES_EPOCH_JDATE, USECS_PER_DAY, USECS_PER_SEC, date2j, days_in_month,
11 is_valid_julian, is_valid_timestamp, j2date, local_offset, timestamp2tm, tm2timestamp,
12 utc_offset,
13 },
14 float::{
15 fits_in_i32, fits_in_i64, int_to_f64, round_ties_even, truncate_to_i32, truncate_to_i64,
16 ts_round,
17 },
18};
19
20const DAYS_PER_MONTH: f64 = 30.0;
21const SECS_PER_DAY: f64 = 86_400.0;
22
23/// Why a timestamp or time shifted by an interval has no value here.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
25pub enum ShiftError {
26 /// The timestamp lies outside PostgreSQL's, or the shift leaves them.
27 #[error("timestamp out of range")]
28 TimestampOutOfRange,
29 /// The interval `timestamp - interval` negates has a field at its minimum.
30 #[error("interval out of range")]
31 IntervalOutOfRange,
32 /// `time + interval` of an infinite interval.
33 #[error("cannot add infinite interval to time")]
34 InfiniteIntervalAddedToTime,
35 /// `time - interval` of an infinite interval.
36 #[error("cannot subtract infinite interval from time")]
37 InfiniteIntervalSubtractedFromTime,
38 /// An IANA time zone asked about an instant outside jiff's years -9999 to 9999.
39 #[error("value outside jiff's years -9999 to 9999")]
40 OutsideJiffRange,
41}
42
43impl PgInterval {
44 /// `Greater` for `infinity`, `Less` for `-infinity`, `None` when finite.
45 const fn infinity(&self) -> Option<Ordering> {
46 if self.fields_equal(&Self::INFINITY) {
47 Some(Ordering::Greater)
48 } else if self.fields_equal(&Self::NEG_INFINITY) {
49 Some(Ordering::Less)
50 } else {
51 None
52 }
53 }
54
55 /// `self` unless its fields spell an infinity, which a finite result may not.
56 const fn finite(self) -> Result<Self, IntervalError> {
57 if self.is_finite() {
58 Ok(self)
59 } else {
60 Err(IntervalError::OutOfRange)
61 }
62 }
63
64 /// The infinity on the side `sign` names.
65 const fn infinite(sign: Ordering) -> Self {
66 match sign {
67 Ordering::Less => Self::NEG_INFINITY,
68 _ => Self::INFINITY,
69 }
70 }
71
72 /// PostgreSQL's `interval_pl`, `self + other`.
73 ///
74 /// # Errors
75 ///
76 /// [`IntervalError::OutOfRange`] where a field overflows, the sum spells an infinity, or
77 /// opposite infinities meet.
78 ///
79 /// ```
80 /// use sql_values::{IntervalError, PgInterval, parse_interval};
81 ///
82 /// let day = parse_interval("1 day").unwrap();
83 /// let hour = parse_interval("-01:00:00").unwrap();
84 /// assert_eq!(day.checked_add(hour).unwrap().to_string(), "1 day -01:00:00");
85 /// assert_eq!(
86 /// PgInterval::INFINITY.checked_add(PgInterval::NEG_INFINITY),
87 /// Err(IntervalError::OutOfRange),
88 /// );
89 /// ```
90 pub fn checked_add(self, other: Self) -> Result<Self, IntervalError> {
91 match (self.infinity(), other.infinity()) {
92 (Some(left), Some(right)) if left != right => Err(IntervalError::OutOfRange),
93 (Some(_), _) => Ok(self),
94 (None, Some(_)) => Ok(other),
95 (None, None) => Self::finite_fields(FieldResults {
96 months: self.months.checked_add(other.months),
97 days: self.days.checked_add(other.days),
98 microseconds: self.microseconds.checked_add(other.microseconds),
99 }),
100 }
101 }
102
103 /// PostgreSQL's `interval_mi`, `self - other`.
104 ///
105 /// # Errors
106 ///
107 /// [`IntervalError::OutOfRange`] where a field overflows, the difference spells an infinity,
108 /// or like infinities meet.
109 pub fn checked_sub(self, other: Self) -> Result<Self, IntervalError> {
110 match (self.infinity(), other.infinity()) {
111 (Some(left), Some(right)) if left == right => Err(IntervalError::OutOfRange),
112 (Some(_), _) => Ok(self),
113 (None, Some(right)) => Ok(Self::infinite(right.reverse())),
114 (None, None) => Self::finite_fields(FieldResults {
115 months: self.months.checked_sub(other.months),
116 days: self.days.checked_sub(other.days),
117 microseconds: self.microseconds.checked_sub(other.microseconds),
118 }),
119 }
120 }
121
122 /// PostgreSQL's `interval_um`, `-self`.
123 ///
124 /// # Errors
125 ///
126 /// [`IntervalError::OutOfRange`] where a field sits at its minimum, or the negation spells an
127 /// infinity.
128 ///
129 /// ```
130 /// use sql_values::{IntervalError, parse_interval};
131 ///
132 /// let span = parse_interval("1 mon -2 days").unwrap();
133 /// assert_eq!(span.checked_neg().unwrap().to_string(), "-1 mons +2 days");
134 /// let minimum = parse_interval("-2147483648 days").unwrap();
135 /// assert_eq!(minimum.checked_neg(), Err(IntervalError::OutOfRange));
136 /// ```
137 pub fn checked_neg(self) -> Result<Self, IntervalError> {
138 match self.infinity() {
139 Some(sign) => Ok(Self::infinite(sign.reverse())),
140 None => Self::finite_fields(FieldResults {
141 months: self.months.checked_neg(),
142 days: self.days.checked_neg(),
143 microseconds: self.microseconds.checked_neg(),
144 }),
145 }
146 }
147
148 /// PostgreSQL's `interval_mul`, `self * factor`.
149 ///
150 /// Months and days scale apart, what a month leaves over cascades into days as 30 and what a
151 /// day leaves over into the clock as 24 hours, each rounded to the microsecond as PostgreSQL
152 /// rounds it.
153 ///
154 /// # Errors
155 ///
156 /// [`IntervalError::OutOfRange`] for a `NaN` factor, zero against an infinity, an infinite
157 /// factor against a zero interval, and a product beyond the type.
158 ///
159 /// ```
160 /// use sql_values::{IntervalError, PgInterval, parse_interval};
161 ///
162 /// let month = parse_interval("1 mon 1 day").unwrap();
163 /// assert_eq!(month.checked_mul(1.5).unwrap().to_string(), "1 mon 16 days 12:00:00");
164 /// assert_eq!(month.checked_mul(f64::INFINITY), Ok(PgInterval::INFINITY));
165 /// assert_eq!(month.checked_mul(f64::NAN), Err(IntervalError::OutOfRange));
166 /// ```
167 pub fn checked_mul(self, factor: f64) -> Result<Self, IntervalError> {
168 if factor.is_nan() {
169 return Err(IntervalError::OutOfRange);
170 }
171 if let Some(sign) = self.infinity() {
172 return match factor.partial_cmp(&0.0) {
173 Some(Ordering::Less) => Ok(Self::infinite(sign.reverse())),
174 Some(Ordering::Greater) => Ok(self),
175 _ => Err(IntervalError::OutOfRange),
176 };
177 }
178 if factor.is_infinite() {
179 return match self.span_microseconds().cmp(&0) {
180 Ordering::Equal => Err(IntervalError::OutOfRange),
181 sign if factor < 0.0 => Ok(Self::infinite(sign.reverse())),
182 sign => Ok(Self::infinite(sign)),
183 };
184 }
185 self.cascade(|field| field * factor)
186 }
187
188 /// PostgreSQL's `interval_div`, `self / factor`, cascading as
189 /// [`checked_mul`](Self::checked_mul) does.
190 ///
191 /// # Errors
192 ///
193 /// [`IntervalError::DivisionByZero`] for a zero factor, and [`IntervalError::OutOfRange`] for
194 /// a `NaN` factor, an infinity divided by an infinity, and a quotient beyond the type.
195 ///
196 /// ```
197 /// use sql_values::{IntervalError, parse_interval};
198 ///
199 /// let span = parse_interval("1 mon 1 day 00:00:01").unwrap();
200 /// assert_eq!(span.checked_div(7.0).unwrap().to_string(), "4 days 10:17:08.6896");
201 /// assert_eq!(span.checked_div(f64::INFINITY).unwrap().to_string(), "00:00:00");
202 /// assert_eq!(span.checked_div(0.0), Err(IntervalError::DivisionByZero));
203 /// ```
204 pub fn checked_div(self, factor: f64) -> Result<Self, IntervalError> {
205 if factor == 0.0 {
206 return Err(IntervalError::DivisionByZero);
207 }
208 if factor.is_nan() {
209 return Err(IntervalError::OutOfRange);
210 }
211 if let Some(sign) = self.infinity() {
212 return if factor.is_infinite() {
213 Err(IntervalError::OutOfRange)
214 } else if factor < 0.0 {
215 Ok(Self::infinite(sign.reverse()))
216 } else {
217 Ok(self)
218 };
219 }
220 self.cascade(|field| field / factor)
221 }
222
223 /// The fields of a finite result, each `None` where it overflowed.
224 fn finite_fields(fields: FieldResults) -> Result<Self, IntervalError> {
225 Self {
226 months: fields.months.ok_or(IntervalError::OutOfRange)?,
227 days: fields.days.ok_or(IntervalError::OutOfRange)?,
228 microseconds: fields.microseconds.ok_or(IntervalError::OutOfRange)?,
229 }
230 .finite()
231 }
232
233 /// The finite part of `interval_mul` and `interval_div`, `scale` being the multiplication or
234 /// the division by the factor.
235 fn cascade(self, scale: impl Fn(f64) -> f64) -> Result<Self, IntervalError> {
236 let month_product = scale(f64::from(self.months));
237 if !fits_in_i32(month_product) {
238 return Err(IntervalError::OutOfRange);
239 }
240 let months = truncate_to_i32(month_product);
241 let day_product = scale(f64::from(self.days));
242 if !fits_in_i32(day_product) {
243 return Err(IntervalError::OutOfRange);
244 }
245 let mut days = truncate_to_i32(day_product);
246 // Under 30 in magnitude, the fraction of a month as days.
247 let month_remainder_days = ts_round((month_product - f64::from(months)) * DAYS_PER_MONTH);
248 let whole_remainder_days = truncate_to_i32(month_remainder_days);
249 let mut sec_remainder = ts_round(
250 (day_product - f64::from(days) + month_remainder_days
251 - f64::from(whole_remainder_days))
252 * SECS_PER_DAY,
253 );
254 if sec_remainder.abs() >= SECS_PER_DAY {
255 // Under two days in magnitude, from two fractions below one day each.
256 let carried = truncate_to_i32(sec_remainder / SECS_PER_DAY);
257 days = days.checked_add(carried).ok_or(IntervalError::OutOfRange)?;
258 sec_remainder -= f64::from(carried) * SECS_PER_DAY;
259 }
260 days = days
261 .checked_add(whole_remainder_days)
262 .ok_or(IntervalError::OutOfRange)?;
263 let microseconds = round_ties_even(
264 scale(int_to_f64(self.microseconds)) + sec_remainder * int_to_f64(USECS_PER_SEC),
265 );
266 if !fits_in_i64(microseconds) {
267 return Err(IntervalError::OutOfRange);
268 }
269 Self {
270 months,
271 days,
272 microseconds: truncate_to_i64(microseconds),
273 }
274 .finite()
275 }
276
277 /// PostgreSQL's `timestamp_pl_interval`, `at + self`: months added to the calendar month with
278 /// the day clamped to the month's last, then days added to the calendar day, then the clock.
279 /// An infinite timestamp or interval gives an infinity.
280 ///
281 /// # Errors
282 ///
283 /// [`ShiftError::TimestampOutOfRange`] where a step leaves PostgreSQL's timestamps, or where
284 /// opposite infinities meet.
285 ///
286 /// ```
287 /// use sql_values::{parse_interval, parse_timestamp};
288 ///
289 /// let at = parse_timestamp("2024-01-31 10:00:00").unwrap();
290 /// let month = parse_interval("1 mon").unwrap();
291 /// assert_eq!(month.add_to_timestamp(at).unwrap().to_string(), "2024-02-29 10:00:00");
292 /// ```
293 pub fn add_to_timestamp(self, at: PgTimestamp) -> Result<PgTimestamp, ShiftError> {
294 let shifted = self.shift(at.pg_micros(), None)?;
295 Ok(PgTimestamp::from_pg_micros(shifted).expect("a shifted timestamp is checked"))
296 }
297
298 /// PostgreSQL's `timestamp_mi_interval`, `at - self`, which adds the negated interval.
299 ///
300 /// # Errors
301 ///
302 /// [`ShiftError::IntervalOutOfRange`] where `interval_um` refuses the interval, and the
303 /// errors of [`add_to_timestamp`](Self::add_to_timestamp).
304 pub fn subtract_from_timestamp(self, at: PgTimestamp) -> Result<PgTimestamp, ShiftError> {
305 self.checked_neg()
306 .map_err(|_| ShiftError::IntervalOutOfRange)?
307 .add_to_timestamp(at)
308 }
309
310 /// PostgreSQL's `timestamptz_pl_interval` with `zone` as the session's `TimeZone`,
311 /// `at + self`, with months and days added on the zone's calendar, each step's local clock
312 /// resolved as [`PgTimestamp::to_timestamptz`] resolves it, then the microseconds added to
313 /// the instant.
314 ///
315 /// # Errors
316 ///
317 /// The errors of [`add_to_timestamp`](Self::add_to_timestamp), and
318 /// [`ShiftError::OutsideJiffRange`] where an IANA zone is asked about an instant outside
319 /// jiff's years.
320 ///
321 /// ```
322 /// use sql_values::{InputContext, PgTimeZone, PgTimestampTz, parse_interval};
323 ///
324 /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
325 /// let at = PgTimestampTz::parse("2026-03-29 12:00:00+02", InputContext::new()).unwrap();
326 /// let day = parse_interval("1 day").unwrap();
327 /// let before = day.subtract_from_timestamptz(at, &rome).unwrap();
328 /// assert_eq!(before.to_string(), "2026-03-28 11:00:00+00");
329 /// ```
330 pub fn add_to_timestamptz(
331 self,
332 at: PgTimestampTz,
333 zone: &PgTimeZone,
334 ) -> Result<PgTimestampTz, ShiftError> {
335 let shifted = self.shift(at.pg_micros(), Some(zone))?;
336 Ok(PgTimestampTz::from_pg_micros(shifted).expect("a shifted timestamp is checked"))
337 }
338
339 /// PostgreSQL's `timestamptz_mi_interval`, `at - self`, which adds the negated interval.
340 ///
341 /// # Errors
342 ///
343 /// [`ShiftError::IntervalOutOfRange`] where `interval_um` refuses the interval, and the
344 /// errors of [`add_to_timestamptz`](Self::add_to_timestamptz).
345 pub fn subtract_from_timestamptz(
346 self,
347 at: PgTimestampTz,
348 zone: &PgTimeZone,
349 ) -> Result<PgTimestampTz, ShiftError> {
350 self.checked_neg()
351 .map_err(|_| ShiftError::IntervalOutOfRange)?
352 .add_to_timestamptz(at, zone)
353 }
354
355 /// `timestamp_pl_interval`, or `timestamptz_pl_interval` in `zone`, over the stored
356 /// microseconds.
357 fn shift(self, at: i64, zone: Option<&PgTimeZone>) -> Result<i64, ShiftError> {
358 let out_of_range = ShiftError::TimestampOutOfRange;
359 match self.infinity() {
360 Some(Ordering::Less) if at == i64::MAX => return Err(out_of_range),
361 Some(Ordering::Less) => return Ok(i64::MIN),
362 Some(Ordering::Greater) if at == i64::MIN => return Err(out_of_range),
363 Some(_) => return Ok(i64::MAX),
364 None if at == i64::MAX || at == i64::MIN => return Ok(at),
365 None => {}
366 }
367 // `timestamp2tm`, in the zone when there is one.
368 let local_fields = |utc: i64| -> Result<_, ShiftError> {
369 let offset = match zone {
370 None => 0,
371 Some(zone) => utc_offset(zone, utc).map_err(shift_error)?,
372 };
373 Ok(timestamp2tm(utc + i64::from(offset) * USECS_PER_SEC))
374 };
375 // `DetermineTimeZoneOffset` in the zone when there is one, then `tm2timestamp`.
376 let rebuild = |year: i32, month: i32, day: i32, clock: i64| {
377 if !is_valid_julian(year, month) {
378 return Err(out_of_range);
379 }
380 let offset = match zone {
381 None => 0,
382 Some(zone) => {
383 let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
384 let local = days
385 .checked_mul(USECS_PER_DAY)
386 .and_then(|micros| micros.checked_add(clock))
387 .ok_or(out_of_range)?;
388 local_offset(zone, local).map_err(shift_error)?
389 }
390 };
391 tm2timestamp(year, month, day, clock, offset).ok_or(out_of_range)
392 };
393 let mut timestamp = at;
394 if self.months != 0 {
395 let (mut year, month, mut day, clock) = local_fields(timestamp)?;
396 let mut month = month.checked_add(self.months).ok_or(out_of_range)?;
397 // C's truncating division and remainder.
398 if month > MONTHS_PER_YEAR {
399 year += (month - 1) / MONTHS_PER_YEAR;
400 month = (month - 1) % MONTHS_PER_YEAR + 1;
401 } else if month < 1 {
402 year += month / MONTHS_PER_YEAR - 1;
403 month = month % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
404 }
405 day = day.min(days_in_month(year, month));
406 timestamp = rebuild(year, month, day, clock)?;
407 }
408 if self.days != 0 {
409 let (year, month, day, clock) = local_fields(timestamp)?;
410 // `timestamp_pl_interval` refuses a Julian day below 0, and
411 // `timestamptz_pl_interval` one below -1, which a local date west of UTC reaches.
412 let lowest = if zone.is_some() { -1 } else { 0 };
413 let julian = date2j(year, month, day)
414 .checked_add(self.days)
415 .filter(|julian| *julian >= lowest)
416 .ok_or(out_of_range)?;
417 let (year, month, day) = j2date(julian);
418 timestamp = rebuild(year, month, day, clock)?;
419 }
420 timestamp
421 .checked_add(self.microseconds)
422 .filter(|×tamp| is_valid_timestamp(timestamp))
423 .ok_or(out_of_range)
424 }
425
426 /// PostgreSQL's `timestamp_mi`, `later - earlier`, with whole days carried into the days
427 /// field as `interval_justify_hours` carries them. An infinite timestamp gives an infinite
428 /// interval.
429 ///
430 /// # Errors
431 ///
432 /// [`ShiftError::IntervalOutOfRange`] where equal infinities meet, or where the difference
433 /// passes 2^63 microseconds.
434 ///
435 /// ```
436 /// use sql_values::{PgInterval, parse_timestamp};
437 ///
438 /// let later = parse_timestamp("2024-03-01 06:00:00").unwrap();
439 /// let earlier = parse_timestamp("2024-02-28 12:00:00").unwrap();
440 /// let span = PgInterval::timestamp_difference(later, earlier).unwrap();
441 /// assert_eq!(span.to_string(), "1 day 18:00:00");
442 /// ```
443 pub fn timestamp_difference(
444 later: PgTimestamp,
445 earlier: PgTimestamp,
446 ) -> Result<Self, ShiftError> {
447 let (later, earlier) = (later.pg_micros(), earlier.pg_micros());
448 let infinite = |micros: i64| micros == i64::MAX || micros == i64::MIN;
449 if infinite(later) || infinite(earlier) {
450 return match (later, earlier) {
451 (i64::MIN, i64::MIN) | (i64::MAX, i64::MAX) => Err(ShiftError::IntervalOutOfRange),
452 (i64::MIN, _) | (_, i64::MAX) => Ok(Self::NEG_INFINITY),
453 _ => Ok(Self::INFINITY),
454 };
455 }
456 // Timestamps at opposite ends of PostgreSQL's range lie more than 2^63 microseconds
457 // apart.
458 let time = later
459 .checked_sub(earlier)
460 .ok_or(ShiftError::IntervalOutOfRange)?;
461 // Division truncates toward zero, so the days and the clock share the sign of the
462 // difference and the sign corrections of `interval_justify_hours` never apply. 2^63
463 // microseconds are under 2^27 days, which `int` holds.
464 let days = i32::try_from(time / USECS_PER_DAY).expect("2^63 microseconds fit int days");
465 Ok(Self {
466 months: 0,
467 days,
468 microseconds: time % USECS_PER_DAY,
469 })
470 }
471
472 /// PostgreSQL's `time_pl_interval`, `at + self`: the clock moved by the interval's
473 /// microseconds, wrapping in 64 bits as PostgreSQL does, then within the day. The months and
474 /// days are ignored.
475 ///
476 /// # Errors
477 ///
478 /// [`ShiftError::InfiniteIntervalAddedToTime`] for an infinite interval.
479 ///
480 /// ```
481 /// use sql_values::{parse_interval, parse_time};
482 ///
483 /// let at = parse_time("23:00:00").unwrap();
484 /// let span = parse_interval("1 day 02:30:00").unwrap();
485 /// assert_eq!(span.add_to_time(at).unwrap().to_string(), "01:30:00");
486 /// ```
487 pub fn add_to_time(self, at: PgTime) -> Result<PgTime, ShiftError> {
488 if !self.is_finite() {
489 return Err(ShiftError::InfiniteIntervalAddedToTime);
490 }
491 Ok(wrap_time(at.micros().wrapping_add(self.microseconds)))
492 }
493
494 /// PostgreSQL's `time_mi_interval`, `at - self`, as [`add_to_time`](Self::add_to_time) with
495 /// the clock subtracted.
496 ///
497 /// # Errors
498 ///
499 /// [`ShiftError::InfiniteIntervalSubtractedFromTime`] for an infinite interval.
500 pub fn subtract_from_time(self, at: PgTime) -> Result<PgTime, ShiftError> {
501 if !self.is_finite() {
502 return Err(ShiftError::InfiniteIntervalSubtractedFromTime);
503 }
504 Ok(wrap_time(at.micros().wrapping_sub(self.microseconds)))
505 }
506}
507
508/// The three fields of an interval result, each `None` where its arithmetic overflowed.
509struct FieldResults {
510 months: Option<i32>,
511 days: Option<i32>,
512 microseconds: Option<i64>,
513}
514
515/// The shift error of a refusal by a zone lookup.
516fn shift_error(error: DateTimeError) -> ShiftError {
517 match error {
518 DateTimeError::OutsideJiffRange => ShiftError::OutsideJiffRange,
519 _ => ShiftError::TimestampOutOfRange,
520 }
521}
522
523/// The time of `moved` microseconds reduced into the day, as `time_pl_interval` reduces it.
524fn wrap_time(moved: i64) -> PgTime {
525 PgTime::from_micros(moved.rem_euclid(USECS_PER_DAY)).expect("a clock within the day is a time")
526}
527
528/// The running state of PostgreSQL's `sum(interval)` and `avg(interval)`.
529///
530/// The finite values are summed exactly per field and the infinities are counted, as PostgreSQL
531/// counts them. PostgreSQL adds in scan order and raises on a partial sum leaving a field's range,
532/// so the same rows can sum or raise by the order they are read in. Whenever a field's net total
533/// fits, some order of the rows never leaves the range, and its answer is that net total, which is
534/// the one reported here.
535///
536/// The counts are signed so that a row leaving is the same type as one arriving, and folding
537/// either in is componentwise addition.
538///
539/// ```
540/// use sql_values::{IntervalSum, PgInterval, parse_interval};
541///
542/// let mut total = IntervalSum::default();
543/// for text in ["1 mon", "2 days", "-01:00:00"] {
544/// total.merge(IntervalSum::of(parse_interval(text).unwrap(), 1));
545/// }
546/// assert_eq!(total.sum().unwrap().unwrap().to_string(), "1 mon 2 days -01:00:00");
547/// assert_eq!(total.avg().unwrap().unwrap().to_string(), "10 days 15:40:00");
548///
549/// total.merge(IntervalSum::of(PgInterval::INFINITY, 1));
550/// assert_eq!(total.avg(), Ok(Some(PgInterval::INFINITY)));
551/// ```
552#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
553#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
554pub struct IntervalSum {
555 finite: i64,
556 positive_infinities: i64,
557 negative_infinities: i64,
558 months: i128,
559 days: i128,
560 microseconds: i128,
561}
562
563impl IntervalSum {
564 /// One row's interval contributing with `weight`, `1` for a row arriving and `-1` for one
565 /// leaving.
566 #[must_use]
567 pub fn of(value: PgInterval, weight: i64) -> Self {
568 match value.infinity() {
569 Some(Ordering::Greater) => Self {
570 positive_infinities: weight,
571 ..Self::default()
572 },
573 Some(_) => Self {
574 negative_infinities: weight,
575 ..Self::default()
576 },
577 None => {
578 let wide = i128::from(weight);
579 Self {
580 finite: weight,
581 positive_infinities: 0,
582 negative_infinities: 0,
583 months: i128::from(value.months) * wide,
584 days: i128::from(value.days) * wide,
585 microseconds: i128::from(value.microseconds) * wide,
586 }
587 }
588 }
589 }
590
591 /// The state a database reports for some rows: the sum of the finite ones, how many there
592 /// are, and how many are each infinity.
593 #[must_use]
594 pub fn seeded(
595 finite_sum: Option<PgInterval>,
596 finite: i64,
597 positive_infinities: i64,
598 negative_infinities: i64,
599 ) -> Self {
600 let (months, days, microseconds) =
601 finite_sum.map_or((0, 0, 0), |sum| (sum.months, sum.days, sum.microseconds));
602 Self {
603 finite,
604 positive_infinities,
605 negative_infinities,
606 months: i128::from(months),
607 days: i128::from(days),
608 microseconds: i128::from(microseconds),
609 }
610 }
611
612 /// Fold `other` in, componentwise.
613 pub const fn merge(&mut self, other: Self) {
614 self.finite += other.finite;
615 self.positive_infinities += other.positive_infinities;
616 self.negative_infinities += other.negative_infinities;
617 self.months += other.months;
618 self.days += other.days;
619 self.microseconds += other.microseconds;
620 }
621
622 /// Whether this moves nothing.
623 #[must_use]
624 pub fn is_zero(&self) -> bool {
625 *self == Self::default()
626 }
627
628 /// The rows folded in.
629 #[must_use]
630 pub const fn count(&self) -> i64 {
631 self.finite + self.positive_infinities + self.negative_infinities
632 }
633
634 /// PostgreSQL's `interval_sum`, `None` over no rows.
635 ///
636 /// # Errors
637 ///
638 /// [`IntervalError::OutOfRange`] for infinities of both signs and for a field whose net total
639 /// leaves its range.
640 pub fn sum(&self) -> Result<Option<PgInterval>, IntervalError> {
641 if self.count() <= 0 {
642 return Ok(None);
643 }
644 match (self.positive_infinities > 0, self.negative_infinities > 0) {
645 (true, true) => Err(IntervalError::OutOfRange),
646 (true, false) => Ok(Some(PgInterval::INFINITY)),
647 (false, true) => Ok(Some(PgInterval::NEG_INFINITY)),
648 (false, false) => PgInterval::finite_fields(FieldResults {
649 months: i32::try_from(self.months).ok(),
650 days: i32::try_from(self.days).ok(),
651 microseconds: i64::try_from(self.microseconds).ok(),
652 })
653 .map(Some),
654 }
655 }
656
657 /// PostgreSQL's `interval_avg`, the sum divided by the count of finite rows as
658 /// `interval_div` divides, `None` over no rows.
659 ///
660 /// # Errors
661 ///
662 /// The errors of [`sum`](Self::sum), and [`IntervalError::OutOfRange`] for a quotient beyond
663 /// the type.
664 pub fn avg(&self) -> Result<Option<PgInterval>, IntervalError> {
665 match self.sum()? {
666 Some(sum) if sum.is_finite() => {
667 // Intended loss, as PostgreSQL divides by the count as a `double`.
668 let count = self.finite as f64;
669 sum.checked_div(count).map(Some)
670 }
671 other => Ok(other),
672 }
673 }
674}