From 08aa6c9b650ba83b58600d0794bcf0bc8eef7a42 Mon Sep 17 00:00:00 2001 From: ltdk Date: Fri, 2 Jun 2023 20:07:26 -0400 Subject: [PATCH] Specialize count for range iterators --- library/core/src/iter/range.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/library/core/src/iter/range.rs b/library/core/src/iter/range.rs index 44feb0a5638..391e03636ab 100644 --- a/library/core/src/iter/range.rs +++ b/library/core/src/iter/range.rs @@ -765,6 +765,15 @@ impl Iterator for ops::Range { } } + #[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 { self.spec_nth(n) @@ -1162,6 +1171,17 @@ impl Iterator for ops::RangeInclusive { } } + #[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 { if self.is_empty() {