|
1 | 1 | use crate::iter;
|
2 |
| -use crate::num::Wrapping; |
| 2 | +use crate::num::{Saturating, Wrapping}; |
3 | 3 |
|
4 | 4 | /// Trait to represent types that can be created by summing up an iterator.
|
5 | 5 | ///
|
@@ -98,6 +98,59 @@ macro_rules! integer_sum_product {
|
98 | 98 | );
|
99 | 99 | }
|
100 | 100 |
|
| 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 | + |
101 | 154 | macro_rules! float_sum_product {
|
102 | 155 | ($($a:ident)*) => ($(
|
103 | 156 | #[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
@@ -147,6 +200,7 @@ macro_rules! float_sum_product {
|
147 | 200 | }
|
148 | 201 |
|
149 | 202 | 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 } |
150 | 204 | float_sum_product! { f32 f64 }
|
151 | 205 |
|
152 | 206 | #[stable(feature = "iter_arith_traits_result", since = "1.16.0")]
|
|
0 commit comments