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 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 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 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 pub(crate) fn cmp_integer(&self, value: i64) -> Ordering {
312 self.key().order(&IntegerDigits::new(value).key())
313 }
314
315 pub(crate) fn hash_integer<H: Hasher>(value: i64, state: &mut H) {
317 IntegerDigits::new(value).key().hash(state);
318 }
319}
320
321#[derive(Hash)]
324struct Key<'a> {
325 class: i8,
326 weight: i64,
327 digits: &'a [u8],
328}
329
330impl Key<'_> {
331 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
347struct IntegerDigits {
350 negative: bool,
351 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 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 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 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 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 fn exponent(&self) -> i64 {
483 self.weight + 1 - i64::try_from(self.digits.len()).expect("a digit count fits i64")
484 }
485
486 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 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 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 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
529fn 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
622fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), NumericError> {
625 let syntax = NumericError::InvalidInputSyntax;
626 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
671fn 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
678impl 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
722impl 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
735impl From<i16> for PgNumeric {
737 fn from(value: i16) -> Self {
738 Self::from(i64::from(value))
739 }
740}
741
742impl From<i32> for PgNumeric {
744 fn from(value: i32) -> Self {
745 Self::from(i64::from(value))
746 }
747}
748
749impl From<i64> for PgNumeric {
751 fn from(value: i64) -> Self {
752 Self(Repr::Finite(Finite::from_i64(value)))
753 }
754}
755
756#[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#[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 let scale = length - 1 - finite.weight;
792 Ok(Self::new(integer, scale).with_scale(finite.dscale))
793 }
794}