diff --git a/src/libcore/iter/range.rs b/src/libcore/iter/range.rs index e9aee4a4676de..66a76a24df45a 100644 --- a/src/libcore/iter/range.rs +++ b/src/libcore/iter/range.rs @@ -251,6 +251,21 @@ impl Iterator for ops::Range { self.start = self.end.clone(); None } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn min(mut self) -> Option { + self.next() + } + + #[inline] + fn max(mut self) -> Option { + self.next_back() + } } // These macros generate `ExactSizeIterator` impls for various range types. @@ -367,6 +382,21 @@ impl Iterator for ops::RangeInclusive { self.end.replace_zero(); None } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn min(mut self) -> Option { + self.next() + } + + #[inline] + fn max(mut self) -> Option { + self.next_back() + } } #[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 5cac5b26d88bd..8997cf9c6bff9 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -1352,6 +1352,51 @@ fn test_range_step() { assert_eq!((isize::MIN..isize::MAX).step_by(1).size_hint(), (usize::MAX, Some(usize::MAX))); } +#[test] +fn test_range_last_max() { + assert_eq!((0..20).last(), Some(19)); + assert_eq!((-20..0).last(), Some(-1)); + assert_eq!((5..5).last(), None); + + assert_eq!((0..20).max(), Some(19)); + assert_eq!((-20..0).max(), Some(-1)); + assert_eq!((5..5).max(), None); +} + +#[test] +fn test_range_inclusive_last_max() { + assert_eq!((0..=20).last(), Some(20)); + assert_eq!((-20..=0).last(), Some(0)); + assert_eq!((5..=5).last(), Some(5)); + let mut r = 10..=10; + r.next(); + assert_eq!(r.last(), None); + + assert_eq!((0..=20).max(), Some(20)); + assert_eq!((-20..=0).max(), Some(0)); + assert_eq!((5..=5).max(), Some(5)); + let mut r = 10..=10; + r.next(); + assert_eq!(r.max(), None); +} + +#[test] +fn test_range_min() { + assert_eq!((0..20).min(), Some(0)); + assert_eq!((-20..0).min(), Some(-20)); + assert_eq!((5..5).min(), None); +} + +#[test] +fn test_range_inclusive_min() { + assert_eq!((0..=20).min(), Some(0)); + assert_eq!((-20..=0).min(), Some(-20)); + assert_eq!((5..=5).min(), Some(5)); + let mut r = 10..=10; + r.next(); + assert_eq!(r.min(), None); +} + #[test] fn test_repeat() { let mut it = repeat(42);