use crate::fpdec_inner::FpdecInner;
use crate::oob_scale_fpdec::OobScaleFpdec;
use crate::ParseError;
use core::{fmt, ops, str::FromStr};
use int_div_cum_error::{checked_divide, Rounding};
#[allow(unused_imports)]
use num_traits::float::FloatCore; use num_traits::{cast::FromPrimitive, Num};
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Default)]
pub struct ConstScaleFpdec<I, const S: i32>(I);
impl<I, const S: i32> ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
crate::none_scale_common::define_none_scale_common!();
pub const SCALE: i32 = S;
pub fn checked_mul<J, const S2: i32, const SR: i32>(
self,
rhs: ConstScaleFpdec<J, S2>,
) -> Option<ConstScaleFpdec<I, SR>>
where
J: FpdecInner,
{
self.checked_mul_ext(rhs, Rounding::Round, None)
}
pub fn checked_mul_ext<J, const S2: i32, const SR: i32>(
self,
rhs: ConstScaleFpdec<J, S2>,
rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<ConstScaleFpdec<I, SR>>
where
J: FpdecInner,
{
self.0
.checked_mul_ext(I::from(rhs.0)?, S + S2 - SR, rounding, cum_error)
.map(ConstScaleFpdec)
}
pub fn checked_div<J, const S2: i32, const SR: i32>(
self,
rhs: ConstScaleFpdec<J, S2>,
) -> Option<ConstScaleFpdec<I, SR>>
where
J: FpdecInner,
{
self.checked_div_ext(rhs, Rounding::Round, None)
}
pub fn checked_div_ext<J, const S2: i32, const SR: i32>(
self,
rhs: ConstScaleFpdec<J, S2>,
rounding: Rounding,
cum_error: Option<&mut I>,
) -> Option<ConstScaleFpdec<I, SR>>
where
J: FpdecInner,
{
self.0
.checked_div_ext(I::from(rhs.0)?, S - S2 - SR, rounding, cum_error)
.map(ConstScaleFpdec)
}
pub fn round(self, scale: i32) -> Self {
self.round_with_rounding(scale, Rounding::Round)
}
pub fn round_with_rounding(self, scale: i32, rounding: Rounding) -> Self {
Self(self.0.round_diff_with_rounding(S - scale, rounding))
}
}
impl<I, const S: i32> fmt::Debug for ConstScaleFpdec<I, S>
where
I: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "Fpdec({},{})", self.0, S)
}
}
impl<I, const S: i32> fmt::Display for ConstScaleFpdec<I, S>
where
I: FpdecInner + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.0.display_fmt(S, f)
}
}
impl<I, const S: i32> FromStr for ConstScaleFpdec<I, S>
where
I: FpdecInner,
ParseError: From<<I as Num>::FromStrRadixErr>,
{
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, ParseError> {
I::try_from_str(s, S).map(Self)
}
}
impl<I, const S: i32> From<OobScaleFpdec<I>> for ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
fn from(od: OobScaleFpdec<I>) -> Self {
Self(od.mantissa())
}
}
macro_rules! convert_from_int {
($from_int_type:ty) => {
impl<I, const S: i32> TryFrom<$from_int_type> for ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
type Error = ParseError;
fn try_from(i: $from_int_type) -> Result<Self, Self::Error> {
if S > 0 {
let i2 = I::from(i).ok_or(ParseError::Overflow)?;
I::checked_from_int(i2, S).map(Self)
} else {
let i2 = i.checked_from_int(S)?;
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, const S: i32> TryFrom<$float_type> for ConstScaleFpdec<I, S>
where
I: FromPrimitive + FpdecInner,
{
type Error = ParseError;
fn try_from(f: $float_type) -> Result<Self, Self::Error> {
let base: $float_type = 10.0;
let inner_f = f * base.powi(S) as $float_type;
I::$from_fn(inner_f.round())
.map(Self)
.ok_or(ParseError::Overflow)
}
}
impl<I, const S: i32> From<ConstScaleFpdec<I, S>> for $float_type
where
I: FpdecInner,
{
fn from(dec: ConstScaleFpdec<I, S>) -> Self {
let base: $float_type = 10.0;
dec.0.$to_fn().unwrap() / base.powi(S)
}
}
};
}
convert_from_float!(f32, from_f32, to_f32);
convert_from_float!(f64, from_f64, to_f64);
impl<I, const S: i32> ops::Neg for ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
type Output = Self;
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
impl<I, const S: i32> ops::Add for ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl<I, const S: i32> ops::Sub for ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self(self.0 - rhs.0)
}
}
impl<I, const S: i32> ops::AddAssign for ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0;
}
}
impl<I, const S: i32> ops::SubAssign for ConstScaleFpdec<I, S>
where
I: FpdecInner,
{
fn sub_assign(&mut self, rhs: Self) {
self.0 -= rhs.0;
}
}
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
impl<I, const S: i32> Serialize for ConstScaleFpdec<I, S>
where
I: FpdecInner + fmt::Display,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
serializer.collect_str(self)
} else {
Into::<f64>::into(*self).serialize(serializer)
}
}
}
#[cfg(feature = "serde")]
impl<'de, I, const S: i32> Deserialize<'de> for ConstScaleFpdec<I, S>
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 ConstScaleFpdecVistor<I, const S: i32>(PhantomData<I>);
macro_rules! visit_num {
($func_name:ident, $num_type:ty) => {
fn $func_name<E: de::Error>(self, n: $num_type) -> Result<Self::Value, E> {
ConstScaleFpdec::try_from(n).map_err(|_| E::custom("decimal overflow"))
}
};
}
impl<'de, I, const S: i32> Visitor<'de> for ConstScaleFpdecVistor<I, S>
where
I: FromPrimitive + FpdecInner,
ParseError: From<<I as Num>::FromStrRadixErr>,
{
type Value = ConstScaleFpdec<I, S>;
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> {
ConstScaleFpdec::from_str(s).map_err(E::custom)
}
visit_num!(visit_f32, f32);
visit_num!(visit_f64, f64);
visit_num!(visit_i8, i8);
visit_num!(visit_i16, i16);
visit_num!(visit_i32, i32);
visit_num!(visit_i64, i64);
visit_num!(visit_i128, i128);
}
deserializer.deserialize_any(ConstScaleFpdecVistor(PhantomData))
}
}