Skip to content

Commit df0e5a9

Browse files
committed
Add Sum and Product impls for Wrapping
1 parent f69cd1b commit df0e5a9

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/libcore/iter/traits.rs

+11-6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010
use ops::{Mul, Add};
11+
use num::Wrapping;
1112

1213
/// Conversion from an `Iterator`.
1314
///
@@ -584,35 +585,39 @@ pub trait Product<A = Self>: Sized {
584585

585586
// NB: explicitly use Add and Mul here to inherit overflow checks
586587
macro_rules! integer_sum_product {
587-
($($a:ident)*) => ($(
588+
(@impls $zero:expr, $one:expr, $($a:ty)*) => ($(
588589
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
589590
impl Sum for $a {
590591
fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
591-
iter.fold(0, Add::add)
592+
iter.fold($zero, Add::add)
592593
}
593594
}
594595

595596
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
596597
impl Product for $a {
597598
fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
598-
iter.fold(1, Mul::mul)
599+
iter.fold($one, Mul::mul)
599600
}
600601
}
601602

602603
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
603604
impl<'a> Sum<&'a $a> for $a {
604605
fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
605-
iter.cloned().fold(0, Add::add)
606+
iter.fold($zero, Add::add)
606607
}
607608
}
608609

609610
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
610611
impl<'a> Product<&'a $a> for $a {
611612
fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
612-
iter.cloned().fold(1, Mul::mul)
613+
iter.fold($one, Mul::mul)
613614
}
614615
}
615-
)*)
616+
)*);
617+
($($a:ty)*) => (
618+
integer_sum_product!(@impls 0, 1, $($a)+);
619+
integer_sum_product!(@impls Wrapping(0), Wrapping(1), $(Wrapping<$a>)+);
620+
);
616621
}
617622

618623
macro_rules! float_sum_product {

0 commit comments

Comments
 (0)