From 27d4d51670710aa44a73baf04130bc262b8de244 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Wed, 7 Feb 2018 11:11:54 -0800 Subject: [PATCH] Simplify RangeInclusive::next[_back] `match`ing on an `Option` seems cause some confusion for LLVM; switching to just using comparison operators removes a few jumps from the simple `for` loops I was trying. --- src/libcore/iter/range.rs | 28 ++++++++++++---------------- src/libcore/tests/iter.rs | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/src/libcore/iter/range.rs b/src/libcore/iter/range.rs index 3b034efcce1..6d582b9a721 100644 --- a/src/libcore/iter/range.rs +++ b/src/libcore/iter/range.rs @@ -331,19 +331,17 @@ impl Iterator for ops::RangeInclusive { #[inline] fn next(&mut self) -> Option { - use cmp::Ordering::*; - - match self.start.partial_cmp(&self.end) { - Some(Less) => { + if self.start <= self.end { + if self.start < self.end { let n = self.start.add_one(); Some(mem::replace(&mut self.start, n)) - }, - Some(Equal) => { + } else { let last = self.start.replace_one(); self.end.replace_zero(); Some(last) - }, - _ => None, + } + } else { + None } } @@ -425,19 +423,17 @@ impl Iterator for ops::RangeInclusive { impl DoubleEndedIterator for ops::RangeInclusive { #[inline] fn next_back(&mut self) -> Option { - use cmp::Ordering::*; - - match self.start.partial_cmp(&self.end) { - Some(Less) => { + if self.start <= self.end { + if self.start < self.end { let n = self.end.sub_one(); Some(mem::replace(&mut self.end, n)) - }, - Some(Equal) => { + } else { let last = self.end.replace_zero(); self.start.replace_one(); Some(last) - }, - _ => None, + } + } else { + None } } diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index dc866d180bf..c742a1d8048 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -1332,6 +1332,18 @@ fn test_range_inclusive_exhaustion() { assert_eq!(r.next_back(), Some(10)); assert_eq!(r, 1..=0); + let mut r = 10..=12; + assert_eq!(r.next(), Some(10)); + assert_eq!(r.next(), Some(11)); + assert_eq!(r.next(), Some(12)); + assert_eq!(r, 1..=0); + + let mut r = 10..=12; + assert_eq!(r.next_back(), Some(12)); + assert_eq!(r.next_back(), Some(11)); + assert_eq!(r.next_back(), Some(10)); + assert_eq!(r, 1..=0); + let mut r = 10..=12; assert_eq!(r.nth(2), Some(12)); assert_eq!(r, 1..=0); @@ -1340,6 +1352,13 @@ fn test_range_inclusive_exhaustion() { assert_eq!(r.nth(5), None); assert_eq!(r, 1..=0); + let mut r = 100..=10; + assert_eq!(r.next(), None); + assert_eq!(r, 100..=10); + + let mut r = 100..=10; + assert_eq!(r.next_back(), None); + assert_eq!(r, 100..=10); } #[test]