Skip to content

Commit 29e6b10

Browse files
committed
Add max and sum specialisations for Range
1 parent 3d9c36f commit 29e6b10

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/libcore/iter/range.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use mem;
1313
use ops::{self, Add, Sub};
1414
use usize;
1515

16-
use super::{FusedIterator, TrustedLen};
16+
use super::{FusedIterator, TrustedLen, Sum};
1717

1818
/// Objects that can be stepped over in both directions.
1919
///
@@ -177,6 +177,20 @@ step_impl_signed!([i64: u64]);
177177
step_impl_no_between!(u64 i64);
178178
step_impl_no_between!(u128 i128);
179179

180+
macro_rules! range_inc_iter_impl {
181+
($($t:ty)*) => ($(
182+
#[stable(feature = "rust1", since = "1.0.0")]
183+
impl Iterator for ops::RangeInclusive<$t> {
184+
#[inline]
185+
fn sum<S>(self) -> S where S: Sum<$t> {
186+
let a = self.start;
187+
let b = self.end;
188+
S::sum(super::once((a + b) * (1 + b - a) / 2))
189+
}
190+
}
191+
)*)
192+
}
193+
180194
macro_rules! range_exact_iter_impl {
181195
($($t:ty)*) => ($(
182196
#[stable(feature = "rust1", since = "1.0.0")]
@@ -251,8 +265,18 @@ impl<A: Step> Iterator for ops::Range<A> {
251265
self.start = self.end.clone();
252266
None
253267
}
268+
269+
#[inline]
270+
fn max(self) -> Option<A> {
271+
if self.start != self.end {
272+
Some(self.end.sub_one())
273+
} else { None }
274+
}
254275
}
255276

277+
// These macros generate specialisations for `Iterator` methods for efficiency purposes.
278+
range_inc_iter_impl!(usize u8 u16 u32 u64 isize i8 i16 i32 i64);
279+
256280
// These macros generate `ExactSizeIterator` impls for various range types.
257281
// Range<{u,i}64> and RangeInclusive<{u,i}{32,64,size}> are excluded
258282
// because they cannot guarantee having a length <= usize::MAX, which is

0 commit comments

Comments
 (0)