use sp_std::{
ops, prelude::*,
convert::{TryFrom, TryInto},
};
use codec::{Encode, Decode};
use crate::{
Perbill,
traits::{
SaturatedConversion, CheckedSub, CheckedAdd, CheckedDiv, Bounded, UniqueSaturatedInto, Saturating
}
};
#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Fixed64(i64);
const DIV: i64 = 1_000_000_000;
impl Fixed64 {
pub fn from_natural(int: i64) -> Self {
Self(int.saturating_mul(DIV))
}
pub fn accuracy() -> i64 {
DIV
}
#[cfg(any(feature = "std", test))]
pub fn into_inner(self) -> i64 { self.0 }
pub fn from_parts(parts: i64) -> Self {
Self(parts)
}
pub fn from_rational(n: i64, d: u64) -> Self {
Self(
(i128::from(n).saturating_mul(i128::from(DIV)) / i128::from(d).max(1))
.try_into()
.unwrap_or_else(|_| Bounded::max_value())
)
}
pub fn saturated_multiply_accumulate<N>(self, int: N) -> N
where
N: TryFrom<u64> + From<u32> + UniqueSaturatedInto<u32> + Bounded + Clone + Saturating +
ops::Rem<N, Output=N> + ops::Div<N, Output=N> + ops::Mul<N, Output=N> +
ops::Add<N, Output=N>,
{
let div = DIV as u64;
let positive = self.0 > 0;
let parts = self.0.checked_abs().map(|v| v as u64).unwrap_or(i64::max_value() as u64 + 1);
let natural_parts = parts / div;
let natural_parts: N = natural_parts.saturated_into();
let perbill_parts = (parts % div) as u32;
let n = int.clone().saturating_mul(natural_parts);
let p = Perbill::from_parts(perbill_parts) * int.clone();
let excess = n.saturating_add(p);
if positive {
int.saturating_add(excess)
} else {
int.saturating_sub(excess)
}
}
}
impl Saturating for Fixed64 {
fn saturating_add(self, rhs: Self) -> Self {
Self(self.0.saturating_add(rhs.0))
}
fn saturating_mul(self, rhs: Self) -> Self {
Self(self.0.saturating_mul(rhs.0) / DIV)
}
fn saturating_sub(self, rhs: Self) -> Self {
Self(self.0.saturating_sub(rhs.0))
}
}
impl ops::Add for Fixed64 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl ops::Sub for Fixed64 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self(self.0 - rhs.0)
}
}
impl ops::Div for Fixed64 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
if rhs.0 == 0 {
let zero = 0;
return Fixed64::from_parts( self.0 / zero);
}
let (n, d) = if rhs.0 < 0 {
(-self.0, rhs.0.abs() as u64)
} else {
(self.0, rhs.0 as u64)
};
Fixed64::from_rational(n, d)
}
}
impl CheckedSub for Fixed64 {
fn checked_sub(&self, rhs: &Self) -> Option<Self> {
self.0.checked_sub(rhs.0).map(Self)
}
}
impl CheckedAdd for Fixed64 {
fn checked_add(&self, rhs: &Self) -> Option<Self> {
self.0.checked_add(rhs.0).map(Self)
}
}
impl CheckedDiv for Fixed64 {
fn checked_div(&self, rhs: &Self) -> Option<Self> {
if rhs.0 == 0 {
None
} else {
Some(*self / *rhs)
}
}
}
impl sp_std::fmt::Debug for Fixed64 {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
write!(f, "Fixed64({},{})", self.0 / DIV, (self.0 % DIV) / 1000)
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn max() -> Fixed64 {
Fixed64::from_parts(i64::max_value())
}
#[test]
fn fixed64_semantics() {
assert_eq!(Fixed64::from_rational(5, 2).0, 5 * 1_000_000_000 / 2);
assert_eq!(Fixed64::from_rational(5, 2), Fixed64::from_rational(10, 4));
assert_eq!(Fixed64::from_rational(5, 0), Fixed64::from_rational(5, 1));
assert_ne!(max(), Fixed64::from_natural(9_223_372_036));
assert_eq!(max(), Fixed64::from_natural(9_223_372_037));
}
#[test]
fn fixed_64_growth_decrease_curve() {
let test_set = vec![0u32, 1, 10, 1000, 1_000_000_000];
let mut fm = Fixed64::from_rational(-1, 2);
test_set.clone().into_iter().for_each(|i| {
assert_eq!(fm.saturated_multiply_accumulate(i) as i32, i as i32 - i as i32 / 2);
});
fm = Fixed64::from_parts(0);
test_set.clone().into_iter().for_each(|i| {
assert_eq!(fm.saturated_multiply_accumulate(i), i);
});
fm = Fixed64::from_rational(1, 2);
test_set.clone().into_iter().for_each(|i| {
assert_eq!(fm.saturated_multiply_accumulate(i), i * 3 / 2);
});
fm = Fixed64::from_rational(1, 1);
test_set.clone().into_iter().for_each(|i| {
assert_eq!(fm.saturated_multiply_accumulate(i), i * 2);
});
}
macro_rules! saturating_mul_acc_test {
($num_type:tt) => {
assert_eq!(
Fixed64::from_rational(100, 1).saturated_multiply_accumulate(10 as $num_type),
1010,
);
assert_eq!(
Fixed64::from_rational(100, 2).saturated_multiply_accumulate(10 as $num_type),
510,
);
assert_eq!(
Fixed64::from_rational(100, 3).saturated_multiply_accumulate(0 as $num_type),
0,
);
assert_eq!(
Fixed64::from_rational(5, 1).saturated_multiply_accumulate($num_type::max_value()),
$num_type::max_value()
);
assert_eq!(
max().saturated_multiply_accumulate($num_type::max_value()),
$num_type::max_value()
);
}
}
#[test]
fn fixed64_multiply_accumulate_works() {
saturating_mul_acc_test!(u32);
saturating_mul_acc_test!(u64);
saturating_mul_acc_test!(u128);
}
#[test]
fn div_works() {
let a = Fixed64::from_rational(12, 10);
let b = Fixed64::from_rational(10, 1);
assert_eq!(a / b, Fixed64::from_rational(12, 100));
let a = Fixed64::from_rational(12, 10);
let b = Fixed64::from_rational(1, 100);
assert_eq!(a / b, Fixed64::from_rational(120, 1));
let a = Fixed64::from_rational(12, 100);
let b = Fixed64::from_rational(10, 1);
assert_eq!(a / b, Fixed64::from_rational(12, 1000));
let a = Fixed64::from_rational(12, 100);
let b = Fixed64::from_rational(1, 100);
assert_eq!(a / b, Fixed64::from_rational(12, 1));
let a = Fixed64::from_rational(-12, 10);
let b = Fixed64::from_rational(10, 1);
assert_eq!(a / b, Fixed64::from_rational(-12, 100));
let a = Fixed64::from_rational(12, 10);
let b = Fixed64::from_rational(-10, 1);
assert_eq!(a / b, Fixed64::from_rational(-12, 100));
let a = Fixed64::from_rational(-12, 10);
let b = Fixed64::from_rational(-10, 1);
assert_eq!(a / b, Fixed64::from_rational(12, 100));
}
#[test]
#[should_panic(expected = "attempt to divide by zero")]
fn div_zero() {
let a = Fixed64::from_rational(12, 10);
let b = Fixed64::from_natural(0);
let _ = a / b;
}
#[test]
fn checked_div_zero() {
let a = Fixed64::from_rational(12, 10);
let b = Fixed64::from_natural(0);
assert_eq!(a.checked_div(&b), None);
}
#[test]
fn checked_div_non_zero() {
let a = Fixed64::from_rational(12, 10);
let b = Fixed64::from_rational(1, 100);
assert_eq!(a.checked_div(&b), Some(Fixed64::from_rational(120, 1)));
}
}