Skip to content

Commit b62b352

Browse files
committed
Check for exhaustion in RangeInclusive::contains
When a range has finished iteration, `is_empty` returns true, so it should also be the case that `contains` returns false.
1 parent cb2462c commit b62b352

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

library/core/src/ops/range.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -479,13 +479,23 @@ impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
479479
/// assert!(!(0.0..=f32::NAN).contains(&0.0));
480480
/// assert!(!(f32::NAN..=1.0).contains(&1.0));
481481
/// ```
482+
///
483+
/// This method always returns `false` after iteration has finished:
484+
///
485+
/// ```
486+
/// let mut r = 3..=5;
487+
/// assert!(r.contains(&3) && r.contains(&5));
488+
/// for _ in r.by_ref() {}
489+
/// // Precise field values are unspecified here
490+
/// assert!(!r.contains(&3) && !r.contains(&5));
491+
/// ```
482492
#[stable(feature = "range_contains", since = "1.35.0")]
483493
pub fn contains<U>(&self, item: &U) -> bool
484494
where
485495
Idx: PartialOrd<U>,
486496
U: ?Sized + PartialOrd<Idx>,
487497
{
488-
<Self as RangeBounds<Idx>>::contains(self, item)
498+
!self.exhausted && <Self as RangeBounds<Idx>>::contains(self, item)
489499
}
490500

491501
/// Returns `true` if the range contains no items.

0 commit comments

Comments
 (0)