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]
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 pub const NAN: Self = Self(Repr::NaN);
121 pub const INFINITY: Self = Self(Repr::Infinity { negative: false });
123 pub const NEG_INFINITY: Self = Self(Repr::Infinity { negative: true });
125
126 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 #[must_use]
193 pub const fn is_nan(&self) -> bool {
194 matches!(self.0, Repr::NaN)
195 }
196
197 #[must_use]
199 pub const fn is_infinite(&self) -> bool {
200 matches!(self.0, Repr::Infinity { .. })
201 }
202
203 #[must_use]
205 pub fn is_zero(&self) -> bool {
206 matches!(&self.0, Repr::Finite(finite) if finite.digits.is_empty())
207 }
208
209 #[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 #[must_use]
228 pub fn is_integral(&self) -> bool {
229 matches!(&self.0, Repr::Finite(finite) if finite.exponent() >= 0)
230 }
231
232 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 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 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 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 pub(crate) fn cmp_integer(&self, value: i64) -> Ordering {
301 self.key().order(&IntegerDigits::new(value).key())
302 }
303
304 pub(crate) fn hash_integer<H: Hasher>(value: i64, state: &mut H) {
306 IntegerDigits::new(value).key().hash(state);
307 }
308}
309
310#[derive(Hash)]
313struct Key<'a> {
314 class: i8,
315 weight: i64,
316 digits: &'a [u8],
317}
318
319impl Key<'_> {
320 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
336struct IntegerDigits {
339 negative: bool,
340 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 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 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 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 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 fn exponent(&self) -> i64 {
472 self.weight + 1 - i64::try_from(self.digits.len()).expect("a digit count fits i64")
473 }
474
475 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 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 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 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
518fn 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
611fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), NumericError> {
614 let syntax = NumericError::InvalidInputSyntax;
615 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
660fn 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
667impl 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
711impl 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
724impl From<i16> for PgNumeric {
726 fn from(value: i16) -> Self {
727 Self::from(i64::from(value))
728 }
729}
730
731impl From<i32> for PgNumeric {
733 fn from(value: i32) -> Self {
734 Self::from(i64::from(value))
735 }
736}
737
738impl From<i64> for PgNumeric {
740 fn from(value: i64) -> Self {
741 Self(Repr::Finite(Finite::from_i64(value)))
742 }
743}
744
745#[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#[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 let scale = length - 1 - finite.weight;
781 Ok(Self::new(integer, scale).with_scale(finite.dscale))
782 }
783}