Skip to content

Commit 02f36e5

Browse files
Hide the Iterator specialization behind a trait
1 parent 55277d4 commit 02f36e5

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
@@ -871,16 +871,33 @@ impl<I: Iterator + ?Sized> Iterator for Box<I> {
871871
fn nth(&mut self, n: usize) -> Option<I::Item> {
872872
(**self).nth(n)
873873
}
874+
fn last(self) -> Option<I::Item> {
875+
BoxIter::last(self)
876+
}
877+
}
878+
879+
trait BoxIter {
880+
type Item;
881+
fn last(self) -> Option<Self::Item>;
882+
}
883+
884+
impl<I: Iterator + ?Sized> BoxIter for Box<I> {
885+
type Item = I::Item;
874886
default fn last(self) -> Option<I::Item> {
875-
let mut last = None;
876-
for x in self { last = Some(x); }
877-
last
887+
#[inline]
888+
fn some<T>(_: Option<T>, x: T) -> Option<T> {
889+
Some(x)
890+
}
891+
892+
self.fold(None, some)
878893
}
879894
}
880895

896+
/// Specialization for sized `I`s that uses `I`s implementation of `last()`
897+
/// instead of the default.
881898
#[stable(feature = "rust1", since = "1.0.0")]
882-
impl<I: Iterator + Sized> Iterator for Box<I> {
883-
fn last(self) -> Option<I::Item> where I: Sized {
899+
impl<I: Iterator> BoxIter for Box<I> {
900+
fn last(self) -> Option<I::Item> {
884901
(*self).last()
885902
}
886903
}

0 commit comments

Comments
 (0)