1mod 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
29pub enum NumericError {
30 #[error("invalid input syntax for type numeric")]
32 InvalidInputSyntax,
33 #[error("value overflows numeric format")]
35 FormatOverflow,
36 #[error("division by zero")]
38 DivisionByZero,
39}
40
41const MAX_DSCALE: i64 = 0x3FFF;
43const MAX_WEIGHT: i64 = 131_071;
46const MAX_EXPONENT: i64 = 1_073_741_823;
48const MAX_PRECISION: u16 = 1000;
50const SCALE_RANGE: core::ops::RangeInclusive<i16> = -1000..=1000;
52
53#[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#[derive(Debug, Clone)]
81struct Finite {
82 negative: bool,
84 digits: Vec<u8>,
86 weight: i64,
88 dscale: i64,
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct NumericTypmod {
95 precision: u16,
96 scale: i16,
97}
98
99impl NumericTypmod {
100 #[must_use]
102 pub const fn precision(self) -> u16 {
103 self.precision
104 }
105
106 #[must_use]
108 pub const fn scale(self) -> i16 {
109 self.scale
110 }
111
112 #[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 pub const NAN: Self = Self(Repr::NaN);
133 pub const INFINITY: Self = Self(Repr::Infinity { negative: false });
135 pub const NEG_INFINITY: Self = Self(Repr::Infinity { negative: true });
137
138 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 #[must_use]
205 pub const fn is_nan(&self) -> bool {
206 matches!(self.0, Repr::NaN)
207 }
208
209 #[must_use]
211 pub const fn is_infinite(&self) -> bool {
212 matches!(self.0, Repr::Infinity { .. })
213 }
214
215 #[must_use]
217 pub fn is_zero(&self) -> bool {
218 matches!(&self.0, Repr::Finite(finite) if finite.digits.is_empty())
219 }
220
221 #[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 #[must_use]
240 pub fn is_integral(&self) -> bool {
241 matches!(&self.0, Repr::Finite(finite) if finite.exponent() >= 0)
242 }
243
244 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 #[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 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 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 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 #[must_use]
324 pub fn cmp_integer(&self, value: i64) -> Ordering {
325 self.key().order(&IntegerDigits::new(value).key())
326 }
327
328 pub(crate) fn hash_integer<H: Hasher>(value: i64, state: &mut H) {
330 IntegerDigits::new(value).key().hash(state);
331 }
332}
333
334#[derive(Hash)]
337struct Key<'a> {
338 class: i8,
339 weight: i64,
340 digits: &'a [u8],
341}
342
343impl Key<'_> {
344 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
360struct IntegerDigits {
363 negative: bool,
364 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 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 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 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 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 fn exponent(&self) -> i64 {
496 self.weight + 1 - i64::try_from(self.digits.len()).expect("a digit count fits i64")
497 }
498
499 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 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 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 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
542fn 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
635fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), NumericError> {
638 let syntax = NumericError::InvalidInputSyntax;
639 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
684fn 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
691impl 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
735impl 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
748impl From<i16> for PgNumeric {
750 fn from(value: i16) -> Self {
751 Self::from(i64::from(value))
752 }
753}
754
755impl From<i32> for PgNumeric {
757 fn from(value: i32) -> Self {
758 Self::from(i64::from(value))
759 }
760}
761
762impl From<i64> for PgNumeric {
764 fn from(value: i64) -> Self {
765 Self(Repr::Finite(Finite::from_i64(value)))
766 }
767}
768
769#[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#[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 let scale = length - 1 - finite.weight;
805 Ok(Self::new(integer, scale).with_scale(finite.dscale))
806 }
807}