use crate::const_scale_fpdec::ConstScaleFpdec;
use crate::fpdec_inner::FpdecInner;
use crate::ParseError;
use core::{fmt, ops, str::FromStr};
use int_div_cum_error::{checked_divide, Rounding};
use num_traits::{cast::FromPrimitive, float::FloatCore, Num};
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Default, Debug)]
pub struct OobScaleFpdec<I>(I);
impl<I> OobScaleFpdec<I>
where
I: FpdecInner,
{
crate::none_scale_common::define_none_scale_common!();
pub fn checked_mul<J>(
self,
rhs: OobScaleFpdec<J>,
diff_scale: i32, ) -> Option<OobScaleFpdec<I>>
where
J: FpdecInner,
{
self.checked_mul_ext(rhs, diff_scale, Rounding::Round, None)
}
pub fn checked_mul_ext<J>(
self,
rhs: OobScaleFpdec<J>,
diff_scale: i32, rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<OobScaleFpdec<I>>
where
J: FpdecInner,
{
self.0
.checked_mul_ext(I::from(rhs.0)?, diff_scale, rounding, cum_error)
.map(Self)
}
pub fn checked_div<J>(
self,
rhs: OobScaleFpdec<J>,
diff_scale: i32, ) -> Option<OobScaleFpdec<I>>
where
J: FpdecInner,
{
self.checked_div_ext(rhs, diff_scale, Rounding::Round, None)
}
pub fn checked_div_ext<J>(
self,
rhs: OobScaleFpdec<J>,
diff_scale: i32, rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<OobScaleFpdec<I>>
where
J: FpdecInner,
{
self.0
.checked_div_ext(I::from(rhs.0)?, diff_scale, rounding, cum_error)
.map(Self)
}
pub fn round_diff(self, diff_scale: i32) -> Self {
self.round_diff_with_rounding(diff_scale, Rounding::Round)
}
pub fn round_diff_with_rounding(self, diff_scale: i32, rounding: Rounding) -> Self {
Self(self.0.round_diff_with_rounding(diff_scale, rounding))
}
pub fn try_from_str(s: &str, scale: i32) -> Result<Self, ParseError>
where
ParseError: From<<I as Num>::FromStrRadixErr>,
{
I::try_from_str(s, scale).map(Self)
}
pub fn to_float<F>(self, scale: i32) -> F
where
F: FloatCore,
{
let base = F::from(10.0).unwrap();
F::from(self.0).unwrap() / base.powi(scale)
}
}
impl<I, const S: i32> From<ConstScaleFpdec<I, S>> for OobScaleFpdec<I>
where
I: FpdecInner,
{
fn from(sd: ConstScaleFpdec<I, S>) -> Self {
Self(sd.mantissa())
}
}
macro_rules! convert_from_int {
($from_int_type:ty) => {
impl<I> TryFrom<($from_int_type, i32)> for OobScaleFpdec<I>
where
I: FpdecInner,
{
type Error = ParseError;
fn try_from(i: ($from_int_type, i32)) -> Result<Self, Self::Error> {
if i.1 > 0 {
let i2 = I::from(i.0).ok_or(ParseError::Overflow)?;
I::checked_from_int(i2, i.1).map(Self)
} else {
let i2 = i.0.checked_from_int(i.1)?;
I::from(i2).ok_or(ParseError::Overflow).map(Self)
}
}
}
};
}
convert_from_int!(i8);
convert_from_int!(i16);
convert_from_int!(i32);
convert_from_int!(i64);
convert_from_int!(i128);
macro_rules! convert_from_float {
($float_type:ty, $from_fn:ident, $to_fn:ident) => {
impl<I> TryFrom<($float_type, i32)> for OobScaleFpdec<I>
where
I: FromPrimitive + FpdecInner,
{
type Error = ParseError;
fn try_from(f: ($float_type, i32)) -> Result<Self, Self::Error> {
let base: $float_type = 10.0;
let inner_f = f.0 * base.powi(f.1) as $float_type;
I::$from_fn(inner_f.round())
.map(Self)
.ok_or(ParseError::Overflow)
}
}
};
}
convert_from_float!(f32, from_f32, to_f32);
convert_from_float!(f64, from_f64, to_f64);
impl<I> ops::Neg for OobScaleFpdec<I>
where
I: FpdecInner,
{
type Output = Self;
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
impl<I> ops::Add for OobScaleFpdec<I>
where
I: FpdecInner,
{
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl<I> ops::Sub for OobScaleFpdec<I>
where
I: FpdecInner,
{
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self(self.0 - rhs.0)
}
}
impl<I> ops::AddAssign for OobScaleFpdec<I>
where
I: FpdecInner,
{
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0;
}
}
impl<I> ops::SubAssign for OobScaleFpdec<I>
where
I: FpdecInner,
{
fn sub_assign(&mut self, rhs: Self) {
self.0 -= rhs.0;
}
}
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Default, Debug)]
pub struct OobFmt<I>(pub OobScaleFpdec<I>, pub i32);
impl<I> fmt::Display for OobFmt<I>
where
I: FpdecInner + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let scale = self.1;
self.0 .0.display_fmt(scale, f)
}
}
impl<I> FromStr for OobFmt<I>
where
I: FpdecInner,
ParseError: From<<I as Num>::FromStrRadixErr>,
{
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (inner, scale) = I::try_from_str_only(s)?;
Ok(OobFmt(OobScaleFpdec(inner), scale))
}
}
impl<I> OobFmt<I>
where
I: FpdecInner,
{
pub fn rescale(self, scale2: i32) -> Result<OobScaleFpdec<I>, ParseError> {
let OobFmt(dec, scale0) = self;
if scale2 == scale0 {
Ok(dec)
} else if scale2 > scale0 {
let inner = I::get_exp((scale2 - scale0) as usize)
.ok_or(ParseError::Overflow)?
.checked_mul(&dec.0)
.ok_or(ParseError::Overflow)?;
Ok(OobScaleFpdec(inner))
} else {
let diff_exp = I::get_exp((scale0 - scale2) as usize).ok_or(ParseError::Precision)?;
let inner = dec.0 / diff_exp;
if (dec.0 % diff_exp).is_zero() {
Ok(OobScaleFpdec(inner))
} else {
Err(ParseError::Precision)
}
}
}
}
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
impl<I> Serialize for OobFmt<I>
where
I: FpdecInner + fmt::Display,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
#[cfg(feature = "serde")]
impl<'de, I> Deserialize<'de> for OobFmt<I>
where
I: FromPrimitive + FpdecInner,
ParseError: From<<I as Num>::FromStrRadixErr>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use core::marker::PhantomData;
use core::str::FromStr;
use serde::de::{self, Visitor};
struct OobFmtVistor<I>(PhantomData<I>);
impl<'de, I> Visitor<'de> for OobFmtVistor<I>
where
I: FromPrimitive + FpdecInner,
ParseError: From<<I as Num>::FromStrRadixErr>,
{
type Value = OobFmt<I>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "decimal")
}
fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> {
OobFmt::from_str(s).map_err(E::custom)
}
}
deserializer.deserialize_str(OobFmtVistor(PhantomData))
}
}