diff --git a/src/libcore/iter/iterator.rs b/src/libcore/iter/iterator.rs index 30d09e5453b37..3d9ed385754de 100644 --- a/src/libcore/iter/iterator.rs +++ b/src/libcore/iter/iterator.rs @@ -203,9 +203,7 @@ pub trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn last(self) -> Option 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. @@ -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; +} +impl SpecLast for T { + default fn last(self) -> Option { + let mut last = None; + for x in self { last = Some(x); } + last + } +} +impl SpecLast for T { + fn last(mut self) -> Option { + self.next_back() + } +} diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index b13e19c030694..8f19838255def 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -1159,11 +1159,6 @@ macro_rules! iterator { self.iter_nth(n) } - #[inline] - fn last(mut self) -> Option<$elem> { - self.next_back() - } - fn all(&mut self, mut predicate: F) -> bool where F: FnMut(Self::Item) -> bool, { diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 547a4899c7118..90cca363b6538 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -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 { - // No need to go through the entire string. - self.next_back() - } } #[stable(feature = "rust1", since = "1.0.0")] @@ -634,12 +628,6 @@ impl<'a> Iterator for CharIndices<'a> { fn size_hint(&self) -> (usize, Option) { 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")] @@ -701,11 +689,6 @@ impl<'a> Iterator for Bytes<'a> { self.0.count() } - #[inline] - fn last(self) -> Option { - self.0.last() - } - #[inline] fn nth(&mut self, n: usize) -> Option { self.0.nth(n)