Skip to main content

sql_values/postgres/numeric/
arithmetic.rs

1//! PostgreSQL 18's `numeric` operators and rounding functions, `numeric_add`, `numeric_sub`,
2//! `numeric_mul`, `numeric_div`, `numeric_mod`, `numeric_uminus`, `numeric_abs`,
3//! `numeric_round`, `numeric_trunc`, `numeric_floor` and `numeric_ceil`.
4
5use core::{cmp::Ordering, ops::Neg};
6
7use super::{Finite, MAX_DSCALE, MAX_WEIGHT, NumericError, PgNumeric, Repr};
8
9/// `NUMERIC_MIN_SIG_DIGITS`, the significant digits a quotient keeps at least.
10const MIN_SIG_DIGITS: i64 = 16;
11/// `NUMERIC_MAX_DISPLAY_SCALE`, the most digits after the point a quotient takes.
12const MAX_DISPLAY_SCALE: i64 = 1000;
13/// `DEC_DIGITS`, the decimal digits in one of PostgreSQL's base-10000 digits.
14const DEC_DIGITS: i64 = 4;
15
16impl PgNumeric {
17    /// `numeric + numeric`, PostgreSQL's `numeric_add`, exact at the larger display scale.
18    /// `NaN` with anything, and opposite infinities, give `NaN`.
19    ///
20    /// # Errors
21    ///
22    /// [`NumericError::FormatOverflow`] for a sum beyond what PostgreSQL stores.
23    ///
24    /// ```
25    /// use sql_values::postgres::PgNumeric;
26    ///
27    /// let numeric = |text| PgNumeric::parse(text).unwrap();
28    /// assert_eq!(numeric("1.50").checked_add(&numeric("2.250")).unwrap().to_string(), "3.750");
29    /// assert!(PgNumeric::INFINITY.checked_add(&PgNumeric::NEG_INFINITY).unwrap().is_nan());
30    /// ```
31    pub fn checked_add(&self, other: &Self) -> Result<Self, NumericError> {
32        match (&self.0, &other.0) {
33            (Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
34            (Repr::Infinity { negative: left }, Repr::Infinity { negative: right })
35                if left != right =>
36            {
37                Ok(Self::NAN)
38            }
39            (Repr::Infinity { .. }, _) => Ok(self.clone()),
40            (_, Repr::Infinity { .. }) => Ok(other.clone()),
41            (Repr::Finite(left), Repr::Finite(right)) => finite(left.add(right, false)),
42        }
43    }
44
45    /// `numeric - numeric`, PostgreSQL's `numeric_sub`, exact at the larger display scale.
46    /// `NaN` with anything, and like infinities, give `NaN`.
47    ///
48    /// # Errors
49    ///
50    /// [`NumericError::FormatOverflow`] for a difference beyond what PostgreSQL stores.
51    pub fn checked_sub(&self, other: &Self) -> Result<Self, NumericError> {
52        match (&self.0, &other.0) {
53            (Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
54            (Repr::Infinity { negative: left }, Repr::Infinity { negative: right })
55                if left == right =>
56            {
57                Ok(Self::NAN)
58            }
59            (Repr::Infinity { .. }, _) => Ok(self.clone()),
60            (_, &Repr::Infinity { negative }) => Ok(Self(Repr::Infinity {
61                negative: !negative,
62            })),
63            (Repr::Finite(left), Repr::Finite(right)) => finite(left.add(right, true)),
64        }
65    }
66
67    /// `numeric * numeric`, PostgreSQL's `numeric_mul`, exact at the sum of the display scales,
68    /// rounded to 16383 digits after the point beyond them. `NaN` with anything, and an infinity
69    /// by zero, give `NaN`.
70    ///
71    /// # Errors
72    ///
73    /// [`NumericError::FormatOverflow`] for a product beyond what PostgreSQL stores.
74    ///
75    /// ```
76    /// use sql_values::postgres::{NumericError, PgNumeric};
77    ///
78    /// let numeric = |text| PgNumeric::parse(text).unwrap();
79    /// assert_eq!(numeric("1.5").checked_mul(&numeric("2.25")).unwrap().to_string(), "3.375");
80    /// assert!(PgNumeric::INFINITY.checked_mul(&numeric("0")).unwrap().is_nan());
81    /// assert_eq!(
82    ///     numeric("1e131071").checked_mul(&numeric("10")),
83    ///     Err(NumericError::FormatOverflow),
84    /// );
85    /// ```
86    pub fn checked_mul(&self, other: &Self) -> Result<Self, NumericError> {
87        match (&self.0, &other.0) {
88            (Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
89            (Repr::Finite(left), Repr::Finite(right)) => finite(left.mul(right)),
90            _ if self.is_zero() || other.is_zero() => Ok(Self::NAN),
91            _ => Ok(Self(Repr::Infinity {
92                negative: self.is_negative() != other.is_negative(),
93            })),
94        }
95    }
96
97    /// `numeric / numeric`, PostgreSQL's `numeric_div`, rounded half away from zero to the scale
98    /// `select_div_scale` picks, at least 16 significant digits and at least either display
99    /// scale, up to 1000 digits after the point. `NaN` with anything, and an infinity by an
100    /// infinity, give `NaN`, and a finite value by an infinity gives zero.
101    ///
102    /// # Errors
103    ///
104    /// [`NumericError::DivisionByZero`] for a divisor of zero, and
105    /// [`NumericError::FormatOverflow`] for a quotient beyond what PostgreSQL stores.
106    ///
107    /// ```
108    /// use sql_values::postgres::{NumericError, PgNumeric};
109    ///
110    /// let numeric = |text| PgNumeric::parse(text).unwrap();
111    /// let third = numeric("10").checked_div(&numeric("3")).unwrap();
112    /// assert_eq!(third.to_string(), "3.3333333333333333");
113    /// assert_eq!(
114    ///     PgNumeric::INFINITY.checked_div(&numeric("0")),
115    ///     Err(NumericError::DivisionByZero),
116    /// );
117    /// ```
118    pub fn checked_div(&self, other: &Self) -> Result<Self, NumericError> {
119        match (&self.0, &other.0) {
120            (Repr::NaN, _) | (_, Repr::NaN) | (Repr::Infinity { .. }, Repr::Infinity { .. }) => {
121                Ok(Self::NAN)
122            }
123            (Repr::Finite(left), Repr::Finite(right)) => finite(left.div(right)?),
124            (Repr::Finite(_), Repr::Infinity { .. }) => Ok(Self(Repr::Finite(Finite::zero(0)))),
125            (Repr::Infinity { negative }, Repr::Finite(right)) => {
126                if right.digits.is_empty() {
127                    Err(NumericError::DivisionByZero)
128                } else {
129                    Ok(Self(Repr::Infinity {
130                        negative: *negative != right.negative,
131                    }))
132                }
133            }
134        }
135    }
136
137    /// `numeric % numeric`, PostgreSQL's `numeric_mod`, the remainder of the quotient truncated
138    /// toward zero, with the dividend's sign, at the larger display scale. `NaN` with anything,
139    /// and an infinity by anything but zero, give `NaN`, and a finite value by an infinity is
140    /// itself.
141    ///
142    /// # Errors
143    ///
144    /// [`NumericError::DivisionByZero`] for a divisor of zero.
145    ///
146    /// ```
147    /// use sql_values::postgres::PgNumeric;
148    ///
149    /// let numeric = |text| PgNumeric::parse(text).unwrap();
150    /// assert_eq!(numeric("-7.5").checked_rem(&numeric("2")).unwrap().to_string(), "-1.5");
151    /// ```
152    pub fn checked_rem(&self, other: &Self) -> Result<Self, NumericError> {
153        match (&self.0, &other.0) {
154            (Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
155            (Repr::Infinity { .. }, _) if other.is_zero() => Err(NumericError::DivisionByZero),
156            (Repr::Infinity { .. }, _) => Ok(Self::NAN),
157            (Repr::Finite(_), Repr::Infinity { .. }) => Ok(self.clone()),
158            (Repr::Finite(left), Repr::Finite(right)) => finite(left.rem(right)?),
159        }
160    }
161
162    /// `abs(numeric)`, PostgreSQL's `numeric_abs`, keeping the display scale.
163    #[must_use]
164    pub fn abs(mut self) -> Self {
165        match &mut self.0 {
166            Repr::NaN => {}
167            Repr::Infinity { negative } => *negative = false,
168            Repr::Finite(finite) => finite.negative = false,
169        }
170        self
171    }
172
173    /// `round(numeric, scale)`, PostgreSQL's `numeric_round`, half away from zero to `scale`
174    /// digits after the point, before it for a negative scale, with a display scale of `scale`
175    /// or zero. `round(numeric)` is a scale of `0`. `NaN` and the infinities are left as they
176    /// are.
177    ///
178    /// # Errors
179    ///
180    /// [`NumericError::FormatOverflow`] where rounding up carries past what PostgreSQL stores.
181    ///
182    /// ```
183    /// use sql_values::postgres::PgNumeric;
184    ///
185    /// let numeric = |text| PgNumeric::parse(text).unwrap();
186    /// assert_eq!(numeric("-2.5").round(0).unwrap().to_string(), "-3");
187    /// assert_eq!(numeric("1234.5678").round(-2).unwrap().to_string(), "1200");
188    /// assert_eq!(numeric("1.5").round(3).unwrap().to_string(), "1.500");
189    /// ```
190    pub fn round(self, scale: i32) -> Result<Self, NumericError> {
191        let Repr::Finite(mut rounded) = self.0 else {
192            return Ok(self);
193        };
194        // An extra digit before the point, in case the leading digit rounds up.
195        rounded.round(i64::from(scale).clamp(-(MAX_WEIGHT + 2), MAX_DSCALE));
196        finite(rounded)
197    }
198
199    /// `trunc(numeric, scale)`, PostgreSQL's `numeric_trunc`, toward zero at `scale` digits after
200    /// the point, before it for a negative scale, with a display scale of `scale` or zero.
201    /// `trunc(numeric)` is a scale of `0`. `NaN` and the infinities are left as they are.
202    ///
203    /// ```
204    /// use sql_values::postgres::PgNumeric;
205    ///
206    /// assert_eq!(PgNumeric::parse("-1.99").unwrap().trunc(1).to_string(), "-1.9");
207    /// ```
208    #[must_use]
209    pub fn trunc(self, scale: i32) -> Self {
210        let Repr::Finite(mut truncated) = self.0 else {
211            return self;
212        };
213        truncated.truncate(i64::from(scale).clamp(-(MAX_WEIGHT + 1), MAX_DSCALE));
214        Self(Repr::Finite(truncated))
215    }
216
217    /// `floor(numeric)`, PostgreSQL's `numeric_floor`, the greatest whole number not above the
218    /// value. `NaN` and the infinities are left as they are.
219    ///
220    /// # Errors
221    ///
222    /// [`NumericError::FormatOverflow`] where the step down carries past what PostgreSQL stores.
223    ///
224    /// ```
225    /// use sql_values::postgres::PgNumeric;
226    ///
227    /// assert_eq!(PgNumeric::parse("-0.5").unwrap().floor().unwrap().to_string(), "-1");
228    /// ```
229    pub fn floor(self) -> Result<Self, NumericError> {
230        self.whole(true)
231    }
232
233    /// `ceil(numeric)`, PostgreSQL's `numeric_ceil`, the least whole number not below the value.
234    /// `NaN` and the infinities are left as they are.
235    ///
236    /// # Errors
237    ///
238    /// [`NumericError::FormatOverflow`] where the step up carries past what PostgreSQL stores.
239    ///
240    /// ```
241    /// use sql_values::postgres::PgNumeric;
242    ///
243    /// assert_eq!(PgNumeric::parse("-0.5").unwrap().ceil().unwrap().to_string(), "0");
244    /// ```
245    pub fn ceil(self) -> Result<Self, NumericError> {
246        self.whole(false)
247    }
248
249    /// `floor_var` when `down`, else `ceil_var`, the value truncated and then stepped by one away
250    /// from zero when that dropped a fraction on the side it rounds toward.
251    fn whole(self, down: bool) -> Result<Self, NumericError> {
252        let Repr::Finite(value) = self.0 else {
253            return Ok(self);
254        };
255        let had_fraction = !value.digits.is_empty() && value.exponent() < 0;
256        let negative = value.negative;
257        let mut whole = value;
258        whole.truncate(0);
259        if had_fraction && negative == down {
260            let step = Finite::from_i64(if down { -1 } else { 1 });
261            whole = whole.add(&step, false);
262        }
263        finite(whole)
264    }
265}
266
267/// `numeric_uminus`, flipping the sign of every value but zero and `NaN`, keeping the display
268/// scale.
269impl Neg for PgNumeric {
270    type Output = Self;
271
272    fn neg(mut self) -> Self {
273        match &mut self.0 {
274            Repr::NaN => {}
275            Repr::Infinity { negative } => *negative = !*negative,
276            Repr::Finite(finite) => finite.negative = !finite.negative && !finite.digits.is_empty(),
277        }
278        self
279    }
280}
281
282impl Finite {
283    /// `add_var`, or `sub_var` when `subtract`, exact at the larger display scale.
284    fn add(&self, other: &Self, subtract: bool) -> Self {
285        let other_negative = other.negative != subtract;
286        let exponent = self.exponent().min(other.exponent());
287        let left = self.mantissa(self.exponent() - exponent);
288        let right = other.mantissa(other.exponent() - exponent);
289        let dscale = self.dscale.max(other.dscale);
290        let (negative, magnitude) = if self.negative == other_negative {
291            (self.negative, left.add(&right))
292        } else {
293            match left.cmp(&right) {
294                Ordering::Less => (other_negative, right.sub(&left)),
295                _ => (self.negative, left.sub(&right)),
296            }
297        };
298        Self::from_mantissa(negative, &magnitude, exponent, dscale)
299    }
300
301    /// `numeric_mul`'s exact `mul_var`, rounded to `NUMERIC_DSCALE_MAX` beyond it.
302    fn mul(&self, other: &Self) -> Self {
303        let product = self.mantissa(0).mul(&other.mantissa(0));
304        let mut result = Self::from_mantissa(
305            self.negative != other.negative,
306            &product,
307            self.exponent() + other.exponent(),
308            self.dscale + other.dscale,
309        );
310        if result.dscale > MAX_DSCALE {
311            result.round(MAX_DSCALE);
312        }
313        result
314    }
315
316    /// `numeric_div`'s exact `div_var` rounded at the scale `select_div_scale` picks.
317    fn div(&self, other: &Self) -> Result<Self, NumericError> {
318        if other.digits.is_empty() {
319            return Err(NumericError::DivisionByZero);
320        }
321        let scale = self.select_div_scale(other);
322        // The exact quotient truncated one digit further rounds half away from zero at `scale`.
323        let mut quotient = self.truncated_quotient(other, scale + 1);
324        quotient.round(scale);
325        Ok(quotient)
326    }
327
328    /// `mod_var`, `self - other * trunc(self / other)`, at the larger display scale.
329    fn rem(&self, other: &Self) -> Result<Self, NumericError> {
330        if other.digits.is_empty() {
331            return Err(NumericError::DivisionByZero);
332        }
333        let exponent = self.exponent().min(other.exponent());
334        let dividend = self.mantissa(self.exponent() - exponent);
335        let divisor = other.mantissa(other.exponent() - exponent);
336        let (_, remainder) = dividend.div_rem(&divisor);
337        let dscale = self.dscale.max(other.dscale);
338        Ok(Self::from_mantissa(
339            self.negative,
340            &remainder,
341            exponent,
342            dscale,
343        ))
344    }
345
346    /// The exact quotient truncated toward zero at `scale` digits after the point.
347    fn truncated_quotient(&self, other: &Self, scale: i64) -> Self {
348        let shift = self.exponent() - other.exponent() + scale;
349        let (dividend, divisor) = if shift >= 0 {
350            (self.mantissa(shift), other.mantissa(0))
351        } else {
352            (self.mantissa(0), other.mantissa(-shift))
353        };
354        let (quotient, _) = dividend.div_rem(&divisor);
355        Self::from_mantissa(
356            self.negative != other.negative,
357            &quotient,
358            -scale,
359            scale.max(0),
360        )
361    }
362
363    /// `select_div_scale`, enough digits after the point for 16 significant digits of the
364    /// quotient as PostgreSQL estimates its weight in base-10000 digits, at least either display
365    /// scale, at most 1000.
366    fn select_div_scale(&self, other: &Self) -> i64 {
367        let (left_weight, left_first) = self.leading_nbase_digit();
368        let (right_weight, right_first) = other.leading_nbase_digit();
369        let mut quotient_weight = left_weight - right_weight;
370        if left_first <= right_first {
371            quotient_weight -= 1;
372        }
373        (MIN_SIG_DIGITS - quotient_weight * DEC_DIGITS)
374            .max(self.dscale)
375            .max(other.dscale)
376            .clamp(0, MAX_DISPLAY_SCALE)
377    }
378
379    /// The weight and value of the leading base-10000 digit as PostgreSQL stores the value,
380    /// `(0, 0)` for zero.
381    fn leading_nbase_digit(&self) -> (i64, u16) {
382        if self.digits.is_empty() {
383            return (0, 0);
384        }
385        let weight = self.weight.div_euclid(DEC_DIGITS);
386        let first = (0..DEC_DIGITS).rev().fold(0, |value, offset| {
387            value * 10 + u16::from(self.digit_at(weight * DEC_DIGITS + offset))
388        });
389        (weight, first)
390    }
391}
392
393/// `make_result`, the finite value once checked to fit what PostgreSQL stores.
394fn finite(value: Finite) -> Result<PgNumeric, NumericError> {
395    value.check_storable()?;
396    Ok(PgNumeric(Repr::Finite(value)))
397}