Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 16 additions & 20 deletions library/core/src/iter/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1431,11 +1431,10 @@ impl<A: Step> RangeInclusiveIteratorImpl for ops::RangeInclusive<A> {
accum = f(accum, n)?;
}

self.exhausted = true;

if self.start == self.end {
accum = f(accum, self.start.clone())?;
}
let (n, o) = Step::forward_overflowing(self.start.clone(), 1);
let last = mem::replace(&mut self.start, n);
self.exhausted = o;
accum = f(accum, last)?;

try { accum }
}
Expand All @@ -1460,11 +1459,10 @@ impl<A: Step> RangeInclusiveIteratorImpl for ops::RangeInclusive<A> {
accum = f(accum, n)?;
}

self.exhausted = true;

if self.start == self.end {
accum = f(accum, self.start.clone())?;
}
let (n, o) = Step::backward_overflowing(self.end.clone(), 1);
let last = mem::replace(&mut self.end, n);
self.exhausted = o;
accum = f(accum, last)?;

try { accum }
}
Expand All @@ -1491,11 +1489,10 @@ impl<T: TrustedStep> RangeInclusiveIteratorImpl for ops::RangeInclusive<T> {
accum = f(accum, n)?;
}

self.exhausted = true;

if self.start == self.end {
accum = f(accum, self.start)?;
}
let (n, o) = Step::forward_overflowing(self.start, 1);
let last = mem::replace(&mut self.start, n);
self.exhausted = o;
accum = f(accum, last)?;

try { accum }
}
Expand All @@ -1520,11 +1517,10 @@ impl<T: TrustedStep> RangeInclusiveIteratorImpl for ops::RangeInclusive<T> {
accum = f(accum, n)?;
}

self.exhausted = true;

if self.start == self.end {
accum = f(accum, self.start)?;
}
let (n, o) = Step::backward_overflowing(self.end, 1);
let last = mem::replace(&mut self.end, n);
self.exhausted = o;
accum = f(accum, last)?;

try { accum }
}
Expand Down
31 changes: 31 additions & 0 deletions library/coretests/tests/iter/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -675,3 +675,34 @@ fn test_nonzero_range() {
(usize::MAX, Some(usize::MAX))
);
}

#[test]
fn test_range_inclusive_try_fold_state_matches_next() {
// normal range
let mut a = 1..=3;
let mut b = 1..=3;
a.try_fold((), |_, _| Some(()));
for _ in b.by_ref() {}
assert_eq!(a, b);

// overflow at the end of the type
let mut a = 250u8..=255;
let mut b = 250u8..=255;
a.try_fold((), |_, _| Some(()));
for _ in b.by_ref() {}
assert_eq!(a, b);

// try_rfold, and overflow at the start of the type
let mut a = 0u8..=5;
let mut b = 0u8..=5;
a.try_rfold((), |_, _| Some(()));
while b.next_back().is_some() {}
assert_eq!(a, b);

// early break on the last element
let mut a = 1..=3;
let mut b = 1..=3;
a.try_fold((), |_, x| if x == 3 { None } else { Some(()) });
for _ in b.by_ref() {}
assert_eq!(a, b);
}
Loading