Skip to content

Commit 246b844

Browse files
committed
implement Sum and Product for Saturating(u*)
1 parent 9748d87 commit 246b844

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

library/core/src/iter/traits/accum.rs

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::iter;
2-
use crate::num::Wrapping;
2+
use crate::num::{Saturating, Wrapping};
33

44
/// Trait to represent types that can be created by summing up an iterator.
55
///
@@ -98,6 +98,59 @@ macro_rules! integer_sum_product {
9898
);
9999
}
100100

101+
macro_rules! saturating_integer_sum_product {
102+
(@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(
103+
#[$attr]
104+
impl Sum for $a {
105+
fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
106+
iter.fold(
107+
$zero,
108+
#[rustc_inherit_overflow_checks]
109+
|a, b| a + b,
110+
)
111+
}
112+
}
113+
114+
#[$attr]
115+
impl Product for $a {
116+
fn product<I: Iterator<Item=Self>>(iter: I) -> Self {
117+
iter.fold(
118+
$one,
119+
#[rustc_inherit_overflow_checks]
120+
|a, b| a * b,
121+
)
122+
}
123+
}
124+
125+
#[$attr]
126+
impl<'a> Sum<&'a $a> for $a {
127+
fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
128+
iter.fold(
129+
$zero,
130+
#[rustc_inherit_overflow_checks]
131+
|a, b| a + b,
132+
)
133+
}
134+
}
135+
136+
#[$attr]
137+
impl<'a> Product<&'a $a> for $a {
138+
fn product<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
139+
iter.fold(
140+
$one,
141+
#[rustc_inherit_overflow_checks]
142+
|a, b| a * b,
143+
)
144+
}
145+
}
146+
)*);
147+
($($a:ty)*) => (
148+
integer_sum_product!(@impls Saturating(0), Saturating(1),
149+
#[stable(feature = "saturating_iter_arith", since = "1.14.0")],
150+
$(Saturating<$a>)*);
151+
);
152+
}
153+
101154
macro_rules! float_sum_product {
102155
($($a:ident)*) => ($(
103156
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
@@ -147,6 +200,7 @@ macro_rules! float_sum_product {
147200
}
148201

149202
integer_sum_product! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
203+
saturating_integer_sum_product! { u8 u16 u32 u64 u128 usize }
150204
float_sum_product! { f32 f64 }
151205

152206
#[stable(feature = "iter_arith_traits_result", since = "1.16.0")]

0 commit comments

Comments
 (0)