diff --git a/library/core/src/iter/adapters/take.rs b/library/core/src/iter/adapters/take.rs index 70252e075b9..c1d8cc4ff57 100644 --- a/library/core/src/iter/adapters/take.rs +++ b/library/core/src/iter/adapters/take.rs @@ -303,13 +303,12 @@ impl SpecTake for Take { } #[inline] - fn spec_for_each(self, f: F) { - // Based on the the Iterator trait default impl. - #[inline] - fn call(mut f: impl FnMut(T)) -> impl FnMut((), T) { - move |(), item| f(item) + fn spec_for_each(mut self, mut f: F) { + let end = self.n.min(self.iter.size()); + for i in 0..end { + // SAFETY: i < end <= self.iter.size() and we discard the iterator at the end + let val = unsafe { self.iter.__iterator_get_unchecked(i) }; + f(val); } - - self.spec_fold((), call(f)); } }