use crate::fpdec_inner::FpdecInner;
use crate::static_prec_fpdec::StaticPrecFpdec;
use crate::ParseError;
use int_div_cum_error::{checked_divide, Rounding};
use num_traits::{cast::FromPrimitive, float::Float, Num};
use std::fmt;
use std::str::FromStr;
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Default, Debug)]
pub struct OobPrecFpdec<I>(I);
impl<I> OobPrecFpdec<I>
where
I: FpdecInner,
{
crate::none_prec_common::define_none_prec_common!();
pub fn checked_mul<J>(
self,
rhs: OobPrecFpdec<J>,
diff_precision: i32, ) -> Option<OobPrecFpdec<I>>
where
J: FpdecInner,
{
self.checked_mul_ext(rhs, diff_precision, Rounding::Round, None)
}
pub fn checked_mul_ext<J>(
self,
rhs: OobPrecFpdec<J>,
diff_precision: i32, rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<OobPrecFpdec<I>>
where
J: FpdecInner,
{
self.0
.checked_mul_ext(I::from(rhs.0)?, diff_precision, rounding, cum_error)
.map(Self)
}
pub fn checked_div<J>(
self,
rhs: OobPrecFpdec<J>,
diff_precision: i32, ) -> Option<OobPrecFpdec<I>>
where
J: FpdecInner,
{
self.checked_div_ext(rhs, diff_precision, Rounding::Round, None)
}
pub fn checked_div_ext<J>(
self,
rhs: OobPrecFpdec<J>,
diff_precision: i32, rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<OobPrecFpdec<I>>
where
J: FpdecInner,
{
self.0
.checked_div_ext(I::from(rhs.0)?, diff_precision, rounding, cum_error)
.map(Self)
}
pub fn shrink(self, reduce_precision: i32) -> Self {
self.shrink_with_rounding(reduce_precision, Rounding::Round)
}
pub fn shrink_with_rounding(self, reduce_precision: i32, rounding: Rounding) -> Self {
Self(self.0.shrink_with_rounding(reduce_precision, rounding))
}
pub fn try_from_str(s: &str, precision: i32) -> Result<Self, ParseError>
where
ParseError: From<<I as Num>::FromStrRadixErr>,
{
I::try_from_str(s, precision).map(Self)
}
pub fn into_float<F>(self, precision: i32) -> F
where
F: Float,
{
let base = F::from(10.0).unwrap();
F::from(self.0).unwrap() / base.powi(precision)
}
}
macro_rules! convert_from_int {
($from_int_type:ty) => {
impl<I> TryFrom<($from_int_type, i32)> for OobPrecFpdec<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 = <$from_int_type>::checked_from_int(i.0, 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 OobPrecFpdec<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> OobPrecFpdec<I>
where
I: FpdecInner,
{
pub fn checked_mul_static<J, const Q: i32>(self, rhs: StaticPrecFpdec<J, Q>) -> Option<Self>
where
J: FpdecInner,
{
self.checked_mul_static_ext(rhs, Rounding::Round, None)
}
pub fn checked_mul_static_ext<J, const Q: i32>(
self,
rhs: StaticPrecFpdec<J, Q>,
rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<Self>
where
J: FpdecInner,
{
self.0
.checked_mul_ext(I::from(rhs.get_inner())?, Q, rounding, cum_error)
.map(Self)
}
pub fn checked_div_static<J, const Q: i32>(self, rhs: StaticPrecFpdec<J, Q>) -> Option<Self>
where
J: FpdecInner,
{
self.checked_div_static_ext(rhs, Rounding::Round, None)
}
pub fn checked_div_static_ext<J, const Q: i32>(
self,
rhs: StaticPrecFpdec<J, Q>,
rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<Self>
where
J: FpdecInner,
{
self.0
.checked_div_ext(I::from(rhs.get_inner())?, -Q, rounding, cum_error)
.map(Self)
}
}
impl<I> std::ops::Neg for OobPrecFpdec<I>
where
I: FpdecInner,
{
type Output = Self;
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
impl<I> std::ops::Add for OobPrecFpdec<I>
where
I: FpdecInner,
{
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl<I> std::ops::Sub for OobPrecFpdec<I>
where
I: FpdecInner,
{
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self(self.0 - rhs.0)
}
}
impl<I> std::ops::AddAssign for OobPrecFpdec<I>
where
I: FpdecInner,
{
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0;
}
}
impl<I> std::ops::SubAssign for OobPrecFpdec<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 OobPrecFpdec<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 precision = self.1;
self.0 .0.display_fmt(precision, 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, precision) = I::try_from_str_only(s)?;
Ok(OobFmt(OobPrecFpdec(inner), precision))
}
}
impl<I> OobFmt<I>
where
I: FpdecInner,
{
pub fn rescale(self, precision: i32) -> Result<OobPrecFpdec<I>, ParseError> {
let OobFmt(dec, prec0) = self;
if precision == prec0 {
Ok(dec)
} else if precision > prec0 {
let inner = I::get_exp((precision - prec0) as usize)
.ok_or(ParseError::Overflow)?
.checked_mul(&dec.0)
.ok_or(ParseError::Overflow)?;
Ok(OobPrecFpdec(inner))
} else {
let diff_exp = I::get_exp((prec0 - precision) as usize).ok_or(ParseError::Precision)?;
let inner = dec.0 / diff_exp;
if (dec.0 % diff_exp).is_zero() {
Ok(OobPrecFpdec(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 serde::de::{self, Visitor};
use std::marker::PhantomData;
use std::str::FromStr;
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| E::custom(format!("decimal {:?}", e)))
}
}
deserializer.deserialize_str(OobFmtVistor(PhantomData))
}
}