Skip to content

Commit 5a909a6

Browse files
committed
optimize Range[Inclusive].count()
1 parent 4f93357 commit 5a909a6

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/libcore/iter/range.rs

+49
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,31 @@ impl<A: Step> Iterator for ops::Range<A> {
268268
}
269269
}
270270

271+
macro_rules! impl_range_count {
272+
($t:ty) => {
273+
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
274+
impl Iterator for ops::Range<$t> {
275+
#[inline]
276+
fn count(self) -> usize {
277+
self.end.wrapping_sub(self.start) as usize
278+
}
279+
}
280+
};
281+
}
282+
283+
impl_range_count!(u8);
284+
impl_range_count!(u16);
285+
impl_range_count!(u32);
286+
impl_range_count!(u64);
287+
impl_range_count!(usize);
288+
289+
impl_range_count!(i8);
290+
impl_range_count!(i16);
291+
impl_range_count!(i32);
292+
impl_range_count!(i64);
293+
impl_range_count!(isize);
294+
295+
271296
// These macros generate `ExactSizeIterator` impls for various range types.
272297
// Range<{u,i}64> and RangeInclusive<{u,i}{32,64,size}> are excluded
273298
// because they cannot guarantee having a length <= usize::MAX, which is
@@ -421,6 +446,30 @@ impl<A: Step> Iterator for ops::RangeInclusive<A> {
421446
}
422447
}
423448

449+
macro_rules! impl_inclusive_range_count {
450+
($t:ty) => {
451+
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
452+
impl Iterator for ops::RangeInclusive<$t> {
453+
#[inline]
454+
fn count(self) -> usize {
455+
(self.end.wrapping_sub(self.start) as usize).wrapping_add(1)
456+
}
457+
}
458+
};
459+
}
460+
461+
impl_inclusive_range_count!(u8);
462+
impl_inclusive_range_count!(u16);
463+
impl_inclusive_range_count!(u32);
464+
impl_inclusive_range_count!(u64);
465+
impl_inclusive_range_count!(usize);
466+
467+
impl_inclusive_range_count!(i8);
468+
impl_inclusive_range_count!(i16);
469+
impl_inclusive_range_count!(i32);
470+
impl_inclusive_range_count!(i64);
471+
impl_inclusive_range_count!(isize);
472+
424473
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
425474
impl<A: Step> DoubleEndedIterator for ops::RangeInclusive<A> {
426475
#[inline]

src/libcore/tests/iter.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1391,6 +1391,13 @@ fn test_range_inclusive_nth() {
13911391
assert_eq!(r, 1..=0); // We may not want to document/promise this detail
13921392
}
13931393

1394+
#[test]
1395+
fn test_range_inclusive_count() {
1396+
assert_eq!((1..=1).count(), 1);
1397+
assert_eq!((0..=10).count(), 11);
1398+
assert_eq!((5..=7).count(), 3);
1399+
}
1400+
13941401
#[test]
13951402
fn test_range_step() {
13961403
#![allow(deprecated)]

0 commit comments

Comments
 (0)