Skip to main content

sql_values/
numeric.rs

1//! PostgreSQL `numeric` values as `numeric_in` reads them, `numeric_out` prints them,
2//! `cmp_numerics` orders them and the `numeric()` length coercion rounds them.
3
4use alloc::vec::Vec;
5use core::{
6    cmp::Ordering,
7    fmt,
8    hash::{Hash, Hasher},
9};
10
11use crate::cast::{CastError, PgType, is_pg_space};
12
13/// `NUMERIC_DSCALE_MAX`, the most digits after the point PostgreSQL stores.
14const MAX_DSCALE: i64 = 0x3FFF;
15/// The decimal weight of the leading digit past which PostgreSQL's base-10000 weight leaves
16/// `int16`, `(32767 + 1) * 4 - 1`.
17const MAX_WEIGHT: i64 = 131_071;
18/// `PG_INT32_MAX / 2`, the exponent `set_var_from_str` refuses beyond.
19const MAX_EXPONENT: i64 = 1_073_741_823;
20/// `NUMERIC_MAX_PRECISION`.
21const MAX_PRECISION: u16 = 1000;
22/// `NUMERIC_MIN_SCALE` and `NUMERIC_MAX_SCALE`.
23const SCALE_RANGE: core::ops::RangeInclusive<i16> = -1000..=1000;
24
25/// A PostgreSQL `numeric`, equal, ordered and hashed by value as `cmp_numerics` compares it, with
26/// `NaN` equal to itself and above `Infinity`.
27///
28/// Its [`Display`](fmt::Display) is `numeric_out`, so equal values can print differently.
29///
30/// ```
31/// use sql_values::{CastTarget, CastValue, Literal, cast_literal};
32///
33/// let numeric = |text| match cast_literal(Literal::Quoted(text), CastTarget::Numeric(None)) {
34///     Ok(CastValue::Numeric(value)) => value,
35///     other => panic!("{other:?}"),
36/// };
37/// assert_eq!(numeric("1.50"), numeric("1.5"));
38/// assert_eq!(numeric("1.50").to_string(), "1.50");
39/// assert!(numeric("NaN") > numeric("Infinity"));
40/// assert!(numeric("-inf") < numeric("-1e1000"));
41/// ```
42#[derive(Debug, Clone)]
43pub struct PgNumeric(Repr);
44
45#[derive(Debug, Clone)]
46enum Repr {
47    NaN,
48    Infinity { negative: bool },
49    Finite(Finite),
50}
51
52/// A finite value as decimal digits, normalised so that equal values have equal fields except
53/// `dscale`.
54#[derive(Debug, Clone)]
55struct Finite {
56    /// Never set for zero.
57    negative: bool,
58    /// Digits `0..=9` with no leading or trailing zero, empty for zero.
59    digits: Vec<u8>,
60    /// The power of ten of `digits[0]`, `0` for zero.
61    weight: i64,
62    /// The digits printed after the point, never fewer than the value has.
63    dscale: i64,
64}
65
66/// The modifier of a `numeric(p, s)` type, the precision and scale it rounds to.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68pub struct NumericTypmod {
69    precision: u16,
70    scale: i16,
71}
72
73impl NumericTypmod {
74    /// `numerictypmodin`, or `None` for a precision outside `1..=1000` or a scale outside
75    /// `-1000..=1000`. `numeric(p)` is a scale of `0`.
76    ///
77    /// ```
78    /// use sql_values::NumericTypmod;
79    ///
80    /// assert!(NumericTypmod::new(4, 1).is_some());
81    /// assert!(NumericTypmod::new(2, -3).is_some());
82    /// assert!(NumericTypmod::new(0, 0).is_none());
83    /// assert!(NumericTypmod::new(1001, 0).is_none());
84    /// ```
85    #[must_use]
86    pub fn new(precision: u16, scale: i16) -> Option<Self> {
87        ((1..=MAX_PRECISION).contains(&precision) && SCALE_RANGE.contains(&scale))
88            .then_some(Self { precision, scale })
89    }
90}
91
92impl PgNumeric {
93    /// `numeric_in` with no type modifier, as an unknown literal is read before its cast.
94    pub(crate) fn parse(text: &str) -> Result<Self, CastError> {
95        let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
96        let bytes = text.as_bytes();
97        let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
98        let signed = &bytes[start..];
99        let (negative, unsigned) = match signed.split_first() {
100            Some((b'-', rest)) => (true, rest),
101            Some((b'+', rest)) => (false, rest),
102            _ => (false, signed),
103        };
104        let (value, rest) = match unsigned.first() {
105            Some(b'0'..=b'9' | b'.') => {
106                let (base, digits) = match unsigned {
107                    [b'0', b'x' | b'X', digits @ ..] => (16, digits),
108                    [b'0', b'o' | b'O', digits @ ..] => (8, digits),
109                    [b'0', b'b' | b'B', digits @ ..] => (2, digits),
110                    _ => (10, unsigned),
111                };
112                let (mut finite, rest) = if base == 10 {
113                    parse_decimal(digits)?
114                } else {
115                    parse_non_decimal(digits, base)?
116                };
117                finite.negative = negative && !finite.digits.is_empty();
118                (Repr::Finite(finite), rest)
119            }
120            _ => {
121                if starts_with_ignore_case(signed, b"NaN") {
122                    (Repr::NaN, &signed[3..])
123                } else if starts_with_ignore_case(unsigned, b"Infinity") {
124                    (Repr::Infinity { negative }, &unsigned[8..])
125                } else if starts_with_ignore_case(unsigned, b"inf") {
126                    (Repr::Infinity { negative }, &unsigned[3..])
127                } else {
128                    return Err(syntax);
129                }
130            }
131        };
132        if !rest.iter().all(|&b| is_pg_space(b)) {
133            return Err(syntax);
134        }
135        if let Repr::Finite(finite) = &value {
136            finite.check_storable()?;
137        }
138        Ok(Self(value))
139    }
140
141    /// `int8_numeric`.
142    pub(crate) fn from_i64(value: i64) -> Self {
143        let mut digits = Vec::new();
144        let mut rest = value.unsigned_abs();
145        while rest > 0 {
146            // A remainder of ten is below `u8::MAX`.
147            digits.push(u8::try_from(rest % 10).expect("a decimal digit fits u8"));
148            rest /= 10;
149        }
150        digits.reverse();
151        let weight = i64::try_from(digits.len()).expect("an i64 has 19 digits") - 1;
152        let mut finite = Finite {
153            negative: value < 0,
154            digits,
155            weight,
156            dscale: 0,
157        };
158        finite.normalise();
159        Self(Repr::Finite(finite))
160    }
161
162    /// The `numeric()` length coercion to `typmod`, rounding half away from zero.
163    pub(crate) fn apply_typmod(self, typmod: NumericTypmod) -> Result<Self, CastError> {
164        match self.0 {
165            Repr::NaN => Ok(self),
166            Repr::Infinity { .. } => Err(CastError::NumericFieldOverflow),
167            Repr::Finite(mut finite) => {
168                let scale = i64::from(typmod.scale);
169                finite.round(scale);
170                let integer_digits = i64::from(typmod.precision) - scale;
171                if !finite.digits.is_empty() && finite.weight + 1 > integer_digits {
172                    return Err(CastError::NumericFieldOverflow);
173                }
174                Ok(Self(Repr::Finite(finite)))
175            }
176        }
177    }
178
179    /// `numericvar_to_int64`, the value rounded half away from zero, or `None` for a value
180    /// beyond `i64` or not finite.
181    pub(crate) fn into_i64_rounded(self) -> Option<i64> {
182        let Repr::Finite(mut rounded) = self.0 else {
183            return None;
184        };
185        rounded.round(0);
186        if rounded.weight >= 19 {
187            return None;
188        }
189        let magnitude = (0..=rounded.weight).rev().fold(0i128, |magnitude, power| {
190            magnitude * 10 + i128::from(rounded.digit_at(power))
191        });
192        i64::try_from(if rounded.negative {
193            -magnitude
194        } else {
195            magnitude
196        })
197        .ok()
198    }
199
200    /// The order class of the value, rising from `-Infinity` through negative, zero, positive and
201    /// `Infinity` to `NaN`.
202    fn class(&self) -> i8 {
203        match &self.0 {
204            Repr::Infinity { negative: true } => -2,
205            Repr::Finite(finite) if finite.digits.is_empty() => 0,
206            Repr::Finite(finite) if finite.negative => -1,
207            Repr::Finite(_) => 1,
208            Repr::Infinity { negative: false } => 2,
209            Repr::NaN => 3,
210        }
211    }
212}
213
214impl Finite {
215    /// Drop leading and trailing zero digits, giving zero its unsigned form.
216    fn normalise(&mut self) {
217        let leading = self.digits.iter().take_while(|&&d| d == 0).count();
218        self.digits.drain(..leading);
219        self.weight -= i64::try_from(leading).expect("a digit count fits i64");
220        let kept = self
221            .digits
222            .iter()
223            .rposition(|&d| d != 0)
224            .map_or(0, |last| last + 1);
225        self.digits.truncate(kept);
226        if self.digits.is_empty() {
227            self.negative = false;
228            self.weight = 0;
229        }
230    }
231
232    /// The digit at `power` of ten.
233    fn digit_at(&self, power: i64) -> u8 {
234        usize::try_from(self.weight - power)
235            .ok()
236            .and_then(|index| self.digits.get(index).copied())
237            .unwrap_or(0)
238    }
239
240    /// `round_var` to `scale` digits after the point, then `apply_typmod`'s non-negative display
241    /// scale.
242    fn round(&mut self, scale: i64) {
243        self.dscale = scale.max(0);
244        let kept = self.weight + scale + 1;
245        let Ok(kept) = usize::try_from(kept) else {
246            *self = Self::zero(self.dscale);
247            return;
248        };
249        if kept >= self.digits.len() {
250            return;
251        }
252        let round_up = self.digits[kept] >= 5;
253        self.digits.truncate(kept);
254        if round_up {
255            let carried = self.digits.iter_mut().rev().try_for_each(|digit| {
256                if *digit == 9 {
257                    *digit = 0;
258                    Ok(())
259                } else {
260                    *digit += 1;
261                    Err(())
262                }
263            });
264            if carried.is_ok() {
265                self.digits.insert(0, 1);
266                self.weight += 1;
267            }
268        }
269        self.normalise();
270    }
271
272    const fn zero(dscale: i64) -> Self {
273        Self {
274            negative: false,
275            digits: Vec::new(),
276            weight: 0,
277            dscale,
278        }
279    }
280
281    /// `make_result`'s check that the weight and display scale fit their stored fields.
282    fn check_storable(&self) -> Result<(), CastError> {
283        let weight_fits = self.digits.is_empty() || self.weight <= MAX_WEIGHT;
284        if weight_fits && self.dscale <= MAX_DSCALE {
285            Ok(())
286        } else {
287            Err(CastError::NumericFormatOverflow)
288        }
289    }
290
291    /// The magnitude order of two values of the same sign.
292    fn cmp_magnitude(&self, other: &Self) -> Ordering {
293        self.weight
294            .cmp(&other.weight)
295            .then_with(|| self.digits.cmp(&other.digits))
296    }
297}
298
299/// `set_var_from_str` from the first digit or point, returning the value and the unread rest.
300fn parse_decimal(bytes: &[u8]) -> Result<(Finite, &[u8]), CastError> {
301    let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
302    let mut digits = Vec::new();
303    let mut integer_digits: i64 = 0;
304    let mut dscale: i64 = 0;
305    let mut have_point = false;
306    let mut at = 0;
307    if bytes.first() == Some(&b'.') {
308        have_point = true;
309        at = 1;
310    }
311    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
312        return Err(syntax);
313    }
314    while let Some(&byte) = bytes.get(at) {
315        match byte {
316            b'0'..=b'9' => {
317                digits.push(byte - b'0');
318                if have_point {
319                    dscale += 1;
320                } else {
321                    integer_digits += 1;
322                }
323                at += 1;
324            }
325            b'.' if have_point => return Err(syntax),
326            b'.' => {
327                have_point = true;
328                at += 1;
329                if bytes.get(at) == Some(&b'_') {
330                    return Err(syntax);
331                }
332            }
333            b'_' => {
334                at += 1;
335                if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
336                    return Err(syntax);
337                }
338            }
339            _ => break,
340        }
341    }
342    let mut weight = integer_digits - 1;
343    if matches!(bytes.get(at), Some(b'e' | b'E')) {
344        at += 1;
345        let negative = match bytes.get(at) {
346            Some(b'+') => {
347                at += 1;
348                false
349            }
350            Some(b'-') => {
351                at += 1;
352                true
353            }
354            _ => false,
355        };
356        if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
357            return Err(syntax);
358        }
359        let mut exponent: i64 = 0;
360        while let Some(&byte) = bytes.get(at) {
361            match byte {
362                b'0'..=b'9' => {
363                    exponent = exponent * 10 + i64::from(byte - b'0');
364                    if exponent > MAX_EXPONENT {
365                        return Err(CastError::NumericFormatOverflow);
366                    }
367                    at += 1;
368                }
369                b'_' => {
370                    at += 1;
371                    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
372                        return Err(syntax);
373                    }
374                }
375                _ => break,
376            }
377        }
378        let exponent = if negative { -exponent } else { exponent };
379        weight += exponent;
380        dscale = (dscale - exponent).max(0);
381    }
382    let mut finite = Finite {
383        negative: false,
384        digits,
385        weight,
386        dscale,
387    };
388    finite.normalise();
389    Ok((finite, &bytes[at..]))
390}
391
392/// `set_var_from_non_decimal_integer_str` after the base prefix, checking the weight after each
393/// group of digits that fills an `int64` as PostgreSQL does.
394fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), CastError> {
395    let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
396    // `mul > PG_INT64_MAX / base` starts a new group after this many digits.
397    let group_len = match base {
398        16 => 15,
399        8 => 20,
400        _ => 62,
401    };
402    let mut limbs = Limbs::default();
403    let mut group: u64 = 0;
404    let mut group_digits: u32 = 0;
405    let mut at = 0;
406    while let Some(&byte) = bytes.get(at) {
407        if let Some(digit) = char::from(byte).to_digit(base) {
408            if group_digits == group_len {
409                limbs.push_group(group, base, group_digits);
410                if limbs.decimal_weight() > MAX_WEIGHT {
411                    return Err(CastError::NumericFormatOverflow);
412                }
413                group = 0;
414                group_digits = 0;
415            }
416            group = group * u64::from(base) + u64::from(digit);
417            group_digits += 1;
418            at += 1;
419        } else if byte == b'_' {
420            at += 1;
421            let next_is_digit = bytes
422                .get(at)
423                .is_some_and(|&next| char::from(next).is_digit(base));
424            if !next_is_digit {
425                return Err(syntax);
426            }
427        } else {
428            break;
429        }
430    }
431    if at == 0 {
432        return Err(syntax);
433    }
434    limbs.push_group(group, base, group_digits);
435    if limbs.decimal_weight() > MAX_WEIGHT {
436        return Err(CastError::NumericFormatOverflow);
437    }
438    Ok((limbs.into_finite(), &bytes[at..]))
439}
440
441/// A non-negative integer in base 10^9 limbs, least significant first.
442#[derive(Default)]
443struct Limbs(Vec<u32>);
444
445const LIMB: u128 = 1_000_000_000;
446
447impl Limbs {
448    /// Multiply by `base^digits` and add `group`.
449    fn push_group(&mut self, group: u64, base: u32, digits: u32) {
450        let factor = u128::from(base).pow(digits);
451        let mut carry = u128::from(group);
452        for limb in &mut self.0 {
453            let value = u128::from(*limb) * factor + carry;
454            *limb = u32::try_from(value % LIMB).expect("a limb is below 10^9");
455            carry = value / LIMB;
456        }
457        while carry > 0 {
458            self.0
459                .push(u32::try_from(carry % LIMB).expect("a limb is below 10^9"));
460            carry /= LIMB;
461        }
462    }
463
464    /// The decimal digits, most significant first, with leading zeros.
465    fn decimal_digits(&self) -> Vec<u8> {
466        let mut digits = Vec::with_capacity(self.0.len() * 9);
467        for &limb in self.0.iter().rev() {
468            let mut rest = limb;
469            let mut chunk = [0u8; 9];
470            for slot in chunk.iter_mut().rev() {
471                *slot = u8::try_from(rest % 10).expect("a decimal digit fits u8");
472                rest /= 10;
473            }
474            digits.extend_from_slice(&chunk);
475        }
476        digits
477    }
478
479    /// The power of ten of the leading digit, `-1` for zero.
480    fn decimal_weight(&self) -> i64 {
481        let Some(&top) = self.0.last() else {
482            return -1;
483        };
484        let top_digits = top.checked_ilog10().map_or(0, |log| i64::from(log) + 1);
485        let lower = i64::try_from(self.0.len() - 1).expect("a limb count fits i64") * 9;
486        lower + top_digits - 1
487    }
488
489    fn into_finite(self) -> Finite {
490        let digits = self.decimal_digits();
491        let weight = i64::try_from(digits.len()).expect("a digit count fits i64") - 1;
492        let mut finite = Finite {
493            negative: false,
494            digits,
495            weight,
496            dscale: 0,
497        };
498        finite.normalise();
499        finite
500    }
501}
502
503/// `pg_strncasecmp(bytes, word, word.len()) == 0`.
504fn starts_with_ignore_case(bytes: &[u8], word: &[u8]) -> bool {
505    bytes
506        .get(..word.len())
507        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
508}
509
510/// `numeric_out`.
511impl fmt::Display for PgNumeric {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        let finite = match &self.0 {
514            Repr::NaN => return f.write_str("NaN"),
515            Repr::Infinity { negative: false } => return f.write_str("Infinity"),
516            Repr::Infinity { negative: true } => return f.write_str("-Infinity"),
517            Repr::Finite(finite) => finite,
518        };
519        if finite.negative {
520            f.write_str("-")?;
521        }
522        let digit = |power| char::from(b'0' + finite.digit_at(power));
523        if finite.weight < 0 || finite.digits.is_empty() {
524            f.write_str("0")?;
525        } else {
526            for power in (0..=finite.weight).rev() {
527                fmt::Write::write_char(f, digit(power))?;
528            }
529        }
530        if finite.dscale > 0 {
531            f.write_str(".")?;
532            for power in 1..=finite.dscale {
533                fmt::Write::write_char(f, digit(-power))?;
534            }
535        }
536        Ok(())
537    }
538}
539
540impl PartialEq for PgNumeric {
541    fn eq(&self, other: &Self) -> bool {
542        self.cmp(other) == Ordering::Equal
543    }
544}
545
546impl Eq for PgNumeric {}
547
548impl PartialOrd for PgNumeric {
549    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
550        Some(self.cmp(other))
551    }
552}
553
554/// `cmp_numerics`, ordering `-Infinity` below finite values by value, then `Infinity`, then `NaN`.
555impl Ord for PgNumeric {
556    fn cmp(&self, other: &Self) -> Ordering {
557        match (&self.0, &other.0) {
558            (Repr::Finite(left), Repr::Finite(right))
559                if left.negative == right.negative && !left.digits.is_empty() =>
560            {
561                let magnitude = left.cmp_magnitude(right);
562                if left.negative {
563                    magnitude.reverse()
564                } else {
565                    magnitude
566                }
567            }
568            _ => self.class().cmp(&other.class()),
569        }
570    }
571}
572
573impl Hash for PgNumeric {
574    fn hash<H: Hasher>(&self, state: &mut H) {
575        self.class().hash(state);
576        if let Repr::Finite(finite) = &self.0 {
577            finite.weight.hash(state);
578            finite.digits.hash(state);
579        }
580    }
581}