use core::result::Result;
pub mod rational;
pub mod typed_decimal;
use crate::prelude::*;
use crate::values::core_values::{
decimal::typed_decimal::TypedDecimal, error::NumberParseError,
};
use bigdecimal::BigDecimal;
use core::{cmp::Ordering, fmt::Display, hash::Hash, str::FromStr};
pub mod equality;
use num::{BigInt, BigRational};
use num_enum::TryFromPrimitive;
use num_traits::{FromPrimitive, Zero};
use rational::Rational;
use serde::{Deserialize, Serialize};
pub mod binrw;
pub mod ops;
pub mod primitive;
pub const DECIMAL_NAN: &str = "nan";
pub const DECIMAL_INFINITY: &str = "infinity";
pub const DECIMAL_NEG_INFINITY: &str = "-infinity";
#[derive(Debug, Clone, Eq, Serialize, Deserialize)]
pub enum Decimal {
#[serde(rename = "nan")]
Nan,
#[serde(rename = "0.0")]
Zero,
#[serde(rename = "-0.0")]
NegZero,
#[serde(rename = "infinity")]
Infinity,
#[serde(rename = "-infinity")]
NegInfinity,
#[serde(untagged)]
Finite(Rational),
}
impl Hash for Decimal {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
match self {
Decimal::Finite(value) => value.hash(state),
Decimal::Nan => 0.hash(state),
Decimal::Zero => 1.hash(state),
Decimal::NegZero => 1.hash(state),
Decimal::Infinity => 2.hash(state),
Decimal::NegInfinity => 3.hash(state),
}
}
}
impl PartialEq for Decimal {
fn eq(&self, other: &Self) -> bool {
if self.is_zero() && other.is_zero() {
return true; }
match (self, other) {
(Decimal::Finite(a), Decimal::Finite(b)) => a == b,
(Decimal::Infinity, Decimal::Infinity) => true,
(Decimal::NegInfinity, Decimal::NegInfinity) => true,
(Decimal::Nan, Decimal::Nan) => true,
_ => false,
}
}
}
impl Decimal {
pub fn into_f32(&self) -> f32 {
match self {
Decimal::Finite(value) => value.to_f32(),
Decimal::Zero => 0.0,
Decimal::NegZero => -0.0,
Decimal::Infinity => f32::INFINITY,
Decimal::NegInfinity => f32::NEG_INFINITY,
Decimal::Nan => f32::NAN,
}
}
pub fn into_f64(&self) -> f64 {
match self {
Decimal::Finite(value) => value.to_f64(),
Decimal::Zero => 0.0,
Decimal::NegZero => -0.0,
Decimal::Infinity => f64::INFINITY,
Decimal::NegInfinity => f64::NEG_INFINITY,
Decimal::Nan => f64::NAN,
}
}
pub fn is_integer(&self) -> bool {
match self {
Decimal::Finite(big_value) => {
big_value.is_integer() && big_value.to_f64().is_finite()
}
Decimal::Zero => true,
Decimal::NegZero => true,
Decimal::Infinity => false,
Decimal::NegInfinity => false,
Decimal::Nan => false,
}
}
pub fn as_integer(&self) -> Option<i64> {
if !self.is_integer() {
return None;
}
match self {
Decimal::Finite(big_value) => big_value.to_i64(),
Decimal::Zero => Some(0),
Decimal::NegZero => Some(-0),
_ => unreachable!("Not an integer"), }
}
pub fn is_finite(&self) -> bool {
core::matches!(
self,
Decimal::Finite(_) | Decimal::Zero | Decimal::NegZero
)
}
pub fn is_infinite(&self) -> bool {
core::matches!(self, Decimal::Infinity | Decimal::NegInfinity)
}
pub fn is_nan(&self) -> bool {
core::matches!(self, Decimal::Nan)
}
pub fn is_zero(&self) -> bool {
core::matches!(self, Decimal::Zero | Decimal::NegZero)
}
pub fn is_sign_positive(&self) -> bool {
match self {
Decimal::Finite(value) => value.is_positive(),
Decimal::Infinity | Decimal::Zero => true,
Decimal::NegZero | Decimal::Nan | Decimal::NegInfinity => false,
}
}
pub fn is_sign_negative(&self) -> bool {
match self {
Decimal::Finite(value) => value.is_negative(),
Decimal::NegZero | Decimal::NegInfinity => true,
Decimal::Zero | Decimal::Infinity | Decimal::Nan => false,
}
}
fn parse_decimal_to_rational(s: &str) -> Option<BigRational> {
let decimal = BigDecimal::from_str(s).ok()?;
let (bigint, scale) = decimal.as_bigint_and_exponent();
let ten = BigInt::from(10);
match scale.cmp(&0) {
Ordering::Equal => Some(BigRational::from(bigint)),
Ordering::Greater => {
let denominator = ten.pow(scale as u32);
Some(BigRational::new(bigint, denominator))
}
Ordering::Less => {
let numerator = bigint * ten.pow((-scale) as u32);
Some(BigRational::from(numerator))
}
}
}
pub fn try_from_string(s: &str) -> Result<Self, NumberParseError> {
match s {
DECIMAL_INFINITY => Ok(Decimal::Infinity),
DECIMAL_NEG_INFINITY => Ok(Decimal::NegInfinity),
DECIMAL_NAN => Ok(Decimal::Nan),
_ => {
let s = &s.trim().replace('_', "");
if s.contains("/") {
let parts: Vec<&str> = s.split('/').collect();
if parts.len() == 2 {
let numer = BigInt::from_str(parts[0])
.map_err(|_| NumberParseError::InvalidFormat)?;
let denom = BigInt::from_str(parts[1])
.map_err(|_| NumberParseError::InvalidFormat)?;
if denom.is_zero() {
return Err(NumberParseError::InvalidFormat);
}
let rational = BigRational::new(numer, denom);
Ok(Decimal::from(Rational::from_big_rational(rational)))
} else {
Err(NumberParseError::InvalidFormat)
}
} else {
let big_rational = Decimal::parse_decimal_to_rational(s);
match big_rational {
Some(big_rational) => {
if big_rational.is_zero() {
if s.starts_with('-') {
Ok(Decimal::NegZero)
} else {
Ok(Decimal::Zero)
}
} else {
Ok(Decimal::Finite(
Rational::from_big_rational(big_rational),
))
}
}
None => Err(NumberParseError::InvalidFormat),
}
}
}
}
}
}
impl Display for Decimal {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Decimal::Finite(value) => core::write!(f, "{value}"),
Decimal::Nan => core::write!(f, "{}", DECIMAL_NAN),
Decimal::Infinity => core::write!(f, "{}", DECIMAL_INFINITY),
Decimal::NegInfinity => core::write!(f, "{}", DECIMAL_NEG_INFINITY),
Decimal::Zero => core::write!(f, "0.0"),
Decimal::NegZero => core::write!(f, "-0.0"),
}
}
}
impl TryFrom<BigDecimalType> for Decimal {
type Error = ();
fn try_from(value: BigDecimalType) -> Result<Self, Self::Error> {
match value {
BigDecimalType::Zero => Ok(Decimal::Zero),
BigDecimalType::NegZero => Ok(Decimal::NegZero),
BigDecimalType::Infinity => Ok(Decimal::Infinity),
BigDecimalType::NegInfinity => Ok(Decimal::NegInfinity),
BigDecimalType::NaN => Ok(Decimal::Nan),
BigDecimalType::Finite => Err(()), }
}
}
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
#[repr(u8)]
pub enum BigDecimalType {
Finite = 0x00,
Zero = 0x01,
NegZero = 0x02,
Infinity = 0x03,
NegInfinity = 0x04,
NaN = 0x05,
}
impl From<&Decimal> for BigDecimalType {
fn from(value: &Decimal) -> Self {
match value {
Decimal::Finite(_) => BigDecimalType::Finite,
Decimal::Zero => BigDecimalType::Zero,
Decimal::NegZero => BigDecimalType::NegZero,
Decimal::Infinity => BigDecimalType::Infinity,
Decimal::NegInfinity => BigDecimalType::NegInfinity,
Decimal::Nan => BigDecimalType::NaN,
}
}
}
impl From<Rational> for Decimal {
fn from(value: Rational) -> Self {
if value.is_zero() {
Decimal::Zero
} else {
Decimal::Finite(value)
}
}
}
impl From<f32> for Decimal {
fn from(value: f32) -> Self {
if value.is_nan() {
Decimal::Nan
} else if value.is_infinite() {
if value.is_sign_positive() {
Decimal::Infinity
} else {
Decimal::NegInfinity
}
} else if value.is_zero() && value.is_sign_negative() {
Decimal::NegZero
} else if value.is_zero() {
Decimal::Zero
} else {
Decimal::Finite(Rational::from_big_rational(
BigRational::from_f32(value).unwrap(),
))
}
}
}
impl From<TypedDecimal> for Decimal {
fn from(value: TypedDecimal) -> Self {
match value {
TypedDecimal::F32(ordered_float) => {
Decimal::from(ordered_float.into_inner())
}
TypedDecimal::F64(ordered_float) => {
Decimal::from(ordered_float.into_inner())
}
TypedDecimal::Decimal(big_decimal) => big_decimal,
}
}
}
impl From<f64> for Decimal {
fn from(value: f64) -> Self {
if value.is_nan() {
Decimal::Nan
} else if value.is_infinite() {
if value.is_sign_positive() {
Decimal::Infinity
} else {
Decimal::NegInfinity
}
} else if value.is_zero() && value.is_sign_negative() {
Decimal::NegZero
} else if value.is_zero() {
Decimal::Zero
} else {
Decimal::Finite(Rational::from_big_rational(
BigRational::from_f64(value).unwrap(),
))
}
}
}
#[cfg(test)]
mod tests {
use crate::{
prelude::*,
traits::{structural_eq::StructuralEq, value_eq::ValueEq},
values::core_values::decimal::Decimal,
};
use core::assert_matches;
#[test]
fn decimal_addition() {
let dec1 = Decimal::try_from_string("12.34").unwrap();
let dec2 = Decimal::try_from_string("56.78").unwrap();
let result = dec1 + dec2;
assert_eq!(result.to_string(), "69.12");
let dec1 = Decimal::try_from_string("-12345.678901234536784").unwrap();
let dec2 = Decimal::try_from_string("3").unwrap();
let result = dec1 + dec2;
assert_eq!(result.to_string(), "-12342.678901234536784");
let dec1 = Decimal::try_from_string("1/3").unwrap();
let dec2 = Decimal::try_from_string("1/3").unwrap();
let result = dec1 + dec2;
assert_eq!(result.to_string(), "2/3");
}
#[test]
fn formatting() {
let dec1 = Decimal::try_from_string("12.34").unwrap();
assert_eq!(dec1.to_string(), "12.34");
let dec2 = Decimal::try_from_string("0.001").unwrap();
assert_eq!(dec2.to_string(), "0.001");
let dec3 = Decimal::try_from_string("-0.001").unwrap();
assert_eq!(dec3.to_string(), "-0.001");
let dec4 = Decimal::try_from_string("infinity").unwrap();
assert_eq!(dec4.to_string(), "infinity");
let dec5 = Decimal::try_from_string("-infinity").unwrap();
assert_eq!(dec5.to_string(), "-infinity");
let dec6 = Decimal::try_from_string("nan").unwrap();
assert_eq!(dec6.to_string(), "nan");
let dec7 = Decimal::try_from_string("1234567").unwrap();
assert_eq!(dec7.to_string(), "1234567.0");
let dec8 = Decimal::try_from_string("-1234567").unwrap();
assert_eq!(dec8.to_string(), "-1234567.0");
let dec9 = Decimal::try_from_string("-0").unwrap();
assert_eq!(dec9.to_string(), "-0.0");
let dec10 = Decimal::try_from_string("0").unwrap();
assert_eq!(dec10.to_string(), "0.0");
let dec11 = Decimal::try_from_string("1/3").unwrap();
assert_eq!(dec11.to_string(), "1/3");
let dec12 = Decimal::try_from_string("-1/3").unwrap();
assert_eq!(dec12.to_string(), "-1/3");
let dec13 = Decimal::try_from_string("1/2").unwrap();
assert_eq!(dec13.to_string(), "0.5");
let dec14 = Decimal::try_from_string("824/16").unwrap();
assert_eq!(dec14.to_string(), "51.5");
}
#[test]
fn zero() {
let a = Decimal::from(0.0f32);
assert!(core::matches!(a, Decimal::Zero));
assert!(!core::matches!(a, Decimal::NegZero));
let b = Decimal::from(0.0f64);
assert!(core::matches!(b, Decimal::Zero));
assert!(!core::matches!(b, Decimal::NegZero));
let c = Decimal::try_from_string("0.0").unwrap();
assert!(core::matches!(c, Decimal::Zero));
assert!(!core::matches!(c, Decimal::NegZero));
}
#[test]
fn neg_zero() {
let a = Decimal::from(-0.0f32);
assert!(core::matches!(a, Decimal::NegZero));
assert!(!core::matches!(a, Decimal::Zero));
let b = Decimal::from(-0.0f64);
assert!(core::matches!(b, Decimal::NegZero));
assert!(!core::matches!(b, Decimal::Zero));
let c = Decimal::try_from_string("-0.0").unwrap();
assert!(core::matches!(c, Decimal::NegZero));
assert!(!core::matches!(c, Decimal::Zero));
}
#[test]
fn inf() {
let a = Decimal::from(f32::INFINITY);
assert!(core::matches!(a, Decimal::Infinity));
let b = Decimal::from(f64::INFINITY);
assert!(core::matches!(b, Decimal::Infinity));
let c = Decimal::try_from_string("infinity").unwrap();
assert!(core::matches!(c, Decimal::Infinity));
}
#[test]
fn neg_inf() {
let a = Decimal::from(f32::NEG_INFINITY);
assert!(core::matches!(a, Decimal::NegInfinity));
let b = Decimal::from(f64::NEG_INFINITY);
assert!(core::matches!(b, Decimal::NegInfinity));
let c = Decimal::try_from_string("-infinity").unwrap();
assert!(core::matches!(c, Decimal::NegInfinity));
}
#[test]
fn nan() {
let a = Decimal::from(f32::NAN);
assert!(core::matches!(a, Decimal::Nan));
let b = Decimal::from(f64::NAN);
assert!(core::matches!(b, Decimal::Nan));
let c = Decimal::try_from_string("nan").unwrap();
assert!(core::matches!(c, Decimal::Nan));
let a = Decimal::from(-f32::NAN);
assert!(core::matches!(a, Decimal::Nan));
let b = Decimal::from(-f64::NAN);
assert!(core::matches!(b, Decimal::Nan));
assert!(Decimal::try_from_string("-nan").is_err());
}
#[test]
fn finite() {
let a = Decimal::from(1.23f32);
assert!(core::matches!(a, Decimal::Finite(_)));
let b = Decimal::from(4.56f64);
assert!(core::matches!(b, Decimal::Finite(_)));
let c = Decimal::try_from_string("7.89").unwrap();
assert!(core::matches!(c, Decimal::Finite(_)));
let d = Decimal::try_from_string("-1.23").unwrap();
assert!(core::matches!(d, Decimal::Finite(_)));
}
#[test]
fn zero_neg_zero() {
let a = Decimal::try_from_string("0.0").unwrap();
let b = Decimal::try_from_string("-0.0").unwrap();
assert_matches!(a, Decimal::Zero);
assert_matches!(b, Decimal::NegZero);
assert_eq!(a, b);
}
#[test]
fn nan_eq() {
let a = Decimal::try_from_string("nan").unwrap();
let b = Decimal::try_from_string("nan").unwrap();
assert_eq!(a, b);
assert!(!a.structural_eq(&b));
assert!(!a.value_eq(&b));
let c = Decimal::Nan;
let d = Decimal::Nan;
assert_eq!(c, d);
assert!(!c.structural_eq(&d));
assert!(!c.value_eq(&d));
let e = Decimal::from(f32::NAN);
let f = Decimal::from(f32::NAN);
assert_eq!(e, f);
assert!(!e.structural_eq(&f));
assert!(!e.value_eq(&f));
let g = Decimal::from(f64::NAN);
let h = Decimal::from(f64::NAN);
assert_eq!(g, h);
assert!(!g.structural_eq(&h));
assert!(!g.value_eq(&h));
assert!(!a.structural_eq(&c));
assert!(!a.structural_eq(&e));
assert!(!a.structural_eq(&g));
assert!(!a.structural_eq(&h));
assert!(!b.structural_eq(&c));
assert!(!b.structural_eq(&e));
assert!(!b.structural_eq(&g));
assert!(!b.structural_eq(&h));
assert!(!c.structural_eq(&e));
assert!(!c.structural_eq(&g));
assert!(!c.structural_eq(&h));
assert!(!d.structural_eq(&e));
assert!(!d.structural_eq(&g));
assert!(!d.structural_eq(&h));
assert!(!e.structural_eq(&g));
assert!(!e.structural_eq(&h));
assert!(!f.structural_eq(&g));
assert!(!f.structural_eq(&h));
assert!(!g.structural_eq(&h));
}
#[test]
fn zero_eq() {
let a = Decimal::try_from_string("0.0").unwrap();
let b = Decimal::try_from_string("0.0").unwrap();
let c = Decimal::try_from_string("-0.0").unwrap();
assert_eq!(a, b);
assert_eq!(a, c);
assert!(a.structural_eq(&b));
assert!(a.structural_eq(&c));
assert!(b.structural_eq(&c));
assert!(a.value_eq(&b));
assert!(a.value_eq(&c));
assert!(b.value_eq(&c));
}
#[test]
fn equality() {
let a = Decimal::try_from_string("1.0").unwrap();
let b = Decimal::try_from_string("1.0").unwrap();
let c = Decimal::try_from_string("2.0").unwrap();
assert!(a.structural_eq(&b));
assert!(!a.structural_eq(&c));
assert!(!b.structural_eq(&c));
let d = Decimal::try_from_string("infinity").unwrap();
let e = Decimal::try_from_string("-infinity").unwrap();
assert!(
d.structural_eq(&Decimal::try_from_string("infinity").unwrap())
);
assert!(
e.structural_eq(&Decimal::try_from_string("-infinity").unwrap())
);
}
#[test]
fn decimal_addition_2() {
let a = Decimal::try_from_string("1.0").unwrap();
let b = Decimal::try_from_string("2.0").unwrap();
let result = a + b;
assert_eq!(result, Decimal::try_from_string("3.0").unwrap());
let c = Decimal::try_from_string("1.5").unwrap();
let d = Decimal::try_from_string("2.5").unwrap();
let result2 = c + d;
assert_eq!(result2, Decimal::from(4.0));
let e = Decimal::try_from_string("0.1").unwrap();
let f = Decimal::try_from_string("0.2").unwrap();
let result3 = &e + &f;
assert_eq!(result3, Decimal::try_from_string("0.3").unwrap());
}
#[test]
fn infinity_calculations() {
let a = Decimal::try_from_string("1.0").unwrap();
let b = Decimal::try_from_string("infinity").unwrap();
let result = a + b;
assert_eq!(result, Decimal::try_from_string("infinity").unwrap());
let a = Decimal::try_from_string("infinity").unwrap();
let b = Decimal::try_from_string("-infinity").unwrap();
let result = a + b;
assert!(result.is_nan());
let a = Decimal::try_from_string("infinity").unwrap();
let b = Decimal::try_from_string("-0.0").unwrap();
let result = a + b;
assert_eq!(result, Decimal::try_from_string("infinity").unwrap());
let a = Decimal::try_from_string("-infinity").unwrap();
let b = Decimal::try_from_string("0.0").unwrap();
let result = a + b;
assert_eq!(result, Decimal::try_from_string("-infinity").unwrap());
let a = Decimal::try_from_string("0.0").unwrap();
let b = Decimal::try_from_string("-0.0").unwrap();
let result = a + b;
assert_eq!(result, Decimal::try_from_string("0.0").unwrap());
let a = Decimal::try_from_string("-0.0").unwrap();
let b = Decimal::try_from_string("0.0").unwrap();
let result = a + b;
assert_eq!(result, Decimal::try_from_string("0.0").unwrap());
let a = Decimal::try_from_string("nan").unwrap();
let b = Decimal::try_from_string("1.0").unwrap();
let result = a + b;
assert!(result.is_nan());
let a = Decimal::try_from_string("1.0").unwrap();
let b = Decimal::try_from_string("nan").unwrap();
let result = a + b;
assert!(result.is_nan());
let a = Decimal::try_from_string("nan").unwrap();
let b = Decimal::try_from_string("nan").unwrap();
let result = a + b;
assert!(result.is_nan());
}
#[test]
fn large_decimal_addition() {
let a = Decimal::try_from_string(
"100000000000000000000.00000000000000000001",
)
.unwrap();
let b = Decimal::try_from_string(
"100000000000000000000.00000000000000000001",
)
.unwrap();
let result = a + b;
assert_eq!(
result,
Decimal::try_from_string(
"200000000000000000000.00000000000000000002"
)
.unwrap()
);
}
#[test]
fn e_notation_decimal_addition() {
let a = Decimal::try_from_string("1e10").unwrap();
let b = Decimal::try_from_string("2e10").unwrap();
let result = a + b;
assert_eq!(result, Decimal::try_from_string("3e10").unwrap());
let c = Decimal::try_from_string("1.5e10").unwrap();
let d = Decimal::try_from_string("2.5e10").unwrap();
let result2 = c + d;
assert_eq!(result2, Decimal::try_from_string("4e10").unwrap());
}
}