Skip to content

Commit 35041d8

Browse files
Hide the Iterator specialization behind a trait
1 parent 6743b77 commit 35041d8

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/liballoc/boxed.rs

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -883,16 +883,33 @@ impl<I: Iterator + ?Sized> Iterator for Box<I> {
883883
fn nth(&mut self, n: usize) -> Option<I::Item> {
884884
(**self).nth(n)
885885
}
886+
fn last(self) -> Option<I::Item> {
887+
BoxIter::last(self)
888+
}
889+
}
890+
891+
trait BoxIter {
892+
type Item;
893+
fn last(self) -> Option<Self::Item>;
894+
}
895+
896+
impl<I: Iterator + ?Sized> BoxIter for Box<I> {
897+
type Item = I::Item;
886898
default fn last(self) -> Option<I::Item> {
887-
let mut last = None;
888-
for x in self { last = Some(x); }
889-
last
899+
#[inline]
900+
fn some<T>(_: Option<T>, x: T) -> Option<T> {
901+
Some(x)
902+
}
903+
904+
self.fold(None, some)
890905
}
891906
}
892907

908+
/// Specialization for sized `I`s that uses `I`s implementation of `last()`
909+
/// instead of the default.
893910
#[stable(feature = "rust1", since = "1.0.0")]
894-
impl<I: Iterator + Sized> Iterator for Box<I> {
895-
fn last(self) -> Option<I::Item> where I: Sized {
911+
impl<I: Iterator> BoxIter for Box<I> {
912+
fn last(self) -> Option<I::Item> {
896913
(*self).last()
897914
}
898915
}

0 commit comments

Comments
 (0)