diff --git a/src/libcore/iter/range.rs b/src/libcore/iter/range.rs index 3b034efcce14c..0248c782910db 100644 --- a/src/libcore/iter/range.rs +++ b/src/libcore/iter/range.rs @@ -268,6 +268,31 @@ impl Iterator for ops::Range { } } +macro_rules! impl_range_count { + ($t:ty) => { + #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")] + impl Iterator for ops::Range<$t> { + #[inline] + fn count(self) -> usize { + self.end.wrapping_sub(self.start) as usize + } + } + }; +} + +impl_range_count!(u8); +impl_range_count!(u16); +impl_range_count!(u32); +impl_range_count!(u64); +impl_range_count!(usize); + +impl_range_count!(i8); +impl_range_count!(i16); +impl_range_count!(i32); +impl_range_count!(i64); +impl_range_count!(isize); + + // These macros generate `ExactSizeIterator` impls for various range types. // Range<{u,i}64> and RangeInclusive<{u,i}{32,64,size}> are excluded // because they cannot guarantee having a length <= usize::MAX, which is @@ -419,6 +444,12 @@ impl Iterator for ops::RangeInclusive { } Try::from_ok(accum) } + + #[inline] + fn count(self) -> usize { + ::steps_between(&self.start, &self.end) + .expect("Overflow on `RangeInclusive::count()`") + 1 + } } #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")] diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index dc866d180bfa0..8e9140595dce8 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -1391,6 +1391,13 @@ fn test_range_inclusive_nth() { assert_eq!(r, 1..=0); // We may not want to document/promise this detail } +#[test] +fn test_range_inclusive_count() { + assert_eq!((1..=1).count(), 1); + assert_eq!((0..=10).count(), 11); + assert_eq!((5..=7).count(), 3); +} + #[test] fn test_range_step() { #![allow(deprecated)]