use alloc::vec::Vec;
use core::{
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
};
use crate::cast::{CastError, PgType, is_pg_space};
const MAX_DSCALE: i64 = 0x3FFF;
const MAX_WEIGHT: i64 = 131_071;
const MAX_EXPONENT: i64 = 1_073_741_823;
const MAX_PRECISION: u16 = 1000;
const SCALE_RANGE: core::ops::RangeInclusive<i16> = -1000..=1000;
#[derive(Debug, Clone)]
pub struct PgNumeric(Repr);
#[derive(Debug, Clone)]
enum Repr {
NaN,
Infinity { negative: bool },
Finite(Finite),
}
#[derive(Debug, Clone)]
struct Finite {
negative: bool,
digits: Vec<u8>,
weight: i64,
dscale: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NumericTypmod {
precision: u16,
scale: i16,
}
impl NumericTypmod {
#[must_use]
pub fn new(precision: u16, scale: i16) -> Option<Self> {
((1..=MAX_PRECISION).contains(&precision) && SCALE_RANGE.contains(&scale))
.then_some(Self { precision, scale })
}
}
impl PgNumeric {
pub(crate) fn parse(text: &str) -> Result<Self, CastError> {
let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
let bytes = text.as_bytes();
let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
let signed = &bytes[start..];
let (negative, unsigned) = match signed.split_first() {
Some((b'-', rest)) => (true, rest),
Some((b'+', rest)) => (false, rest),
_ => (false, signed),
};
let (value, rest) = match unsigned.first() {
Some(b'0'..=b'9' | b'.') => {
let (base, digits) = match unsigned {
[b'0', b'x' | b'X', digits @ ..] => (16, digits),
[b'0', b'o' | b'O', digits @ ..] => (8, digits),
[b'0', b'b' | b'B', digits @ ..] => (2, digits),
_ => (10, unsigned),
};
let (mut finite, rest) = if base == 10 {
parse_decimal(digits)?
} else {
parse_non_decimal(digits, base)?
};
finite.negative = negative && !finite.digits.is_empty();
(Repr::Finite(finite), rest)
}
_ => {
if starts_with_ignore_case(signed, b"NaN") {
(Repr::NaN, &signed[3..])
} else if starts_with_ignore_case(unsigned, b"Infinity") {
(Repr::Infinity { negative }, &unsigned[8..])
} else if starts_with_ignore_case(unsigned, b"inf") {
(Repr::Infinity { negative }, &unsigned[3..])
} else {
return Err(syntax);
}
}
};
if !rest.iter().all(|&b| is_pg_space(b)) {
return Err(syntax);
}
if let Repr::Finite(finite) = &value {
finite.check_storable()?;
}
Ok(Self(value))
}
pub(crate) fn from_i64(value: i64) -> Self {
let mut digits = Vec::new();
let mut rest = value.unsigned_abs();
while rest > 0 {
digits.push(u8::try_from(rest % 10).expect("a decimal digit fits u8"));
rest /= 10;
}
digits.reverse();
let weight = i64::try_from(digits.len()).expect("an i64 has 19 digits") - 1;
let mut finite = Finite {
negative: value < 0,
digits,
weight,
dscale: 0,
};
finite.normalise();
Self(Repr::Finite(finite))
}
pub(crate) fn apply_typmod(self, typmod: NumericTypmod) -> Result<Self, CastError> {
match self.0 {
Repr::NaN => Ok(self),
Repr::Infinity { .. } => Err(CastError::NumericFieldOverflow),
Repr::Finite(mut finite) => {
let scale = i64::from(typmod.scale);
finite.round(scale);
let integer_digits = i64::from(typmod.precision) - scale;
if !finite.digits.is_empty() && finite.weight + 1 > integer_digits {
return Err(CastError::NumericFieldOverflow);
}
Ok(Self(Repr::Finite(finite)))
}
}
}
pub(crate) fn into_i64_rounded(self) -> Option<i64> {
let Repr::Finite(mut rounded) = self.0 else {
return None;
};
rounded.round(0);
if rounded.weight >= 19 {
return None;
}
let magnitude = (0..=rounded.weight).rev().fold(0i128, |magnitude, power| {
magnitude * 10 + i128::from(rounded.digit_at(power))
});
i64::try_from(if rounded.negative {
-magnitude
} else {
magnitude
})
.ok()
}
fn class(&self) -> i8 {
match &self.0 {
Repr::Infinity { negative: true } => -2,
Repr::Finite(finite) if finite.digits.is_empty() => 0,
Repr::Finite(finite) if finite.negative => -1,
Repr::Finite(_) => 1,
Repr::Infinity { negative: false } => 2,
Repr::NaN => 3,
}
}
}
impl Finite {
fn normalise(&mut self) {
let leading = self.digits.iter().take_while(|&&d| d == 0).count();
self.digits.drain(..leading);
self.weight -= i64::try_from(leading).expect("a digit count fits i64");
let kept = self
.digits
.iter()
.rposition(|&d| d != 0)
.map_or(0, |last| last + 1);
self.digits.truncate(kept);
if self.digits.is_empty() {
self.negative = false;
self.weight = 0;
}
}
fn digit_at(&self, power: i64) -> u8 {
usize::try_from(self.weight - power)
.ok()
.and_then(|index| self.digits.get(index).copied())
.unwrap_or(0)
}
fn round(&mut self, scale: i64) {
self.dscale = scale.max(0);
let kept = self.weight + scale + 1;
let Ok(kept) = usize::try_from(kept) else {
*self = Self::zero(self.dscale);
return;
};
if kept >= self.digits.len() {
return;
}
let round_up = self.digits[kept] >= 5;
self.digits.truncate(kept);
if round_up {
let carried = self.digits.iter_mut().rev().try_for_each(|digit| {
if *digit == 9 {
*digit = 0;
Ok(())
} else {
*digit += 1;
Err(())
}
});
if carried.is_ok() {
self.digits.insert(0, 1);
self.weight += 1;
}
}
self.normalise();
}
const fn zero(dscale: i64) -> Self {
Self {
negative: false,
digits: Vec::new(),
weight: 0,
dscale,
}
}
fn check_storable(&self) -> Result<(), CastError> {
let weight_fits = self.digits.is_empty() || self.weight <= MAX_WEIGHT;
if weight_fits && self.dscale <= MAX_DSCALE {
Ok(())
} else {
Err(CastError::NumericFormatOverflow)
}
}
fn cmp_magnitude(&self, other: &Self) -> Ordering {
self.weight
.cmp(&other.weight)
.then_with(|| self.digits.cmp(&other.digits))
}
}
fn parse_decimal(bytes: &[u8]) -> Result<(Finite, &[u8]), CastError> {
let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
let mut digits = Vec::new();
let mut integer_digits: i64 = 0;
let mut dscale: i64 = 0;
let mut have_point = false;
let mut at = 0;
if bytes.first() == Some(&b'.') {
have_point = true;
at = 1;
}
if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
return Err(syntax);
}
while let Some(&byte) = bytes.get(at) {
match byte {
b'0'..=b'9' => {
digits.push(byte - b'0');
if have_point {
dscale += 1;
} else {
integer_digits += 1;
}
at += 1;
}
b'.' if have_point => return Err(syntax),
b'.' => {
have_point = true;
at += 1;
if bytes.get(at) == Some(&b'_') {
return Err(syntax);
}
}
b'_' => {
at += 1;
if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
return Err(syntax);
}
}
_ => break,
}
}
let mut weight = integer_digits - 1;
if matches!(bytes.get(at), Some(b'e' | b'E')) {
at += 1;
let negative = match bytes.get(at) {
Some(b'+') => {
at += 1;
false
}
Some(b'-') => {
at += 1;
true
}
_ => false,
};
if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
return Err(syntax);
}
let mut exponent: i64 = 0;
while let Some(&byte) = bytes.get(at) {
match byte {
b'0'..=b'9' => {
exponent = exponent * 10 + i64::from(byte - b'0');
if exponent > MAX_EXPONENT {
return Err(CastError::NumericFormatOverflow);
}
at += 1;
}
b'_' => {
at += 1;
if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
return Err(syntax);
}
}
_ => break,
}
}
let exponent = if negative { -exponent } else { exponent };
weight += exponent;
dscale = (dscale - exponent).max(0);
}
let mut finite = Finite {
negative: false,
digits,
weight,
dscale,
};
finite.normalise();
Ok((finite, &bytes[at..]))
}
fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), CastError> {
let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
let group_len = match base {
16 => 15,
8 => 20,
_ => 62,
};
let mut limbs = Limbs::default();
let mut group: u64 = 0;
let mut group_digits: u32 = 0;
let mut at = 0;
while let Some(&byte) = bytes.get(at) {
if let Some(digit) = char::from(byte).to_digit(base) {
if group_digits == group_len {
limbs.push_group(group, base, group_digits);
if limbs.decimal_weight() > MAX_WEIGHT {
return Err(CastError::NumericFormatOverflow);
}
group = 0;
group_digits = 0;
}
group = group * u64::from(base) + u64::from(digit);
group_digits += 1;
at += 1;
} else if byte == b'_' {
at += 1;
let next_is_digit = bytes
.get(at)
.is_some_and(|&next| char::from(next).is_digit(base));
if !next_is_digit {
return Err(syntax);
}
} else {
break;
}
}
if at == 0 {
return Err(syntax);
}
limbs.push_group(group, base, group_digits);
if limbs.decimal_weight() > MAX_WEIGHT {
return Err(CastError::NumericFormatOverflow);
}
Ok((limbs.into_finite(), &bytes[at..]))
}
#[derive(Default)]
struct Limbs(Vec<u32>);
const LIMB: u128 = 1_000_000_000;
impl Limbs {
fn push_group(&mut self, group: u64, base: u32, digits: u32) {
let factor = u128::from(base).pow(digits);
let mut carry = u128::from(group);
for limb in &mut self.0 {
let value = u128::from(*limb) * factor + carry;
*limb = u32::try_from(value % LIMB).expect("a limb is below 10^9");
carry = value / LIMB;
}
while carry > 0 {
self.0
.push(u32::try_from(carry % LIMB).expect("a limb is below 10^9"));
carry /= LIMB;
}
}
fn decimal_digits(&self) -> Vec<u8> {
let mut digits = Vec::with_capacity(self.0.len() * 9);
for &limb in self.0.iter().rev() {
let mut rest = limb;
let mut chunk = [0u8; 9];
for slot in chunk.iter_mut().rev() {
*slot = u8::try_from(rest % 10).expect("a decimal digit fits u8");
rest /= 10;
}
digits.extend_from_slice(&chunk);
}
digits
}
fn decimal_weight(&self) -> i64 {
let Some(&top) = self.0.last() else {
return -1;
};
let top_digits = top.checked_ilog10().map_or(0, |log| i64::from(log) + 1);
let lower = i64::try_from(self.0.len() - 1).expect("a limb count fits i64") * 9;
lower + top_digits - 1
}
fn into_finite(self) -> Finite {
let digits = self.decimal_digits();
let weight = i64::try_from(digits.len()).expect("a digit count fits i64") - 1;
let mut finite = Finite {
negative: false,
digits,
weight,
dscale: 0,
};
finite.normalise();
finite
}
}
fn starts_with_ignore_case(bytes: &[u8], word: &[u8]) -> bool {
bytes
.get(..word.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
}
impl fmt::Display for PgNumeric {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let finite = match &self.0 {
Repr::NaN => return f.write_str("NaN"),
Repr::Infinity { negative: false } => return f.write_str("Infinity"),
Repr::Infinity { negative: true } => return f.write_str("-Infinity"),
Repr::Finite(finite) => finite,
};
if finite.negative {
f.write_str("-")?;
}
let digit = |power| char::from(b'0' + finite.digit_at(power));
if finite.weight < 0 || finite.digits.is_empty() {
f.write_str("0")?;
} else {
for power in (0..=finite.weight).rev() {
fmt::Write::write_char(f, digit(power))?;
}
}
if finite.dscale > 0 {
f.write_str(".")?;
for power in 1..=finite.dscale {
fmt::Write::write_char(f, digit(-power))?;
}
}
Ok(())
}
}
impl PartialEq for PgNumeric {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for PgNumeric {}
impl PartialOrd for PgNumeric {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PgNumeric {
fn cmp(&self, other: &Self) -> Ordering {
match (&self.0, &other.0) {
(Repr::Finite(left), Repr::Finite(right))
if left.negative == right.negative && !left.digits.is_empty() =>
{
let magnitude = left.cmp_magnitude(right);
if left.negative {
magnitude.reverse()
} else {
magnitude
}
}
_ => self.class().cmp(&other.class()),
}
}
}
impl Hash for PgNumeric {
fn hash<H: Hasher>(&self, state: &mut H) {
self.class().hash(state);
if let Repr::Finite(finite) = &self.0 {
finite.weight.hash(state);
finite.digits.hash(state);
}
}
}