Skip to content

Commit

Permalink
Return a correct size_hint for degenerate inclusive ranges
Browse files Browse the repository at this point in the history
Fixes #42135

Found while fixing run-pass/range_inclusive test failure.
  • Loading branch information
scottmcm committed May 21, 2017
1 parent f166bd9 commit 7eaca60
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
4 changes: 4 additions & 0 deletions src/libcore/iter/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,10 @@ impl<A: Step> Iterator for ops::RangeInclusive<A> where

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
if !(self.start <= self.end) {
return (0, Some(0));
}

match Step::steps_between_by_one(&self.start, &self.end) {
Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
None => (0, None),
Expand Down
5 changes: 5 additions & 0 deletions src/libcore/tests/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,9 @@ fn test_range_inclusive() {
r = RangeInclusive { start: -128i8, end: -128 };
assert_eq!(r.next_back(), Some(-128));
assert_eq!(r.next_back(), None);

// degenerate
r = RangeInclusive { start: 1, end: -1 };
assert_eq!(r.size_hint(), (0, Some(0)));
assert_eq!(r.next(), None);
}
14 changes: 7 additions & 7 deletions src/test/run-pass/range_inclusive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub fn main() {
short.next();
assert_eq!(long.size_hint(), (255, Some(255)));
assert_eq!(short.size_hint(), (0, Some(0)));
assert_eq!(short, RangeInclusive::Empty { at: 42 });
assert_eq!(short, 1...0);

assert_eq!(long.len(), 255);
assert_eq!(short.len(), 0);
Expand All @@ -97,28 +97,28 @@ pub fn main() {
for i in 3...251 {
assert_eq!(long.next(), Some(i));
}
assert_eq!(long, RangeInclusive::Empty { at: 251 });
assert_eq!(long, 1...0);

// check underflow
let mut narrow = 1...0;
assert_eq!(narrow.next_back(), None);
assert_eq!(narrow, RangeInclusive::Empty { at: 0 });
assert_eq!(narrow, 1...0);
let mut zero = 0u8...0;
assert_eq!(zero.next_back(), Some(0));
assert_eq!(zero.next_back(), None);
assert_eq!(zero, RangeInclusive::Empty { at: 0 });
assert_eq!(zero, 1...0);
let mut high = 255u8...255;
assert_eq!(high.next_back(), Some(255));
assert_eq!(high.next_back(), None);
assert_eq!(high, RangeInclusive::Empty { at: 255 });
assert_eq!(high, 1...0);

// what happens if you have a nonsense range?
let mut nonsense = 10...5;
assert_eq!(nonsense.next(), None);
assert_eq!(nonsense, RangeInclusive::Empty { at: 10 });
assert_eq!(nonsense, 10...5);

// output
assert_eq!(format!("{:?}", 0...10), "0...10");
assert_eq!(format!("{:?}", ...10), "...10");
assert_eq!(format!("{:?}", long), "[empty range @ 251]");
assert_eq!(format!("{:?}", long), "1...0");
}

0 comments on commit 7eaca60

Please sign in to comment.