sql_values/postgres/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::postgres::{
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::postgres::{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::postgres::{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::postgres::{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::postgres::{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::postgres::{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::postgres::{InputContext, PgTimeZone, PgTimestampTz, parse_interval};
323 ///
324 /// #[cfg(feature = "tzdb")]
325 /// {
326 /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
327 /// let at = PgTimestampTz::parse("2026-03-29 12:00:00+02", InputContext::new()).unwrap();
328 /// let day = parse_interval("1 day").unwrap();
329 /// let before = day.subtract_from_timestamptz(at, &rome).unwrap();
330 /// assert_eq!(before.to_string(), "2026-03-28 11:00:00+00");
331 /// }
332 /// ```
333 pub fn add_to_timestamptz(
334 self,
335 at: PgTimestampTz,
336 zone: &PgTimeZone,
337 ) -> Result<PgTimestampTz, ShiftError> {
338 let shifted = self.shift(at.pg_micros(), Some(zone))?;
339 Ok(PgTimestampTz::from_pg_micros(shifted).expect("a shifted timestamp is checked"))
340 }
341
342 /// PostgreSQL's `timestamptz_mi_interval`, `at - self`, which adds the negated interval.
343 ///
344 /// # Errors
345 ///
346 /// [`ShiftError::IntervalOutOfRange`] where `interval_um` refuses the interval, and the
347 /// errors of [`add_to_timestamptz`](Self::add_to_timestamptz).
348 pub fn subtract_from_timestamptz(
349 self,
350 at: PgTimestampTz,
351 zone: &PgTimeZone,
352 ) -> Result<PgTimestampTz, ShiftError> {
353 self.checked_neg()
354 .map_err(|_| ShiftError::IntervalOutOfRange)?
355 .add_to_timestamptz(at, zone)
356 }
357
358 /// `timestamp_pl_interval`, or `timestamptz_pl_interval` in `zone`, over the stored
359 /// microseconds.
360 fn shift(self, at: i64, zone: Option<&PgTimeZone>) -> Result<i64, ShiftError> {
361 let out_of_range = ShiftError::TimestampOutOfRange;
362 match self.infinity() {
363 Some(Ordering::Less) if at == i64::MAX => return Err(out_of_range),
364 Some(Ordering::Less) => return Ok(i64::MIN),
365 Some(Ordering::Greater) if at == i64::MIN => return Err(out_of_range),
366 Some(_) => return Ok(i64::MAX),
367 None if at == i64::MAX || at == i64::MIN => return Ok(at),
368 None => {}
369 }
370 // `timestamp2tm`, in the zone when there is one.
371 let local_fields = |utc: i64| -> Result<_, ShiftError> {
372 let offset = match zone {
373 None => 0,
374 Some(zone) => utc_offset(zone, utc).map_err(shift_error)?,
375 };
376 Ok(timestamp2tm(utc + i64::from(offset) * USECS_PER_SEC))
377 };
378 // `DetermineTimeZoneOffset` in the zone when there is one, then `tm2timestamp`.
379 let rebuild = |year: i32, month: i32, day: i32, clock: i64| {
380 if !is_valid_julian(year, month) {
381 return Err(out_of_range);
382 }
383 let offset = match zone {
384 None => 0,
385 Some(zone) => {
386 let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
387 let local = days
388 .checked_mul(USECS_PER_DAY)
389 .and_then(|micros| micros.checked_add(clock))
390 .ok_or(out_of_range)?;
391 local_offset(zone, local).map_err(shift_error)?
392 }
393 };
394 tm2timestamp(year, month, day, clock, offset).ok_or(out_of_range)
395 };
396 let mut timestamp = at;
397 if self.months != 0 {
398 let (mut year, month, mut day, clock) = local_fields(timestamp)?;
399 let mut month = month.checked_add(self.months).ok_or(out_of_range)?;
400 // C's truncating division and remainder.
401 if month > MONTHS_PER_YEAR {
402 year += (month - 1) / MONTHS_PER_YEAR;
403 month = (month - 1) % MONTHS_PER_YEAR + 1;
404 } else if month < 1 {
405 year += month / MONTHS_PER_YEAR - 1;
406 month = month % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
407 }
408 day = day.min(days_in_month(year, month));
409 timestamp = rebuild(year, month, day, clock)?;
410 }
411 if self.days != 0 {
412 let (year, month, day, clock) = local_fields(timestamp)?;
413 // `timestamp_pl_interval` refuses a Julian day below 0, and
414 // `timestamptz_pl_interval` one below -1, which a local date west of UTC reaches.
415 let lowest = if zone.is_some() { -1 } else { 0 };
416 let julian = date2j(year, month, day)
417 .checked_add(self.days)
418 .filter(|julian| *julian >= lowest)
419 .ok_or(out_of_range)?;
420 let (year, month, day) = j2date(julian);
421 timestamp = rebuild(year, month, day, clock)?;
422 }
423 timestamp
424 .checked_add(self.microseconds)
425 .filter(|×tamp| is_valid_timestamp(timestamp))
426 .ok_or(out_of_range)
427 }
428
429 /// PostgreSQL's `timestamp_mi`, `later - earlier`, with whole days carried into the days
430 /// field as `interval_justify_hours` carries them. An infinite timestamp gives an infinite
431 /// interval.
432 ///
433 /// # Errors
434 ///
435 /// [`ShiftError::IntervalOutOfRange`] where equal infinities meet, or where the difference
436 /// passes 2^63 microseconds.
437 ///
438 /// ```
439 /// use sql_values::postgres::{PgInterval, parse_timestamp};
440 ///
441 /// let later = parse_timestamp("2024-03-01 06:00:00").unwrap();
442 /// let earlier = parse_timestamp("2024-02-28 12:00:00").unwrap();
443 /// let span = PgInterval::timestamp_difference(later, earlier).unwrap();
444 /// assert_eq!(span.to_string(), "1 day 18:00:00");
445 /// ```
446 pub fn timestamp_difference(
447 later: PgTimestamp,
448 earlier: PgTimestamp,
449 ) -> Result<Self, ShiftError> {
450 let (later, earlier) = (later.pg_micros(), earlier.pg_micros());
451 let infinite = |micros: i64| micros == i64::MAX || micros == i64::MIN;
452 if infinite(later) || infinite(earlier) {
453 return match (later, earlier) {
454 (i64::MIN, i64::MIN) | (i64::MAX, i64::MAX) => Err(ShiftError::IntervalOutOfRange),
455 (i64::MIN, _) | (_, i64::MAX) => Ok(Self::NEG_INFINITY),
456 _ => Ok(Self::INFINITY),
457 };
458 }
459 // Timestamps at opposite ends of PostgreSQL's range lie more than 2^63 microseconds
460 // apart.
461 let time = later
462 .checked_sub(earlier)
463 .ok_or(ShiftError::IntervalOutOfRange)?;
464 // Division truncates toward zero, so the days and the clock share the sign of the
465 // difference and the sign corrections of `interval_justify_hours` never apply. 2^63
466 // microseconds are under 2^27 days, which `int` holds.
467 let days = i32::try_from(time / USECS_PER_DAY).expect("2^63 microseconds fit int days");
468 Ok(Self {
469 months: 0,
470 days,
471 microseconds: time % USECS_PER_DAY,
472 })
473 }
474
475 /// PostgreSQL's `time_pl_interval`, `at + self`: the clock moved by the interval's
476 /// microseconds, wrapping in 64 bits as PostgreSQL does, then within the day. The months and
477 /// days are ignored.
478 ///
479 /// # Errors
480 ///
481 /// [`ShiftError::InfiniteIntervalAddedToTime`] for an infinite interval.
482 ///
483 /// ```
484 /// use sql_values::postgres::{parse_interval, parse_time};
485 ///
486 /// let at = parse_time("23:00:00").unwrap();
487 /// let span = parse_interval("1 day 02:30:00").unwrap();
488 /// assert_eq!(span.add_to_time(at).unwrap().to_string(), "01:30:00");
489 /// ```
490 pub fn add_to_time(self, at: PgTime) -> Result<PgTime, ShiftError> {
491 if !self.is_finite() {
492 return Err(ShiftError::InfiniteIntervalAddedToTime);
493 }
494 Ok(wrap_time(at.micros().wrapping_add(self.microseconds)))
495 }
496
497 /// PostgreSQL's `time_mi_interval`, `at - self`, as [`add_to_time`](Self::add_to_time) with
498 /// the clock subtracted.
499 ///
500 /// # Errors
501 ///
502 /// [`ShiftError::InfiniteIntervalSubtractedFromTime`] for an infinite interval.
503 pub fn subtract_from_time(self, at: PgTime) -> Result<PgTime, ShiftError> {
504 if !self.is_finite() {
505 return Err(ShiftError::InfiniteIntervalSubtractedFromTime);
506 }
507 Ok(wrap_time(at.micros().wrapping_sub(self.microseconds)))
508 }
509}
510
511/// The three fields of an interval result, each `None` where its arithmetic overflowed.
512struct FieldResults {
513 months: Option<i32>,
514 days: Option<i32>,
515 microseconds: Option<i64>,
516}
517
518/// The shift error of a refusal by a zone lookup.
519fn shift_error(error: DateTimeError) -> ShiftError {
520 match error {
521 DateTimeError::OutsideJiffRange => ShiftError::OutsideJiffRange,
522 _ => ShiftError::TimestampOutOfRange,
523 }
524}
525
526/// The time of `moved` microseconds reduced into the day, as `time_pl_interval` reduces it.
527fn wrap_time(moved: i64) -> PgTime {
528 PgTime::from_micros(moved.rem_euclid(USECS_PER_DAY)).expect("a clock within the day is a time")
529}
530
531/// The running state of PostgreSQL's `sum(interval)` and `avg(interval)`.
532///
533/// The finite values are summed exactly per field and the infinities are counted, as PostgreSQL
534/// counts them. PostgreSQL adds in scan order and raises on a partial sum leaving a field's range,
535/// so the same rows can sum or raise by the order they are read in. Whenever a field's net total
536/// fits, some order of the rows never leaves the range, and its answer is that net total, which is
537/// the one reported here.
538///
539/// The counts are signed so that a row leaving is the same type as one arriving, and folding
540/// either in is componentwise addition.
541///
542/// ```
543/// use sql_values::postgres::{IntervalSum, PgInterval, parse_interval};
544///
545/// let mut total = IntervalSum::default();
546/// for text in ["1 mon", "2 days", "-01:00:00"] {
547/// total.merge(IntervalSum::of(parse_interval(text).unwrap(), 1));
548/// }
549/// assert_eq!(total.sum().unwrap().unwrap().to_string(), "1 mon 2 days -01:00:00");
550/// assert_eq!(total.avg().unwrap().unwrap().to_string(), "10 days 15:40:00");
551///
552/// total.merge(IntervalSum::of(PgInterval::INFINITY, 1));
553/// assert_eq!(total.avg(), Ok(Some(PgInterval::INFINITY)));
554/// ```
555#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
556#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
557pub struct IntervalSum {
558 // Row counts in `i128` as the sums are, so that no run of `i64` weights overflows them.
559 finite: i128,
560 positive_infinities: i128,
561 negative_infinities: i128,
562 months: i128,
563 days: i128,
564 microseconds: i128,
565}
566
567impl IntervalSum {
568 /// One row's interval contributing with `weight`, `1` for a row arriving and `-1` for one
569 /// leaving.
570 #[must_use]
571 pub fn of(value: PgInterval, weight: i64) -> Self {
572 let wide = i128::from(weight);
573 match value.infinity() {
574 Some(Ordering::Greater) => Self {
575 positive_infinities: wide,
576 ..Self::default()
577 },
578 Some(_) => Self {
579 negative_infinities: wide,
580 ..Self::default()
581 },
582 None => Self {
583 finite: wide,
584 positive_infinities: 0,
585 negative_infinities: 0,
586 months: i128::from(value.months) * wide,
587 days: i128::from(value.days) * wide,
588 microseconds: i128::from(value.microseconds) * wide,
589 },
590 }
591 }
592
593 /// The state a database reports for some rows: the sum of the finite ones, how many there
594 /// are, and how many are each infinity.
595 ///
596 /// ```
597 /// use sql_values::postgres::{IntervalSum, parse_interval};
598 ///
599 /// let mut state = IntervalSum::seeded(Some(parse_interval("3 days").unwrap()), 2, 0, 0);
600 /// assert_eq!(state.count(), 2);
601 /// state.merge(IntervalSum::of(parse_interval("3 days").unwrap(), 1));
602 /// assert_eq!(state.avg().unwrap().unwrap().to_string(), "2 days");
603 /// ```
604 #[must_use]
605 pub fn seeded(
606 finite_sum: Option<PgInterval>,
607 finite: i64,
608 positive_infinities: i64,
609 negative_infinities: i64,
610 ) -> Self {
611 let (months, days, microseconds) =
612 finite_sum.map_or((0, 0, 0), |sum| (sum.months, sum.days, sum.microseconds));
613 Self {
614 finite: i128::from(finite),
615 positive_infinities: i128::from(positive_infinities),
616 negative_infinities: i128::from(negative_infinities),
617 months: i128::from(months),
618 days: i128::from(days),
619 microseconds: i128::from(microseconds),
620 }
621 }
622
623 /// Fold `other` in, componentwise.
624 pub const fn merge(&mut self, other: Self) {
625 self.finite += other.finite;
626 self.positive_infinities += other.positive_infinities;
627 self.negative_infinities += other.negative_infinities;
628 self.months += other.months;
629 self.days += other.days;
630 self.microseconds += other.microseconds;
631 }
632
633 /// Whether this moves nothing.
634 #[must_use]
635 pub fn is_zero(&self) -> bool {
636 *self == Self::default()
637 }
638
639 /// The rows folded in.
640 #[must_use]
641 pub const fn count(&self) -> i128 {
642 self.finite + self.positive_infinities + self.negative_infinities
643 }
644
645 /// PostgreSQL's `interval_sum`, `None` over no rows.
646 ///
647 /// # Errors
648 ///
649 /// [`IntervalError::OutOfRange`] for infinities of both signs and for a field whose net total
650 /// leaves its range.
651 pub fn sum(&self) -> Result<Option<PgInterval>, IntervalError> {
652 if self.count() <= 0 {
653 return Ok(None);
654 }
655 match (self.positive_infinities > 0, self.negative_infinities > 0) {
656 (true, true) => Err(IntervalError::OutOfRange),
657 (true, false) => Ok(Some(PgInterval::INFINITY)),
658 (false, true) => Ok(Some(PgInterval::NEG_INFINITY)),
659 (false, false) => PgInterval::finite_fields(FieldResults {
660 months: i32::try_from(self.months).ok(),
661 days: i32::try_from(self.days).ok(),
662 microseconds: i64::try_from(self.microseconds).ok(),
663 })
664 .map(Some),
665 }
666 }
667
668 /// PostgreSQL's `interval_avg`, the sum divided by the count of finite rows as
669 /// `interval_div` divides, `None` over no rows.
670 ///
671 /// # Errors
672 ///
673 /// The errors of [`sum`](Self::sum), and [`IntervalError::OutOfRange`] for a quotient beyond
674 /// the type.
675 pub fn avg(&self) -> Result<Option<PgInterval>, IntervalError> {
676 match self.sum()? {
677 Some(sum) if sum.is_finite() => {
678 // Intended loss, as PostgreSQL divides by the count as a `double`.
679 let count = self.finite as f64;
680 sum.checked_div(count).map(Some)
681 }
682 other => Ok(other),
683 }
684 }
685}