Skip to main content

sql_values/postgres/
numeric.rs

1//! PostgreSQL `numeric` values as `numeric_in` reads them, `numeric_out` prints them,
2//! `cmp_numerics` orders them, the `numeric()` length coercion rounds them and the operators and
3//! rounding functions compute them.
4
5mod arithmetic;
6mod magnitude;
7
8use alloc::vec::Vec;
9use core::{
10    cmp::Ordering,
11    fmt,
12    hash::{Hash, Hasher},
13};
14
15use super::cast::{CastError, is_pg_space};
16use magnitude::Magnitude;
17
18/// Why PostgreSQL refuses to read or compute a `numeric`, one variant per message it raises.
19///
20/// ```
21/// use sql_values::postgres::{NumericError, PgNumeric};
22///
23/// assert_eq!(PgNumeric::parse("1.5x"), Err(NumericError::InvalidInputSyntax));
24/// let one = PgNumeric::from(1);
25/// let zero = PgNumeric::from(0);
26/// assert_eq!(one.checked_div(&zero), Err(NumericError::DivisionByZero));
27/// ```
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
29pub enum NumericError {
30    /// Text `numeric_in` cannot read.
31    #[error("invalid input syntax for type numeric")]
32    InvalidInputSyntax,
33    /// A value beyond the weight or display scale PostgreSQL stores.
34    #[error("value overflows numeric format")]
35    FormatOverflow,
36    /// A division or remainder by zero.
37    #[error("division by zero")]
38    DivisionByZero,
39}
40
41/// `NUMERIC_DSCALE_MAX`, the most digits after the point PostgreSQL stores.
42const MAX_DSCALE: i64 = 0x3FFF;
43/// The decimal weight of the leading digit past which PostgreSQL's base-10000 weight leaves
44/// `int16`, `(32767 + 1) * 4 - 1`.
45const MAX_WEIGHT: i64 = 131_071;
46/// `PG_INT32_MAX / 2`, the exponent `set_var_from_str` refuses beyond.
47const MAX_EXPONENT: i64 = 1_073_741_823;
48/// `NUMERIC_MAX_PRECISION`.
49const MAX_PRECISION: u16 = 1000;
50/// `NUMERIC_MIN_SCALE` and `NUMERIC_MAX_SCALE`.
51const SCALE_RANGE: core::ops::RangeInclusive<i16> = -1000..=1000;
52
53/// A PostgreSQL `numeric`, equal, ordered and hashed by value as `cmp_numerics` compares it, with
54/// `NaN` equal to itself and above `Infinity`.
55///
56/// Its [`Display`](fmt::Display) is `numeric_out`, so equal values can print differently.
57///
58/// ```
59/// use sql_values::postgres::PgNumeric;
60///
61/// let numeric = |text| PgNumeric::parse(text).unwrap();
62/// assert_eq!(numeric("1.50"), numeric("1.5"));
63/// assert_eq!(numeric("1.50").to_string(), "1.50");
64/// assert!(numeric("NaN") > numeric("Infinity"));
65/// assert!(numeric("-inf") < numeric("-1e1000"));
66/// assert_eq!(PgNumeric::from(-12_i64), numeric("-12.0"));
67/// ```
68#[derive(Debug, Clone)]
69pub struct PgNumeric(Repr);
70
71#[derive(Debug, Clone)]
72enum Repr {
73    NaN,
74    Infinity { negative: bool },
75    Finite(Finite),
76}
77
78/// A finite value as decimal digits, normalised so that equal values have equal fields except
79/// `dscale`.
80#[derive(Debug, Clone)]
81struct Finite {
82    /// Never set for zero.
83    negative: bool,
84    /// Digits `0..=9` with no leading or trailing zero, empty for zero.
85    digits: Vec<u8>,
86    /// The power of ten of `digits[0]`, `0` for zero.
87    weight: i64,
88    /// The digits printed after the point, never fewer than the value has.
89    dscale: i64,
90}
91
92/// The modifier of a `numeric(p, s)` type, the precision and scale it rounds to.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct NumericTypmod {
95    precision: u16,
96    scale: i16,
97}
98
99impl NumericTypmod {
100    /// The total decimal precision.
101    #[must_use]
102    pub const fn precision(self) -> u16 {
103        self.precision
104    }
105
106    /// The decimal scale, which may be negative.
107    #[must_use]
108    pub const fn scale(self) -> i16 {
109        self.scale
110    }
111
112    /// `numerictypmodin`, or `None` for a precision outside `1..=1000` or a scale outside
113    /// `-1000..=1000`. `numeric(p)` is a scale of `0`.
114    ///
115    /// ```
116    /// use sql_values::postgres::NumericTypmod;
117    ///
118    /// assert!(NumericTypmod::new(4, 1).is_some());
119    /// assert!(NumericTypmod::new(2, -3).is_some());
120    /// assert!(NumericTypmod::new(0, 0).is_none());
121    /// assert!(NumericTypmod::new(1001, 0).is_none());
122    /// ```
123    #[must_use]
124    pub fn new(precision: u16, scale: i16) -> Option<Self> {
125        ((1..=MAX_PRECISION).contains(&precision) && SCALE_RANGE.contains(&scale))
126            .then_some(Self { precision, scale })
127    }
128}
129
130impl PgNumeric {
131    /// `NaN`, equal to itself and above every other value.
132    pub const NAN: Self = Self(Repr::NaN);
133    /// `Infinity`.
134    pub const INFINITY: Self = Self(Repr::Infinity { negative: false });
135    /// `-Infinity`.
136    pub const NEG_INFINITY: Self = Self(Repr::Infinity { negative: true });
137
138    /// PostgreSQL's `numeric_in` with no type modifier, reading blanks, a sign, a decimal number
139    /// with an optional exponent, a `0x`, `0o` or `0b` integer, `NaN` or an infinity, then
140    /// blanks.
141    ///
142    /// # Errors
143    ///
144    /// [`NumericError::InvalidInputSyntax`] for text `numeric_in` cannot read, and
145    /// [`NumericError::FormatOverflow`] for a value beyond what PostgreSQL stores.
146    ///
147    /// ```
148    /// use sql_values::postgres::{NumericError, PgNumeric};
149    ///
150    /// assert_eq!(PgNumeric::parse(" -1_000.50 ").unwrap().to_string(), "-1000.50");
151    /// assert_eq!(PgNumeric::parse("0x1F").unwrap().to_string(), "31");
152    /// assert_eq!(PgNumeric::parse("1e-3").unwrap().to_string(), "0.001");
153    /// assert!(PgNumeric::parse("-inf").unwrap().is_infinite());
154    /// assert_eq!(PgNumeric::parse("1e131072"), Err(NumericError::FormatOverflow));
155    /// ```
156    pub fn parse(text: &str) -> Result<Self, NumericError> {
157        let syntax = NumericError::InvalidInputSyntax;
158        let bytes = text.as_bytes();
159        let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
160        let signed = &bytes[start..];
161        let (negative, unsigned) = match signed.split_first() {
162            Some((b'-', rest)) => (true, rest),
163            Some((b'+', rest)) => (false, rest),
164            _ => (false, signed),
165        };
166        let (value, rest) = match unsigned.first() {
167            Some(b'0'..=b'9' | b'.') => {
168                let (base, digits) = match unsigned {
169                    [b'0', b'x' | b'X', digits @ ..] => (16, digits),
170                    [b'0', b'o' | b'O', digits @ ..] => (8, digits),
171                    [b'0', b'b' | b'B', digits @ ..] => (2, digits),
172                    _ => (10, unsigned),
173                };
174                let (mut finite, rest) = if base == 10 {
175                    parse_decimal(digits)?
176                } else {
177                    parse_non_decimal(digits, base)?
178                };
179                finite.negative = negative && !finite.digits.is_empty();
180                (Repr::Finite(finite), rest)
181            }
182            _ => {
183                if starts_with_ignore_case(signed, b"NaN") {
184                    (Repr::NaN, &signed[3..])
185                } else if starts_with_ignore_case(unsigned, b"Infinity") {
186                    (Repr::Infinity { negative }, &unsigned[8..])
187                } else if starts_with_ignore_case(unsigned, b"inf") {
188                    (Repr::Infinity { negative }, &unsigned[3..])
189                } else {
190                    return Err(syntax);
191                }
192            }
193        };
194        if !rest.iter().all(|&b| is_pg_space(b)) {
195            return Err(syntax);
196        }
197        if let Repr::Finite(finite) = &value {
198            finite.check_storable()?;
199        }
200        Ok(Self(value))
201    }
202
203    /// Whether the value is `NaN`.
204    #[must_use]
205    pub const fn is_nan(&self) -> bool {
206        matches!(self.0, Repr::NaN)
207    }
208
209    /// Whether the value is `Infinity` or `-Infinity`.
210    #[must_use]
211    pub const fn is_infinite(&self) -> bool {
212        matches!(self.0, Repr::Infinity { .. })
213    }
214
215    /// Whether the value is zero, at any display scale.
216    #[must_use]
217    pub fn is_zero(&self) -> bool {
218        matches!(&self.0, Repr::Finite(finite) if finite.digits.is_empty())
219    }
220
221    /// Whether the value is below zero, `-Infinity` included.
222    #[must_use]
223    pub const fn is_negative(&self) -> bool {
224        matches!(
225            self.0,
226            Repr::Infinity { negative: true } | Repr::Finite(Finite { negative: true, .. })
227        )
228    }
229
230    /// Whether the value is a finite whole number, at any display scale.
231    ///
232    /// ```
233    /// use sql_values::postgres::PgNumeric;
234    ///
235    /// assert!(PgNumeric::parse("2.00").unwrap().is_integral());
236    /// assert!(!PgNumeric::parse("2.5").unwrap().is_integral());
237    /// assert!(!PgNumeric::INFINITY.is_integral());
238    /// ```
239    #[must_use]
240    pub fn is_integral(&self) -> bool {
241        matches!(&self.0, Repr::Finite(finite) if finite.exponent() >= 0)
242    }
243
244    /// The `numeric()` length coercion to `typmod`, rounding half away from zero.
245    pub(crate) fn apply_typmod(self, typmod: NumericTypmod) -> Result<Self, CastError> {
246        match self.0 {
247            Repr::NaN => Ok(self),
248            Repr::Infinity { .. } => Err(CastError::NumericFieldOverflow),
249            Repr::Finite(mut finite) => {
250                let scale = i64::from(typmod.scale);
251                finite.round(scale);
252                let integer_digits = i64::from(typmod.precision) - scale;
253                if !finite.digits.is_empty() && finite.weight + 1 > integer_digits {
254                    return Err(CastError::NumericFieldOverflow);
255                }
256                Ok(Self(Repr::Finite(finite)))
257            }
258        }
259    }
260
261    /// `numericvar_to_int64`, the value rounded half away from zero, or `None` for a value
262    /// beyond `i64` or not finite.
263    #[must_use]
264    pub fn to_i64_rounded(&self) -> Option<i64> {
265        let Repr::Finite(finite) = &self.0 else {
266            return None;
267        };
268        if finite.weight >= 19 {
269            return None;
270        }
271        let magnitude = (0..=finite.weight).rev().fold(0i128, |magnitude, power| {
272            magnitude * 10 + i128::from(finite.digit_at(power))
273        }) + i128::from(finite.digit_at(-1) >= 5);
274        i64::try_from(if finite.negative {
275            -magnitude
276        } else {
277            magnitude
278        })
279        .ok()
280    }
281
282    /// `int64_div_fast_to_numeric`, `value / 10^scale` printed with `scale` digits after the
283    /// point.
284    pub(crate) fn from_scaled_i64(value: i64, scale: i64) -> Self {
285        let mut finite = Finite::from_i64(value);
286        if !finite.digits.is_empty() {
287            finite.weight -= scale;
288        }
289        finite.dscale = scale;
290        Self(Repr::Finite(finite))
291    }
292
293    /// The order class of the value, rising from `-Infinity` through negative, zero, positive and
294    /// `Infinity` to `NaN`.
295    fn class(&self) -> i8 {
296        match &self.0 {
297            Repr::Infinity { negative: true } => -2,
298            Repr::Finite(finite) if finite.digits.is_empty() => 0,
299            Repr::Finite(finite) if finite.negative => -1,
300            Repr::Finite(_) => 1,
301            Repr::Infinity { negative: false } => 2,
302            Repr::NaN => 3,
303        }
304    }
305
306    /// What `cmp_numerics` orders the value by.
307    fn key(&self) -> Key<'_> {
308        match &self.0 {
309            Repr::Finite(finite) => Key {
310                class: self.class(),
311                weight: finite.weight,
312                digits: &finite.digits,
313            },
314            _ => Key {
315                class: self.class(),
316                weight: 0,
317                digits: &[],
318            },
319        }
320    }
321
322    /// The order of the value against the `numeric` of an integer, without making it.
323    #[must_use]
324    pub fn cmp_integer(&self, value: i64) -> Ordering {
325        self.key().order(&IntegerDigits::new(value).key())
326    }
327
328    /// Feeds `state` what the `numeric` of an integer feeds it, without making it.
329    pub(crate) fn hash_integer<H: Hasher>(value: i64, state: &mut H) {
330        IntegerDigits::new(value).key().hash(state);
331    }
332}
333
334/// What `cmp_numerics` orders a value by, its order class and, for a nonzero finite value, the
335/// weight and digits of its magnitude.
336#[derive(Hash)]
337struct Key<'a> {
338    class: i8,
339    weight: i64,
340    digits: &'a [u8],
341}
342
343impl Key<'_> {
344    /// The class first, then the magnitude, reversed for a negative value.
345    fn order(&self, other: &Key<'_>) -> Ordering {
346        self.class.cmp(&other.class).then_with(|| {
347            let magnitude = self
348                .weight
349                .cmp(&other.weight)
350                .then_with(|| self.digits.cmp(other.digits));
351            if self.class < 0 {
352                magnitude.reverse()
353            } else {
354                magnitude
355            }
356        })
357    }
358}
359
360/// The decimal digits of an `i64` as `int64_to_numeric` makes them, normalised as [`Finite`]
361/// holds them, without allocating.
362struct IntegerDigits {
363    negative: bool,
364    /// The digits, the first `len` of them significant.
365    digits: [u8; 19],
366    len: usize,
367    weight: i64,
368}
369
370impl IntegerDigits {
371    fn new(value: i64) -> Self {
372        let mut digits = [0; 19];
373        let mut count = 0;
374        let mut rest = value.unsigned_abs();
375        while rest > 0 {
376            digits[count] = u8::try_from(rest % 10).expect("a decimal digit fits u8");
377            rest /= 10;
378            count += 1;
379        }
380        digits[..count].reverse();
381        let len = digits[..count]
382            .iter()
383            .rposition(|&digit| digit != 0)
384            .map_or(0, |last| last + 1);
385        let weight = if len == 0 {
386            0
387        } else {
388            i64::try_from(count).expect("an i64 has 19 digits") - 1
389        };
390        Self {
391            negative: value < 0,
392            digits,
393            len,
394            weight,
395        }
396    }
397
398    fn digits(&self) -> &[u8] {
399        &self.digits[..self.len]
400    }
401
402    fn key(&self) -> Key<'_> {
403        let class = match (self.len, self.negative) {
404            (0, _) => 0,
405            (_, true) => -1,
406            (_, false) => 1,
407        };
408        Key {
409            class,
410            weight: self.weight,
411            digits: self.digits(),
412        }
413    }
414}
415
416impl Finite {
417    /// Drop leading and trailing zero digits, giving zero its unsigned form.
418    fn normalise(&mut self) {
419        let leading = self.digits.iter().take_while(|&&d| d == 0).count();
420        self.digits.drain(..leading);
421        self.weight -= i64::try_from(leading).expect("a digit count fits i64");
422        let kept = self
423            .digits
424            .iter()
425            .rposition(|&d| d != 0)
426            .map_or(0, |last| last + 1);
427        self.digits.truncate(kept);
428        if self.digits.is_empty() {
429            self.negative = false;
430            self.weight = 0;
431        }
432    }
433
434    /// The digit at `power` of ten.
435    fn digit_at(&self, power: i64) -> u8 {
436        usize::try_from(self.weight - power)
437            .ok()
438            .and_then(|index| self.digits.get(index).copied())
439            .unwrap_or(0)
440    }
441
442    /// `round_var` to `scale` digits after the point, then `apply_typmod`'s non-negative display
443    /// scale.
444    fn round(&mut self, scale: i64) {
445        self.dscale = scale.max(0);
446        let kept = self.weight + scale + 1;
447        let Ok(kept) = usize::try_from(kept) else {
448            *self = Self::zero(self.dscale);
449            return;
450        };
451        if kept >= self.digits.len() {
452            return;
453        }
454        let round_up = self.digits[kept] >= 5;
455        self.digits.truncate(kept);
456        if round_up {
457            let carried = self.digits.iter_mut().rev().try_for_each(|digit| {
458                if *digit == 9 {
459                    *digit = 0;
460                    Ok(())
461                } else {
462                    *digit += 1;
463                    Err(())
464                }
465            });
466            if carried.is_ok() {
467                self.digits.insert(0, 1);
468                self.weight += 1;
469            }
470        }
471        self.normalise();
472    }
473
474    const fn zero(dscale: i64) -> Self {
475        Self {
476            negative: false,
477            digits: Vec::new(),
478            weight: 0,
479            dscale,
480        }
481    }
482
483    /// `int64_to_numeric`.
484    fn from_i64(value: i64) -> Self {
485        let integer = IntegerDigits::new(value);
486        Self {
487            negative: integer.negative,
488            digits: integer.digits().to_vec(),
489            weight: integer.weight,
490            dscale: 0,
491        }
492    }
493
494    /// The power of ten of the last digit, `1` for zero.
495    fn exponent(&self) -> i64 {
496        self.weight + 1 - i64::try_from(self.digits.len()).expect("a digit count fits i64")
497    }
498
499    /// The digits as an integer followed by `zeros` zeros, the value's magnitude over
500    /// `10^(exponent - zeros)`.
501    fn mantissa(&self, zeros: i64) -> Magnitude {
502        let zeros = usize::try_from(zeros).expect("a shift toward a lower exponent");
503        Magnitude::from_digits(&self.digits, zeros)
504    }
505
506    /// The value `±mantissa × 10^exponent` printed with `dscale` digits after the point.
507    fn from_mantissa(negative: bool, mantissa: &Magnitude, exponent: i64, dscale: i64) -> Self {
508        let digits = mantissa.decimal_digits();
509        let weight = exponent + i64::try_from(digits.len()).expect("a digit count fits i64") - 1;
510        let mut finite = Self {
511            negative,
512            digits,
513            weight,
514            dscale,
515        };
516        finite.normalise();
517        finite
518    }
519
520    /// `trunc_var` toward zero at `scale` digits after the point, with a non-negative display
521    /// scale.
522    fn truncate(&mut self, scale: i64) {
523        self.dscale = scale.max(0);
524        let kept = usize::try_from(self.weight + scale + 1).unwrap_or(0);
525        if kept < self.digits.len() {
526            self.digits.truncate(kept);
527            self.normalise();
528        }
529    }
530
531    /// `make_result`'s check that the weight and display scale fit their stored fields.
532    fn check_storable(&self) -> Result<(), NumericError> {
533        let weight_fits = self.digits.is_empty() || self.weight <= MAX_WEIGHT;
534        if weight_fits && self.dscale <= MAX_DSCALE {
535            Ok(())
536        } else {
537            Err(NumericError::FormatOverflow)
538        }
539    }
540}
541
542/// `set_var_from_str` from the first digit or point, returning the value and the unread rest.
543fn parse_decimal(bytes: &[u8]) -> Result<(Finite, &[u8]), NumericError> {
544    let syntax = NumericError::InvalidInputSyntax;
545    let mut digits = Vec::new();
546    let mut integer_digits: i64 = 0;
547    let mut dscale: i64 = 0;
548    let mut have_point = false;
549    let mut at = 0;
550    if bytes.first() == Some(&b'.') {
551        have_point = true;
552        at = 1;
553    }
554    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
555        return Err(syntax);
556    }
557    while let Some(&byte) = bytes.get(at) {
558        match byte {
559            b'0'..=b'9' => {
560                digits.push(byte - b'0');
561                if have_point {
562                    dscale += 1;
563                } else {
564                    integer_digits += 1;
565                }
566                at += 1;
567            }
568            b'.' if have_point => return Err(syntax),
569            b'.' => {
570                have_point = true;
571                at += 1;
572                if bytes.get(at) == Some(&b'_') {
573                    return Err(syntax);
574                }
575            }
576            b'_' => {
577                at += 1;
578                if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
579                    return Err(syntax);
580                }
581            }
582            _ => break,
583        }
584    }
585    let mut weight = integer_digits - 1;
586    if matches!(bytes.get(at), Some(b'e' | b'E')) {
587        at += 1;
588        let negative = match bytes.get(at) {
589            Some(b'+') => {
590                at += 1;
591                false
592            }
593            Some(b'-') => {
594                at += 1;
595                true
596            }
597            _ => false,
598        };
599        if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
600            return Err(syntax);
601        }
602        let mut exponent: i64 = 0;
603        while let Some(&byte) = bytes.get(at) {
604            match byte {
605                b'0'..=b'9' => {
606                    exponent = exponent * 10 + i64::from(byte - b'0');
607                    if exponent > MAX_EXPONENT {
608                        return Err(NumericError::FormatOverflow);
609                    }
610                    at += 1;
611                }
612                b'_' => {
613                    at += 1;
614                    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
615                        return Err(syntax);
616                    }
617                }
618                _ => break,
619            }
620        }
621        let exponent = if negative { -exponent } else { exponent };
622        weight += exponent;
623        dscale = (dscale - exponent).max(0);
624    }
625    let mut finite = Finite {
626        negative: false,
627        digits,
628        weight,
629        dscale,
630    };
631    finite.normalise();
632    Ok((finite, &bytes[at..]))
633}
634
635/// `set_var_from_non_decimal_integer_str` after the base prefix, checking the weight after each
636/// group of digits that fills an `int64` as PostgreSQL does.
637fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), NumericError> {
638    let syntax = NumericError::InvalidInputSyntax;
639    // `mul > PG_INT64_MAX / base` starts a new group after this many digits.
640    let group_len = match base {
641        16 => 15,
642        8 => 20,
643        _ => 62,
644    };
645    let mut limbs = Magnitude::default();
646    let mut group: u64 = 0;
647    let mut group_digits: u32 = 0;
648    let mut at = 0;
649    while let Some(&byte) = bytes.get(at) {
650        if let Some(digit) = char::from(byte).to_digit(base) {
651            if group_digits == group_len {
652                limbs.push_group(group, base, group_digits);
653                if limbs.decimal_weight() > MAX_WEIGHT {
654                    return Err(NumericError::FormatOverflow);
655                }
656                group = 0;
657                group_digits = 0;
658            }
659            group = group * u64::from(base) + u64::from(digit);
660            group_digits += 1;
661            at += 1;
662        } else if byte == b'_' {
663            at += 1;
664            let next_is_digit = bytes
665                .get(at)
666                .is_some_and(|&next| char::from(next).is_digit(base));
667            if !next_is_digit {
668                return Err(syntax);
669            }
670        } else {
671            break;
672        }
673    }
674    if at == 0 {
675        return Err(syntax);
676    }
677    limbs.push_group(group, base, group_digits);
678    if limbs.decimal_weight() > MAX_WEIGHT {
679        return Err(NumericError::FormatOverflow);
680    }
681    Ok((Finite::from_mantissa(false, &limbs, 0, 0), &bytes[at..]))
682}
683
684/// `pg_strncasecmp(bytes, word, word.len()) == 0`.
685fn starts_with_ignore_case(bytes: &[u8], word: &[u8]) -> bool {
686    bytes
687        .get(..word.len())
688        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
689}
690
691/// `numeric_out`.
692impl fmt::Display for PgNumeric {
693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
694        let finite = match &self.0 {
695            Repr::NaN => return f.write_str("NaN"),
696            Repr::Infinity { negative: false } => return f.write_str("Infinity"),
697            Repr::Infinity { negative: true } => return f.write_str("-Infinity"),
698            Repr::Finite(finite) => finite,
699        };
700        if finite.negative {
701            f.write_str("-")?;
702        }
703        let digit = |power| char::from(b'0' + finite.digit_at(power));
704        if finite.weight < 0 || finite.digits.is_empty() {
705            f.write_str("0")?;
706        } else {
707            for power in (0..=finite.weight).rev() {
708                fmt::Write::write_char(f, digit(power))?;
709            }
710        }
711        if finite.dscale > 0 {
712            f.write_str(".")?;
713            for power in 1..=finite.dscale {
714                fmt::Write::write_char(f, digit(-power))?;
715            }
716        }
717        Ok(())
718    }
719}
720
721impl PartialEq for PgNumeric {
722    fn eq(&self, other: &Self) -> bool {
723        self.cmp(other) == Ordering::Equal
724    }
725}
726
727impl Eq for PgNumeric {}
728
729impl PartialOrd for PgNumeric {
730    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
731        Some(self.cmp(other))
732    }
733}
734
735/// `cmp_numerics`, ordering `-Infinity` below finite values by value, then `Infinity`, then `NaN`.
736impl Ord for PgNumeric {
737    fn cmp(&self, other: &Self) -> Ordering {
738        self.key().order(&other.key())
739    }
740}
741
742impl Hash for PgNumeric {
743    fn hash<H: Hasher>(&self, state: &mut H) {
744        self.key().hash(state);
745    }
746}
747
748/// `int2_numeric`.
749impl From<i16> for PgNumeric {
750    fn from(value: i16) -> Self {
751        Self::from(i64::from(value))
752    }
753}
754
755/// `int4_numeric`.
756impl From<i32> for PgNumeric {
757    fn from(value: i32) -> Self {
758        Self::from(i64::from(value))
759    }
760}
761
762/// `int8_numeric`.
763impl From<i64> for PgNumeric {
764    fn from(value: i64) -> Self {
765        Self(Repr::Finite(Finite::from_i64(value)))
766    }
767}
768
769/// Why a `numeric` has no `BigDecimal`, which holds finite values alone.
770#[cfg(feature = "decimal")]
771#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
772#[error("NaN and the infinities have no BigDecimal")]
773pub struct NonFiniteNumeric;
774
775/// The finite value at the scale `numeric_out` prints it with, so `1.50` keeps its scale of 2.
776///
777/// ```
778/// use bigdecimal::BigDecimal;
779/// use sql_values::postgres::{NonFiniteNumeric, PgNumeric};
780///
781/// let numeric = |text| PgNumeric::parse(text).unwrap();
782/// assert_eq!(BigDecimal::try_from(&numeric("1.50")).unwrap().to_string(), "1.50");
783/// assert_eq!(BigDecimal::try_from(&numeric("NaN")), Err(NonFiniteNumeric));
784/// ```
785#[cfg(feature = "decimal")]
786impl TryFrom<&PgNumeric> for bigdecimal::BigDecimal {
787    type Error = NonFiniteNumeric;
788
789    fn try_from(numeric: &PgNumeric) -> Result<Self, Self::Error> {
790        use bigdecimal::num_bigint::{BigInt, Sign};
791
792        let Repr::Finite(finite) = &numeric.0 else {
793            return Err(NonFiniteNumeric);
794        };
795        let sign = if finite.negative {
796            Sign::Minus
797        } else {
798            Sign::Plus
799        };
800        let integer = BigInt::from_radix_be(sign, &finite.digits, 10)
801            .expect("numeric digits are decimal digits");
802        let length = i64::try_from(finite.digits.len()).expect("a numeric has under 2^63 digits");
803        // The last digit sits at power `weight - length + 1` of ten.
804        let scale = length - 1 - finite.weight;
805        Ok(Self::new(integer, scale).with_scale(finite.dscale))
806    }
807}