use std::{
cmp::Ordering,
error, fmt,
hash::{Hash, Hasher},
str::FromStr,
};
use crate::types::{Decimal, Int256, UInt256};
pub(crate) const MAX_PRECISION: u8 = 76;
#[derive(Clone, Copy)]
pub struct Decimal256 {
value: Int256,
precision: u8,
scale: u8,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParseDecimal256Error;
impl fmt::Display for ParseDecimal256Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("not a decimal of at most 76 digits")
}
}
impl error::Error for ParseDecimal256Error {}
impl Decimal256 {
pub fn new(value: Int256, scale: u8) -> Decimal256 {
if scale > MAX_PRECISION {
panic!("scale can't be greater than {MAX_PRECISION}");
}
let decimal = Decimal256::from_raw(value, MAX_PRECISION, scale);
if !decimal.fits(MAX_PRECISION) {
panic!("{value} has more than {MAX_PRECISION} digits");
}
decimal
}
pub(crate) fn from_raw(value: Int256, precision: u8, scale: u8) -> Decimal256 {
Decimal256 {
value,
precision,
scale,
}
}
pub fn internal(&self) -> Int256 {
self.value
}
pub(crate) fn internal_ref(&self) -> &Int256 {
&self.value
}
pub fn scale(&self) -> usize {
usize::from(self.scale)
}
pub fn precision(&self) -> usize {
usize::from(self.precision)
}
pub(crate) fn fits(&self, precision: u8) -> bool {
precision <= MAX_PRECISION
&& UInt256::pow10(u32::from(precision))
.is_some_and(|limit| self.value.unsigned_abs() < limit)
}
pub(crate) fn rescaled(&self, scale: u8) -> Option<Int256> {
let negative = self.value.is_negative();
let mut magnitude = self.value.unsigned_abs();
match scale.cmp(&self.scale) {
Ordering::Equal => return Some(self.value),
Ordering::Greater => {
for _ in self.scale..scale {
magnitude = magnitude.checked_mul_small(10)?;
}
}
Ordering::Less => {
for _ in scale..self.scale {
magnitude = magnitude.div_rem_small(10).0;
}
}
}
Int256::from_sign_magnitude(negative, magnitude)
}
fn normalized(&self) -> (bool, UInt256, u8) {
let mut magnitude = self.value.unsigned_abs();
let mut scale = self.scale;
while scale > 0 {
let (quotient, rem) = magnitude.div_rem_small(10);
if rem != 0 {
break;
}
magnitude = quotient;
scale -= 1;
}
(self.value.is_negative(), magnitude, scale)
}
}
impl From<Decimal> for Decimal256 {
fn from(decimal: Decimal) -> Self {
Decimal256::from_raw(
Int256::from(decimal.internal128()),
MAX_PRECISION,
decimal.scale,
)
}
}
impl PartialEq for Decimal256 {
fn eq(&self, other: &Self) -> bool {
self.normalized() == other.normalized()
}
}
impl Eq for Decimal256 {}
impl Hash for Decimal256 {
fn hash<H: Hasher>(&self, state: &mut H) {
self.normalized().hash(state);
}
}
impl fmt::Display for Decimal256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut digits = self.value.unsigned_abs().to_string();
let scale = self.scale();
while digits.len() <= scale {
digits.insert(0, '0');
}
if scale > 0 {
digits.insert(digits.len() - scale, '.');
}
if self.value.is_negative() {
digits.insert(0, '-');
}
f.write_str(&digits)
}
}
impl fmt::Debug for Decimal256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl FromStr for Decimal256 {
type Err = ParseDecimal256Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let (negative, body) = match text.as_bytes().first() {
Some(b'-') => (true, &text[1..]),
Some(b'+') => (false, &text[1..]),
_ => (false, text),
};
let (whole, fraction) = body.split_once('.').unwrap_or((body, ""));
let digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit());
if whole.is_empty() && fraction.is_empty() || !digits(whole) || !digits(fraction) {
return Err(ParseDecimal256Error);
}
let scale = u8::try_from(fraction.len()).map_err(|_| ParseDecimal256Error)?;
let magnitude: UInt256 = format!("{whole}{fraction}")
.parse()
.map_err(|_| ParseDecimal256Error)?;
let value = Int256::from_sign_magnitude(negative, magnitude).ok_or(ParseDecimal256Error)?;
let decimal = Decimal256::from_raw(value, MAX_PRECISION, scale);
if scale > MAX_PRECISION || !decimal.fits(MAX_PRECISION) {
return Err(ParseDecimal256Error);
}
Ok(decimal)
}
}
impl From<Decimal256> for f64 {
fn from(decimal: Decimal256) -> Self {
decimal.to_string().parse().unwrap_or(f64::NAN)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_text() {
let largest = "9".repeat(76);
let d: Decimal256 = largest.parse().unwrap();
assert_eq!(d.to_string(), largest);
assert!("1".repeat(77).parse::<Decimal256>().is_err());
for text in ["-0.05", "0.000", "7", "123.4500", "-1", "+5.5"] {
let d: Decimal256 = text.parse().unwrap();
assert_eq!(d.to_string(), text.trim_start_matches('+'), "{text}");
}
for text in ["", ".", "1.2.3", "--1", "1a", "-"] {
assert!(text.parse::<Decimal256>().is_err(), "{text}");
}
assert_eq!(".5".parse::<Decimal256>().unwrap().to_string(), "0.5");
}
#[test]
fn test_equality_and_rescaling() {
let a: Decimal256 = "2.0".parse().unwrap();
let b: Decimal256 = "2.000".parse().unwrap();
assert_eq!(a, b);
assert_ne!(a, "2.01".parse::<Decimal256>().unwrap());
assert_eq!(a.rescaled(3), Some(b.internal()));
let cut: Decimal256 = "-1.239".parse().unwrap();
assert_eq!(cut.rescaled(2), Some(Int256::from(-123)));
let largest: Decimal256 = "9".repeat(76).parse().unwrap();
assert_eq!(largest.rescaled(10), None);
assert!(largest.fits(76) && !largest.fits(75));
let from_decimal = Decimal256::from(Decimal::new(12345, 2));
assert_eq!(from_decimal.precision(), 76);
assert_eq!(from_decimal, "123.45".parse().unwrap());
assert_eq!(f64::from(from_decimal), 123.45);
let exact: Decimal256 = "900719925474099.5".parse().unwrap();
assert_eq!(f64::from(exact), 900_719_925_474_099.5);
let wide: Decimal256 = "166153499473114502559719956244594689".parse().unwrap();
assert_eq!(f64::from(wide), 1.6615349947311452e35);
assert!(!wide.fits(78));
}
}