use std::cmp::Ordering;
use std::fmt;
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Pow, Signed, ToPrimitive, Zero};
use crate::error::Fault;
use crate::int::Int;
pub const DIVISION_DIGITS: u32 = 34;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Decimal {
coefficient: BigInt,
exponent: i64,
}
impl Decimal {
pub fn new(coefficient: BigInt, exponent: i64) -> Result<Self, Fault> {
if coefficient.is_zero() {
return Ok(Decimal {
coefficient,
exponent: 0,
});
}
let (coefficient, zeros) = strip_zeros(coefficient);
let raised = i64::try_from(zeros)
.ok()
.and_then(|zeros| exponent.checked_add(zeros))
.ok_or(Fault::Limit)?;
Ok(Decimal {
coefficient,
exponent: raised,
})
}
pub fn parse(spelling: &str) -> Option<Self> {
let (whole, fraction) = spelling.split_once('.').unwrap_or((spelling, "0"));
Int::parse(whole)?;
if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
let coefficient = Int::parse(&format!("{whole}{fraction}"))?.into_bigint();
let exponent = i64::try_from(fraction.len()).ok()?;
Decimal::new(coefficient, -exponent).ok()
}
pub fn coefficient(&self) -> &BigInt {
&self.coefficient
}
pub fn exponent(&self) -> i64 {
self.exponent
}
pub fn is_zero(&self) -> bool {
self.coefficient.is_zero()
}
pub fn add(&self, other: &Decimal) -> Result<Decimal, Fault> {
if self.is_zero() {
return Ok(other.clone());
}
if other.is_zero() {
return Ok(self.clone());
}
let exponent = self.exponent.min(other.exponent);
let left = &self.coefficient * pow10(self.exponent.abs_diff(exponent));
let right = &other.coefficient * pow10(other.exponent.abs_diff(exponent));
Decimal::new(left + right, exponent)
}
pub fn sub(&self, other: &Decimal) -> Result<Decimal, Fault> {
self.add(&other.neg())
}
#[must_use]
pub fn neg(&self) -> Decimal {
Decimal {
coefficient: -&self.coefficient,
exponent: self.exponent,
}
}
pub fn mul(&self, other: &Decimal) -> Result<Decimal, Fault> {
let exponent = self
.exponent
.checked_add(other.exponent)
.ok_or(Fault::Limit)?;
Decimal::new(&self.coefficient * &other.coefficient, exponent)
}
pub fn div(&self, divisor: &Decimal) -> Result<Decimal, Fault> {
if divisor.is_zero() {
return Err(Fault::DivisionByZero);
}
let negative = self.coefficient.is_negative() != divisor.coefficient.is_negative();
let shared = self.coefficient.gcd(&divisor.coefficient);
let numerator = self.coefficient.abs() / &shared;
let denominator = divisor.coefficient.abs() / &shared;
let exponent = self
.exponent
.checked_sub(divisor.exponent)
.ok_or(Fault::Limit)?;
let (twos, fives, rest) = twos_and_fives(&denominator);
let (magnitude, exponent) = if rest.is_one() {
let k = twos.max(fives);
let factor = pow10(k) / &denominator;
let shifted = exponent
.checked_sub(i64::try_from(k).map_err(|_| Fault::Limit)?)
.ok_or(Fault::Limit)?;
(numerator * factor, shifted)
} else {
rounded_quotient(&numerator, &denominator, exponent)?
};
let signed = if negative { -magnitude } else { magnitude };
Decimal::new(signed, exponent)
}
pub fn floor(&self) -> Int {
if self.adjusted_exponent() <= 0 {
return Int::from(if self.coefficient.is_negative() {
BigInt::from(-1)
} else {
BigInt::zero()
});
}
let up = pow10(self.exponent.max(0).unsigned_abs());
let down = pow10(self.exponent.min(0).unsigned_abs());
Int::from((&self.coefficient * up).div_floor(&down))
}
pub fn floor_within(&self, max_bits: u64) -> Option<Int> {
if self.adjusted_exponent() > i128::from(max_bits) {
return None;
}
let floor = self.floor();
(floor.bits() <= max_bits).then_some(floor)
}
pub fn text_len(&self) -> u128 {
let digits = u128::from(digit_count(&self.coefficient));
let places = u128::from(self.exponent.unsigned_abs());
let plain = if self.exponent >= 0 {
digits + places
} else if digits > places {
digits + 1
} else {
places + 2
};
plain + u128::from(self.coefficient.is_negative())
}
fn adjusted_exponent(&self) -> i128 {
i128::from(self.exponent) + i128::from(digit_count(&self.coefficient))
}
}
impl From<&Int> for Decimal {
fn from(value: &Int) -> Self {
Decimal::new(value.as_bigint().clone(), 0)
.expect("an integer has fewer trailing zeros than an exponent can count")
}
}
impl Ord for Decimal {
fn cmp(&self, other: &Self) -> Ordering {
let by_sign = self.coefficient.sign().cmp(&other.coefficient.sign());
if by_sign != Ordering::Equal {
return by_sign;
}
let magnitude = self
.adjusted_exponent()
.cmp(&other.adjusted_exponent())
.then_with(|| {
let (left, right) = (self.coefficient.magnitude(), other.coefficient.magnitude());
let shift = pow10(self.exponent.abs_diff(other.exponent)).into_parts().1;
if self.exponent > other.exponent {
(left * shift).cmp(right)
} else {
left.cmp(&(right * shift))
}
});
if self.coefficient.is_negative() {
magnitude.reverse()
} else {
magnitude
}
}
}
impl PartialOrd for Decimal {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let sign = if self.coefficient.is_negative() {
"-"
} else {
""
};
let digits = self.coefficient.magnitude().to_string();
let Ok(places) = usize::try_from(-self.exponent) else {
let zeros = "0".repeat(usize::try_from(self.exponent).unwrap_or(usize::MAX));
return write!(f, "{sign}{digits}{zeros}");
};
if places >= digits.len() {
let zeros = "0".repeat(places - digits.len());
write!(f, "{sign}0.{zeros}{digits}")
} else {
let (whole, fraction) = digits.split_at(digits.len() - places);
if fraction.is_empty() {
write!(f, "{sign}{whole}")
} else {
write!(f, "{sign}{whole}.{fraction}")
}
}
}
}
impl fmt::Debug for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
fn pow10(places: u64) -> BigInt {
Pow::pow(BigInt::from(10), places)
}
fn digit_count(value: &BigInt) -> u64 {
let magnitude = value.magnitude();
if let Some(small) = magnitude.to_u64() {
return small
.checked_ilog10()
.map_or(1, |below| u64::from(below) + 1);
}
let bits = u128::from(magnitude.bits());
let estimate = (bits - 1) * 301_029_995_663_981 / 1_000_000_000_000_000;
let mut digits = u64::try_from(estimate).expect("a third of a bit count fits 64 bits") + 1;
let mut next = pow10(digits);
while magnitude >= next.magnitude() {
digits += 1;
next *= 10;
}
digits
}
fn strip_zeros(coefficient: BigInt) -> (BigInt, u64) {
let twos = coefficient.trailing_zeros().unwrap_or(0);
let mut rest = coefficient;
let mut zeros = 0;
for (step, power) in [(19, 10_000_000_000_000_000_000_u64), (1, 10)] {
while twos - zeros >= step {
let (quotient, remainder) = rest.div_rem(&BigInt::from(power));
if !remainder.is_zero() {
break;
}
rest = quotient;
zeros += step;
}
}
(rest, zeros)
}
fn twos_and_fives(value: &BigInt) -> (u64, u64, BigInt) {
let mut rest = value.clone();
let twos = rest.trailing_zeros().unwrap_or(0);
rest >>= twos;
let five = BigInt::from(5);
let mut fives = 0;
for _ in 0..value.bits() {
let (quotient, remainder) = rest.div_rem(&five);
if !remainder.is_zero() {
break;
}
rest = quotient;
fives += 1;
}
(twos, fives, rest)
}
fn rounded_quotient(
numerator: &BigInt,
denominator: &BigInt,
exponent: i64,
) -> Result<(BigInt, i64), Fault> {
let digits = i64::from(DIVISION_DIGITS);
let low = pow10(u64::from(DIVISION_DIGITS));
let mut shift = digits + digits_i64(denominator) - digits_i64(numerator);
let mut guarded = shifted_quotient(numerator, denominator, shift);
if guarded < low {
shift += 1;
guarded = shifted_quotient(numerator, denominator, shift);
}
let rounded = (guarded + 5) / 10;
let exponent = exponent.checked_sub(shift - 1).ok_or(Fault::Limit)?;
Ok((rounded, exponent))
}
fn shifted_quotient(numerator: &BigInt, denominator: &BigInt, shift: i64) -> BigInt {
let places = shift.unsigned_abs();
if shift >= 0 {
(numerator * pow10(places)) / denominator
} else {
numerator / (denominator * pow10(places))
}
}
fn digits_i64(value: &BigInt) -> i64 {
i64::try_from(digit_count(value)).unwrap_or(i64::MAX)
}