Skip to content
Closed
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
21 changes: 18 additions & 3 deletions src/libcore/iter/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,7 @@ pub trait Iterator {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn last(self) -> Option<Self::Item> where Self: Sized {
let mut last = None;
for x in self { last = Some(x); }
last
SpecLast::last(self)
}

/// Returns the `n`th element of the iterator.
Expand Down Expand Up @@ -2239,3 +2237,20 @@ impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
(**self).nth(n)
}
}

/// Allows specialization for `Iterator::last`.
trait SpecLast: Iterator + Sized {
fn last(self) -> Option<Self::Item>;
}
impl<T: Iterator> SpecLast for T {
default fn last(self) -> Option<Self::Item> {
let mut last = None;
for x in self { last = Some(x); }
last
}
}
impl<T: DoubleEndedIterator> SpecLast for T {
fn last(mut self) -> Option<Self::Item> {
self.next_back()
}
}
5 changes: 0 additions & 5 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1159,11 +1159,6 @@ macro_rules! iterator {
self.iter_nth(n)
}

#[inline]
fn last(mut self) -> Option<$elem> {
self.next_back()
}

fn all<F>(&mut self, mut predicate: F) -> bool
where F: FnMut(Self::Item) -> bool,
{
Expand Down
17 changes: 0 additions & 17 deletions src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,12 +542,6 @@ impl<'a> Iterator for Chars<'a> {
// `isize::MAX` (that's well below `usize::MAX`).
((len + 3) / 4, Some(len))
}

#[inline]
fn last(mut self) -> Option<char> {
// No need to go through the entire string.
self.next_back()
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down Expand Up @@ -634,12 +628,6 @@ impl<'a> Iterator for CharIndices<'a> {
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}

#[inline]
fn last(mut self) -> Option<(usize, char)> {
// No need to go through the entire string.
self.next_back()
}
}

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

#[inline]
fn last(self) -> Option<Self::Item> {
self.0.last()
}

#[inline]
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.0.nth(n)
Expand Down