Skip to content

Commit

Permalink
Specialize count for range iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
clarfonthey committed Sep 16, 2023
1 parent e81f85f commit 08aa6c9
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions library/core/src/iter/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,15 @@ impl<A: Step> Iterator for ops::Range<A> {
}
}

#[inline]
fn count(self) -> usize {
if self.start < self.end {
Step::steps_between(&self.start, &self.end).expect("count overflowed usize")
} else {
0
}
}

#[inline]
fn nth(&mut self, n: usize) -> Option<A> {
self.spec_nth(n)
Expand Down Expand Up @@ -1162,6 +1171,17 @@ impl<A: Step> Iterator for ops::RangeInclusive<A> {
}
}

#[inline]
fn count(self) -> usize {
if self.is_empty() {
return 0;
}

Step::steps_between(&self.start, &self.end)
.and_then(|steps| steps.checked_add(1))
.expect("count overflowed usize")
}

#[inline]
fn nth(&mut self, n: usize) -> Option<A> {
if self.is_empty() {
Expand Down

0 comments on commit 08aa6c9

Please sign in to comment.