Skip to content

Commit

Permalink
Implement Product (#525)
Browse files Browse the repository at this point in the history
  • Loading branch information
c410-f3r committed Jun 27, 2022
1 parent 941351a commit aff1b9f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
8 changes: 8 additions & 0 deletions benches/lib_benches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,14 @@ fn iterator_individual(b: &mut ::test::Bencher) {
});
}

#[bench]
fn iterator_product(b: &mut ::test::Bencher) {
b.iter(|| {
let result: Decimal = DecimalIterator::new().product();
::test::black_box(result);
});
}

#[bench]
fn iterator_sum(b: &mut ::test::Bencher) {
b.iter(|| {
Expand Down
24 changes: 23 additions & 1 deletion src/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use core::{
cmp::{Ordering::Equal, *},
fmt,
hash::{Hash, Hasher},
iter::Sum,
iter::{Product, Sum},
ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign},
str::FromStr,
};
Expand Down Expand Up @@ -2525,6 +2525,28 @@ impl Ord for Decimal {
}
}

impl Product for Decimal {
/// Panics if out-of-bounds
fn product<I: Iterator<Item = Decimal>>(iter: I) -> Self {
let mut product = ONE;
for i in iter {
product *= i;
}
product
}
}

impl<'a> Product<&'a Decimal> for Decimal {
/// Panics if out-of-bounds
fn product<I: Iterator<Item = &'a Decimal>>(iter: I) -> Self {
let mut product = ONE;
for i in iter {
product *= i;
}
product
}
}

impl Sum for Decimal {
fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Self {
let mut sum = ZERO;
Expand Down
18 changes: 15 additions & 3 deletions tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3230,19 +3230,31 @@ fn test_zero_eq_negative_zero() {
assert_eq!(zero, -zero);
}

#[test]
fn declarative_dec_product() {
let vs = (1..5).map(|i| i.into()).collect::<Vec<Decimal>>();
let product: Decimal = vs.into_iter().product();
assert_eq!(product, Decimal::from(24))
}

#[test]
fn declarative_ref_dec_product() {
let vs = (1..5).map(|i| i.into()).collect::<Vec<Decimal>>();
let product: Decimal = vs.iter().product();
assert_eq!(product, Decimal::from(24))
}

#[test]
fn declarative_dec_sum() {
let vs = (0..10).map(|i| i.into()).collect::<Vec<Decimal>>();
let sum: Decimal = vs.iter().cloned().sum();

let sum: Decimal = vs.into_iter().sum();
assert_eq!(sum, Decimal::from(45))
}

#[test]
fn declarative_ref_dec_sum() {
let vs = (0..10).map(|i| i.into()).collect::<Vec<Decimal>>();
let sum: Decimal = vs.iter().sum();

assert_eq!(sum, Decimal::from(45))
}

Expand Down

0 comments on commit aff1b9f

Please sign in to comment.