Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add impls for &Wrapping. Also Sum, Product impls for both Wrapping and &Wrapping. #37356

Merged
merged 2 commits into from
Nov 5, 2016
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/libcore/iter/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ops::{Mul, Add};
use num::Wrapping;

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

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

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

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

#[stable(feature = "iter_arith_traits", since = "1.12.0")]
impl<'a> Product<&'a $a> for $a {
fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cloned stuff is not necessary (and wasn't before) since Add::add etc are implemented for references of primitives (as well as, now, Wrapping).

iter.cloned().fold(1, Mul::mul)
iter.fold($one, Mul::mul)
}
}
)*)
)*);
($($a:ty)*) => (
integer_sum_product!(@impls 0, 1, $($a)+);
integer_sum_product!(@impls Wrapping(0), Wrapping(1), $(Wrapping<$a>)+);
);
}

macro_rules! float_sum_product {
Expand Down