Rollup merge of #60130 - khuey:efficient_last, r=sfackler
Add implementations of last in terms of next_back on a bunch of DoubleEndedIterators Provided a `DoubleEndedIterator` has finite length, `Iterator::last` is equivalent to `DoubleEndedIterator::next_back`. But searching forwards through the iterator when it's unnecessary is obviously not good for performance. I ran into this on one of the collection iterators. I tried adding appropriate overloads for a bunch of the iterator adapters like filter, map, etc, but I ran into a lot of type inference failures after doing so. The other interesting case is what to do with `Repeat`. Do we consider it part of the contract that `Iterator::last` will loop forever on it? The docs do say that the iterator will be evaluated until it returns None. This is also relevant for the adapters, it's trivially easy to observe whether a `Map` adapter invoked its closure a zillion times or just once for the last element.
This commit is contained in:
commit
bab03cecfe
14 changed files with 159 additions and 0 deletions
|
@ -746,6 +746,10 @@ impl Iterator for Args {
|
|||
self.inner.next().map(|s| s.into_string().unwrap())
|
||||
}
|
||||
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
|
||||
#[inline]
|
||||
fn last(mut self) -> Option<String> {
|
||||
self.next_back()
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "env", since = "1.0.0")]
|
||||
|
@ -781,6 +785,8 @@ impl Iterator for ArgsOs {
|
|||
type Item = OsString;
|
||||
fn next(&mut self) -> Option<OsString> { self.inner.next() }
|
||||
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
|
||||
#[inline]
|
||||
fn last(mut self) -> Option<OsString> { self.next_back() }
|
||||
}
|
||||
|
||||
#[stable(feature = "env", since = "1.0.0")]
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue