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    /// `int64_div_fast_to_numeric`, `value / 10^scale` printed with `scale` digits after the
271    /// point.
272    pub(crate) fn from_scaled_i64(value: i64, scale: i64) -> Self {
273        let mut finite = Finite::from_i64(value);
274        if !finite.digits.is_empty() {
275            finite.weight -= scale;
276        }
277        finite.dscale = scale;
278        Self(Repr::Finite(finite))
279    }
280
281    /// The order class of the value, rising from `-Infinity` through negative, zero, positive and
282    /// `Infinity` to `NaN`.
283    fn class(&self) -> i8 {
284        match &self.0 {
285            Repr::Infinity { negative: true } => -2,
286            Repr::Finite(finite) if finite.digits.is_empty() => 0,
287            Repr::Finite(finite) if finite.negative => -1,
288            Repr::Finite(_) => 1,
289            Repr::Infinity { negative: false } => 2,
290            Repr::NaN => 3,
291        }
292    }
293
294    /// What `cmp_numerics` orders the value by.
295    fn key(&self) -> Key<'_> {
296        match &self.0 {
297            Repr::Finite(finite) => Key {
298                class: self.class(),
299                weight: finite.weight,
300                digits: &finite.digits,
301            },
302            _ => Key {
303                class: self.class(),
304                weight: 0,
305                digits: &[],
306            },
307        }
308    }
309
310    /// The order of the value against the `numeric` of an integer, without making it.
311    pub(crate) fn cmp_integer(&self, value: i64) -> Ordering {
312        self.key().order(&IntegerDigits::new(value).key())
313    }
314
315    /// Feeds `state` what the `numeric` of an integer feeds it, without making it.
316    pub(crate) fn hash_integer<H: Hasher>(value: i64, state: &mut H) {
317        IntegerDigits::new(value).key().hash(state);
318    }
319}
320
321/// What `cmp_numerics` orders a value by, its order class and, for a nonzero finite value, the
322/// weight and digits of its magnitude.
323#[derive(Hash)]
324struct Key<'a> {
325    class: i8,
326    weight: i64,
327    digits: &'a [u8],
328}
329
330impl Key<'_> {
331    /// The class first, then the magnitude, reversed for a negative value.
332    fn order(&self, other: &Key<'_>) -> Ordering {
333        self.class.cmp(&other.class).then_with(|| {
334            let magnitude = self
335                .weight
336                .cmp(&other.weight)
337                .then_with(|| self.digits.cmp(other.digits));
338            if self.class < 0 {
339                magnitude.reverse()
340            } else {
341                magnitude
342            }
343        })
344    }
345}
346
347/// The decimal digits of an `i64` as `int64_to_numeric` makes them, normalised as [`Finite`]
348/// holds them, without allocating.
349struct IntegerDigits {
350    negative: bool,
351    /// The digits, the first `len` of them significant.
352    digits: [u8; 19],
353    len: usize,
354    weight: i64,
355}
356
357impl IntegerDigits {
358    fn new(value: i64) -> Self {
359        let mut digits = [0; 19];
360        let mut count = 0;
361        let mut rest = value.unsigned_abs();
362        while rest > 0 {
363            digits[count] = u8::try_from(rest % 10).expect("a decimal digit fits u8");
364            rest /= 10;
365            count += 1;
366        }
367        digits[..count].reverse();
368        let len = digits[..count]
369            .iter()
370            .rposition(|&digit| digit != 0)
371            .map_or(0, |last| last + 1);
372        let weight = if len == 0 {
373            0
374        } else {
375            i64::try_from(count).expect("an i64 has 19 digits") - 1
376        };
377        Self {
378            negative: value < 0,
379            digits,
380            len,
381            weight,
382        }
383    }
384
385    fn digits(&self) -> &[u8] {
386        &self.digits[..self.len]
387    }
388
389    fn key(&self) -> Key<'_> {
390        let class = match (self.len, self.negative) {
391            (0, _) => 0,
392            (_, true) => -1,
393            (_, false) => 1,
394        };
395        Key {
396            class,
397            weight: self.weight,
398            digits: self.digits(),
399        }
400    }
401}
402
403impl Finite {
404    /// Drop leading and trailing zero digits, giving zero its unsigned form.
405    fn normalise(&mut self) {
406        let leading = self.digits.iter().take_while(|&&d| d == 0).count();
407        self.digits.drain(..leading);
408        self.weight -= i64::try_from(leading).expect("a digit count fits i64");
409        let kept = self
410            .digits
411            .iter()
412            .rposition(|&d| d != 0)
413            .map_or(0, |last| last + 1);
414        self.digits.truncate(kept);
415        if self.digits.is_empty() {
416            self.negative = false;
417            self.weight = 0;
418        }
419    }
420
421    /// The digit at `power` of ten.
422    fn digit_at(&self, power: i64) -> u8 {
423        usize::try_from(self.weight - power)
424            .ok()
425            .and_then(|index| self.digits.get(index).copied())
426            .unwrap_or(0)
427    }
428
429    /// `round_var` to `scale` digits after the point, then `apply_typmod`'s non-negative display
430    /// scale.
431    fn round(&mut self, scale: i64) {
432        self.dscale = scale.max(0);
433        let kept = self.weight + scale + 1;
434        let Ok(kept) = usize::try_from(kept) else {
435            *self = Self::zero(self.dscale);
436            return;
437        };
438        if kept >= self.digits.len() {
439            return;
440        }
441        let round_up = self.digits[kept] >= 5;
442        self.digits.truncate(kept);
443        if round_up {
444            let carried = self.digits.iter_mut().rev().try_for_each(|digit| {
445                if *digit == 9 {
446                    *digit = 0;
447                    Ok(())
448                } else {
449                    *digit += 1;
450                    Err(())
451                }
452            });
453            if carried.is_ok() {
454                self.digits.insert(0, 1);
455                self.weight += 1;
456            }
457        }
458        self.normalise();
459    }
460
461    const fn zero(dscale: i64) -> Self {
462        Self {
463            negative: false,
464            digits: Vec::new(),
465            weight: 0,
466            dscale,
467        }
468    }
469
470    /// `int64_to_numeric`.
471    fn from_i64(value: i64) -> Self {
472        let integer = IntegerDigits::new(value);
473        Self {
474            negative: integer.negative,
475            digits: integer.digits().to_vec(),
476            weight: integer.weight,
477            dscale: 0,
478        }
479    }
480
481    /// The power of ten of the last digit, `1` for zero.
482    fn exponent(&self) -> i64 {
483        self.weight + 1 - i64::try_from(self.digits.len()).expect("a digit count fits i64")
484    }
485
486    /// The digits as an integer followed by `zeros` zeros, the value's magnitude over
487    /// `10^(exponent - zeros)`.
488    fn mantissa(&self, zeros: i64) -> Magnitude {
489        let zeros = usize::try_from(zeros).expect("a shift toward a lower exponent");
490        Magnitude::from_digits(&self.digits, zeros)
491    }
492
493    /// The value `±mantissa × 10^exponent` printed with `dscale` digits after the point.
494    fn from_mantissa(negative: bool, mantissa: &Magnitude, exponent: i64, dscale: i64) -> Self {
495        let digits = mantissa.decimal_digits();
496        let weight = exponent + i64::try_from(digits.len()).expect("a digit count fits i64") - 1;
497        let mut finite = Self {
498            negative,
499            digits,
500            weight,
501            dscale,
502        };
503        finite.normalise();
504        finite
505    }
506
507    /// `trunc_var` toward zero at `scale` digits after the point, with a non-negative display
508    /// scale.
509    fn truncate(&mut self, scale: i64) {
510        self.dscale = scale.max(0);
511        let kept = usize::try_from(self.weight + scale + 1).unwrap_or(0);
512        if kept < self.digits.len() {
513            self.digits.truncate(kept);
514            self.normalise();
515        }
516    }
517
518    /// `make_result`'s check that the weight and display scale fit their stored fields.
519    fn check_storable(&self) -> Result<(), NumericError> {
520        let weight_fits = self.digits.is_empty() || self.weight <= MAX_WEIGHT;
521        if weight_fits && self.dscale <= MAX_DSCALE {
522            Ok(())
523        } else {
524            Err(NumericError::FormatOverflow)
525        }
526    }
527}
528
529/// `set_var_from_str` from the first digit or point, returning the value and the unread rest.
530fn parse_decimal(bytes: &[u8]) -> Result<(Finite, &[u8]), NumericError> {
531    let syntax = NumericError::InvalidInputSyntax;
532    let mut digits = Vec::new();
533    let mut integer_digits: i64 = 0;
534    let mut dscale: i64 = 0;
535    let mut have_point = false;
536    let mut at = 0;
537    if bytes.first() == Some(&b'.') {
538        have_point = true;
539        at = 1;
540    }
541    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
542        return Err(syntax);
543    }
544    while let Some(&byte) = bytes.get(at) {
545        match byte {
546            b'0'..=b'9' => {
547                digits.push(byte - b'0');
548                if have_point {
549                    dscale += 1;
550                } else {
551                    integer_digits += 1;
552                }
553                at += 1;
554            }
555            b'.' if have_point => return Err(syntax),
556            b'.' => {
557                have_point = true;
558                at += 1;
559                if bytes.get(at) == Some(&b'_') {
560                    return Err(syntax);
561                }
562            }
563            b'_' => {
564                at += 1;
565                if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
566                    return Err(syntax);
567                }
568            }
569            _ => break,
570        }
571    }
572    let mut weight = integer_digits - 1;
573    if matches!(bytes.get(at), Some(b'e' | b'E')) {
574        at += 1;
575        let negative = match bytes.get(at) {
576            Some(b'+') => {
577                at += 1;
578                false
579            }
580            Some(b'-') => {
581                at += 1;
582                true
583            }
584            _ => false,
585        };
586        if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
587            return Err(syntax);
588        }
589        let mut exponent: i64 = 0;
590        while let Some(&byte) = bytes.get(at) {
591            match byte {
592                b'0'..=b'9' => {
593                    exponent = exponent * 10 + i64::from(byte - b'0');
594                    if exponent > MAX_EXPONENT {
595                        return Err(NumericError::FormatOverflow);
596                    }
597                    at += 1;
598                }
599                b'_' => {
600                    at += 1;
601                    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
602                        return Err(syntax);
603                    }
604                }
605                _ => break,
606            }
607        }
608        let exponent = if negative { -exponent } else { exponent };
609        weight += exponent;
610        dscale = (dscale - exponent).max(0);
611    }
612    let mut finite = Finite {
613        negative: false,
614        digits,
615        weight,
616        dscale,
617    };
618    finite.normalise();
619    Ok((finite, &bytes[at..]))
620}
621
622/// `set_var_from_non_decimal_integer_str` after the base prefix, checking the weight after each
623/// group of digits that fills an `int64` as PostgreSQL does.
624fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), NumericError> {
625    let syntax = NumericError::InvalidInputSyntax;
626    // `mul > PG_INT64_MAX / base` starts a new group after this many digits.
627    let group_len = match base {
628        16 => 15,
629        8 => 20,
630        _ => 62,
631    };
632    let mut limbs = Magnitude::default();
633    let mut group: u64 = 0;
634    let mut group_digits: u32 = 0;
635    let mut at = 0;
636    while let Some(&byte) = bytes.get(at) {
637        if let Some(digit) = char::from(byte).to_digit(base) {
638            if group_digits == group_len {
639                limbs.push_group(group, base, group_digits);
640                if limbs.decimal_weight() > MAX_WEIGHT {
641                    return Err(NumericError::FormatOverflow);
642                }
643                group = 0;
644                group_digits = 0;
645            }
646            group = group * u64::from(base) + u64::from(digit);
647            group_digits += 1;
648            at += 1;
649        } else if byte == b'_' {
650            at += 1;
651            let next_is_digit = bytes
652                .get(at)
653                .is_some_and(|&next| char::from(next).is_digit(base));
654            if !next_is_digit {
655                return Err(syntax);
656            }
657        } else {
658            break;
659        }
660    }
661    if at == 0 {
662        return Err(syntax);
663    }
664    limbs.push_group(group, base, group_digits);
665    if limbs.decimal_weight() > MAX_WEIGHT {
666        return Err(NumericError::FormatOverflow);
667    }
668    Ok((Finite::from_mantissa(false, &limbs, 0, 0), &bytes[at..]))
669}
670
671/// `pg_strncasecmp(bytes, word, word.len()) == 0`.
672fn starts_with_ignore_case(bytes: &[u8], word: &[u8]) -> bool {
673    bytes
674        .get(..word.len())
675        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
676}
677
678/// `numeric_out`.
679impl fmt::Display for PgNumeric {
680    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
681        let finite = match &self.0 {
682            Repr::NaN => return f.write_str("NaN"),
683            Repr::Infinity { negative: false } => return f.write_str("Infinity"),
684            Repr::Infinity { negative: true } => return f.write_str("-Infinity"),
685            Repr::Finite(finite) => finite,
686        };
687        if finite.negative {
688            f.write_str("-")?;
689        }
690        let digit = |power| char::from(b'0' + finite.digit_at(power));
691        if finite.weight < 0 || finite.digits.is_empty() {
692            f.write_str("0")?;
693        } else {
694            for power in (0..=finite.weight).rev() {
695                fmt::Write::write_char(f, digit(power))?;
696            }
697        }
698        if finite.dscale > 0 {
699            f.write_str(".")?;
700            for power in 1..=finite.dscale {
701                fmt::Write::write_char(f, digit(-power))?;
702            }
703        }
704        Ok(())
705    }
706}
707
708impl PartialEq for PgNumeric {
709    fn eq(&self, other: &Self) -> bool {
710        self.cmp(other) == Ordering::Equal
711    }
712}
713
714impl Eq for PgNumeric {}
715
716impl PartialOrd for PgNumeric {
717    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
718        Some(self.cmp(other))
719    }
720}
721
722/// `cmp_numerics`, ordering `-Infinity` below finite values by value, then `Infinity`, then `NaN`.
723impl Ord for PgNumeric {
724    fn cmp(&self, other: &Self) -> Ordering {
725        self.key().order(&other.key())
726    }
727}
728
729impl Hash for PgNumeric {
730    fn hash<H: Hasher>(&self, state: &mut H) {
731        self.key().hash(state);
732    }
733}
734
735/// `int2_numeric`.
736impl From<i16> for PgNumeric {
737    fn from(value: i16) -> Self {
738        Self::from(i64::from(value))
739    }
740}
741
742/// `int4_numeric`.
743impl From<i32> for PgNumeric {
744    fn from(value: i32) -> Self {
745        Self::from(i64::from(value))
746    }
747}
748
749/// `int8_numeric`.
750impl From<i64> for PgNumeric {
751    fn from(value: i64) -> Self {
752        Self(Repr::Finite(Finite::from_i64(value)))
753    }
754}
755
756/// Why a `numeric` has no `BigDecimal`, which holds finite values alone.
757#[cfg(feature = "decimal")]
758#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
759#[error("NaN and the infinities have no BigDecimal")]
760pub struct NonFiniteNumeric;
761
762/// The finite value at the scale `numeric_out` prints it with, so `1.50` keeps its scale of 2.
763///
764/// ```
765/// use bigdecimal::BigDecimal;
766/// use sql_values::postgres::{NonFiniteNumeric, PgNumeric};
767///
768/// let numeric = |text| PgNumeric::parse(text).unwrap();
769/// assert_eq!(BigDecimal::try_from(&numeric("1.50")).unwrap().to_string(), "1.50");
770/// assert_eq!(BigDecimal::try_from(&numeric("NaN")), Err(NonFiniteNumeric));
771/// ```
772#[cfg(feature = "decimal")]
773impl TryFrom<&PgNumeric> for bigdecimal::BigDecimal {
774    type Error = NonFiniteNumeric;
775
776    fn try_from(numeric: &PgNumeric) -> Result<Self, Self::Error> {
777        use bigdecimal::num_bigint::{BigInt, Sign};
778
779        let Repr::Finite(finite) = &numeric.0 else {
780            return Err(NonFiniteNumeric);
781        };
782        let sign = if finite.negative {
783            Sign::Minus
784        } else {
785            Sign::Plus
786        };
787        let integer = BigInt::from_radix_be(sign, &finite.digits, 10)
788            .expect("numeric digits are decimal digits");
789        let length = i64::try_from(finite.digits.len()).expect("a numeric has under 2^63 digits");
790        // The last digit sits at power `weight - length + 1` of ten.
791        let scale = length - 1 - finite.weight;
792        Ok(Self::new(integer, scale).with_scale(finite.dscale))
793    }
794}