use core::{cmp::Ordering, ops::Neg};
use super::{Finite, MAX_DSCALE, MAX_WEIGHT, NumericError, PgNumeric, Repr};
const MIN_SIG_DIGITS: i64 = 16;
const MAX_DISPLAY_SCALE: i64 = 1000;
const DEC_DIGITS: i64 = 4;
impl PgNumeric {
pub fn checked_add(&self, other: &Self) -> Result<Self, NumericError> {
match (&self.0, &other.0) {
(Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
(Repr::Infinity { negative: left }, Repr::Infinity { negative: right })
if left != right =>
{
Ok(Self::NAN)
}
(Repr::Infinity { .. }, _) => Ok(self.clone()),
(_, Repr::Infinity { .. }) => Ok(other.clone()),
(Repr::Finite(left), Repr::Finite(right)) => finite(left.add(right, false)),
}
}
pub fn checked_sub(&self, other: &Self) -> Result<Self, NumericError> {
match (&self.0, &other.0) {
(Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
(Repr::Infinity { negative: left }, Repr::Infinity { negative: right })
if left == right =>
{
Ok(Self::NAN)
}
(Repr::Infinity { .. }, _) => Ok(self.clone()),
(_, &Repr::Infinity { negative }) => Ok(Self(Repr::Infinity {
negative: !negative,
})),
(Repr::Finite(left), Repr::Finite(right)) => finite(left.add(right, true)),
}
}
pub fn checked_mul(&self, other: &Self) -> Result<Self, NumericError> {
match (&self.0, &other.0) {
(Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
(Repr::Finite(left), Repr::Finite(right)) => finite(left.mul(right)),
_ if self.is_zero() || other.is_zero() => Ok(Self::NAN),
_ => Ok(Self(Repr::Infinity {
negative: self.is_negative() != other.is_negative(),
})),
}
}
pub fn checked_div(&self, other: &Self) -> Result<Self, NumericError> {
match (&self.0, &other.0) {
(Repr::NaN, _) | (_, Repr::NaN) | (Repr::Infinity { .. }, Repr::Infinity { .. }) => {
Ok(Self::NAN)
}
(Repr::Finite(left), Repr::Finite(right)) => finite(left.div(right)?),
(Repr::Finite(_), Repr::Infinity { .. }) => Ok(Self(Repr::Finite(Finite::zero(0)))),
(Repr::Infinity { negative }, Repr::Finite(right)) => {
if right.digits.is_empty() {
Err(NumericError::DivisionByZero)
} else {
Ok(Self(Repr::Infinity {
negative: *negative != right.negative,
}))
}
}
}
}
pub fn checked_rem(&self, other: &Self) -> Result<Self, NumericError> {
match (&self.0, &other.0) {
(Repr::NaN, _) | (_, Repr::NaN) => Ok(Self::NAN),
(Repr::Infinity { .. }, _) if other.is_zero() => Err(NumericError::DivisionByZero),
(Repr::Infinity { .. }, _) => Ok(Self::NAN),
(Repr::Finite(_), Repr::Infinity { .. }) => Ok(self.clone()),
(Repr::Finite(left), Repr::Finite(right)) => finite(left.rem(right)?),
}
}
#[must_use]
pub fn abs(mut self) -> Self {
match &mut self.0 {
Repr::NaN => {}
Repr::Infinity { negative } => *negative = false,
Repr::Finite(finite) => finite.negative = false,
}
self
}
pub fn round(self, scale: i32) -> Result<Self, NumericError> {
let Repr::Finite(mut rounded) = self.0 else {
return Ok(self);
};
rounded.round(i64::from(scale).clamp(-(MAX_WEIGHT + 2), MAX_DSCALE));
finite(rounded)
}
#[must_use]
pub fn trunc(self, scale: i32) -> Self {
let Repr::Finite(mut truncated) = self.0 else {
return self;
};
truncated.truncate(i64::from(scale).clamp(-(MAX_WEIGHT + 1), MAX_DSCALE));
Self(Repr::Finite(truncated))
}
pub fn floor(self) -> Result<Self, NumericError> {
self.whole(true)
}
pub fn ceil(self) -> Result<Self, NumericError> {
self.whole(false)
}
fn whole(self, down: bool) -> Result<Self, NumericError> {
let Repr::Finite(value) = self.0 else {
return Ok(self);
};
let had_fraction = !value.digits.is_empty() && value.exponent() < 0;
let negative = value.negative;
let mut whole = value;
whole.truncate(0);
if had_fraction && negative == down {
let step = Finite::from_i64(if down { -1 } else { 1 });
whole = whole.add(&step, false);
}
finite(whole)
}
}
impl Neg for PgNumeric {
type Output = Self;
fn neg(mut self) -> Self {
match &mut self.0 {
Repr::NaN => {}
Repr::Infinity { negative } => *negative = !*negative,
Repr::Finite(finite) => finite.negative = !finite.negative && !finite.digits.is_empty(),
}
self
}
}
impl Finite {
fn add(&self, other: &Self, subtract: bool) -> Self {
let other_negative = other.negative != subtract;
let exponent = self.exponent().min(other.exponent());
let left = self.mantissa(self.exponent() - exponent);
let right = other.mantissa(other.exponent() - exponent);
let dscale = self.dscale.max(other.dscale);
let (negative, magnitude) = if self.negative == other_negative {
(self.negative, left.add(&right))
} else {
match left.cmp(&right) {
Ordering::Less => (other_negative, right.sub(&left)),
_ => (self.negative, left.sub(&right)),
}
};
Self::from_mantissa(negative, &magnitude, exponent, dscale)
}
fn mul(&self, other: &Self) -> Self {
let product = self.mantissa(0).mul(&other.mantissa(0));
let mut result = Self::from_mantissa(
self.negative != other.negative,
&product,
self.exponent() + other.exponent(),
self.dscale + other.dscale,
);
if result.dscale > MAX_DSCALE {
result.round(MAX_DSCALE);
}
result
}
fn div(&self, other: &Self) -> Result<Self, NumericError> {
if other.digits.is_empty() {
return Err(NumericError::DivisionByZero);
}
let scale = self.select_div_scale(other);
let mut quotient = self.truncated_quotient(other, scale + 1);
quotient.round(scale);
Ok(quotient)
}
fn rem(&self, other: &Self) -> Result<Self, NumericError> {
if other.digits.is_empty() {
return Err(NumericError::DivisionByZero);
}
let exponent = self.exponent().min(other.exponent());
let dividend = self.mantissa(self.exponent() - exponent);
let divisor = other.mantissa(other.exponent() - exponent);
let (_, remainder) = dividend.div_rem(&divisor);
let dscale = self.dscale.max(other.dscale);
Ok(Self::from_mantissa(
self.negative,
&remainder,
exponent,
dscale,
))
}
fn truncated_quotient(&self, other: &Self, scale: i64) -> Self {
let shift = self.exponent() - other.exponent() + scale;
let (dividend, divisor) = if shift >= 0 {
(self.mantissa(shift), other.mantissa(0))
} else {
(self.mantissa(0), other.mantissa(-shift))
};
let (quotient, _) = dividend.div_rem(&divisor);
Self::from_mantissa(
self.negative != other.negative,
"ient,
-scale,
scale.max(0),
)
}
fn select_div_scale(&self, other: &Self) -> i64 {
let (left_weight, left_first) = self.leading_nbase_digit();
let (right_weight, right_first) = other.leading_nbase_digit();
let mut quotient_weight = left_weight - right_weight;
if left_first <= right_first {
quotient_weight -= 1;
}
(MIN_SIG_DIGITS - quotient_weight * DEC_DIGITS)
.max(self.dscale)
.max(other.dscale)
.clamp(0, MAX_DISPLAY_SCALE)
}
fn leading_nbase_digit(&self) -> (i64, u16) {
if self.digits.is_empty() {
return (0, 0);
}
let weight = self.weight.div_euclid(DEC_DIGITS);
let first = (0..DEC_DIGITS).rev().fold(0, |value, offset| {
value * 10 + u16::from(self.digit_at(weight * DEC_DIGITS + offset))
});
(weight, first)
}
}
fn finite(value: Finite) -> Result<PgNumeric, NumericError> {
value.check_storable()?;
Ok(PgNumeric(Repr::Finite(value)))
}