2 use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen};
3 use crate::ops::{ControlFlow, Try};
5 /// An iterator that only iterates over the first `n` iterations of `iter`.
7 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
8 /// documentation for more.
10 /// [`take`]: Iterator::take
11 /// [`Iterator`]: trait.Iterator.html
12 #[derive(Clone, Debug)]
13 #[must_use = "iterators are lazy and do nothing unless consumed"]
14 #[stable(feature = "rust1", since = "1.0.0")]
21 pub(in crate::iter) fn new(iter: I, n: usize) -> Take<I> {
26 #[stable(feature = "rust1", since = "1.0.0")]
27 impl<I> Iterator for Take<I>
31 type Item = <I as Iterator>::Item;
34 fn next(&mut self) -> Option<<I as Iterator>::Item> {
44 fn nth(&mut self, n: usize) -> Option<I::Item> {
50 self.iter.nth(self.n - 1);
58 fn size_hint(&self) -> (usize, Option<usize>) {
63 let (lower, upper) = self.iter.size_hint();
65 let lower = cmp::min(lower, self.n);
67 let upper = match upper {
68 Some(x) if x < self.n => Some(x),
76 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
79 Fold: FnMut(Acc, Self::Item) -> R,
82 fn check<'a, T, Acc, R: Try<Output = Acc>>(
84 mut fold: impl FnMut(Acc, T) -> R + 'a,
85 ) -> impl FnMut(Acc, T) -> ControlFlow<R, Acc> + 'a {
89 if *n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
97 self.iter.try_fold(init, check(n, fold)).into_try()
101 impl_fold_via_try_fold! { fold -> try_fold }
104 #[rustc_inherit_overflow_checks]
105 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
106 let min = self.n.min(n);
107 match self.iter.advance_by(min) {
110 if min < n { Err(min) } else { Ok(()) }
112 ret @ Err(advanced) => {
120 #[unstable(issue = "none", feature = "inplace_iteration")]
121 unsafe impl<I> SourceIter for Take<I>
125 type Source = I::Source;
128 unsafe fn as_inner(&mut self) -> &mut I::Source {
129 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
130 unsafe { SourceIter::as_inner(&mut self.iter) }
134 #[unstable(issue = "none", feature = "inplace_iteration")]
135 unsafe impl<I: InPlaceIterable> InPlaceIterable for Take<I> {}
137 #[stable(feature = "double_ended_take_iterator", since = "1.38.0")]
138 impl<I> DoubleEndedIterator for Take<I>
140 I: DoubleEndedIterator + ExactSizeIterator,
143 fn next_back(&mut self) -> Option<Self::Item> {
149 self.iter.nth_back(self.iter.len().saturating_sub(n))
154 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
155 let len = self.iter.len();
157 let m = len.saturating_sub(self.n) + n;
159 self.iter.nth_back(m)
162 self.iter.nth_back(len - 1);
169 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
172 Fold: FnMut(Acc, Self::Item) -> R,
173 R: Try<Output = Acc>,
178 let len = self.iter.len();
179 if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
182 self.iter.try_rfold(init, fold)
188 fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
191 Fold: FnMut(Acc, Self::Item) -> Acc,
196 let len = self.iter.len();
197 if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
200 self.iter.rfold(init, fold)
206 #[rustc_inherit_overflow_checks]
207 fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
208 // The amount by which the inner iterator needs to be shortened for it to be
209 // at most as long as the take() amount.
210 let trim_inner = self.iter.len().saturating_sub(self.n);
211 // The amount we need to advance inner to fulfill the caller's request.
212 // take(), advance_by() and len() all can be at most usize, so we don't have to worry
213 // about having to advance more than usize::MAX here.
214 let advance_by = trim_inner.saturating_add(n);
216 let advanced = match self.iter.advance_back_by(advance_by) {
217 Ok(_) => advance_by - trim_inner,
218 Err(advanced) => advanced - trim_inner,
221 return if advanced < n { Err(advanced) } else { Ok(()) };
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
228 #[stable(feature = "fused", since = "1.26.0")]
229 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
231 #[unstable(feature = "trusted_len", issue = "37572")]
232 unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}