Skip to content

Commit

Permalink
added neg operator, iter::sum
Browse files Browse the repository at this point in the history
  • Loading branch information
DrunkRandomWalker committed Sep 7, 2023
1 parent fd6f9fe commit 550587a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/injective-math/src/fp_decimal/arithmetic.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// Arithmetic operators for FPDecimal
use crate::fp_decimal::{FPDecimal, U256};
use std::iter;
use std::ops;

impl FPDecimal {
Expand Down Expand Up @@ -162,6 +163,15 @@ impl ops::Div for FPDecimal {
}
}

impl<'a> iter::Sum<&'a Self> for FPDecimal {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(FPDecimal::ZERO, |a, b| a + *b)
}
}

#[cfg(test)]
mod tests {
use std::str::FromStr;
Expand Down Expand Up @@ -578,4 +588,19 @@ mod tests {
let ans = lhs.abs_diff(&rhs);
assert_eq!(FPDecimal::from(3u128), ans);
}
#[test]
fn test_chain_sum() {
let vector = vec![FPDecimal::ZERO, FPDecimal::ONE, FPDecimal::TWO, FPDecimal::THREE];
assert_eq!(FPDecimal::SIX, vector.iter().sum());
}
#[test]
fn test_chain_sum_equal_zero() {
let vector = vec![FPDecimal::ZERO, FPDecimal::ONE, FPDecimal::TWO, -FPDecimal::THREE];
assert_eq!(FPDecimal::ZERO, vector.iter().sum());
}
// #[test]
// fn test_chain_sum_equal_zero() {
// let vector = vec![FPDecimal::ZERO, FPDecimal::ONE, FPDecimal::TWO, -FPDecimal::THREE];
// assert_eq!(FPDecimal::ZERO, vector.iter().sum());
// }
}
37 changes: 37 additions & 0 deletions packages/injective-math/src/fp_decimal/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::ops::Neg;
use std::str::FromStr;

use bigint::U256;
Expand Down Expand Up @@ -77,6 +78,24 @@ impl From<Uint256> for FPDecimal {
}
}

impl Neg for FPDecimal {
type Output = FPDecimal;
fn neg(mut self) -> Self::Output {
if self.is_zero() {
return self;
}
match self.sign {
0 => {
self.sign = 1;
}
_ => {
self.sign = 0;
}
}
self
}
}

// #[cfg(not(target_arch = "wasm32"))]
// impl convert::From<FPDecimal> for f32 {
// fn from(x: FPDecimal) -> f32 {
Expand Down Expand Up @@ -247,3 +266,21 @@ mod log;
pub mod scale;
mod serde;
mod trigonometry;

#[cfg(test)]
mod tests {
use crate::FPDecimal;
#[test]
fn test_neg_sign() {
let lhs = FPDecimal::ZERO - FPDecimal::ONE;
let rhs = -FPDecimal::ONE;
assert_eq!(lhs, rhs);
}

#[test]
fn test_neg_zero() {
let lhs = FPDecimal::ZERO;
let rhs = -FPDecimal::ZERO;
assert_eq!(lhs, rhs);
}
}

0 comments on commit 550587a

Please sign in to comment.