use bigdecimal::BigDecimal;
use bigdecimal::num_bigint::{BigInt, BigUint, Sign};
use bigdecimal::num_traits::Zero;
use crate::ascii::Dropped;
use crate::round::decide;
use crate::{Dec19, OutOfRange, Round, TryFromBigError, UDec19};
fn to_steps(
x: &BigDecimal,
mode: Option<Round>,
) -> Result<(bool, u128, bool), OutOfRange> {
let (digits, scale) = x.as_bigint_and_scale();
let negative = digits.sign() == Sign::Minus;
let magnitude = digits.magnitude();
if magnitude.is_zero() {
return Ok((false, 0, false));
}
let ten = BigUint::from(10u8);
let shift = 19 - scale as i128;
if shift >= 0 {
if shift > 38 {
return Err(OutOfRange);
}
let stored = magnitude * ten.pow(shift as u32);
let stored = u128::try_from(&stored).map_err(|_| OutOfRange)?;
return Ok((negative, stored, false));
}
let k = -shift;
let (q, dropped) = if (x.digits() as i128) < k {
(0, Dropped::BelowHalf)
} else {
let unit = ten.pow(k as u32);
let q = magnitude / &unit;
let r = magnitude % &unit;
let q = u128::try_from(&q).map_err(|_| OutOfRange)?;
let dropped = if r.is_zero() {
Dropped::Nothing
} else {
match (r << 1u32).cmp(&unit) {
core::cmp::Ordering::Less => Dropped::BelowHalf,
core::cmp::Ordering::Equal => Dropped::Half,
core::cmp::Ordering::Greater => Dropped::AboveHalf,
}
};
(q, dropped)
};
let inexact = !matches!(dropped, Dropped::Nothing);
let Some(mode) = mode else {
return Ok((negative, q, inexact));
};
let away = decide(
mode,
negative,
q & 1 == 1,
matches!(dropped, Dropped::AboveHalf),
matches!(dropped, Dropped::Half),
inexact,
);
let q = q.checked_add(away as u128).ok_or(OutOfRange)?;
Ok((negative, q, false))
}
macro_rules! impl_big {
($T:ident, $mac:literal) => {
impl From<$T> for BigDecimal {
fn from(v: $T) -> BigDecimal {
BigDecimal::new(BigInt::from(v.to_raw()), 19)
}
}
impl $T {
#[doc = concat!("```\nuse decimix::{", stringify!($T), ", Round, ", $mac, "};\n")]
#[doc = concat!("let b = ", $mac, "!(113.725).to_big();")]
#[doc = "assert_eq!(b.to_string(), \"113.7250000000000000000\");"]
#[doc = "```"]
#[must_use]
pub fn to_big(self) -> BigDecimal {
self.into()
}
pub fn from_big(x: &BigDecimal, mode: Round) -> Result<Self, OutOfRange> {
let (negative, magnitude, _) = to_steps(x, Some(mode))?;
Self::from_parts(negative, magnitude).ok_or(OutOfRange)
}
}
impl TryFrom<&BigDecimal> for $T {
type Error = TryFromBigError;
fn try_from(x: &BigDecimal) -> Result<Self, TryFromBigError> {
let (negative, magnitude, inexact) =
to_steps(x, None).map_err(|_| TryFromBigError::OutOfRange)?;
let v = Self::from_parts(negative, magnitude)
.ok_or(TryFromBigError::OutOfRange)?;
if inexact {
return Err(TryFromBigError::Inexact);
}
Ok(v)
}
}
};
}
impl_big!(Dec19, "dec");
impl_big!(UDec19, "udec");