Skip to content

Commit 66bb0aa

Browse files
author
Clar Charr
committed
Specialize Iterator::last for DoubleEndedIterator.
1 parent 995f741 commit 66bb0aa

File tree

3 files changed

+18
-25
lines changed

3 files changed

+18
-25
lines changed

src/libcore/iter/iterator.rs

+18-3
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,7 @@ pub trait Iterator {
203203
#[inline]
204204
#[stable(feature = "rust1", since = "1.0.0")]
205205
fn last(self) -> Option<Self::Item> where Self: Sized {
206-
let mut last = None;
207-
for x in self { last = Some(x); }
208-
last
206+
SpecLast::last(self)
209207
}
210208

211209
/// Returns the `n`th element of the iterator.
@@ -2239,3 +2237,20 @@ impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
22392237
(**self).nth(n)
22402238
}
22412239
}
2240+
2241+
/// Allows specialization for `Iterator::last`.
2242+
trait SpecLast: Iterator + Sized {
2243+
fn last(self) -> Option<Self::Item>;
2244+
}
2245+
impl<T: Iterator> SpecLast for T {
2246+
default fn last(self) -> Option<Self::Item> {
2247+
let mut last = None;
2248+
for x in self { last = Some(x); }
2249+
last
2250+
}
2251+
}
2252+
impl<T: DoubleEndedIterator> SpecLast for T {
2253+
fn last(mut self) -> Option<Self::Item> {
2254+
self.next_back()
2255+
}
2256+
}

src/libcore/slice/mod.rs

-5
Original file line numberDiff line numberDiff line change
@@ -1159,11 +1159,6 @@ macro_rules! iterator {
11591159
self.iter_nth(n)
11601160
}
11611161

1162-
#[inline]
1163-
fn last(mut self) -> Option<$elem> {
1164-
self.next_back()
1165-
}
1166-
11671162
fn all<F>(&mut self, mut predicate: F) -> bool
11681163
where F: FnMut(Self::Item) -> bool,
11691164
{

src/libcore/str/mod.rs

-17
Original file line numberDiff line numberDiff line change
@@ -542,12 +542,6 @@ impl<'a> Iterator for Chars<'a> {
542542
// `isize::MAX` (that's well below `usize::MAX`).
543543
((len + 3) / 4, Some(len))
544544
}
545-
546-
#[inline]
547-
fn last(mut self) -> Option<char> {
548-
// No need to go through the entire string.
549-
self.next_back()
550-
}
551545
}
552546

553547
#[stable(feature = "rust1", since = "1.0.0")]
@@ -634,12 +628,6 @@ impl<'a> Iterator for CharIndices<'a> {
634628
fn size_hint(&self) -> (usize, Option<usize>) {
635629
self.iter.size_hint()
636630
}
637-
638-
#[inline]
639-
fn last(mut self) -> Option<(usize, char)> {
640-
// No need to go through the entire string.
641-
self.next_back()
642-
}
643631
}
644632

645633
#[stable(feature = "rust1", since = "1.0.0")]
@@ -701,11 +689,6 @@ impl<'a> Iterator for Bytes<'a> {
701689
self.0.count()
702690
}
703691

704-
#[inline]
705-
fn last(self) -> Option<Self::Item> {
706-
self.0.last()
707-
}
708-
709692
#[inline]
710693
fn nth(&mut self, n: usize) -> Option<Self::Item> {
711694
self.0.nth(n)

0 commit comments

Comments
 (0)