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